-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.cpp
More file actions
1428 lines (1235 loc) · 43.3 KB
/
client.cpp
File metadata and controls
1428 lines (1235 loc) · 43.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 <iostream>
#include <stdio.h> /* printf, sprintf */
#include <stdlib.h> /* exit, atoi, malloc, free */
#include <unistd.h> /* read, write, close */
#include <string.h> /* memcpy, memset */
#include <sys/socket.h> /* socket, connect */
#include <netinet/in.h> /* struct sockaddr_in, struct sockaddr */
#include <netdb.h> /* struct hostent, gethostbyname */
#include <arpa/inet.h>
#include <vector>
#include <string>
#include "helpers.hpp"
#include "requests.hpp"
#include "nlohmann/json.hpp"
using json = nlohmann::json;
#define PORT 8081
#define LOGIN "/api/v1/tema/admin/login"
#define USERS "/api/v1/tema/admin/users"
#define PAYLOAD_TYPE "application/json"
#define LOGIN_USER_URL "/api/v1/tema/user/login"
#define LIB_ACCESS "/api/v1/tema/library/access"
#define MOVIES "/api/v1/tema/library/movies"
#define COLLECTIONS "/api/v1/tema/library/collections"
#define LOGOUT_USER "/api/v1/tema/user/logout"
using namespace std;
/* Extracts the first cookie (up to ';' or CRLF) */
char *extract_cookie(char *response, char **cookies, int *cookie_count) {
char *start = strstr(response, "Set-Cookie: ");
if (!start) return NULL;
start += strlen("Set-Cookie: ");
char *end = strstr(start, ";");
if (!end) end = strstr(start, "\r\n");
int len = end - start;
cookies[*cookie_count] = (char *)calloc(len+1, 1);
strncpy(cookies[*cookie_count], start, len);
(*cookie_count)++;
return cookies[*cookie_count - 1];
}
/* Extracts the value from JSON: "key":"<value>" */
char *extract_key(char *response) {
char *p = strstr(response, "\"key\"");
if (!p) return NULL;
p = strchr(p, ':');
if (!p) return NULL;
p++;
while (*p == ' ' || *p == '\"') p++;
char *end = strchr(p, '\"');
if (!end) return NULL;
int len = end - p;
char *key = (char *) calloc(len+1, 1);
strncpy(key, p, len);
return key;
}
void extract_cookies(char *response, char **cookies, int *cookie_count) {
*cookie_count = 0;
char *p = response;
while ((p = strstr(p, "Set-Cookie: ")) != nullptr && *cookie_count < 16) {
p += strlen("Set-Cookie: ");
char *end = strstr(p, ";");
if (!end) end = strstr(p, "\r\n");
if (!end) break;
int len = end - p;
cookies[*cookie_count] = (char*)calloc(len + 1, 1);
strncpy(cookies[*cookie_count], p, len);
(*cookie_count)++;
}
}
void handle_response_and_store_cookies(char *response, std::vector<char *> &cookie_storage, const std::string &success_msg, const std::string &error_msg) {
int code = 0;
sscanf(response, "HTTP/%*s %d", &code);
// Check if the HTTP response code indicates success
if (code >= 200 && code < 300) {
std::cout << success_msg << "\n";
// Extract cookies from the response and store them
char *cookie_arr[16];
int cookie_count = 0;
extract_cookies(response, cookie_arr, &cookie_count);
for (int i = 0; i < cookie_count; i++) {
cookie_storage.push_back(cookie_arr[i]);
}
} else {
// Print error message if the response code is not successful
std::cout << error_msg << "\n";
}
}
void send_json_auth_request(const std::string &endpoint,
const std::string &success_msg,
const std::string &error_msg,
int sockfd,
std::vector<char *> &cookies,
const char *hostIp) {
std::string username, password;
// Prompt for username and password from the user
std::cout << "username=";
std::getline(std::cin, username);
std::cout << "password=";
std::getline(std::cin, password);
// Validate input: must not be empty or contain spaces
if (username.empty() || password.empty() ||
username.find(' ') != std::string::npos ||
password.find(' ') != std::string::npos) {
std::cout << "ERROR: Invalid username or password\n";
return;
}
// Build JSON payload for authentication
json request_json = {
{"username", username},
{"password", password}
};
std::string payload = request_json.dump();
char *payload_body = strdup(payload.c_str());
char *request = compute_post_request(
(char *)hostIp,
(char *)endpoint.c_str(),
(char *)PAYLOAD_TYPE,
&payload_body,
1,
cookies,
cookies.size(),
nullptr
);
// Send request and handle response
send_to_server(sockfd, request);
char *response = receive_from_server(sockfd);
close_connection(sockfd);
// Handle response and store cookies if authentication is successful
handle_response_and_store_cookies(response, cookies, success_msg, error_msg);
free(payload_body);
free(request);
free(response);
}
void login_admin(int sockfd, std::vector<char *> &admin_cookies, char *hostIp) {
send_json_auth_request(LOGIN, "SUCCESS: Admin authenticated successfully",
"ERROR: Authentication failed",
sockfd, admin_cookies, hostIp);
}
void add_user(int sockfd, std::vector<char *> &admin_cookies, char *hostIp) {
send_json_auth_request(USERS, "SUCCESS: User added successfully",
"ERROR: User addition failed",
sockfd, admin_cookies, hostIp);
}
void get_users(int sockfd, std::vector<char *> &admin_cookies, char *hostIp) {
// Build the GET request for the users endpoint, including admin cookies
char *request = compute_get_request(
hostIp,
(char *)USERS,
nullptr,
admin_cookies,
(int)admin_cookies.size(),
nullptr
);
// Send the request to the server
send_to_server(sockfd, request);
// Receive the response from the server
char *resp = receive_from_server(sockfd);
// Close the socket connection
close_connection(sockfd);
// Parse the HTTP status code from the response
int code = 0;
sscanf(resp, "HTTP/%*s %d", &code);
if (code >= 200 && code < 300) {
// Find the start of the response body (after headers)
char *body = strstr(resp, "\r\n\r\n");
if (body) {
body += 4; // Skip the header delimiter
// Parse the JSON body
nlohmann::json json_response = nlohmann::json::parse(body, nullptr, false);
std::cout << "SUCCESS: Users list\n";
// If the response is an object with a "users" array
if (json_response.is_object() && json_response.contains("users") && json_response["users"].is_array()) {
for (const auto &user : json_response["users"]) {
int id = user.value("id", -1);
std::string name = user.value("username", "");
std::string pass = user.value("password", "");
std::cout << "#" << id << " " << name << ":" << pass << "\n";
}
}
// If the response is a top-level array
else if (json_response.is_array()) {
for (const auto &user : json_response) {
int id = user.value("id", -1);
std::string name = user.value("username", "");
std::string pass = user.value("password", "");
std::cout << "#" << id << " " << name << ":" << pass << "\n";
}
}
} else {
// No body found, but still a success code
std::cout << "SUCCESS: Users List\n";
}
} else {
// Non-success HTTP code
std::cout << "ERROR: Failed to retrieve users\n";
}
// Free allocated memory for request and response
free(request);
free(resp);
}
void delete_user(int sockfd, std::vector<char *> &admin_cookies, const char *hostIp, char *token) {
// Prompt the admin to enter the username of the user to delete
std::cout << "username=";
std::string username;
std::getline(std::cin, username);
// Check if the username is empty and print an error if so
if (username.empty()) {
std::cout << "ERROR: Invalid username\n";
return;
}
// Construct the API path for deleting the specified user
std::string path = "/api/v1/tema/admin/users/" + username;
auto build_delete_message = [&](const std::string &host,
const std::string &resource,
const std::vector<char *> &cookies)
-> std::string {
std::ostringstream out;
// Start the DELETE request line
out << "DELETE " << resource << " HTTP/1.1\r\n";
// Add the Host header
out << "Host: " << host << "\r\n";
// Add cookies if any are present
if (!cookies.empty()) {
out << "Cookie: ";
for (size_t i = 0; i < cookies.size(); ++i) {
out << cookies[i];
if (i + 1 < cookies.size()) {
out << "; ";
}
}
out << "\r\n";
}
// End of headers
out << "\r\n";
return out.str();
};
// Build and send the DELETE request message
std::string raw_request = build_delete_message(hostIp, path, admin_cookies);
char *request_buf = strdup(raw_request.c_str());
send_to_server(sockfd, request_buf);
free(request_buf);
// Get the response
char *resp = receive_from_server(sockfd);
close_connection(sockfd);
// HTTP code check
int code = 0;
if (sscanf(resp, "HTTP/%*s %d", &code) != 1) {
std::cout << "ERROR: Invalid response from server\n";
free(resp);
return;
}
if (code / 100 == 2) {
std::cout << "SUCCESS: User deleted\n";
} else {
std::cout << "ERROR: User deletion failed (code " << code << ")\n";
}
free(resp);
}
void login(int sockfd,
std::vector<char *> &admin_cookies,
std::vector<char *> &user_cookies, char *hostIp) {
std::string admin_username;
std::string username;
std::string passwd;
// Read credentials
std::cout << "admin_username=";
std::getline(std::cin, admin_username);
std::cout << "username=";
std::getline(std::cin, username);
std::cout << "password=";
std::getline(std::cin, passwd);
// Validate credentials
auto invalid = [](const std::string &s) {
return s.empty() || s.find(' ') != std::string::npos;
};
if (invalid(admin_username) || invalid(username) || invalid(passwd)) {
std::cout << "ERROR: Invalid credentials format\n";
return;
}
// Build the JSON payload
nlohmann::json j = {
{"admin_username", admin_username},
{"username", username},
{"password", passwd}
};
std::string payload = j.dump();
// Prepare the request
char *body = strdup(payload.c_str());
char *request = compute_post_request(
hostIp,
LOGIN_USER_URL,
PAYLOAD_TYPE,
&body, 1,
admin_cookies, admin_cookies.size(),
nullptr
);
// Send the request and receive the response
send_to_server(sockfd, request);
char *resp = receive_from_server(sockfd);
close_connection(sockfd);
// HTTP code check
int code = 0;
sscanf(resp, "HTTP/%*s %d", &code);
if (code >= 200 && code < 300) {
std::cout << "SUCCESS: Authentication successful\n";
// Extract the JWT token
char *cookies_buf[16];
int cookies_count = 0;
extract_cookie(resp, cookies_buf, &cookies_count);
for (int i = 0; i < cookies_count; ++i) {
user_cookies.push_back(cookies_buf[i]);
}
} else {
std::cout << "ERROR: Authentication failed\n";
}
free(request);
free(resp);
free(body);
}
void logout_admin(char *hostIp, std::vector<char *> &admin_cookies)
{
// Check if admin is authenticated (has cookies)
if (admin_cookies.empty()) {
std::cout << "ERROR: Admin is not authenticated\n";
return;
}
// Open a new connection to the server
int sockfd = open_connection(hostIp, PORT, AF_INET, SOCK_STREAM, 0);
// Prepare the logout endpoint path
const char *logout_path = "/api/v1/tema/admin/logout";
// Build the GET request for admin logout, including cookies
char *request = compute_get_request(
hostIp,
(char *)logout_path,
nullptr,
admin_cookies,
static_cast<int>(admin_cookies.size()),
nullptr
);
// Send the logout request to the server
send_to_server(sockfd, request);
// Receive the server's response
char *response = receive_from_server(sockfd);
close_connection(sockfd);
// Parse the HTTP status code from the response
int status = 0;
sscanf(response, "HTTP/%*s %d", &status);
// If logout was successful, clear admin cookies
if (status >= 200 && status < 300) {
std::cout << "SUCCESS: Admin logged out\n";
for (char *cookie : admin_cookies) {
free(cookie);
}
admin_cookies.clear();
} else {
std::cout << "ERROR: Logout failed\n";
}
// Free allocated memory for request and response
free(request);
free(response);
}
void get_access(char *hostIp,
std::vector<char *> &user_cookies,
char **token)
{
// Verify if user is authenticated
if (user_cookies.empty()) {
std::cout << "ERROR: User is not authenticated\n";
return;
}
// Open a new connection
int sockfd = open_connection(hostIp, PORT, AF_INET, SOCK_STREAM, 0);
// Send the GET request for library access
char *request = compute_get_request(
hostIp,
LIB_ACCESS,
nullptr,
user_cookies,
static_cast<int>(user_cookies.size()),
nullptr
);
send_to_server(sockfd, request);
// Get the response
char *response = receive_from_server(sockfd);
close_connection(sockfd);
// HTTP code check
int code = 0;
sscanf(response, "HTTP/%*s %d", &code);
if (code >= 200 && code < 300) {
// Extract the JWT token
char *body = strstr(response, "\r\n\r\n");
if (body) {
body += 4;
auto j = json::parse(body, nullptr, false);
if (!j.is_discarded()) {
std::string tok = j.value("token", "");
if (!tok.empty() && token) {
*token = strdup(tok.c_str());
}
}
}
std::cout << "SUCCESS: JWT token received\n";
} else {
std::cout << "ERROR: Authentication required\n";
}
free(request);
free(response);
}
void add_movie(char *hostIp,
int sockfd,
char *token,
std::vector<char *> &user_cookies) {
// Verify if user is authenticated
if (!token || !*token || user_cookies.empty()) {
std::cout << "ERROR: No library access or invalid data\n";
return;
}
// Read movie details
std::string title, description, year_str, rating_str;
std::cout << "title=";
std::getline(std::cin, title);
std::cout << "description=";
std::getline(std::cin, description);
std::cout << "year=";
std::getline(std::cin, year_str);
std::cout << "rating=";
std::getline(std::cin, rating_str);
// Validate input
if (title.empty() || description.empty() ||
year_str.empty() || rating_str.empty()) {
std::cout << "ERROR: No library access or invalid data\n";
return;
}
int year;
double rating;
char *endptr1 = nullptr, *endptr2 = nullptr;
year = strtol(year_str.c_str(), &endptr1, 10);
rating = strtod(rating_str.c_str(), &endptr2);
if (!endptr1 || *endptr1 != '\0' || !endptr2 || *endptr2 != '\0') {
std::cout << "ERROR: No library access or invalid data\n";
return;
}
// Build the JSON payload
json j = {
{"title", title},
{"year", year},
{"description", description},
{"rating", rating}
};
std::string payload = j.dump();
char *body = strdup(payload.c_str());
// Build the request
char *request = compute_post_request(
hostIp,
MOVIES,
(char*)PAYLOAD_TYPE,
&body, 1,
user_cookies,
(int)user_cookies.size(),
token
);
// Send the request and receive the response
send_to_server(sockfd, request);
char *resp = receive_from_server(sockfd);
close_connection(sockfd);
// Verify HTTP code
int code = 0;
sscanf(resp, "HTTP/%*s %d", &code);
if (code >= 200 && code < 300) {
std::cout << "SUCCESS: Movie added\n";
} else {
std::cout << "ERROR: No library access or invalid data\n";
}
free(request);
free(resp);
free(body);
}
void get_movies(int sockfd,
std::vector<char *> &user_cookies,
char *token, char *hostIp)
{
// Send GET request for movies
char *req = compute_get_request(
hostIp,
MOVIES,
nullptr,
user_cookies,
static_cast<int>(user_cookies.size()),
token
);
send_to_server(sockfd, req);
// Receive response
char *resp = receive_from_server(sockfd);
int status = 0;
sscanf(resp, "HTTP/%*s %d", &status);
if (status < 200 || status >= 300) {
std::cout << "ERROR: No library access\n";
free(req);
free(resp);
return;
}
// Extract JSON body
char *json_body = basic_extract_json_response(resp);
if (!json_body) {
std::cout << "ERROR: No library access\n";
free(req);
free(resp);
return;
}
// Keep the JSON body for parsing
auto parsed = json::parse(json_body, nullptr, false);
if (parsed.is_discarded()) {
std::cout << "No library acces\n";
free(req);
free(resp);
return;
}
// Determine where the movies array is in the parsed JSON
const json *movie_list = nullptr;
if (parsed.is_array()) {
movie_list = &parsed;
} else if (parsed.is_object() && parsed.contains("movies") && parsed["movies"].is_array()) {
movie_list = &parsed.at("movies");
}
std::cout << "SUCCESS: Film list" << std::endl;
if (movie_list) {
for (auto it = movie_list->begin(); it != movie_list->end(); ++it) {
int id = it->contains("id") ? (*it)["id"].get<int>() : -1;
std::string title = it->contains("title") ? (*it)["title"].get<std::string>() : "";
std::cout << "#" << id << " " << title << std::endl;
}
}
free(req);
free(resp);
}
void get_movie(int sockfd,
std::vector<char *> &user_cookies,
char *token, char *hostIp)
{
// Read movie ID
std::cout << "id=";
std::string id_str;
std::getline(std::cin, id_str);
if (id_str.empty()) {
std::cout << "ERROR: Invalid movie ID\n";
return;
}
// Build the GET request
std::string path = MOVIES + std::string("/") + id_str;
char *req = compute_get_request(
hostIp,
(char *)path.c_str(),
nullptr,
user_cookies,
static_cast<int>(user_cookies.size()),
token
);
send_to_server(sockfd, req);
// Receive the response
char *resp = receive_from_server(sockfd);
close_connection(sockfd);
// Verify HTTP code
int code = 0;
sscanf(resp, "HTTP/%*s %d", &code);
if (code >= 200 && code < 300) {
// Extract JSON body
char *json_body = basic_extract_json_response(resp);
if (json_body) {
auto parsed = json::parse(json_body, nullptr, false);
if (!parsed.is_discarded()) {
std::cout << "SUCCESS: Movie details\n";
std::cout << parsed.dump(4) << "\n"; // Pretty print JSON
} else {
std::cout << "ERROR: Invalid JSON response\n";
}
} else {
std::cout << "ERROR: Invalid JSON response\n";
}
} else {
std::cout << "ERROR: Movie not found\n";
}
free(req);
free(resp);
}
void update_movie(char *hostIp,
int sockfd,
char *token,
std::vector<char *> &user_cookies)
{
// Verify if user is authenticated
if (!token || !*token || user_cookies.empty()) {
std::cout << "ERROR: No library access or invalid data\n";
return;
}
// Read movie ID
std::cout << "id=";
std::string id_str;
std::getline(std::cin, id_str);
if (id_str.empty()) {
std::cout << "ERROR: Invalid movie ID\n";
return;
}
// Read movie details
std::string title, description, year_str, rating_str;
std::cout << "title=";
std::getline(std::cin, title);
std::cout << "description=";
std::getline(std::cin, description);
std::cout << "year=";
std::getline(std::cin, year_str);
std::cout << "rating=";
std::getline(std::cin, rating_str);
// Build the JSON payload
json j;
if (!title.empty()) j["title"] = title;
if (!description.empty()) j["description"] = description;
if (!year_str.empty()) {
char *endptr = nullptr;
int year = strtol(year_str.c_str(), &endptr, 10);
if (!endptr || *endptr != '\0') {
std::cout << "ERROR: Invalid year\n";
return;
}
j["year"] = year;
}
// If the user provided a new rating, validate and add it to the JSON payload
if (!rating_str.empty()) {
char *endptr = nullptr;
double rating = strtod(rating_str.c_str(), &endptr);
// Check if the rating is a valid number
if (!endptr || *endptr != '\0') {
std::cout << "ERROR: Invalid rating\n";
return;
}
j["rating"] = rating;
}
// If no fields were provided for update, show an error and abort
if (j.empty()) {
std::cout << "ERROR: No fields to update were provided\n";
return;
}
std::string payload = j.dump();
char *body = strdup(payload.c_str());
std::string path = std::string(MOVIES) + "/" + id_str;
// Build the PUT request
char *request = compute_put_request(
hostIp,
(char *)path.c_str(),
PAYLOAD_TYPE,
payload,
user_cookies,
(int)user_cookies.size(),
token
);
// Send the request and receive the response
send_to_server(sockfd, request);
char *resp = receive_from_server(sockfd);
close_connection(sockfd);
// Verify HTTP code
int code = 0;
sscanf(resp, "HTTP/%*s %d", &code);
if (code >= 200 && code < 300) {
std::cout << "SUCCESS: Movie updated\n";
} else {
std::cout << "ERROR: Update failed or no access\n";
}
free(request);
free(resp);
free(body);
}
void delete_movie(int sockfd,
std::vector<char *> &user_cookies,
char *token, char *hostIp)
{
// Read movie ID
std::cout << "id=";
std::string id_str;
std::getline(std::cin, id_str);
if (id_str.empty()) {
std::cout << "ERROR: Invalid movie ID\n";
return;
}
// Build the DELETE request
std::string path = MOVIES + std::string("/") + id_str;
char *req = compute_delete_request(
hostIp,
(char *)path.c_str(),
user_cookies,
static_cast<int>(user_cookies.size()),
token
);
send_to_server(sockfd, req);
// Get the response
char *resp = receive_from_server(sockfd);
close_connection(sockfd);
// Verify HTTP code
int code = 0;
sscanf(resp, "HTTP/%*s %d", &code);
if (code >= 200 && code < 300) {
std::cout << "SUCCESS: Movie deleted\n";
} else {
std::cout << "ERROR: Deletion failed or no access\n";
}
free(req);
free(resp);
}
void add_collection(char *hostIp,
int sockfd,
std::vector<char *> &user_cookies,
char *token)
{
// Verify if user is authenticated and has access
if (!token || !*token || user_cookies.empty()) {
std::cout << "ERROR: No library access or invalid data\n";
return;
}
// Prompt for collection title
std::cout << "title=";
std::string title;
std::getline(std::cin, title);
if (title.empty()) {
std::cout << "ERROR: Invalid collection title\n";
return;
}
// Prompt for number of movies to add to the collection
std::cout << "num_movies=";
std::string num_str;
std::getline(std::cin, num_str);
int num = 0;
char *endptr = nullptr;
num = strtol(num_str.c_str(), &endptr, 10);
if (!endptr || *endptr != '\0') {
std::cout << "ERROR: num_movies invalid\n";
return;
}
if (num <= 0) {
std::cout << "ERROR: num_movies must be positive\n";
return;
}
// Read each movie ID from user input
std::vector<int> movie_ids;
for (int i = 0; i < num; ++i) {
std::cout << "movie_id["<<i<<"]=";
std::string mid;
std::getline(std::cin, mid);
char *endptr = nullptr;
int movie_id = strtol(mid.c_str(), &endptr, 10);
if (!endptr || *endptr != '\0') {
std::cout << "ERROR: movie_id invalid\n";
return;
}
movie_ids.push_back(movie_id);
}
// Create the collection by sending a POST request with the title
nlohmann::json create_j = {{"title", title}};
std::string create_payload = create_j.dump();
char *create_body = strdup(create_payload.c_str());
char *create_req = compute_post_request(
hostIp,
(char*)COLLECTIONS,
(char*)PAYLOAD_TYPE,
&create_body, 1,
user_cookies,
(int)user_cookies.size(),
token
);
send_to_server(sockfd, create_req);
char *create_resp = receive_from_server(sockfd);
close_connection(sockfd);
// Extract HTTP code from the response
int code = 0;
sscanf(create_resp, "HTTP/%*s %d", &code);
if (code < 200 || code >= 300) {
std::cout << "ERROR: No library access or invalid data\n";
free(create_req);
free(create_resp);
free(create_body);
return;
}
// Parse the response body to get the new collection ID
char *body = strstr(create_resp, "\r\n\r\n");
if (!body) {
std::cout << "ERROR: Invalid response\n";
free(create_req);
free(create_resp);
free(create_body);
return;
}
nlohmann::json resp_j = nlohmann::json::parse(body + 4);
int coll_id = resp_j.value("id", -1);
if (coll_id < 0) {
std::cout << "ERROR: Invalid response\n";
free(create_req);
free(create_resp);
free(create_body);
return;
}
// Open a new connection for adding movies to the collection
sockfd = open_connection(hostIp, PORT, AF_INET, SOCK_STREAM, 0);
// For each movie ID, send a POST request to add it to the collection
for (int mid : movie_ids) {
nlohmann::json add_j = {{"id", mid}};
std::string add_payload = add_j.dump();
char *add_body = strdup(add_payload.c_str());
// Build the path for adding a movie to the collection
std::string path = std::string(COLLECTIONS) + "/"
+ std::to_string(coll_id)
+ "/movies";
char *add_req = compute_post_request(
hostIp,
(char*)path.c_str(),
(char*)PAYLOAD_TYPE,
&add_body, 1,
user_cookies,
(int)user_cookies.size(),
token
);
send_to_server(sockfd, add_req);
char *add_resp = receive_from_server(sockfd);
close_connection(sockfd);
// Free memory for each request/response
free(add_req);
free(add_resp);
free(add_body);
// Reopen the connection for the next movie (if any)
sockfd = open_connection(hostIp, PORT, AF_INET, SOCK_STREAM, 0);
}
// Print success message after all movies have been added
std::cout << "SUCCESS: Collection added\n";
// Free memory for the initial collection creation request/response
free(create_req);
free(create_resp);
free(create_body);
}
// helper: print a parsed JSON “collections” array (or top-level array)
void print_collections_list(const nlohmann::json &json_obj) {
const nlohmann::json *collections = nullptr;
// Check if the top-level JSON is an array (list of collections)
if (json_obj.type() == nlohmann::json::value_t::array) {
collections = &json_obj;
// Or if it's an object with a "collections" array field
} else if (json_obj.type() == nlohmann::json::value_t::object &&
json_obj.contains("collections") &&
json_obj["collections"].is_array()) {
collections = &json_obj.at("collections");
}
std::cout << "SUCCESS: Collection list\n";
if (collections) {
// Iterate through each collection in the array
for (const auto &item : *collections) {
// Extract id and title for each collection
int id = item.value("id", -1);
std::string title = item.value("title", "");
// Print collection info in the required format
std::cout << "#" << id << ": " << title << "\n";
}
}
}
void get_collections(char *hostIp,
int sockfd,
std::vector<char *> &user_cookies,
char *token)
{