-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.cpp
More file actions
1137 lines (996 loc) · 44.3 KB
/
Copy pathserver.cpp
File metadata and controls
1137 lines (996 loc) · 44.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <sys/socket.h>
#include <iostream>
#include <cstring>
#include <netinet/in.h>
#include <unistd.h>
#include <fstream>
#include <string>
#include <mutex>
#include <algorithm>
#include <thread>
#include <vector>
#include "Database.h"
#include <sqlite3.h>
#include "OnlineManager.h"
#include <chrono>
#include <ctime>
#include <iomanip> // For std::put_time
#include "user.h"
#include <sstream>
#include <filesystem>
#include <sys/types.h>
#include <sys/stat.h>
/*
Compile:
g++ -std=c++17 server.cpp OnlineManager.cpp Database.cpp user.cpp -o server -lsqlite3
TODO
- Remove legacy code, ln curses, chat logs, etc. Implement logs in db
- Restructrue legacy functions
- Turn all message types to ints rather than strings
- add classes to server.cpp
- in db, fix user to have autoincrement id and not manually pulled from server_info
- Friend requests needs to be seperate thread to constantly wait, when launched pull everything from db,
then when sent, will update live. If request is sent and user is offline, keep it in db. Same with messages.
Threads need to be asynchronous
- Reorg threads to have classes or objects
- For message system, make "active_users_in_chat" variable in message class to be set when switching to that chat to make global
then can be accessed in the send message and display messages, probably array of user_ids
*/
std::mutex clients_mutex;
std::vector<int> client_sockets;
//
std::string getCurrentTimestamp() {
// Get the current time as a time_point
auto now = std::chrono::system_clock::now();
// Convert time_point to time_t, which represents calendar time in seconds since epoch
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
// Convert time_t to string and return
return std::to_string(now_time);
}
std::string read_header(int client_socket) {
std::string header;
char c;
while (true) {
ssize_t bytes_received = recv(client_socket, &c, 1, 0);
if (bytes_received <= 0) {
return "";
}
if (c == '\n') {
break;
}
header += c;
}
return header;
}
std::string read_pipe_ended_gen_data(int client_socket)
{
std::string data;
char c;
while (true) {
ssize_t bytes_received = recv(client_socket, &c, 1, 0);
if (bytes_received <= 0) {
return "";
}
if (c == '|') {
break;
}
data += c;
}
return data;
}
//user_id is client's id
void handle_message_client(int client_socket, Database* DB, OnlineManager& user_management_system, int user_id)
{
while (true)
{
std::cout << "Reading MESSAGE Header" << std::endl;
std::string data_type = read_header(client_socket);
std::cout << "data type read: " << data_type << std::endl;
if (data_type.empty()) {
std::cerr << "Error: Client Disconnected or No Header Sent" << std::endl;
break;
}
if (data_type == "image") {
char buffer[1024];
std::vector<char> image_data;
size_t bytes_rec;
while ((bytes_rec = recv(client_socket, buffer, sizeof(buffer), 0)) > 0)
{
image_data.insert(image_data.end(), buffer, buffer + bytes_rec);
if (bytes_rec < sizeof(buffer))
{
std::cout << "image recieved" << std::endl;
//should prob be break
}
}
}
if(data_type == "init_chat")
{
//recv the id's of everyone in the chat, for now just 1. Later refactor to except arr for gc
std::string msg_id = read_pipe_ended_gen_data(client_socket);
std::cout << "ID read to init chat: " << msg_id << std::endl;
std::vector<int> member_id_list = {stoi(msg_id), user_id};
std::vector<std::vector<std::string>> chats = DB->pull_chat_messages(member_id_list);
for(auto data : chats)
{
std::string data_sendable = data[0] + "\\+" + data[1] + "\\-" + data[2] + "\\|";
ssize_t bytes_sent = send(client_socket, data_sendable.c_str(), data_sendable.size(), 0);
}
ssize_t bytes_sent = send(client_socket, "-", 1, 0);
std::cout << "Finished initializing chat" << std::endl;
//pull all chat times, sender, and content per id in messages table
} else if (data_type == "get_all_chats")
{
std::vector<std::vector<std::string>> chats = DB->pull_non_exclusive_chat_messages(user_id);
//SELECT DISTINCT m.timestamp, m.sender_username, m.sender_id, m.conversation_id, m.message_text, m.image_path, m.message_id
std::cout << "Chats pulled successfully" << std::endl;
for (const auto& data : chats)
{
int image_size = 0;
std::string image_path = data[5];
std::cout << "Image path: " << image_path << std::endl;
if(!image_path.empty())
{
//pull image and send
std::ifstream image_file(image_path, std::ios::binary);
if (image_file) {
std::vector<char> image_data((std::istreambuf_iterator<char>(image_file)),
std::istreambuf_iterator<char>());
image_file.close();
image_size = image_data.size();
std::cout << "Image Size: " << image_size << std::endl;
// Now image_data contains the contents of the image file
// You can process it as needed
std::string data_sendable = data[0] + "\\+" + data[1] + "\\-" + data[2] + "\\]" + data[3] + "\\[" + data[4] + "\\$" + data[6] + "\\~" + std::to_string(image_size) + "\\|";
std::cout << "Data to send: " << data_sendable << std::endl;
ssize_t bytes_sent = send(client_socket, data_sendable.c_str(), data_sendable.size(), 0);
if(bytes_sent > 0)
{
//send image
std::this_thread::sleep_for(std::chrono::milliseconds(100));
ssize_t image_bytes_sent = send(client_socket, image_data.data(), image_size, 0);
if (image_bytes_sent == image_size)
{
std::cout << "Finished sending image" << std::endl;
}
}
else
{
std::cout << "Not attempting image send, init message failed to be received" << std::endl;
}
} else
{
std::cerr << "ERROR: Unable to open image file" << std::endl;
std::string data_sendable = data[0] + "\\+" + data[1] + "\\-" + data[2] + "\\]" + data[3] + "\\[" + data[4] + "\\$" + data[6] + "\\~" + std::to_string(image_size) + "\\|";
//send without image
std::cout << "DATA SENT: " << data_sendable << std::endl;
ssize_t bytes_sent = send(client_socket, data_sendable.c_str(), data_sendable.size(), 0);
if (bytes_sent == -1)
{
std::cerr << "Failed to send chat message data to client." << std::endl;
break;
}
}
}
else
{
//send without image
std::string data_sendable = data[0] + "\\+" + data[1] + "\\-" + data[2] + "\\]" + data[3] + "\\[" + data[4] + "\\$" + data[6] + "\\~" + std::to_string(image_size) + "\\|";
std::cout << "DATA SENT: " << data_sendable << std::endl;
ssize_t bytes_sent = send(client_socket, data_sendable.c_str(), data_sendable.size(), 0);
if (bytes_sent == -1)
{
std::cerr << "Failed to send chat message data to client." << std::endl;
break;
}
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
std::string termination_signal = "#";
ssize_t end_signal_sent = send(client_socket, termination_signal.c_str(), termination_signal.size(), 0);
if (end_signal_sent == -1)
{
std::cerr << "Failed to send termination signal to client." << std::endl;
}
std::cout << "Finished sending all chats" << std::endl;
} else if (data_type == "incoming_message") {
std::string data;
char c;
bool found_backslash = false;
std::string username;
std::string message_contents;
int conversation_id;
int image_size = 0;
// Read message metadata until '\\|'
while (true) {
ssize_t bytes_received = recv(client_socket, &c, 1, 0);
if (bytes_received <= 0) {
data = "";
std::cerr << "ERROR: no data received in message" << std::endl;
break;
}
data += c;
if (found_backslash && c == '|') {
break;
}
found_backslash = (c == '\\');
}
if (!data.empty()) {
// Parse data
size_t dash_pos = data.find("\\-");
if (dash_pos != std::string::npos) {
username = data.substr(0, dash_pos);
size_t plus_pos = data.find("\\+", dash_pos + 2);
if (plus_pos != std::string::npos) {
std::string convo_id_str = data.substr(dash_pos + 2, plus_pos - (dash_pos + 2));
conversation_id = std::stoi(convo_id_str);
size_t dollar_pos = data.find("\\$", plus_pos + 2);
if (dollar_pos != std::string::npos) {
message_contents = data.substr(plus_pos + 2, dollar_pos - (plus_pos + 2));
size_t pipe_pos = data.find("\\|", dollar_pos + 2);
if (pipe_pos != std::string::npos) {
std::string image_size_str = data.substr(dollar_pos + 2, pipe_pos - (dollar_pos + 2));
image_size = std::stoi(image_size_str);
}
}
}
}
// Read image data if present
std::vector<char> image_data;
if (image_size > 0) {
image_data.resize(image_size);
size_t total_received = 0;
while (total_received < image_size) {
ssize_t bytes_received = recv(client_socket, &image_data[total_received], image_size - total_received, 0);
if (bytes_received <= 0) {
std::cerr << "ERROR: Failed to receive image data" << std::endl;
break;
}
total_received += bytes_received;
}
}
// **Insert the message into the database without image_path**
std::string insert_query = "INSERT INTO messages(sender_id, conversation_id, message_text, sender_username) VALUES(?, ?, ?, ?);";
sqlite3_stmt* stmt;
sqlite3_prepare_v2(DB->get_database(), insert_query.c_str(), -1, &stmt, nullptr);
sqlite3_bind_int(stmt, 1, user_id);
sqlite3_bind_int(stmt, 2, conversation_id);
sqlite3_bind_text(stmt, 3, message_contents.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 4, username.c_str(), -1, SQLITE_TRANSIENT);
if (sqlite3_step(stmt) != SQLITE_DONE) {
std::cerr << "ERROR: Failed to insert message into database." << std::endl;
}
sqlite3_finalize(stmt);
// **Retrieve the last inserted message_id**
int message_id = sqlite3_last_insert_rowid(DB->get_database());
std::string image_path = "";
if (image_size > 0) {
// **Save image data to file with message_id in filename**
std::string image_directory = "./IMAGEMESSAGE/";
std::string image_filename = "image_message" + std::to_string(message_id);
image_path = image_directory + image_filename;
// Ensure directory exists
struct stat st = {0};
if (stat(image_directory.c_str(), &st) == -1) {
mkdir(image_directory.c_str(), 0700);
}
std::ofstream image_file(image_path, std::ios::binary);
if (image_file) {
image_file.write(image_data.data(), image_data.size());
image_file.close();
} else {
std::cerr << "ERROR: Unable to save image to file" << std::endl;
}
// **Update the image_path in the database for this message_id**
std::string update_query = "UPDATE messages SET image_path = ? WHERE message_id = ?;";
sqlite3_prepare_v2(DB->get_database(), update_query.c_str(), -1, &stmt, nullptr);
sqlite3_bind_text(stmt, 1, image_path.c_str(), -1, SQLITE_TRANSIENT);
sqlite3_bind_int(stmt, 2, message_id);
if (sqlite3_step(stmt) != SQLITE_DONE) {
std::cerr << "ERROR: Failed to update image_path in database." << std::endl;
}
sqlite3_finalize(stmt);
}
// **Send message to conversation members**
std::vector<int> conversation_member_ids = DB->getUserIdsInConversation(conversation_id);
for (auto &id : conversation_member_ids) {
if (id != user_id) {
int sock = user_management_system.getSocket(id);
if (sock != -1) {
std::string timestamp = getCurrentTimestamp();
std::string message_complete = timestamp + "\\+" + username + "\\-" + std::to_string(user_id) + "\\]" + std::to_string(conversation_id) + "\\[" + message_contents + "\\$" + std::to_string(image_size) + "\\&" + std::to_string(message_id) + "\\|";
ssize_t message_bytes = send(sock, message_complete.c_str(), message_complete.size(), 0);
if (message_bytes > 0)
{
std::cout << "Message sent: " << message_complete << std::endl;
}
if (image_size > 0) {
send(sock, image_data.data(), image_size, 0);
}
}
}
}
}
} else {
std::cerr << "Unkown message data type: " << data_type << std::endl;
}
}
{
std::lock_guard<std::mutex> lock(clients_mutex);
client_sockets.erase(std::remove(client_sockets.begin(), client_sockets.end(), client_socket), client_sockets.end());
}
close(client_socket);
}
void handle_relations_client(int client_socket, Database* DB, int user_id)
{
//TODO - fix friend_requests table (1-username error)
/*
*/
sqlite3* Database = DB->get_database();
while (true)
{
std::cout << "Reading RELATIONS Header" << std::endl;
std::string data_type = read_header(client_socket);
std::cout << "data type read: " << data_type << std::endl;
if (data_type.empty()) {
std::cerr << "Error: Client Disconnected or No Header Sent" << std::endl;
break;
}
//error handle to send message of already accepted if trying to add current friend
if (data_type == "new_friend_request")
{
std::string data = read_pipe_ended_gen_data(client_socket);
std::cout << "Friend request data recieved" << data << std::endl;
std::string receiver_username = data.substr(0, data.find('+'));
size_t plus_pos = data.find("+");
size_t dash_pos = data.find("-", plus_pos + 1); // Start searching for '-' after '+'
std::string sender_id = data.substr(plus_pos + 1, dash_pos - plus_pos - 1);
std::string sender_username = data.substr(dash_pos + 1);
std::cout << "Receiver Username: " << receiver_username << std::endl;
std::cout << "Sender ID: " << sender_id << std::endl;
std::cout << "Sender Username: " << sender_username << std::endl;
//1. check if the user exists
int user_exists = DB->check_unique_username(receiver_username);
if (user_exists == 0)
{
//send back error that it doesnt exists
std::string error_msg = "User to be added does not exist|";
std::cout << error_msg << std::endl;
send(client_socket, error_msg.c_str(), error_msg.size(), 0);
} else if (user_exists == 1)
{
// process request
std::cout << "User to be added exists" << std::endl;
//get receiver id
std::string receiver_id = DB->get_receiver_id(receiver_username);
//check for duplicatesssssss!!!!!!!!! ADDDd----------------------
int exists = DB->verify_unique_friend_request(sender_id, receiver_id);
if (exists == 0){
//process
std::string query = "INSERT INTO friend_requests(sender_id, reciever_id, sender_username, receiver_username) VALUES('" + sender_id + "', '" + receiver_id + "', '" + sender_username + "', '" + receiver_username + "');";
int result_of_insert = DB->generic_insert_function(query);
std::cout << "result of id inserts: " << result_of_insert << std::endl;
std::string error_msg = "Request Sen1!|";
std::cout << error_msg << std::endl;
send(client_socket, error_msg.c_str(), error_msg.size(), 0);
}
else if (exists == 1){
//send back duplicat message
std::string error_msg = "Request to this user already pending|";
std::cout << error_msg << std::endl;
send(client_socket, error_msg.c_str(), error_msg.size(), 0);
}
else {
//send back error
std::string error_msg = "Verification of request failed|";
std::cout << error_msg << std::endl;
send(client_socket, error_msg.c_str(), error_msg.size(), 0);
}
//sent back success or failure
} else {
//send another sort of error
std::string error_msg = "ERROR: Server error, please try again later.|";
std::cout << error_msg << std::endl;
send(client_socket, error_msg.c_str(), error_msg.size(), 0);
}
} else if (data_type == "get_incoming_friends")
{
sqlite3_stmt *stmt;
// Prepare the query to retrieve incoming friend requests
std::string query = "SELECT sender_id, sender_username FROM friend_requests WHERE reciever_id = '" + std::to_string(user_id) + "' AND status = 'pending';";
const char *query_cstr = query.c_str();
int rc;
rc = sqlite3_prepare_v2(Database, query_cstr, -1, &stmt, NULL);
if (rc != SQLITE_OK)
{
std::cerr << "Failed to prepare friend retrieval statement: " << sqlite3_errmsg(Database) << std::endl;
// Optionally send an error message back to the client here
}
else
{
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW)
{
int sender_id = sqlite3_column_int(stmt, 0);
const unsigned char *sender_username = sqlite3_column_text(stmt, 1);
if (sender_username == NULL) {
std::cerr << "Error: NULL sender username." << std::endl;
continue;
}
std::string data_to_send = std::to_string(sender_id) + "+" + std::string(reinterpret_cast<const char *>(sender_username)) + "|";
std::cout << "DATA TO SEND IN get_incoming_friend_requests: " << data_to_send << std::endl;
ssize_t bytes_sent = send(client_socket, data_to_send.c_str(), data_to_send.size(), 0);
if (bytes_sent == -1)
{
std::cerr << "Failed to send friend request data to client." << std::endl;
break;
}
std::cout << "Sender ID: " << sender_id << ", Sender Username: " << sender_username << std::endl;
}
if (rc != SQLITE_DONE)
{
std::cerr << "Error during friend request iteration: " << sqlite3_errmsg(Database) << std::endl;
}
sqlite3_finalize(stmt);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
ssize_t end_signal_sent = send(client_socket, "-", 1, 0);
if (end_signal_sent == -1)
{
std::cerr << "Failed to send termination signal to client." << std::endl;
}
}
} else if (data_type == "accept_friend_request")
{
std::string sender_id = read_pipe_ended_gen_data(client_socket);
int receiver_id = user_id;
int err_msg = DB->handle_friend_request(std::stoi(sender_id), receiver_id, "accepted");
if (err_msg != 0)
{
//send error
std::string msg = "accept_failed|";
std::cerr << msg << std::endl;
send(client_socket, msg.c_str(), msg.size(), 0);
} else if (err_msg == 0)
{
//send sucess
std::string msg = "accept_succeeded|";
std::cerr << msg << std::endl;
send(client_socket, msg.c_str(), msg.size(), 0);
}
} else if (data_type == "decline_friend_request")
{
std::string sender_id = read_pipe_ended_gen_data(client_socket);
int receiver_id = user_id;
int err_msg = DB->handle_friend_request(std::stoi(sender_id), receiver_id, "declined");
if (err_msg !=0)
{
std::string msg = "decline_failed|";
std::cerr << msg << std::endl;
send(client_socket, msg.c_str(), msg.size(), 0);
} else if (err_msg == 0)
{
std::string msg = "decline_succeeded|";
std::cerr << msg << std::endl;
send(client_socket, msg.c_str(), msg.size(), 0);
}
} else if (data_type == "get_outbound_friends")
{
sqlite3_stmt *stmt;
// Prepare the query to retrieve incoming friend requests
std::string query = "SELECT reciever_id, receiver_username FROM friend_requests WHERE sender_id = '" + std::to_string(user_id) + "' AND status = 'pending';";
const char *query_cstr = query.c_str();
int rc;
rc = sqlite3_prepare_v2(Database, query_cstr, -1, &stmt, NULL);
if (rc != SQLITE_OK)
{
std::cerr << "Failed to prepare friend retrieval statement: " << sqlite3_errmsg(Database) << std::endl;
// Optionally send an error message back to the client here
}
else
{
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW)
{
int sender_id = sqlite3_column_int(stmt, 0);
const unsigned char *sender_username = sqlite3_column_text(stmt, 1);
if (sender_username == NULL) {
std::cerr << "Error: NULL sender username." << std::endl;
continue;
}
std::string data_to_send = std::to_string(sender_id) + "+" + std::string(reinterpret_cast<const char *>(sender_username)) + "|";
ssize_t bytes_sent = send(client_socket, data_to_send.c_str(), data_to_send.size(), 0);
if (bytes_sent == -1)
{
std::cerr << "Failed to send friend request data to client." << std::endl;
break;
}
std::cout << "Sender ID: " << sender_id << ", Sender Username: " << sender_username << std::endl;
}
if (rc != SQLITE_DONE)
{
std::cerr << "Error during friend request iteration: " << sqlite3_errmsg(Database) << std::endl;
}
sqlite3_finalize(stmt);
ssize_t end_signal_sent = send(client_socket, "-", 1, 0);
if (end_signal_sent == -1)
{
std::cerr << "Failed to send termination signal to client." << std::endl;
}
}
} else if (data_type == "get_friends")
{
sqlite3_stmt *stmt;
// Prepare the query to retrieve incoming friend requests
std::string query = "SELECT sender_id, sender_username FROM friend_requests WHERE reciever_id = '"
+ std::to_string(user_id) + "' AND status = 'accepted' "
"UNION "
"SELECT reciever_id, receiver_username FROM friend_requests WHERE sender_id = '"
+ std::to_string(user_id) + "' AND status = 'accepted';";
const char *query_cstr = query.c_str();
int rc;
rc = sqlite3_prepare_v2(Database, query_cstr, -1, &stmt, NULL);
if (rc != SQLITE_OK)
{
std::cerr << "Failed to prepare friend retrieval statement: " << sqlite3_errmsg(Database) << std::endl;
// Optionally send an error message back to the client here
}
else
{
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW)
{
int sender_id = sqlite3_column_int(stmt, 0);
const unsigned char *sender_username = sqlite3_column_text(stmt, 1);
if (sender_username == NULL) {
std::cerr << "Error: NULL sender username." << std::endl;
continue;
}
std::string data_to_send = std::to_string(sender_id) + "+" + std::string(reinterpret_cast<const char *>(sender_username)) + "|";
ssize_t bytes_sent = send(client_socket, data_to_send.c_str(), data_to_send.size(), 0);
if (bytes_sent == -1)
{
std::cerr << "Failed to send friend request data to client." << std::endl;
break;
}
std::cout << "Sender ID: " << sender_id << ", Sender Username: " << sender_username << std::endl;
}
if (rc != SQLITE_DONE)
{
std::cerr << "Error during friend request iteration: " << sqlite3_errmsg(Database) << std::endl;
}
sqlite3_finalize(stmt);
std::this_thread::sleep_for(std::chrono::milliseconds(10));
ssize_t end_signal_sent = send(client_socket, "-", 1, 0);
if (end_signal_sent == -1)
{
std::cerr << "Failed to send termination signal to client." << std::endl;
}
}
} else if (data_type == "new_conversation")
{
std::string buff = read_pipe_ended_gen_data(client_socket);
std::cout << "Buffer: " << buff << std::endl;
buff += "|";
std::vector<int> id_list;
int count = 0;
char i = buff[count];
while (i != '|')
{
std::string tmp_str = "";
while (i != '-' && i != '|') {
std::cout << "i = " << i << std::endl;
tmp_str += i;
count++;
if (count >= buff.length()) break;
i = buff[count];
}
if (!tmp_str.empty()) {
id_list.push_back(std::stoi(tmp_str));
}
count++;
if (count < buff.length()) {
i = buff[count];
} else {
break;
}
}
int conversation_id = DB->create_conversation("");
id_list.push_back(user_id);
for(auto &id : id_list)
{
bool status = DB->addMemberToConversation(conversation_id, id);
}
//send back good status
//pick up here
} else if (data_type == "get_user_convos")
{
sqlite3_stmt *stmt;
// Parameterized query to prevent SQL injection
std::string query = "SELECT c.conversation_id, c.conversation_name, cm.user_id AS member_id, u.username AS member_username "
"FROM conversations c "
"JOIN conversation_members cm ON c.conversation_id = cm.conversation_id "
"JOIN users u ON cm.user_id = u.id "
"WHERE c.conversation_id IN ( "
" SELECT conversation_id "
" FROM conversation_members "
" WHERE user_id = ? "
") "
"ORDER BY c.conversation_id;";
int rc = sqlite3_prepare_v2(Database, query.c_str(), -1, &stmt, NULL);
if (rc != SQLITE_OK)
{
std::cerr << "Failed to prepare statement: " << sqlite3_errmsg(Database) << std::endl;
}
else
{
// Bind user_id to the query
sqlite3_bind_int(stmt, 1, user_id);
int prev_convo_id = -1;
while ((rc = sqlite3_step(stmt)) == SQLITE_ROW)
{
int conversation_id = sqlite3_column_int(stmt, 0);
const unsigned char *conversation_name = sqlite3_column_text(stmt, 1);
int conversation_member_id = sqlite3_column_int(stmt, 2);
const unsigned char *conversation_member_username = sqlite3_column_text(stmt, 3);
std::string data_to_send;
if (conversation_id != prev_convo_id)
{
// New conversation, send a termination signal for the previous conversation
if (prev_convo_id != -1)
{
// Send termination signal with delimiter
if (send(client_socket, "-|", 2, 0) == -1)
{
std::cerr << "Failed to send conversation termination signal." << std::endl;
break;
}
}
// Send conversation ID and name, ensure name is included even if empty
data_to_send = std::to_string(conversation_id) + "+" +
(conversation_name ? reinterpret_cast<const char *>(conversation_name) : "") + "|";
if (send(client_socket, data_to_send.c_str(), data_to_send.size(), 0) == -1)
{
std::cerr << "Failed to send conversation data." << std::endl;
break;
}
}
// Send member ID and username
data_to_send = std::to_string(conversation_member_id) + "+" +
(conversation_member_username ? reinterpret_cast<const char *>(conversation_member_username) : "") + "|";
if (send(client_socket, data_to_send.c_str(), data_to_send.size(), 0) == -1)
{
std::cerr << "Failed to send member data." << std::endl;
break;
}
prev_convo_id = conversation_id;
}
if (rc != SQLITE_DONE)
{
std::cerr << "SQLite error: " << sqlite3_errmsg(Database) << std::endl;
}
// Finalize statement and send termination signals
sqlite3_finalize(stmt);
if (prev_convo_id != -1)
{
// Send termination signal for the last conversation
if (send(client_socket, "-|", 2, 0) == -1)
{
std::cerr << "Failed to send final conversation termination signal." << std::endl;
}
}
// Send end-of-data signal
if (send(client_socket, "--|", 3, 0) == -1)
{
std::cerr << "Failed to send end-of-data signal." << std::endl;
}
}
} else {
std::cerr << "Unkown message data type: " << data_type << std::endl;
}
}
{
std::lock_guard<std::mutex> lock(clients_mutex);
client_sockets.erase(std::remove(client_sockets.begin(), client_sockets.end(), client_socket), client_sockets.end());
}
close(client_socket);
}
void handle_logic_client(int logic_client_socket, Database* DB, user* User)
{
//once verified, pull user id and assign to this thread
while (true)
{
std::cout << "Reading LOGIC Header" << std::endl;
std::string data_type = read_header(logic_client_socket);
std::cout << "data type read: " << data_type << std::endl;
if (data_type.empty()) {
std::cerr << "Error: Client Disconnected or No Header Sent" << std::endl;
break;
}
if (data_type == "verify_user")
{
std::cerr << "HIT VERIFY USER" << std::endl;
std::string data;
char buffer[1024];
size_t bytes_rec = recv(logic_client_socket, buffer, sizeof(buffer), 0);
if (bytes_rec > 0)
{
//---Breaking here, not recieving fill buffer, something else is receiving the beginning
data = std::string(buffer, bytes_rec);
std::cout << "Recieved user data to verify: " << data << std::endl;
}
else
{
std::cerr << "Verification info failed to recieve" << std::endl;
}
//comes in format USERNAME|PASSWORD
std::string username = data.substr(0, data.find('|'));
std::string password = data.substr(data.find('|') + 1);
std::cout << "Username: " << username << "\nPassword: " << password << std::endl;
int verification_status = DB->db_verify_login(username, password);
if (verification_status == 1){
std::cerr << "User Verified. Good!" << std::endl;
std::string msg = "verification_succeeded|";
send(logic_client_socket, msg.c_str(), msg.size(), 0);
} else if (verification_status == -1) {
std::cerr << "Error Verifying User" << std::endl;
//send to client
std::string msg = "Error Verifying|";
send(logic_client_socket, msg.c_str(), msg.size(), 0);
} else if (verification_status == 0) {
std::cout << "User Not Found" << std::endl;
std::string msg = "verification_failed|";
send(logic_client_socket, msg.c_str(), msg.size(), 0);
}
else{
std::cerr << "Major error verifying" << std::endl;
}
std::cout << "Verification completed" << std::endl;
} else if (data_type == "new_user")
{
std::cerr << "New User Process Started -----------" << std::endl;
//add pfp insert later
std::string data;
char buffer[1024];
size_t bytes_rec = recv(logic_client_socket, buffer, sizeof(buffer), 0);
if (bytes_rec > 0)
{
data = std::string(buffer, bytes_rec);
std::cout << "Recieved user data to insert: " << data << std::endl;
}
else
{
std::cerr << "Insertion info failed to recieve" << std::endl;
}
//comes in format USERNAME|PASSWORD
std::string username = data.substr(0, data.find('|'));
std::string password = data.substr(data.find('|') + 1);
std::cout << "New Username: " << username << "\nNew Password: " << password << std::endl;
//check if username already in use
int username_in_use = DB->check_unique_username(username);
if (username_in_use == 0){
std::cerr << "Username Available!" << std::endl;
std::string msg = "Username Available|";
send(logic_client_socket, msg.c_str(), msg.size(), 0);
} else if (username_in_use == -1) {
std::cerr << "Error Checking Username" << std::endl;
//send to client
std::string msg = "Error Checking Username|";
send(logic_client_socket, msg.c_str(), msg.size(), 0);
} else if (username_in_use == 1) {
std::cout << "Username Taken!" << std::endl;
std::string msg = "Username Taken|";
send(logic_client_socket, msg.c_str(), msg.size(), 0);
}
if (username_in_use == 0){
int insert_return = DB->db_new_user(username, password);
if (insert_return == -1){
std::cerr << "User not added" << std::endl;
}
else if (insert_return == 0){
std::cout << "User added" << std::endl;
}
}
else {
std::cout << "Username not unique so its not added" << std::endl;
}
} else if (data_type == "get_user_id")
{
std::string username_to_check = read_pipe_ended_gen_data(logic_client_socket);
std::cout << "GETTING ID FOR USERNAME: " << username_to_check;
std::string id_str = DB->get_receiver_id(username_to_check);
User->set_user_id(std::stoi(id_str));
id_str += "|";
std::cout << "ID_STR: " << id_str << std::endl;
send(logic_client_socket, id_str.c_str(), id_str.size(), 0);
std::cout << "ID SENT TO CLIENT" << std::endl;
} else if (data_type == "upload_pfp")
{
uint64_t image_size;
if (recv(logic_client_socket, &image_size, sizeof(image_size), 0) == 0)
{
std::cout << "Received image size" << std::endl;
}
else
{
std::cerr << "Failed to receive image size." << std::endl;
}
std::vector<char> buffer(image_size);
size_t total_bytes_rec = 0;
while (total_bytes_rec < image_size)
{
ssize_t bytes_received = recv(logic_client_socket, buffer.data() + total_bytes_rec, image_size - total_bytes_rec, 0);
if (bytes_received <= 0)
{
std::cerr << "Failed to receive image data" << std::endl;
break;
}
total_bytes_rec += bytes_received;
}
if(image_size == total_bytes_rec)
{
std::cout << "Image data received successfully." << std::endl;
std::string file_name = "PFP_DATA/profile_picture_user_" + std::to_string(User->get_user_id());
std::ofstream outFile(file_name, std::ios::binary);
if (outFile)
{
outFile.write(buffer.data(), buffer.size());
outFile.close();
std::string query = "UPDATE users SET profile_picture_path = '" + file_name + "' WHERE id = " + std::to_string(User->get_user_id()) + ";";
DB->generic_insert_function(query);
std::cout << "Image saved successfully as " << file_name << std::endl;
}
else
{
std::cerr << "Failed to open file for writing: " << file_name << std::endl;
}
}
else
{
std::cerr << "Mismatch between expected and received image size." << std::endl;
}
} else if (data_type == "get_profile_pic")
{
// Step 1: Retrieve the user ID
int user_id = User->get_user_id(); // Assuming you have the user ID stored in the User object
// Step 2: Query the database to get the profile picture path
std::string query = "SELECT profile_picture_path FROM users WHERE id = '" + std::to_string(user_id) + "';";
std::string result = DB->get_profile_pic_from_db(query);
std::cout << "PROFILE PICTURE PATH: " << result << std::endl;
if (result.empty())
{
std::cerr << "No profile picture found for user with ID: " << user_id << std::endl;
std::string no_pfp_image_size = "0";
ssize_t size_bytes = send(logic_client_socket, no_pfp_image_size.c_str(), no_pfp_image_size.size(), 0);
if (size_bytes > 0)
{
std::cout << "sent image size" << std::endl;
}
return;
}
std::string file_path = result;
if (file_path.empty())
{
std::cerr << "Profile picture path is empty for user with ID: " << user_id << std::endl;
return;
}
std::ifstream file(file_path, std::ios::binary);
if (!file.is_open())
{
std::cerr << "Failed to open file: " << file_path << std::endl;
return;
}
std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();