forked from meganz/sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSdkTest_test.cpp
More file actions
4972 lines (3937 loc) · 179 KB
/
SdkTest_test.cpp
File metadata and controls
4972 lines (3937 loc) · 179 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
/**
* @file tests/sdk_test.cpp
* @brief Mega SDK test file
*
* (c) 2015 by Mega Limited, Wellsford, New Zealand
*
* This file is part of the MEGA SDK - Client Access Engine.
*
* Applications using the MEGA API must present a valid application key
* and comply with the the rules set forth in the Terms of Service.
*
* The MEGA SDK is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* @copyright Simplified (2-clause) BSD License.
*
* You should have received a copy of the license along with this
* program.
*/
#include "test.h"
#include "SdkTest_test.h"
#include "mega/testhooks.h"
#include "megaapi_impl.h"
#include <algorithm>
#ifdef WIN32
#include <filesystem>
namespace fs = ::std::filesystem;
#else
#include <experimental/filesystem>
namespace fs = ::std::experimental::filesystem;
#endif
using namespace std;
MegaFileSystemAccess fileSystemAccess;
#ifdef _WIN32
#if (__cplusplus >= 201700L)
namespace fs = std::filesystem;
#else
namespace fs = std::experimental::filesystem;
#endif
#endif
#ifdef _WIN32
DWORD ThreadId()
{
return GetCurrentThreadId();
}
#else
pthread_t ThreadId()
{
return pthread_self();
}
#endif
#ifndef WIN32
#define DOTSLASH "./"
#else
#define DOTSLASH ".\\"
#endif
const char* cwd()
{
// for windows and linux
static char path[1024];
const char* ret;
#ifdef _WIN32
ret = _getcwd(path, sizeof path);
#else
ret = getcwd(path, sizeof path);
#endif
assert(ret);
return ret;
}
bool fileexists(const std::string& fn)
{
#ifdef _WIN32
return fs::exists(fn);
#else
struct stat buffer;
return (stat(fn.c_str(), &buffer) == 0);
#endif
}
void copyFile(std::string& from, std::string& to)
{
LocalPath f = LocalPath::fromPath(from, fileSystemAccess);
LocalPath t = LocalPath::fromPath(to, fileSystemAccess);
fileSystemAccess.copylocal(f, t, m_time());
}
std::string megaApiCacheFolder(int index)
{
std::string p(cwd());
#ifdef _WIN32
p += "\\";
#else
p += "/";
#endif
p += "sdk_test_mega_cache_" + to_string(index);
if (!fileexists(p))
{
#ifdef _WIN32
#ifndef NDEBUG
bool success =
#endif
fs::create_directory(p);
assert(success);
#else
mkdir(p.c_str(), S_IRWXU);
assert(fileexists(p));
#endif
}
return p;
}
void WaitMillisec(unsigned n)
{
#ifdef _WIN32
Sleep(n);
#else
usleep(n * 1000);
#endif
}
bool WaitFor(std::function<bool()>&& f, unsigned millisec)
{
unsigned waited = 0;
for (;;)
{
if (f()) return true;
if (waited >= millisec) return false;
WaitMillisec(100);
waited += 100;
}
}
enum { USERALERT_ARRIVAL_MILLISEC = 1000 };
#ifdef _WIN32
#include "mega/autocomplete.h"
#include <filesystem>
#define getcwd _getcwd
void usleep(int n)
{
Sleep(n / 1000);
}
#endif
// helper functions and struct/classes
namespace
{
bool buildLocalFolders(fs::path targetfolder, const string& prefix, int n, int recurselevel, int filesperfolder)
{
fs::path p = targetfolder / fs::u8path(prefix);
if (!fs::create_directory(p))
return false;
for (int i = 0; i < filesperfolder; ++i)
{
string filename = "file" + to_string(i) + "_" + prefix;
fs::path fp = p / fs::u8path(filename);
#if (__cplusplus >= 201700L)
ofstream fs(fp/*, ios::binary*/);
#else
ofstream fs(fp.u8string()/*, ios::binary*/);
#endif
fs << filename;
}
if (recurselevel > 0)
{
for (int i = 0; i < n; ++i)
{
if (!buildLocalFolders(p, prefix + "_" + to_string(i), n, recurselevel - 1, filesperfolder))
return false;
}
}
return true;
}
bool createLocalFile(fs::path path, const char *name)
{
if (!name)
{
return false;
}
fs::path fp = path / fs::u8path(name);
#if (__cplusplus >= 201700L)
ofstream fs(fp/*, ios::binary*/);
#else
ofstream fs(fp.u8string()/*, ios::binary*/);
#endif
fs << name;
return true;
}
}
std::map<int, std::string> gSessionIDs;
void SdkTest::SetUp()
{
// do some initialization
if (megaApi.size() < 2)
{
megaApi.resize(2);
mApi.resize(2);
}
char *buf = getenv("MEGA_EMAIL");
if (buf)
mApi[0].email.assign(buf);
ASSERT_LT((size_t)0, mApi[0].email.length()) << "Set your username at the environment variable $MEGA_EMAIL";
buf = getenv("MEGA_PWD");
if (buf)
mApi[0].pwd.assign(buf);
ASSERT_LT((size_t)0, mApi[0].pwd.length()) << "Set your password at the environment variable $MEGA_PWD";
gTestingInvalidArgs = false;
if (megaApi[0].get() == NULL)
{
megaApi[0].reset(new MegaApi(APP_KEY.c_str(), megaApiCacheFolder(0).c_str(), USER_AGENT.c_str(), int(0), unsigned(THREADS_PER_MEGACLIENT)));
mApi[0].megaApi = megaApi[0].get();
megaApi[0]->setLoggingName("0");
megaApi[0]->addListener(this);
LOG_info << "___ Initializing test (SetUp()) ___";
if (!gResumeSessions || gSessionIDs[0].empty())
{
ASSERT_NO_FATAL_FAILURE( login(0) );
}
else
{
ASSERT_NO_FATAL_FAILURE( loginBySessionId(0, gSessionIDs[0].c_str()) );
}
ASSERT_NO_FATAL_FAILURE( fetchnodes(0) );
}
// In case the last test exited without cleaning up (eg, debugging etc)
Cleanup();
}
void SdkTest::TearDown()
{
// do some cleanup
if (gResumeSessions && gSessionIDs[0].empty())
{
if (auto p = unique_ptr<char[]>(megaApi[0]->dumpSession()))
{
gSessionIDs[0] = p.get();
}
}
gTestingInvalidArgs = false;
LOG_info << "___ Cleaning up test (TearDown()) ___";
Cleanup();
releaseMegaApi(1);
releaseMegaApi(2);
if (megaApi[0])
{
releaseMegaApi(0);
}
}
void SdkTest::Cleanup()
{
deleteFile(UPFILE);
deleteFile(DOWNFILE);
deleteFile(PUBLICFILE);
deleteFile(AVATARDST);
if (megaApi[0])
{
// Remove nodes in Cloud & Rubbish
purgeTree(std::unique_ptr<MegaNode>{megaApi[0]->getRootNode()}.get(), false);
purgeTree(std::unique_ptr<MegaNode>{megaApi[0]->getRubbishNode()}.get(), false);
// megaApi[0]->cleanRubbishBin();
// Remove auxiliar contact
std::unique_ptr<MegaUserList> ul{megaApi[0]->getContacts()};
for (int i = 0; i < ul->size(); i++)
{
removeContact(ul->get(i)->getEmail());
}
// Remove pending contact requests
std::unique_ptr<MegaContactRequestList> crl{megaApi[0]->getOutgoingContactRequests()};
for (int i = 0; i < crl->size(); i++)
{
MegaContactRequest *cr = crl->get(i);
megaApi[0]->inviteContact(cr->getTargetEmail(), "Removing you", MegaContactRequest::INVITE_ACTION_DELETE);
}
}
}
int SdkTest::getApiIndex(MegaApi* api)
{
int apiIndex = -1;
for (int i = int(megaApi.size()); i--; ) if (megaApi[i].get() == api) apiIndex = i;
if (apiIndex == -1)
{
LOG_warn << "Instance of MegaApi not recognized"; // this can occur during MegaApi deletion due to callbacks on shutdown
}
return apiIndex;
}
void SdkTest::onRequestFinish(MegaApi *api, MegaRequest *request, MegaError *e)
{
if (request->getType() == MegaRequest::TYPE_DELETE)
{
return;
}
int apiIndex = getApiIndex(api);
if (apiIndex < 0) return;
mApi[apiIndex].requestFlags[request->getType()] = true;
mApi[apiIndex].lastError = e->getErrorCode();
// there could be a race on these getting set?
LOG_info << "lastError (by request) for MegaApi " << apiIndex << ": " << mApi[apiIndex].lastError;
switch(request->getType())
{
case MegaRequest::TYPE_CREATE_FOLDER:
mApi[apiIndex].h = request->getNodeHandle();
break;
case MegaRequest::TYPE_COPY:
mApi[apiIndex].h = request->getNodeHandle();
break;
case MegaRequest::TYPE_EXPORT:
if (mApi[apiIndex].lastError == API_OK)
{
mApi[apiIndex].h = request->getNodeHandle();
if (request->getAccess())
{
link.assign(request->getLink());
}
}
break;
case MegaRequest::TYPE_GET_PUBLIC_NODE:
if (mApi[apiIndex].lastError == API_OK)
{
publicNode = request->getPublicMegaNode();
}
break;
case MegaRequest::TYPE_IMPORT_LINK:
mApi[apiIndex].h = request->getNodeHandle();
break;
case MegaRequest::TYPE_GET_ATTR_USER:
if ( (mApi[apiIndex].lastError == API_OK) && (request->getParamType() != MegaApi::USER_ATTR_AVATAR) )
{
attributeValue = request->getText();
}
if (request->getParamType() == MegaApi::USER_ATTR_AVATAR)
{
if (mApi[apiIndex].lastError == API_OK)
{
attributeValue = "Avatar changed";
}
if (mApi[apiIndex].lastError == API_ENOENT)
{
attributeValue = "Avatar not found";
}
}
break;
#ifdef ENABLE_CHAT
case MegaRequest::TYPE_CHAT_CREATE:
if (mApi[apiIndex].lastError == API_OK)
{
MegaTextChat *chat = request->getMegaTextChatList()->get(0)->copy();
mApi[apiIndex].chatid = chat->getHandle();
mApi[apiIndex].chats[mApi[apiIndex].chatid].reset(chat);
}
break;
case MegaRequest::TYPE_CHAT_INVITE:
if (mApi[apiIndex].lastError == API_OK)
{
mApi[apiIndex].chatid = request->getNodeHandle();
if (mApi[apiIndex].chats.find(mApi[apiIndex].chatid) != mApi[apiIndex].chats.end())
{
MegaTextChat *chat = mApi[apiIndex].chats[mApi[apiIndex].chatid].get();
MegaHandle uh = request->getParentHandle();
int priv = request->getAccess();
unique_ptr<userpriv_vector> privsbuf{new userpriv_vector};
const MegaTextChatPeerList *privs = chat->getPeerList();
if (privs)
{
for (int i = 0; i < privs->size(); i++)
{
if (privs->getPeerHandle(i) != uh)
{
privsbuf->push_back(userpriv_pair(privs->getPeerHandle(i), (privilege_t) privs->getPeerPrivilege(i)));
}
}
}
privsbuf->push_back(userpriv_pair(uh, (privilege_t) priv));
privs = new MegaTextChatPeerListPrivate(privsbuf.get());
chat->setPeerList(privs);
delete privs;
}
else
{
LOG_err << "Trying to remove a peer from unknown chat";
}
}
break;
case MegaRequest::TYPE_CHAT_REMOVE:
if (mApi[apiIndex].lastError == API_OK)
{
mApi[apiIndex].chatid = request->getNodeHandle();
if (mApi[apiIndex].chats.find(mApi[apiIndex].chatid) != mApi[apiIndex].chats.end())
{
MegaTextChat *chat = mApi[apiIndex].chats[mApi[apiIndex].chatid].get();
MegaHandle uh = request->getParentHandle();
std::unique_ptr<userpriv_vector> privsbuf{new userpriv_vector};
const MegaTextChatPeerList *privs = chat->getPeerList();
if (privs)
{
for (int i = 0; i < privs->size(); i++)
{
if (privs->getPeerHandle(i) != uh)
{
privsbuf->push_back(userpriv_pair(privs->getPeerHandle(i), (privilege_t) privs->getPeerPrivilege(i)));
}
}
}
privs = new MegaTextChatPeerListPrivate(privsbuf.get());
chat->setPeerList(privs);
delete privs;
}
else
{
LOG_err << "Trying to remove a peer from unknown chat";
}
}
break;
case MegaRequest::TYPE_CHAT_URL:
if (mApi[apiIndex].lastError == API_OK)
{
link.assign(request->getLink());
}
break;
#endif
case MegaRequest::TYPE_CREATE_ACCOUNT:
if (mApi[apiIndex].lastError == API_OK)
{
sid = request->getSessionKey();
}
break;
case MegaRequest::TYPE_FETCH_NODES:
if (apiIndex == 0)
{
megaApi[0]->enableTransferResumption();
}
break;
case MegaRequest::TYPE_GET_REGISTERED_CONTACTS:
if (mApi[apiIndex].lastError == API_OK)
{
stringTable.reset(request->getMegaStringTable()->copy());
}
break;
case MegaRequest::TYPE_GET_COUNTRY_CALLING_CODES:
if (mApi[apiIndex].lastError == API_OK)
{
stringListMap.reset(request->getMegaStringListMap()->copy());
}
break;
case MegaRequest::TYPE_FETCH_TIMEZONE:
mApi[apiIndex].tzDetails.reset(mApi[apiIndex].lastError == API_OK ? request->getMegaTimeZoneDetails()->copy() : nullptr);
break;
case MegaRequest::TYPE_GET_USER_EMAIL:
if (mApi[apiIndex].lastError == API_OK)
{
mApi[apiIndex].email = request->getEmail();
}
break;
case MegaRequest::TYPE_ACCOUNT_DETAILS:
mApi[apiIndex].accountDetails.reset(mApi[apiIndex].lastError == API_OK ? request->getMegaAccountDetails() : nullptr);
break;
}
}
void SdkTest::onTransferFinish(MegaApi* api, MegaTransfer *transfer, MegaError* e)
{
int apiIndex = getApiIndex(api);
if (apiIndex < 0) return;
mApi[apiIndex].transferFlags[transfer->getType()] = true;
mApi[apiIndex].lastError = e->getErrorCode(); // todo: change the rest of the transfer test code to use lastTransferError instead.
mApi[apiIndex].lastTransferError = e->getErrorCode();
// there could be a race on these getting set?
LOG_info << "lastError (by transfer) for MegaApi " << apiIndex << ": " << mApi[apiIndex].lastError;
onTranferFinishedCount += 1;
if (mApi[apiIndex].lastError == MegaError::API_OK)
mApi[apiIndex].h = transfer->getNodeHandle();
}
void SdkTest::onTransferUpdate(MegaApi *api, MegaTransfer *transfer)
{
onTransferUpdate_progress = transfer->getTransferredBytes();
onTransferUpdate_filesize = transfer->getTotalBytes();
}
void SdkTest::onAccountUpdate(MegaApi* api)
{
int apiIndex = getApiIndex(api);
if (apiIndex < 0) return;
mApi[apiIndex].accountUpdated = true;
}
void SdkTest::onUsersUpdate(MegaApi* api, MegaUserList *users)
{
int apiIndex = getApiIndex(api);
if (apiIndex < 0) return;
if (!users)
return;
for (int i = 0; i < users->size(); i++)
{
MegaUser *u = users->get(i);
if (u->hasChanged(MegaUser::CHANGE_TYPE_AVATAR)
|| u->hasChanged(MegaUser::CHANGE_TYPE_FIRSTNAME)
|| u->hasChanged(MegaUser::CHANGE_TYPE_LASTNAME))
{
mApi[apiIndex].userUpdated = true;
}
else
{
// Contact is removed from main account
mApi[apiIndex].requestFlags[MegaRequest::TYPE_REMOVE_CONTACT] = true;
mApi[apiIndex].userUpdated = true;
}
}
}
void SdkTest::onNodesUpdate(MegaApi* api, MegaNodeList *nodes)
{
int apiIndex = getApiIndex(api);
if (apiIndex < 0) return;
mApi[apiIndex].nodeUpdated = true;
}
void SdkTest::onContactRequestsUpdate(MegaApi* api, MegaContactRequestList* requests)
{
int apiIndex = getApiIndex(api);
if (apiIndex < 0) return;
mApi[apiIndex].contactRequestUpdated = true;
}
#ifdef ENABLE_CHAT
void SdkTest::onChatsUpdate(MegaApi *api, MegaTextChatList *chats)
{
int apiIndex = getApiIndex(api);
if (apiIndex < 0) return;
MegaTextChatList *list = NULL;
if (chats)
{
list = chats->copy();
}
else
{
list = megaApi[apiIndex]->getChatList();
}
for (int i = 0; i < list->size(); i++)
{
handle chatid = list->get(i)->getHandle();
if (mApi[apiIndex].chats.find(chatid) != mApi[apiIndex].chats.end())
{
mApi[apiIndex].chats[chatid].reset(list->get(i)->copy());
}
else
{
mApi[apiIndex].chats[chatid].reset(list->get(i)->copy());
}
}
delete list;
mApi[apiIndex].chatUpdated = true;
}
void SdkTest::createChat(bool group, MegaTextChatPeerList *peers, int timeout)
{
int apiIndex = 0;
mApi[apiIndex].requestFlags[MegaRequest::TYPE_CHAT_CREATE] = false;
megaApi[0]->createChat(group, peers);
waitForResponse(&mApi[apiIndex].requestFlags[MegaRequest::TYPE_CHAT_CREATE], timeout);
if (timeout)
{
ASSERT_TRUE(mApi[apiIndex].requestFlags[MegaRequest::TYPE_CHAT_CREATE]) << "Chat creation not finished after " << timeout << " seconds";
}
ASSERT_EQ(MegaError::API_OK, mApi[apiIndex].lastError) << "Chat creation failed (error: " << mApi[apiIndex].lastError << ")";
}
#endif
void SdkTest::onEvent(MegaApi*, MegaEvent *event)
{
std::lock_guard<std::mutex> lock{lastEventMutex};
lastEvent.reset(event->copy());
}
void SdkTest::login(unsigned int apiIndex, int timeout)
{
mApi[apiIndex].requestFlags[MegaRequest::TYPE_LOGIN] = false;
mApi[apiIndex].megaApi->login(mApi[apiIndex].email.data(), mApi[apiIndex].pwd.data());
ASSERT_TRUE(waitForResponse(&mApi[apiIndex].requestFlags[MegaRequest::TYPE_LOGIN], timeout))
<< "Login failed after " << timeout << " seconds";
ASSERT_EQ(MegaError::API_OK, mApi[apiIndex].lastError) << "Login failed (error: " << mApi[apiIndex].lastError << ")";
ASSERT_TRUE(mApi[apiIndex].megaApi->isLoggedIn());
}
void SdkTest::loginBySessionId(unsigned int apiIndex, const std::string& sessionId, int timeout)
{
mApi[apiIndex].requestFlags[MegaRequest::TYPE_LOGIN] = false;
mApi[apiIndex].megaApi->fastLogin(sessionId.c_str());
ASSERT_TRUE(waitForResponse(&mApi[apiIndex].requestFlags[MegaRequest::TYPE_LOGIN], timeout))
<< "Login failed after " << timeout << " seconds";
ASSERT_EQ(MegaError::API_OK, mApi[apiIndex].lastError) << "Login failed (error: " << mApi[apiIndex].lastError << ")";
ASSERT_TRUE(mApi[apiIndex].megaApi->isLoggedIn());
}
void SdkTest::fetchnodes(unsigned int apiIndex, int timeout, bool resumeSyncs)
{
mApi[apiIndex].requestFlags[MegaRequest::TYPE_FETCH_NODES] = false;
if (resumeSyncs)
{
mApi[apiIndex].megaApi->fetchNodesAndResumeSyncs();
}
else
{
mApi[apiIndex].megaApi->fetchNodes();
}
ASSERT_TRUE( waitForResponse(&mApi[apiIndex].requestFlags[MegaRequest::TYPE_FETCH_NODES], timeout) )
<< "Fetchnodes failed after " << timeout << " seconds";
ASSERT_EQ(MegaError::API_OK, mApi[apiIndex].lastError) << "Fetchnodes failed (error: " << mApi[apiIndex].lastError << ")";
}
void SdkTest::logout(unsigned int apiIndex, int timeout)
{
mApi[apiIndex].requestFlags[MegaRequest::TYPE_LOGOUT] = false;
mApi[apiIndex].megaApi->logout(this);
EXPECT_TRUE( waitForResponse(&mApi[apiIndex].requestFlags[MegaRequest::TYPE_LOGOUT], timeout) )
<< "Logout failed after " << timeout << " seconds";
// if the connection was closed before the response of the request was received, the result is ESID
if (mApi[apiIndex].lastError == MegaError::API_ESID) mApi[apiIndex].lastError = MegaError::API_OK;
EXPECT_EQ(MegaError::API_OK, mApi[apiIndex].lastError) << "Logout failed (error: " << mApi[apiIndex].lastError << ")";
}
char* SdkTest::dumpSession()
{
return megaApi[0]->dumpSession();
}
void SdkTest::locallogout(int timeout)
{
int apiIndex = 0;
mApi[apiIndex].requestFlags[MegaRequest::TYPE_LOGOUT] = false;
megaApi[apiIndex]->localLogout(this);
EXPECT_TRUE( waitForResponse(&mApi[apiIndex].requestFlags[MegaRequest::TYPE_LOGOUT], timeout) )
<< "Local logout failed after " << timeout << " seconds";
ASSERT_EQ(MegaError::API_OK, mApi[apiIndex].lastError) << "Local logout failed (error: " << mApi[apiIndex].lastError << ")";
}
void SdkTest::resumeSession(const char *session, int timeout)
{
int apiIndex = 0;
ASSERT_EQ(MegaError::API_OK, synchronousFastLogin(apiIndex, session, this)) << "Resume session failed (error: " << mApi[apiIndex].lastError << ")";
}
void SdkTest::purgeTree(MegaNode *p, bool depthfirst)
{
int apiIndex = 0;
std::unique_ptr<MegaNodeList> children{megaApi[0]->getChildren(p)};
for (int i = 0; i < children->size(); i++)
{
MegaNode *n = children->get(i);
// removing the folder removes the children anyway
if (depthfirst && n->isFolder())
purgeTree(n);
string nodepath = n->getName() ? n->getName() : "<no name>";
auto result = synchronousRemove(apiIndex, n);
if (result == API_EEXIST)
{
LOG_warn << "node " << nodepath << " was already removed in api " << apiIndex;
result = API_OK;
}
ASSERT_EQ(MegaError::API_OK, result) << "Remove node operation failed (error: " << mApi[apiIndex].lastError << ")";
}
}
bool SdkTest::waitForResponse(bool *responseReceived, unsigned int timeout)
{
timeout *= 1000000; // convert to micro-seconds
unsigned int tWaited = 0; // microseconds
bool connRetried = false;
while(!(*responseReceived))
{
WaitMillisec(pollingT / 1000);
if (timeout)
{
tWaited += pollingT;
if (tWaited >= timeout)
{
return false; // timeout is expired
}
// if no response after 2 minutes...
else if (!connRetried && tWaited > (pollingT * 240))
{
megaApi[0]->retryPendingConnections(true);
if (megaApi[1] && megaApi[1]->isLoggedIn())
{
megaApi[1]->retryPendingConnections(true);
}
connRetried = true;
}
}
}
return true; // response is received
}
bool SdkTest::synchronousTransfer(unsigned apiIndex, int type, std::function<void()> f, unsigned int timeout)
{
auto& flag = mApi[apiIndex].transferFlags[type];
flag = false;
f();
auto result = waitForResponse(&flag, timeout);
EXPECT_TRUE(result) << "Transfer (type " << type << ") not finished yet after " << timeout << " seconds";
if (!result) mApi[apiIndex].lastError = -999; // local timeout
if (!result) mApi[apiIndex].lastTransferError = -999; // local timeout TODO: switch all transfer code to use lastTransferError . Some still uses lastError
return result;
}
bool SdkTest::synchronousRequest(unsigned apiIndex, int type, std::function<void()> f, unsigned int timeout)
{
auto& flag = mApi[apiIndex].requestFlags[type];
flag = false;
f();
auto result = waitForResponse(&flag, timeout);
EXPECT_TRUE(result) << "Request (type " << type << ") failed after " << timeout << " seconds";
if (!result) mApi[apiIndex].lastError = -999;
return result;
}
void SdkTest::createFile(string filename, bool largeFile)
{
FILE *fp;
fp = fopen(filename.c_str(), "w");
if (fp)
{
int limit = 2000;
// create a file large enough for long upload/download times (5-10MB)
if (largeFile)
limit = 1000000 + rand() % 1000000;
for (int i = 0; i < limit; i++)
{
fprintf(fp, "test ");
}
fclose(fp);
}
}
int64_t SdkTest::getFilesize(string filename)
{
struct stat stat_buf;
int rc = stat(filename.c_str(), &stat_buf);
return rc == 0 ? int64_t(stat_buf.st_size) : int64_t(-1);
}
void SdkTest::deleteFile(string filename)
{
remove(filename.c_str());
}
void SdkTest::getMegaApiAux(unsigned index)
{
if (index >= megaApi.size())
{
megaApi.resize(index + 1);
mApi.resize(index + 1);
}
if (megaApi[index].get() == NULL)
{
string strIndex = index > 1 ? to_string(index) : "";
if (const char *buf = getenv(("MEGA_EMAIL_AUX" + strIndex).c_str()))
{
mApi[index].email.assign(buf);
}
ASSERT_LT((size_t) 0, mApi[index].email.length()) << "Set auxiliar username at the environment variable $MEGA_EMAIL_AUX" << strIndex;
if (const char* buf = getenv(("MEGA_PWD_AUX" + strIndex).c_str()))
{
mApi[index].pwd.assign(buf);
}
ASSERT_LT((size_t) 0, mApi[index].pwd.length()) << "Set the auxiliar password at the environment variable $MEGA_PWD_AUX" << strIndex;
megaApi[index].reset(new MegaApi(APP_KEY.c_str(), megaApiCacheFolder(index).c_str(), USER_AGENT.c_str(), int(0), unsigned(THREADS_PER_MEGACLIENT)));
mApi[index].megaApi = megaApi[index].get();
megaApi[index]->setLoggingName(to_string(index).c_str());
megaApi[index]->setLogLevel(MegaApi::LOG_LEVEL_DEBUG);
megaApi[index]->addListener(this); // TODO: really should be per api
ASSERT_NO_FATAL_FAILURE( login(index) );
ASSERT_NO_FATAL_FAILURE( fetchnodes(index) );
}
}
void SdkTest::releaseMegaApi(unsigned int apiIndex)
{
if (mApi.size() <= apiIndex)
{
return;
}
assert(megaApi[apiIndex].get() == mApi[apiIndex].megaApi);
if (mApi[apiIndex].megaApi)
{
if (mApi[apiIndex].megaApi->isLoggedIn())
{
if (!gResumeSessions)
ASSERT_NO_FATAL_FAILURE( logout(apiIndex) );
else
ASSERT_NO_FATAL_FAILURE( locallogout(apiIndex) );
}
megaApi[apiIndex].reset();
mApi[apiIndex].megaApi = NULL;
}
}
void SdkTest::inviteContact(string email, string message, int action)
{
int apiIndex = 0;
ASSERT_EQ(MegaError::API_OK, synchronousInviteContact(apiIndex, email.data(), message.data(), action)) << "Contact invitation failed";
}
void SdkTest::replyContact(MegaContactRequest *cr, int action)
{
int apiIndex = 1;
ASSERT_EQ(MegaError::API_OK, synchronousReplyContactRequest(apiIndex, cr, action)) << "Contact reply failed";
}
void SdkTest::removeContact(string email, int timeout)
{
int apiIndex = 0;
MegaUser *u = megaApi[apiIndex]->getContact(email.data());
bool null_pointer = (u == NULL);
ASSERT_FALSE(null_pointer) << "Cannot find the specified contact (" << email << ")";
if (u->getVisibility() != MegaUser::VISIBILITY_VISIBLE)
{
mApi[apiIndex].userUpdated = true; // nothing to do
delete u;
return;
}
auto result = synchronousRemoveContact(apiIndex, u);
if (result == API_EEXIST)
{
LOG_warn << "Contact " << email << " was already removed in api " << apiIndex;
result = API_OK;
}
ASSERT_EQ(MegaError::API_OK, result) << "Contact deletion of " << email << " failed on api " << apiIndex;
delete u;
}
void SdkTest::shareFolder(MegaNode *n, const char *email, int action, int timeout)
{
int apiIndex = 0;
ASSERT_EQ(MegaError::API_OK, synchronousShare(apiIndex, n, email, action)) << "Folder sharing failed" << endl << "User: " << email << " Action: " << action;
}
void SdkTest::createPublicLink(unsigned apiIndex, MegaNode *n, m_time_t expireDate, int timeout)
{
mApi[apiIndex].requestFlags[MegaRequest::TYPE_EXPORT] = false;
auto err = synchronousExportNode(apiIndex, n, expireDate);
if (!expireDate)
{
ASSERT_EQ(MegaError::API_OK, err) << "Public link creation failed (error: " << mApi[apiIndex].lastError << ")";
}
else
{
bool res = MegaError::API_OK != err && err != -999;
ASSERT_TRUE(res) << "Public link creation with expire time on free account (" << mApi[apiIndex].email << ") succeed, and it mustn't";
}
}
void SdkTest::importPublicLink(unsigned apiIndex, string link, MegaNode *parent, int timeout)
{
mApi[apiIndex].requestFlags[MegaRequest::TYPE_IMPORT_LINK] = false;
mApi[apiIndex].megaApi->importFileLink(link.data(), parent);
ASSERT_TRUE(waitForResponse(&mApi[apiIndex].requestFlags[MegaRequest::TYPE_IMPORT_LINK], timeout) )
<< "Public link import not finished after " << timeout << " seconds";
ASSERT_EQ(MegaError::API_OK, mApi[apiIndex].lastError) << "Public link import failed (error: " << mApi[apiIndex].lastError << ")";
}
void SdkTest::getPublicNode(unsigned apiIndex, string link, int timeout)
{
mApi[apiIndex].requestFlags[MegaRequest::TYPE_GET_PUBLIC_NODE] = false;
mApi[apiIndex].megaApi->getPublicNode(link.data());
ASSERT_TRUE(waitForResponse(&mApi[apiIndex].requestFlags[MegaRequest::TYPE_GET_PUBLIC_NODE], timeout) )
<< "Public link retrieval not finished after " << timeout << " seconds";
ASSERT_EQ(MegaError::API_OK, mApi[apiIndex].lastError) << "Public link retrieval failed (error: " << mApi[apiIndex].lastError << ")";
}
void SdkTest::removePublicLink(unsigned apiIndex, MegaNode *n, int timeout)
{
mApi[apiIndex].requestFlags[MegaRequest::TYPE_EXPORT] = false;
mApi[apiIndex].megaApi->disableExport(n);
ASSERT_TRUE( waitForResponse(&mApi[apiIndex].requestFlags[MegaRequest::TYPE_EXPORT], timeout) )
<< "Public link removal not finished after " << timeout << " seconds";
ASSERT_EQ(MegaError::API_OK, mApi[apiIndex].lastError) << "Public link removal failed (error: " << mApi[apiIndex].lastError << ")";
}
void SdkTest::getContactRequest(unsigned int apiIndex, bool outgoing, int expectedSize)
{
MegaContactRequestList *crl;
if (outgoing)
{