forked from itinance/react-native-fs
-
-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathReactNativeModule.cpp
1122 lines (959 loc) · 39.2 KB
/
ReactNativeModule.cpp
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
// Copyright (C) Microsoft Corporation. All rights reserved.
#include "pch.h"
#include "ReactNativeModule.h"
#include <filesystem>
#include <sstream>
#include <stack>
#include <windows.h>
#include <winrt/Windows.Storage.FileProperties.h>
#include <winrt/Windows.Storage.Streams.h>
#include <winrt/Windows.Storage.h>
#include <winrt/Windows.Web.Http.h>
#include <winrt/Windows.Web.Http.Headers.h>
#include <winrt/Windows.ApplicationModel.h>
#include <winrt/Windows.Foundation.h>
#include "RNFSException.h"
using namespace winrt;
using namespace winrt::ReactNativeFs;
using namespace winrt::Windows::ApplicationModel;
using namespace winrt::Windows::Storage;
using namespace winrt::Windows::Storage::Streams;
using namespace winrt::Windows::Foundation;
using namespace winrt::Windows::Web::Http;
union touchTime {
int64_t initialTime;
DWORD splitTime[2];
};
//
// For downloads and uploads
//
CancellationDisposable::CancellationDisposable(IAsyncInfo const& async, std::function<void()>&& onCancel) noexcept
: m_async{ async }
, m_onCancel{ std::move(onCancel) }
{
}
CancellationDisposable::CancellationDisposable(CancellationDisposable&& other) noexcept
: m_async{ std::move(other.m_async) }
, m_onCancel{ std::move(other.m_onCancel) }
{
}
CancellationDisposable& CancellationDisposable::operator=(CancellationDisposable&& other) noexcept
{
if (this != &other)
{
CancellationDisposable temp{ std::move(*this) };
m_async = std::move(other.m_async);
m_onCancel = std::move(other.m_onCancel);
}
return *this;
}
CancellationDisposable::~CancellationDisposable() noexcept
{
Cancel();
}
void CancellationDisposable::Cancel() noexcept
{
if (m_async)
{
if (m_async.Status() == AsyncStatus::Started)
{
m_async.Cancel();
}
if (m_onCancel)
{
m_onCancel();
}
}
}
TaskCancellationManager::~TaskCancellationManager() noexcept
{
// Do the explicit cleaning to make sure that CancellationDisposable
// destructors run while this instance still has valid fields because
// they are used by the onCancel callback.
// We also want to clear the m_pendingTasks before running the
// CancellationDisposable destructors since they touch the m_pendingTasks.
std::map<JobId, CancellationDisposable> pendingTasks;
{
std::scoped_lock lock{ m_mutex };
pendingTasks = std::move(m_pendingTasks);
}
}
IAsyncAction TaskCancellationManager::Add(JobId jobId, IAsyncAction const& asyncAction) noexcept
{
std::scoped_lock lock{ m_mutex };
m_pendingTasks.try_emplace(jobId, asyncAction, [this, jobId]()
{
Cancel(jobId);
});
return asyncAction;
}
void TaskCancellationManager::Cancel(JobId jobId) noexcept
{
// The destructor of the token does the cancellation. We must do it outside of lock.
CancellationDisposable token;
{
std::scoped_lock lock{ m_mutex };
if (!m_pendingTasks.empty())
{
if (auto it = m_pendingTasks.find(jobId); it != m_pendingTasks.end())
{
token = std::move(it->second);
m_pendingTasks.erase(it);
}
}
}
}
//
// For stat implementation
//
struct handle_closer
{
void operator()(HANDLE h) noexcept
{
assert(h != INVALID_HANDLE_VALUE); if (h) CloseHandle(h);
}
};
static inline HANDLE safe_handle(HANDLE h) noexcept
{
return (h == INVALID_HANDLE_VALUE) ? nullptr : h;
}
void ReactNativeModule::Initialize(ReactContext const& reactContext) noexcept
{
m_reactContext = reactContext;
}
//
// RNFS implementations
//
ReactNativeFsSpec_Constants ReactNativeModule::GetConstants() noexcept
{
ReactNativeFsSpec_Constants res;
res.MainBundlePath = to_string(Package::Current().InstalledLocation().Path());
res.CachesDirectoryPath = to_string(ApplicationData::Current().LocalCacheFolder().Path());
res.DocumentDirectoryPath = to_string(ApplicationData::Current().LocalFolder().Path());
res.DownloadDirectoryPath = to_string(UserDataPaths::GetDefault().Downloads());
res.ExternalDirectoryPath = to_string(UserDataPaths::GetDefault().Documents());
res.TemporaryDirectoryPath = to_string(ApplicationData::Current().TemporaryFolder().Path());
res.PicturesDirectoryPath = to_string(UserDataPaths::GetDefault().Pictures());
// TODO: Check to see if these can be accessed after package created
res.RoamingDirectoryPath = to_string(ApplicationData::Current().RoamingFolder().Path());
res.FileTypeRegular = "0";
res.FileTypeDirectory = "1";
return res;
}
winrt::fire_and_forget ReactNativeModule::mkdir(std::string directory, JSValueObject options, ReactPromise<void> promise) noexcept
try
{
size_t pathLength{ directory.length() };
if (pathLength <= 0) {
promise.Reject("Invalid path length");
}
else {
bool hasTrailingSlash{ directory[pathLength - 1] == '\\' || directory[pathLength - 1] == '/' };
std::filesystem::path path(hasTrailingSlash ? directory.substr(0, pathLength - 1) : directory);
path.make_preferred();
auto parentPath{ path.parent_path().wstring() };
std::stack<std::wstring> directoriesToMake;
directoriesToMake.push(path.filename().wstring());
StorageFolder folder{ nullptr };
while (folder == nullptr) {
try {
folder = co_await StorageFolder::GetFolderFromPathAsync(parentPath);
}
catch (const hresult_error& ex) {
hresult result{ ex.code() };
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) {
auto index{ parentPath.find_last_of('\\') };
directoriesToMake.push(parentPath.substr(index + 1));
parentPath = parentPath.substr(0, index);
}
else {
promise.Reject(winrt::to_string(ex.message()).c_str());
}
}
}
while (!directoriesToMake.empty()) {
folder = co_await folder.CreateFolderAsync(directoriesToMake.top(), CreationCollisionOption::OpenIfExists);
directoriesToMake.pop();
}
promise.Resolve();
}
}
catch (const hresult_error& ex)
{
// "Unexpected error while making directory."
promise.Reject( winrt::to_string(ex.message()).c_str() );
}
winrt::fire_and_forget ReactNativeModule::moveFile(std::string filepath, std::string destpath, JSValueObject options, ReactPromise<void> promise) noexcept
try
{
winrt::hstring srcDirectoryPath, srcFileName;
splitPath(filepath, srcDirectoryPath, srcFileName);
winrt::hstring destDirectoryPath, destFileName;
splitPath(destpath, destDirectoryPath, destFileName);
StorageFolder srcFolder{ co_await StorageFolder::GetFolderFromPathAsync(srcDirectoryPath) };
StorageFolder destFolder{ co_await StorageFolder::GetFolderFromPathAsync(destDirectoryPath) };
StorageFile file{ co_await srcFolder.GetFileAsync(srcFileName) };
co_await file.MoveAsync(destFolder, destFileName, NameCollisionOption::ReplaceExisting);
promise.Resolve();
}
catch (const hresult_error& ex)
{
// "Failed to move file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
winrt::fire_and_forget ReactNativeModule::copyFile(std::string filepath, std::string destpath, JSValueObject options, ReactPromise<void> promise) noexcept
try
{
winrt::hstring srcDirectoryPath, srcFileName;
splitPath(filepath, srcDirectoryPath, srcFileName);
winrt::hstring destDirectoryPath, destFileName;
splitPath(destpath, destDirectoryPath, destFileName);
StorageFolder srcFolder{ co_await StorageFolder::GetFolderFromPathAsync(srcDirectoryPath) };
StorageFolder destFolder{ co_await StorageFolder::GetFolderFromPathAsync(destDirectoryPath) };
StorageFile file{ co_await srcFolder.GetFileAsync(srcFileName) };
co_await file.CopyAsync(destFolder, destFileName, NameCollisionOption::ReplaceExisting);
promise.Resolve();
}
catch (const hresult_error& ex)
{
// "Failed to copy file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
winrt::fire_and_forget ReactNativeModule::copyFolder(
std::string srcFolderPath,
std::string destFolderPath,
ReactPromise<void> promise) noexcept
try
{
std::filesystem::path srcPath{ srcFolderPath };
srcPath.make_preferred();
std::filesystem::path destPath{ destFolderPath };
destPath.make_preferred();
StorageFolder srcFolder{ co_await StorageFolder::GetFolderFromPathAsync(winrt::to_hstring(srcPath.c_str())) };
StorageFolder destFolder{ co_await StorageFolder::GetFolderFromPathAsync(winrt::to_hstring(destPath.c_str())) };
auto items{ co_await srcFolder.GetItemsAsync() };
for (auto item : items)
{
if (item.IsOfType(StorageItemTypes::File))
{
StorageFile file{ co_await StorageFile::GetFileFromPathAsync(item.Path()) };
co_await file.CopyAsync(destFolder, file.Name(), NameCollisionOption::ReplaceExisting);
}
else if (item.IsOfType(StorageItemTypes::Folder))
{
StorageFolder src{ co_await StorageFolder::GetFolderFromPathAsync(item.Path()) };
StorageFolder dest{ co_await destFolder.CreateFolderAsync(item.Name(), CreationCollisionOption::OpenIfExists) };
copyFolderHelper(src, dest);
}
}
promise.Resolve();
co_return;
}
catch (const hresult_error& ex)
{
// "Failed to copy file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
winrt::fire_and_forget ReactNativeModule::copyFolderHelper(
winrt::Windows::Storage::StorageFolder src,
winrt::Windows::Storage::StorageFolder dest) noexcept
try
{
auto items{ co_await src.GetItemsAsync() };
for (auto item : items)
{
if (item.IsOfType(StorageItemTypes::File))
{
StorageFile file{ co_await StorageFile::GetFileFromPathAsync(item.Path()) };
co_await file.CopyAsync(dest, file.Name(), NameCollisionOption::ReplaceExisting);
}
else if (item.IsOfType(StorageItemTypes::Folder))
{
StorageFolder srcFolder{ co_await StorageFolder::GetFolderFromPathAsync(item.Path()) };
StorageFolder destFolder{ co_await dest.CreateFolderAsync(item.Name(), CreationCollisionOption::OpenIfExists) };
copyFolderHelper(srcFolder, destFolder);
}
}
}
catch (...)
{
co_return;
}
winrt::fire_and_forget ReactNativeModule::getFSInfo(ReactPromise<JSValueObject> promise) noexcept
try
{
auto localFolder{ Windows::Storage::ApplicationData::Current().LocalFolder() };
auto properties{ co_await localFolder.Properties().RetrievePropertiesAsync({L"System.FreeSpace", L"System.Capacity"}) };
JSValueObject result;
result["freeSpace"] = unbox_value<uint64_t>(properties.Lookup(L"System.FreeSpace"));
result["totalSpace"] = unbox_value<uint64_t>(properties.Lookup(L"System.Capacity"));
promise.Resolve(result);
}
catch (const hresult_error& ex)
{
// "Failed to retrieve file system info."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
winrt::fire_and_forget ReactNativeModule::unlink(std::string filepath, ReactPromise<void> promise) noexcept
try
{
size_t pathLength{ filepath.length() };
if (pathLength <= 0) {
promise.Reject("Invalid path.");
}
else {
bool hasTrailingSlash{ filepath[pathLength - 1] == '\\' || filepath[pathLength - 1] == '/' };
std::filesystem::path path(hasTrailingSlash ? filepath.substr(0, pathLength - 1) : filepath);
path.make_preferred();
StorageFolder folder{ co_await StorageFolder::GetFolderFromPathAsync(path.parent_path().wstring()) };
auto target{ co_await folder.GetItemAsync(path.filename().wstring()) };
co_await target.DeleteAsync();
promise.Resolve();
}
}
catch (const hresult_error& ex)
{
hresult result{ ex.code() };
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) // FileNotFoundException
{
promise.Reject(ReactError{ "ENOENT", "ENOENT: no such file or directory, open " + filepath });
}
else
{
// "Failed to unlink file"
promise.Reject( winrt::to_string(ex.message()).c_str() );
}
}
winrt::fire_and_forget ReactNativeModule::exists(std::string filepath, ReactPromise<bool> promise) noexcept
try
{
size_t fileLength{ filepath.length() };
if (fileLength <= 0) {
promise.Resolve(false);
}
else {
bool hasTrailingSlash{ filepath[fileLength - 1] == '\\' || filepath[fileLength - 1] == '/' };
std::filesystem::path path(hasTrailingSlash ? filepath.substr(0, fileLength - 1) : filepath);
winrt::hstring directoryPath, fileName;
splitPath(filepath, directoryPath, fileName);
StorageFolder folder{ co_await StorageFolder::GetFolderFromPathAsync(directoryPath) };
if (fileName.size() > 0) {
co_await folder.GetItemAsync(fileName);
}
promise.Resolve(true);
}
}
catch (const hresult_error& ex)
{
hresult result{ ex.code() };
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) {
promise.Resolve(false);
}
// "Failed to check if file or directory exists.
promise.Reject(winrt::to_string(ex.message()).c_str());
}
void ReactNativeModule::stopDownload(int32_t jobID) noexcept
{
m_tasks.Cancel(jobID);
}
void ReactNativeModule::stopUpload(int32_t jobID) noexcept
{
m_tasks.Cancel(jobID);
}
winrt::fire_and_forget ReactNativeModule::readFile(std::string filepath, ReactPromise<std::string> promise) noexcept
try
{
winrt::hstring directoryPath, fileName;
splitPath(filepath, directoryPath, fileName);
StorageFolder folder{ co_await StorageFolder::GetFolderFromPathAsync(directoryPath) };
StorageFile file{ co_await folder.GetFileAsync(fileName) };
Streams::IBuffer buffer{ co_await FileIO::ReadBufferAsync(file) };
winrt::hstring base64Content{ Cryptography::CryptographicBuffer::EncodeToBase64String(buffer) };
promise.Resolve(winrt::to_string(base64Content));
}
catch (const hresult_error& ex)
{
hresult result{ ex.code() };
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) // FileNotFoundException
{
promise.Reject(ReactError{ "ENOENT", "ENOENT: no such file or directory, open " + filepath });
}
else if (result == HRESULT_FROM_WIN32(E_ACCESSDENIED)) // UnauthorizedAccessException
{
promise.Reject(ReactError{ "EISDIR", "EISDIR: illegal operation on a directory, read" });
}
else
{
// "Failed to read file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
}
winrt::fire_and_forget ReactNativeModule::stat(std::string filepath, ReactPromise<JSValueObject> promise) noexcept
try
{
size_t pathLength{ filepath.length() };
if (pathLength <= 0) {
promise.Reject("Invalid path.");
}
else {
bool hasTrailingSlash{ filepath[pathLength - 1] == '\\' || filepath[pathLength - 1] == '/' };
std::filesystem::path path(hasTrailingSlash ? filepath.substr(0, pathLength - 1) : filepath);
path.make_preferred();
StorageFolder folder{ co_await StorageFolder::GetFolderFromPathAsync(path.parent_path().wstring()) };
IStorageItem item{ co_await folder.GetItemAsync(path.filename().wstring()) };
auto properties{ co_await item.GetBasicPropertiesAsync() };
JSValueObject fileInfo;
fileInfo["ctime"] = winrt::clock::to_time_t(item.DateCreated());
fileInfo["mtime"] = winrt::clock::to_time_t(properties.DateModified());
fileInfo["size"] = std::to_string(properties.Size());
fileInfo["type"] = item.IsOfType(StorageItemTypes::Folder) ? 1 : 0;
promise.Resolve(fileInfo);
}
}
catch (...)
{
promise.Reject(ReactError{ "ENOENT", "ENOENT: no such file or directory, open " + filepath });
}
winrt::fire_and_forget ReactNativeModule::readDir(std::string directory, ReactPromise<JSValueArray> promise) noexcept
try
{
std::filesystem::path path(directory);
path.make_preferred();
StorageFolder targetDirectory{ co_await StorageFolder::GetFolderFromPathAsync(path.c_str()) };
JSValueArray resultsArray;
auto items{ co_await targetDirectory.GetItemsAsync() };
for (auto item : items)
{
auto properties{ co_await item.GetBasicPropertiesAsync() };
JSValueObject itemInfo;
itemInfo["ctime"] = winrt::clock::to_time_t(targetDirectory.DateCreated());
itemInfo["mtime"] = winrt::clock::to_time_t(properties.DateModified());
itemInfo["name"] = to_string(item.Name());
itemInfo["path"] = to_string(item.Path());
itemInfo["size"] = properties.Size();
itemInfo["type"] = item.IsOfType(StorageItemTypes::Folder) ? 1 : 0;
resultsArray.push_back(std::move(itemInfo));
}
promise.Resolve(resultsArray);
}
catch (const hresult_error& ex)
{
// "Failed to read directory."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
winrt::fire_and_forget ReactNativeModule::read(std::string filepath, uint32_t length, uint64_t position, ReactPromise<std::string> promise) noexcept
try
{
winrt::hstring directoryPath, fileName;
splitPath(filepath, directoryPath, fileName);
StorageFolder folder{ co_await StorageFolder::GetFolderFromPathAsync(directoryPath) };
StorageFile file{ co_await folder.GetFileAsync(fileName) };
Streams::Buffer buffer{ length };
Streams::IRandomAccessStream stream{ co_await file.OpenReadAsync() };
stream.Seek(position);
stream.ReadAsync(buffer, length, Streams::InputStreamOptions::None);
std::string result{ winrt::to_string(Cryptography::CryptographicBuffer::EncodeToBase64String(buffer)) };
promise.Resolve(result);
}
catch (const hresult_error& ex)
{
hresult result{ ex.code() };
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) // FileNotFoundException
{
promise.Reject(ReactError{ "ENOENT", "ENOENT: no such file or directory, open " + filepath });
}
else if (result == HRESULT_FROM_WIN32(E_ACCESSDENIED)) // UnauthorizedAccessException
{
promise.Reject(ReactError{"EISDIR", "EISDIR: Could not open file for reading" });
}
else
{
// "Failed to read from file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
}
winrt::fire_and_forget ReactNativeModule::hash(std::string filepath, std::string algorithm, ReactPromise<std::string> promise) noexcept
try
{
// Note: SHA224 is not part of winrt
if (algorithm.compare("sha224") == 0)
{
promise.Reject(ReactError{ "Error", "WinRT does not offer sha224 encryption." });
co_return;
}
winrt::hstring directoryPath, fileName;
splitPath(filepath, directoryPath, fileName);
StorageFolder folder{ co_await StorageFolder::GetFolderFromPathAsync(directoryPath) };
StorageFile file{ co_await folder.GetFileAsync(fileName) };
auto search{ availableHashes.find(algorithm) };
if (search == availableHashes.end())
{
promise.Reject(ReactError{ "Error", "Invalid hash algorithm " + algorithm});
co_return;
}
CryptographyCore::HashAlgorithmProvider provider{ search->second() };
Streams::IBuffer buffer{ co_await FileIO::ReadBufferAsync(file) };
auto hashedBuffer{ provider.HashData(buffer) };
auto result{ winrt::to_string(Cryptography::CryptographicBuffer::EncodeToHexString(hashedBuffer)) };
promise.Resolve(result);
}
catch (const hresult_error& ex)
{
hresult result{ ex.code() };
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) // FileNotFoundException
{
promise.Reject(ReactError{ "ENOENT", "ENOENT: no such file or directory, open " + filepath });
}
else if (result == HRESULT_FROM_WIN32(E_ACCESSDENIED)) // UnauthorizedAccessException
{
promise.Reject(ReactError{ "EISDIR", "EISDIR: illegal operation on a directory, read" });
}
else
{
// "Failed to get checksum from file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
}
winrt::fire_and_forget ReactNativeModule::writeFile(std::string filepath, std::string base64Content, JSValueObject options, ReactPromise<void> promise) noexcept
try
{
winrt::hstring base64ContentStr{ winrt::to_hstring(base64Content) };
Streams::IBuffer buffer{ Cryptography::CryptographicBuffer::DecodeFromBase64String(base64ContentStr) };
winrt::hstring directoryPath, fileName;
splitPath(filepath, directoryPath, fileName);
StorageFolder folder{ co_await StorageFolder::GetFolderFromPathAsync(directoryPath) };
StorageFile file{ co_await folder.CreateFileAsync(fileName, CreationCollisionOption::ReplaceExisting) };
Streams::IRandomAccessStream stream{ co_await file.OpenAsync(FileAccessMode::ReadWrite) };
co_await stream.WriteAsync(buffer);
promise.Resolve();
}
catch (const hresult_error& ex)
{
hresult result{ ex.code() };
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) // FileNotFoundException
{
promise.Reject(ReactError{ "ENOENT", "ENOENT: no such file or directory, open " + filepath });
}
else
{
// Failed to write to file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
}
winrt::fire_and_forget ReactNativeModule::appendFile(std::string filepath, std::string base64Content, ReactPromise<void> promise) noexcept
try
{
size_t fileLength = filepath.length();
bool hasTrailingSlash{ filepath[fileLength - 1] == '\\' || filepath[fileLength - 1] == '/' };
std::filesystem::path path(hasTrailingSlash ? filepath.substr(0, fileLength - 1) : filepath);
winrt::hstring directoryPath, fileName;
splitPath(filepath, directoryPath, fileName);
StorageFolder folder{ co_await StorageFolder::GetFolderFromPathAsync(directoryPath) };
StorageFile file{ co_await folder.CreateFileAsync(fileName, CreationCollisionOption::OpenIfExists) };
winrt::hstring base64ContentStr{ winrt::to_hstring(base64Content) };
Streams::IBuffer buffer{ Cryptography::CryptographicBuffer::DecodeFromBase64String(base64ContentStr) };
Streams::IRandomAccessStream stream{ co_await file.OpenAsync(FileAccessMode::ReadWrite) };
stream.Seek(stream.Size()); // Writes to end of file
co_await stream.WriteAsync(buffer);
promise.Resolve();
}
catch (const hresult_error& ex)
{
hresult result{ ex.code() };
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) // FileNotFoundException
{
promise.Reject(ReactError{ "ENOENT", "ENOENT: no such file or directory, open " + filepath });
}
else
{
// "Failed to append to file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
}
winrt::fire_and_forget ReactNativeModule::write(std::string filepath, std::string base64Content, int position, ReactPromise<void> promise) noexcept
try
{
winrt::hstring directoryPath, fileName;
splitPath(filepath, directoryPath, fileName);
StorageFolder folder{ co_await StorageFolder::GetFolderFromPathAsync(directoryPath) };
StorageFile file{ co_await folder.GetFileAsync(fileName) };
winrt::hstring base64ContentStr{ winrt::to_hstring(base64Content) };
Streams::IBuffer buffer{ Cryptography::CryptographicBuffer::DecodeFromBase64String(base64ContentStr) };
Streams::IRandomAccessStream stream{ co_await file.OpenAsync(FileAccessMode::ReadWrite) };
if (position < 0)
{
stream.Seek(stream.Size()); // Writes to end of file
}
else
{
stream.Seek(position);
}
co_await stream.WriteAsync(buffer);
promise.Resolve();
}
catch (const hresult_error& ex)
{
hresult result{ ex.code() };
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) // FileNotFoundException
{
promise.Reject(ReactError{ "ENOENT", "ENOENT: no such file or directory, open " + filepath });
}
else
{
// Failed to write to file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
}
winrt::fire_and_forget ReactNativeModule::downloadFile(JSValueObject options, ReactPromise<JSValueObject> promise) noexcept
{
//JobID
auto jobId{ options["jobId"].AsInt32() };
try
{
//Filepath
std::filesystem::path path(options["toFile"].AsString());
path.make_preferred();
if (path.filename().empty())
{
promise.Reject("Failed to determine filename in path");
co_return;
}
auto filePath{ winrt::to_hstring(path.c_str()) };
//URL
std::string fromURLString{ options["fromUrl"].AsString() };
std::wstring URLForURI(fromURLString.begin(), fromURLString.end());
Uri uri{ URLForURI };
//Headers
auto const& headers{ options["headers"].AsObject() };
//Progress Interval
auto progressInterval{ options["progressInterval"].AsInt64() };
//Progress Divider
auto progressDivider{ options["progressDivider"].AsInt64() };
winrt::Windows::Web::Http::HttpRequestMessage request{ winrt::Windows::Web::Http::HttpMethod::Get(), uri };
Buffer buffer{ 8 * 1024 };
HttpBufferContent content{ buffer };
for (const auto& header : headers)
{
if (!request.Headers().TryAppendWithoutValidation(winrt::to_hstring(header.first), winrt::to_hstring(header.second.AsString())))
{
content.Headers().TryAppendWithoutValidation(winrt::to_hstring(header.first), winrt::to_hstring(header.second.AsString()));
}
}
request.Content(content);
co_await m_tasks.Add(jobId, ProcessDownloadRequestAsync(promise, request, filePath, jobId, progressInterval, progressDivider));
}
catch (const hresult_error& ex)
{
// "Failed to download file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
m_tasks.Cancel(jobId);
}
winrt::fire_and_forget ReactNativeModule::uploadFiles(JSValueObject options, ReactPromise<JSValueObject> promise) noexcept
{
auto jobId{ options["jobId"].AsInt32() };
try
{
auto method{ options["method"].AsString() };
winrt::Windows::Web::Http::HttpMethod httpMethod{ winrt::Windows::Web::Http::HttpMethod::Post() };
if (method.compare("POST") != 0)
{
if (method.compare("PUT") == 0)
{
httpMethod = winrt::Windows::Web::Http::HttpMethod::Put();
}
else
{
promise.Reject("Invalid HTTP request: neither a POST nor a PUT request.");
co_return;
}
}
auto const& files{ options["files"].AsArray() };
uint64_t totalUploadSize = 0;
for (const auto& fileInfo : files)
{
auto const& fileObj{ fileInfo.AsObject() };
auto filepath{ fileObj["filepath"].AsString() };
winrt::hstring directoryPath, fileName;
splitPath(filepath, directoryPath, fileName);
try
{
StorageFolder folder{ co_await StorageFolder::GetFolderFromPathAsync(directoryPath) };
StorageFile file{ co_await folder.GetFileAsync(fileName) };
auto fileProperties{ co_await file.GetBasicPropertiesAsync() };
totalUploadSize += fileProperties.Size();
}
catch (...)
{
continue;
}
}
if (totalUploadSize <= 0)
{
promise.Reject("No files to upload");
co_return;
}
co_await m_tasks.Add(jobId, ProcessUploadRequestAsync(promise, options, httpMethod, files, jobId, totalUploadSize));
}
catch (const hresult_error& ex)
{
// "Failed to upload file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
m_tasks.Cancel(jobId);
}
void ReactNativeModule::touch(std::string filepath, int64_t mtime, int64_t ctime, bool modifyCreationTime, ReactPromise<std::string> promise) noexcept
try
{
std::filesystem::path path(filepath);
path.make_preferred();
auto s_path{ path.c_str() };
PCWSTR actual_path{ s_path };
DWORD accessMode{ GENERIC_READ | GENERIC_WRITE };
DWORD shareMode{ FILE_SHARE_WRITE };
DWORD creationMode{ OPEN_EXISTING };
std::unique_ptr<void, handle_closer> handle(safe_handle(CreateFile2(actual_path, accessMode, shareMode, creationMode, nullptr)));
if (!handle)
{
promise.Reject("Failed to create handle for file to touch.");
return;
}
touchTime mtime_64{ mtime * 10000 + UNIX_EPOCH_IN_WINRT_INTERVAL };
FILETIME mFileTime;
mFileTime.dwLowDateTime = mtime_64.splitTime[0];
mFileTime.dwHighDateTime = mtime_64.splitTime[1];
if (modifyCreationTime)
{
touchTime ctime_64{ ctime * 10000 + UNIX_EPOCH_IN_WINRT_INTERVAL };
FILETIME cFileTime;
cFileTime.dwLowDateTime = ctime_64.splitTime[0];
cFileTime.dwHighDateTime = ctime_64.splitTime[1];
if (SetFileTime(handle.get(), &cFileTime, nullptr, &mFileTime) == 0)
{
promise.Reject("Failed to set new creation time and modified time of file.");
}
else
{
promise.Resolve(winrt::to_string(s_path));
}
}
else
{
if (SetFileTime(handle.get(), nullptr, nullptr, &mFileTime) == 0)
{
promise.Reject("Failed to set new creation time and modified time of file.");
}
else
{
promise.Resolve(winrt::to_string(s_path));
}
}
}
catch (const hresult_error& ex)
{
hresult result{ ex.code() };
if (result == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) // FileNotFoundException
{
promise.Reject("ENOENT: no such file.");
}
else
{
// "Failed to touch file."
promise.Reject(winrt::to_string(ex.message()).c_str());
}
}
void ReactNativeModule::splitPath(const std::string& fullPath, winrt::hstring& directoryPath, winrt::hstring& fileName) noexcept
{
std::filesystem::path path(fullPath);
path.make_preferred();
directoryPath = path.has_parent_path() ? winrt::to_hstring(path.parent_path().c_str()) : L"";
fileName = path.has_filename() ? winrt::to_hstring(path.filename().c_str()) : L"";
}
IAsyncAction ReactNativeModule::ProcessDownloadRequestAsync(ReactPromise<JSValueObject> promise,
winrt::Windows::Web::Http::HttpRequestMessage request, std::wstring_view filePath, int32_t jobId, int64_t progressInterval, int64_t progressDivider)
{
try
{
HttpResponseMessage response = co_await m_httpClient.SendRequestAsync(request, HttpCompletionOption::ResponseHeadersRead);
IReference<uint64_t> contentLength{ response.Content().Headers().ContentLength() };
{
JSValueObject headersMap;
for (auto const& header : response.Headers())
{
headersMap[to_string(header.Key())] = to_string(header.Value());
}
emitDownloadBegin(
JSValueObject{
{ "jobId", jobId },
{ "statusCode", (int)response.StatusCode() },
{ "contentLength", contentLength && contentLength.Type() == PropertyType::UInt64
? JSValue(contentLength.Value())
: JSValue{nullptr} },
{ "headers", std::move(headersMap) },
});
}
uint64_t totalRead{ 0 };
std::filesystem::path fsFilePath{ filePath };
StorageFolder storageFolder{ co_await StorageFolder::GetFolderFromPathAsync(fsFilePath.parent_path().wstring()) };
StorageFile storageFile{ co_await storageFolder.CreateFileAsync(fsFilePath.filename().wstring(), CreationCollisionOption::ReplaceExisting) };
IRandomAccessStream stream{ co_await storageFile.OpenAsync(FileAccessMode::ReadWrite) };
IOutputStream outputStream{ stream.GetOutputStreamAt(0) };
auto contentStream = co_await response.Content().ReadAsInputStreamAsync();
auto contentLengthForProgress = contentLength && contentLength.Type() == PropertyType::UInt64 ? contentLength.Value() : -1;
Buffer buffer{ 8 * 1024 };
uint32_t read = 0;
int64_t initialProgressTime{ winrt::clock::now().time_since_epoch().count() / 10000 };
int64_t currentProgressTime;
uint64_t progressDividerUnsigned{ uint64_t(progressDivider) };
for (;;)
{
buffer.Length(0);
auto readBuffer = co_await contentStream.ReadAsync(buffer, buffer.Capacity(), InputStreamOptions::None);
read = readBuffer.Length();
if (readBuffer.Length() == 0)
{
break;
}
co_await outputStream.WriteAsync(readBuffer);
totalRead += read;
if (progressInterval > 0)
{
currentProgressTime = winrt::clock::now().time_since_epoch().count() / 10000;
if(currentProgressTime - initialProgressTime >= progressInterval)
{
m_reactContext.CallJSFunction(L"RCTDeviceEventEmitter", L"emit", L"DownloadProgress",
JSValueObject{
{ "jobId", jobId },
{ "contentLength", contentLength && contentLength.Type() == PropertyType::UInt64
? JSValue(contentLength.Value()) : JSValue{nullptr} },
{ "bytesWritten", totalRead },
});
initialProgressTime = winrt::clock::now().time_since_epoch().count() / 10000;
}
}
else if (progressDivider <= 0)
{
m_reactContext.CallJSFunction(L"RCTDeviceEventEmitter", L"emit", L"DownloadProgress",
JSValueObject{
{ "jobId", jobId },
{ "contentLength", contentLength && contentLength.Type() == PropertyType::UInt64
? JSValue(contentLength.Value()) : JSValue{nullptr} },
{ "bytesWritten", totalRead },
});
}
else
{
if (totalRead * 100 / contentLengthForProgress >= progressDividerUnsigned ||
totalRead == contentLengthForProgress) {
m_reactContext.CallJSFunction(L"RCTDeviceEventEmitter", L"emit", L"DownloadProgress",
JSValueObject{
{ "jobId", jobId },
{ "contentLength", contentLength && contentLength.Type() == PropertyType::UInt64
? JSValue(contentLength.Value()) : JSValue{nullptr} },
{ "bytesWritten", totalRead },
});