-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathFileService.cs
More file actions
2483 lines (2231 loc) · 116 KB
/
Copy pathFileService.cs
File metadata and controls
2483 lines (2231 loc) · 116 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
#nullable disable
using BlazorBootstrap;
using Microsoft.AspNetCore.Components.Forms;
using Microsoft.AspNetCore.StaticFiles;
using MongoDB.Driver;
using Newtonsoft.Json;
using Syncfusion.Blazor.FileManager;
using Syncfusion.Blazor.Inputs;
using Syncfusion.EJ2.FileManager.PhysicalFileProvider;
using Syncfusion.EJ2.Linq;
using System.Dynamic;
using System.IO.Compression;
using System.IO.Hashing;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using TelegramDownloader.Data.db;
using TelegramDownloader.Models;
using TelegramDownloader.Services;
using TL;
namespace TelegramDownloader.Data
{
public class FileService : IFileService
{
public static readonly List<string> ImageExtensions = new List<string> { ".JPG", ".JPEG", ".JPE", ".BMP", ".GIF", ".PNG" };
public static string IMGDIR = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "img", "telegram");
public static string LOCALDIR = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "local");
public static string RELATIVELOCALDIR = System.IO.Path.Combine("local");
public static string STATICRELATIVELOCALDIR = System.IO.Path.Combine("local");
public static string TEMPDIR = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "local", "temp");
public static string TEMPORARYPDIR = System.IO.Path.Combine(Directory.GetCurrentDirectory(), "local", "temp", "_temp");
public static string RELATIVETEMPDIR = System.IO.Path.Combine("local", "temp");
public static readonly Dictionary<string, string> MIMETypesDictionary = new Dictionary<string, string>
{
{"ai", "application/postscript"},
{"aif", "audio/x-aiff"},
{"aifc", "audio/x-aiff"},
{"aiff", "audio/x-aiff"},
{"asc", "text/plain"},
{"atom", "application/atom+xml"},
{"au", "audio/basic"},
{"avi", "video/x-msvideo"},
{"bcpio", "application/x-bcpio"},
{"bin", "application/octet-stream"},
{"bmp", "image/bmp"},
{"cdf", "application/x-netcdf"},
{"cgm", "image/cgm"},
{"class", "application/octet-stream"},
{"cpio", "application/x-cpio"},
{"cpt", "application/mac-compactpro"},
{"csh", "application/x-csh"},
{"css", "text/css"},
{"dcr", "application/x-director"},
{"dif", "video/x-dv"},
{"dir", "application/x-director"},
{"djv", "image/vnd.djvu"},
{"djvu", "image/vnd.djvu"},
{"dll", "application/octet-stream"},
{"dmg", "application/octet-stream"},
{"dms", "application/octet-stream"},
{"doc", "application/msword"},
{"docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
{"dotx", "application/vnd.openxmlformats-officedocument.wordprocessingml.template"},
{"docm","application/vnd.ms-word.document.macroEnabled.12"},
{"dotm","application/vnd.ms-word.template.macroEnabled.12"},
{"dtd", "application/xml-dtd"},
{"dv", "video/x-dv"},
{"dvi", "application/x-dvi"},
{"dxr", "application/x-director"},
{"eps", "application/postscript"},
{"etx", "text/x-setext"},
{"exe", "application/octet-stream"},
{"ez", "application/andrew-inset"},
{"flac", "audio/flac"},
{"gif", "image/gif"},
{"gram", "application/srgs"},
{"grxml", "application/srgs+xml"},
{"gtar", "application/x-gtar"},
{"hdf", "application/x-hdf"},
{"hqx", "application/mac-binhex40"},
{"htm", "text/html"},
{"html", "text/html"},
{"ice", "x-conference/x-cooltalk"},
{"ico", "image/x-icon"},
{"ics", "text/calendar"},
{"ief", "image/ief"},
{"ifb", "text/calendar"},
{"iges", "model/iges"},
{"igs", "model/iges"},
{"jnlp", "application/x-java-jnlp-file"},
{"jp2", "image/jp2"},
{"jpe", "image/jpeg"},
{"jpeg", "image/jpeg"},
{"jpg", "image/jpeg"},
{"js", "application/x-javascript"},
{"kar", "audio/midi"},
{"latex", "application/x-latex"},
{"lha", "application/octet-stream"},
{"lzh", "application/octet-stream"},
{"m3u", "audio/x-mpegurl"},
{"m4a", "audio/mp4a-latm"},
{"m4b", "audio/mp4a-latm"},
{"m4p", "audio/mp4a-latm"},
{"m4u", "video/vnd.mpegurl"},
{"m4v", "video/x-m4v"},
{"mac", "image/x-macpaint"},
{"man", "application/x-troff-man"},
{"mathml", "application/mathml+xml"},
{"me", "application/x-troff-me"},
{"mesh", "model/mesh"},
{"mid", "audio/midi"},
{"midi", "audio/midi"},
{"mif", "application/vnd.mif"},
{"mkv", "video/x-matroska" },
{"mov", "video/quicktime"},
{"movie", "video/x-sgi-movie"},
{"mp2", "audio/mpeg"},
{"mp3", "audio/mpeg"},
{"mp4", "video/mp4"},
{"mpe", "video/mpeg"},
{"mpeg", "video/mpeg"},
{"mpg", "video/mpeg"},
{"mpga", "audio/mpeg"},
{"ms", "application/x-troff-ms"},
{"msh", "model/mesh"},
{"mxu", "video/vnd.mpegurl"},
{"nc", "application/x-netcdf"},
{"oda", "application/oda"},
{"ogg", "application/ogg"},
{"pbm", "image/x-portable-bitmap"},
{"pct", "image/pict"},
{"pdb", "chemical/x-pdb"},
{"pdf", "application/pdf"},
{"pgm", "image/x-portable-graymap"},
{"pgn", "application/x-chess-pgn"},
{"pic", "image/pict"},
{"pict", "image/pict"},
{"png", "image/png"},
{"pnm", "image/x-portable-anymap"},
{"pnt", "image/x-macpaint"},
{"pntg", "image/x-macpaint"},
{"ppm", "image/x-portable-pixmap"},
{"ppt", "application/vnd.ms-powerpoint"},
{"pptx","application/vnd.openxmlformats-officedocument.presentationml.presentation"},
{"potx","application/vnd.openxmlformats-officedocument.presentationml.template"},
{"ppsx","application/vnd.openxmlformats-officedocument.presentationml.slideshow"},
{"ppam","application/vnd.ms-powerpoint.addin.macroEnabled.12"},
{"pptm","application/vnd.ms-powerpoint.presentation.macroEnabled.12"},
{"potm","application/vnd.ms-powerpoint.template.macroEnabled.12"},
{"ppsm","application/vnd.ms-powerpoint.slideshow.macroEnabled.12"},
{"ps", "application/postscript"},
{"qt", "video/quicktime"},
{"qti", "image/x-quicktime"},
{"qtif", "image/x-quicktime"},
{"ra", "audio/x-pn-realaudio"},
{"ram", "audio/x-pn-realaudio"},
{"ras", "image/x-cmu-raster"},
{"rdf", "application/rdf+xml"},
{"rgb", "image/x-rgb"},
{"rm", "application/vnd.rn-realmedia"},
{"roff", "application/x-troff"},
{"rtf", "text/rtf"},
{"rtx", "text/richtext"},
{"sgm", "text/sgml"},
{"sgml", "text/sgml"},
{"sh", "application/x-sh"},
{"shar", "application/x-shar"},
{"silo", "model/mesh"},
{"sit", "application/x-stuffit"},
{"skd", "application/x-koan"},
{"skm", "application/x-koan"},
{"skp", "application/x-koan"},
{"skt", "application/x-koan"},
{"smi", "application/smil"},
{"smil", "application/smil"},
{"snd", "audio/basic"},
{"so", "application/octet-stream"},
{"spl", "application/x-futuresplash"},
{"src", "application/x-wais-source"},
{"sv4cpio", "application/x-sv4cpio"},
{"sv4crc", "application/x-sv4crc"},
{"svg", "image/svg+xml"},
{"swf", "application/x-shockwave-flash"},
{"t", "application/x-troff"},
{"tar", "application/x-tar"},
{"tcl", "application/x-tcl"},
{"tex", "application/x-tex"},
{"texi", "application/x-texinfo"},
{"texinfo", "application/x-texinfo"},
{"tif", "image/tiff"},
{"tiff", "image/tiff"},
{"tr", "application/x-troff"},
{"tsv", "text/tab-separated-values"},
{"txt", "text/plain"},
{"ustar", "application/x-ustar"},
{"vcd", "application/x-cdlink"},
{"vrml", "model/vrml"},
{"vxml", "application/voicexml+xml"},
{"wav", "audio/x-wav"},
{"wbmp", "image/vnd.wap.wbmp"},
{"wbmxl", "application/vnd.wap.wbxml"},
{"wma", "audio/wma"},
{"wml", "text/vnd.wap.wml"},
{"wmlc", "application/vnd.wap.wmlc"},
{"wmls", "text/vnd.wap.wmlscript"},
{"wmlsc", "application/vnd.wap.wmlscriptc"},
{"wrl", "model/vrml"},
{"xbm", "image/x-xbitmap"},
{"xht", "application/xhtml+xml"},
{"xhtml", "application/xhtml+xml"},
{"xls", "application/vnd.ms-excel"},
{"xml", "application/xml"},
{"xpm", "image/x-xpixmap"},
{"xsl", "application/xml"},
{"xlsx","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
{"xltx","application/vnd.openxmlformats-officedocument.spreadsheetml.template"},
{"xlsm","application/vnd.ms-excel.sheet.macroEnabled.12"},
{"xltm","application/vnd.ms-excel.template.macroEnabled.12"},
{"xlam","application/vnd.ms-excel.addin.macroEnabled.12"},
{"xlsb","application/vnd.ms-excel.sheet.binary.macroEnabled.12"},
{"xslt", "application/xslt+xml"},
{"xul", "application/vnd.mozilla.xul+xml"},
{"xwd", "image/x-xwindowdump"},
{"xyz", "chemical/x-xyz"},
{"zip", "application/zip"}
};
public static List<string> refreshChannelList = new List<string>();
protected PhysicalFileProvider operation = new PhysicalFileProvider();
protected ITelegramService _ts { get; set; }
protected IDbService _db { get; set; }
protected ILogger<IFileService> _logger { get; set; }
protected TransactionInfoService _tis { get; set; }
protected ToastService _toastService { get; set; }
protected ITaskPersistenceService _persistence { get; set; }
private static Mutex refreshMutex = new Mutex();
const int MaxSize = 1024 * 1024 * 1000; // 1GB
public FileService(ITelegramService ts, IDbService db, ILogger<IFileService> logger, TransactionInfoService tis, ToastService toastService, ITaskPersistenceService persistence)
{
_ts = ts;
_db = db;
_tis = tis;
_toastService = toastService;
_logger = logger;
_persistence = persistence;
createTempFolder();
}
private void createTempFolder()
{
if (!Directory.Exists(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "local", "temp")))
{
Directory.CreateDirectory(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "local", "temp"));
}
if (!Directory.Exists(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "local", "temp", "_temp")))
{
Directory.CreateDirectory(System.IO.Path.Combine(Directory.GetCurrentDirectory(), "local", "temp", "_temp"));
}
}
public void cleanTempFolder()
{
if (Directory.Exists(TEMPORARYPDIR))
{
Directory.Delete(TEMPORARYPDIR, true);
createTempFolder();
}
}
public async Task<BsonFileManagerModel> getItemById(string dbName, string id)
{
return await _db.getFileById(dbName, id);
}
public async Task<BsonFileManagerModel> getSharedItemById(string id, string collection)
{
return await _db.getFileById(DbService.SHARED_DB_NAME, id, collection);
}
public async Task<BsonSharedInfoModel> GetSharedInfoById(string id)
{
return await _db.getSingleFile(id);
}
public async Task DeleteShared(string id, string collectionId)
{
await _db.DeleteSharedCollection(collectionId);
await _db.DeleteSharedInfo(id);
}
public async Task<MemoryStream> exportAllData(string dbName)
{
var json = System.Text.Json.JsonSerializer.Serialize(await _db.getAllDatabaseData(dbName));
var bytes = System.Text.Encoding.UTF8.GetBytes(json);
return new MemoryStream(bytes);
}
public async Task<List<BsonFileManagerModel>> ShareFile(string dbName, string bsonId)
{
return await _db.getShareFolder(dbName, bsonId);
}
public async Task<FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>> SearchAsync(string dbName, string path, string searchText, string? collectionId = null)
{
FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent> response = new FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>();
var files = collectionId == null ? await _db.Search(dbName, path, searchText) : await _db.Search(dbName, path, searchText, collectionName: collectionId);
response.Files = files.Select(x => x.toFileManagerContent()).ToList();
return response;
}
public FileStream? ExistFileIntempFolder(string id)
{
String filePath = System.IO.Path.Combine(TEMPDIR, "_temp", id);
if (File.Exists(filePath))
{
return new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
}
return null;
}
public async Task<FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>> itemDeleteAsync(string dbName, ItemsDeleteEventArgs<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent> args)
{
_logger.LogInformation("Deleting items - DbName: {DbName}, Count: {Count}, Path: {Path}",
dbName, args.Files.Count(), args.Path);
string[] names = args.Files.Select(x => x.Name).ToArray();
bool isMyChannel = _ts.isMyChat(Convert.ToInt64(dbName));
// args.Response = await FileManagerService.Delete(args.Path, names, args.Files.ToArray());
foreach (Syncfusion.Blazor.FileManager.FileManagerDirectoryContent File in args.Files)
{
BsonFileManagerModel entry = await _db.getEntry(dbName, File.FilterPath, File.Name);
if (entry == null)
throw new Exception($"File {System.IO.Path.Combine(File.FilterPath, File.Name)} not found");
if (!entry.IsFile)
{
List<BsonFileManagerModel> allChilds = await _db.getAllChildFilesInDirectory(dbName, File.FilterPath + File.Name + "/");
foreach (BsonFileManagerModel child in allChilds)
{
await _db.deleteEntry(dbName, child.Id);
if (child.IsFile)
{
if (child.isSplit)
{
foreach (int id in child.ListMessageId)
{
if (isMyChannel && !await _db.existItemByTelegramId(dbName, id))
await _ts.deleteFile(dbName, id);
}
}
else
{
if (isMyChannel && !await _db.existItemByTelegramId(dbName, (int)child.MessageId))
await _ts.deleteFile(dbName, (int)child.MessageId);
}
}
//if (item.IsFile)
// await _db.subBytesToFolder(dbName, item.ParentId, item.Size);
}
await _db.deleteEntry(dbName, entry.Id);
// await _db.subBytesToFolder(dbName, entry.ParentId, entry.Size);
}
if (entry.IsFile)
{
await _db.deleteEntry(dbName, entry.Id);
if (entry.isSplit)
{
foreach (int id in entry.ListMessageId)
{
if (isMyChannel && !await _db.existItemByTelegramId(dbName, id))
await _ts.deleteFile(dbName, id);
}
}
else
{
if (isMyChannel && !await _db.existItemByTelegramId(dbName, (int)entry.MessageId))
await _ts.deleteFile(dbName, (int)entry.MessageId);
}
}
await _db.subBytesToFolder(dbName, entry.ParentId, entry.Size);
}
var firstFile = args.Files.FirstOrDefault();
if (firstFile != null)
{
await _db.checkAndSetDirectoryHasChild(dbName, firstFile.ParentId);
}
return await GetFilesPath(dbName, args.Path);
}
private async Task itemDeleteAsync(string dbName, string filterPath, string name, string parentId, string path)
{
BsonFileManagerModel entry = await _db.getEntry(dbName, filterPath, name);
if (entry == null)
throw new Exception($"File {System.IO.Path.Combine(filterPath, name)} not found");
if (!entry.IsFile)
{
List<BsonFileManagerModel> allChilds = await _db.getAllChildFilesInDirectory(dbName, filterPath + name + "/");
foreach (BsonFileManagerModel child in allChilds)
{
await _db.deleteEntry(dbName, child.Id);
if (child.IsFile)
{
if (child.isSplit)
{
foreach (int id in child.ListMessageId)
{
if (!await _db.existItemByTelegramId(dbName, id))
await _ts.deleteFile(dbName, id);
}
}
else
{
if (!await _db.existItemByTelegramId(dbName, (int)child.MessageId))
await _ts.deleteFile(dbName, (int)child.MessageId);
}
}
//if (item.IsFile)
// await _db.subBytesToFolder(dbName, item.ParentId, item.Size);
}
await _db.deleteEntry(dbName, entry.Id);
// await _db.subBytesToFolder(dbName, entry.ParentId, entry.Size);
}
if (entry.IsFile)
{
await _db.deleteEntry(dbName, entry.Id);
if (entry.isSplit)
{
foreach (int id in entry.ListMessageId)
{
if (!await _db.existItemByTelegramId(dbName, id))
await _ts.deleteFile(dbName, id);
}
}
else
{
if (!await _db.existItemByTelegramId(dbName, (int)entry.MessageId))
await _ts.deleteFile(dbName, (int)entry.MessageId);
}
}
await _db.subBytesToFolder(dbName, entry.ParentId, entry.Size);
await _db.checkAndSetDirectoryHasChild(dbName, parentId);
}
public async Task oneItemDeleteAsync(string dbName, Syncfusion.Blazor.FileManager.FileManagerDirectoryContent File)
{
BsonFileManagerModel entry = await _db.getEntry(dbName, File.FilterPath, File.Name);
if (entry == null)
throw new Exception($"File {System.IO.Path.Combine(File.FilterPath, File.Name)} not found");
if (!entry.IsFile)
{
List<BsonFileManagerModel> allChilds = await _db.getAllChildFilesInDirectory(dbName, File.FilterPath + File.Name + "/");
foreach (BsonFileManagerModel child in allChilds)
{
if (child.IsFile)
{
if (child.isSplit)
{
foreach (int id in child.ListMessageId)
{
if (!await _db.existItemByTelegramId(dbName, id))
await _ts.deleteFile(dbName, id);
}
}
else
{
if (!await _db.existItemByTelegramId(dbName, (int)child.MessageId))
await _ts.deleteFile(dbName, (int)child.MessageId);
}
}
await _db.deleteEntry(dbName, child.Id);
//if (item.IsFile)
// await _db.subBytesToFolder(dbName, item.ParentId, item.Size);
}
await _db.subBytesToFolder(dbName, entry.ParentId, entry.Size);
}
if (entry.IsFile)
if (entry.isSplit)
{
foreach (int id in entry.ListMessageId)
{
if (!await _db.existItemByTelegramId(dbName, id))
await _ts.deleteFile(dbName, id);
}
}
else
{
if (!await _db.existItemByTelegramId(dbName, (int)entry.MessageId))
await _ts.deleteFile(dbName, (int)entry.MessageId);
}
await _db.deleteEntry(dbName, entry.Id);
await _db.subBytesToFolder(dbName, entry.ParentId, entry.Size);
}
public async Task<FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>> RenameFileOrFolder(string dbName, Syncfusion.Blazor.FileManager.FileManagerDirectoryContent file, string newName)
{
FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent> fm = new FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>();
var lista = new List<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>();
lista.Add((await _db.updateName(dbName, file.Id, newName, file.Name, file.IsFile, file.FilterPath)).toFileManagerContent());
fm.Files = lista;
return fm;
}
public async Task<FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>> CopyItems(string dbName, ItemsMoveEventArgs<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent> args)
{
try
{
FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent> fm = new FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>();
var lista = new List<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>();
foreach (var item in args.Files)
{
if (!item.IsFile)
{
// Pass args.IsCopy to handle internal files correctly (delete originals when moving)
var result = await copyAllDirectoryFiles(dbName, item.Id, args.TargetData, args.TargetPath + item.Name + "/", args.IsCopy);
lista.Add(result.toFileManagerContentInCopy());
// Note: copyAllDirectoryFiles now handles deletion of the folder when IsCopy=false
}
else
{
var result = await _db.copyItem(dbName, item.Id, args.TargetData, args.TargetPath, item.IsFile);
lista.Add(result.toFileManagerContentInCopy());
if (!args.IsCopy)
{
await _db.deleteEntry(dbName, item.Id);
}
}
await _db.addBytesToFolder(dbName, item.ParentId, item.Size);
}
fm.Files = lista;
return fm;
}
catch (Exception e)
{
_logger.LogError(e, "Error on CopyItems");
if (e is MongoWriteException ex)
{
if (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
NotificationModel nm = new NotificationModel();
nm.sendEvent(new Notification("The file exist in the directory", "Duplicate", NotificationTypes.Error));
}
}
throw e;
}
}
public async Task<FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>> CopyOrMoveItems(string dbName, Syncfusion.Blazor.FileManager.FileManagerDirectoryContent[] files, string targetPath, Syncfusion.Blazor.FileManager.FileManagerDirectoryContent targetData, bool isCopy)
{
try
{
FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent> fm = new FileManagerResponse<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>();
var lista = new List<Syncfusion.Blazor.FileManager.FileManagerDirectoryContent>();
foreach (var item in files)
{
if (!item.IsFile)
{
// Pass isCopy to handle internal files correctly (delete originals when moving)
var result = await copyAllDirectoryFiles(dbName, item.Id, targetData, targetPath + item.Name + "/", isCopy);
lista.Add(result.toFileManagerContentInCopy());
// Note: copyAllDirectoryFiles now handles deletion of the folder when isCopy=false
}
else
{
var result = await _db.copyItem(dbName, item.Id, targetData, targetPath, item.IsFile);
lista.Add(result.toFileManagerContentInCopy());
if (!isCopy)
{
await _db.deleteEntry(dbName, item.Id);
}
}
await _db.addBytesToFolder(dbName, item.ParentId, item.Size);
}
fm.Files = lista;
return fm;
}
catch (Exception e)
{
_logger.LogError(e, "Error on CopyOrMoveItems");
if (e is MongoWriteException ex)
{
if (ex.WriteError.Category == ServerErrorCategory.DuplicateKey)
{
NotificationModel nm = new NotificationModel();
nm.sendEvent(new Notification("The file exist in the directory", "Duplicate", NotificationTypes.Error));
}
}
throw e;
}
}
private async Task<BsonFileManagerModel> copyAllDirectoryFiles(string dbName, string idfolder, Syncfusion.Blazor.FileManager.FileManagerDirectoryContent target, string targetPath, bool isCopy = true)
{
var result = await _db.copyItem(dbName, idfolder, target, targetPath, false);
var files = await _db.getAllFilesInDirectoryById(dbName, idfolder);
foreach (var file in files)
{
if (file.IsFile)
{
await _db.copyItem(dbName, file.Id, result.toFileManagerContent(), targetPath, file.IsFile);
if (!isCopy)
{
await _db.deleteEntry(dbName, file.Id);
}
}
else
{
// Pass isCopy to recursive call to handle nested folders correctly
await copyAllDirectoryFiles(dbName, file.Id, result.toFileManagerContent(), targetPath + file.Name + "/", isCopy);
// Note: recursive call handles deletion when isCopy=false, no need to delete here
}
}
if (!isCopy)
{
await _db.deleteEntry(dbName, idfolder);
}
return result;
}
public async Task<MemoryStream> getImage(string dbName, string path, string fileName, MemoryStream ms = null, string? collectionId = null)
{
try
{
BsonFileManagerModel file = collectionId == null ? _db.getFileByPathSync(dbName, path + fileName) : _db.getFileByPathSync(dbName, path + fileName, collectionId);
string currentFilePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), RELATIVELOCALDIR, dbName + path);
Directory.CreateDirectory(currentFilePath);
if (file == null)
throw new Exception($"{path} does not exist");
if (file.isSplit)
{
int i = 1;
List<string> splitPaths = new List<string>();
foreach (int messageId in file.ListMessageId)
{
string filePathPart = System.IO.Path.Combine(currentFilePath, $"({i})" + fileName);
await downloadFromTelegram(dbName, messageId, filePathPart);
splitPaths.Add(filePathPart);
i++;
}
await mergeFileStreamAsync(splitPaths, System.IO.Path.Combine(currentFilePath, fileName));
foreach (string filePath in splitPaths)
{
File.Delete(filePath);
}
using (FileStream ff = new FileStream(System.IO.Path.Combine(currentFilePath, fileName), FileMode.Open, FileAccess.Read, FileShare.Read))
{
ms = await ToMemoryStreamAsync(ff);
}
File.Delete(System.IO.Path.Combine(currentFilePath, fileName));
return ms;
}
else
{
return await downloadFromTelegramAndReturn(dbName, (int)file.MessageId, System.IO.Path.Combine(currentFilePath, fileName));
}
}
catch (Exception ex)
{
_logger.LogError(ex, "Error on getImage");
throw ex;
}
}
public async Task downloadFile(string dbName, string path, List<string> files, string targetPath, string? collectionId = null, string? channelId = null)
{
_logger.LogInformation("Starting download - DbName: {DbName}, Path: {Path}, FilesCount: {Count}, TargetPath: {TargetPath}",
dbName, path, files.Count, targetPath);
NotificationModel nm = new NotificationModel();
try
{
nm.sendEvent(new Notification("Download Start", "Download", NotificationTypes.Info));
if (targetPath == null) targetPath = path;
foreach (string fileName in files)
{
WaitingTime wt = new WaitingTime();
BsonFileManagerModel file = collectionId == null ? _db.getFileByPathSync(dbName, path + fileName) : _db.getFileByPathSync(dbName, path + fileName, collectionId);
string currentFilePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), RELATIVETEMPDIR, targetPath[0] == '/' ? targetPath.Substring(1) : targetPath);
if (file == null)
{
Directory.CreateDirectory(System.IO.Path.Combine(currentFilePath, fileName));
var filesInDir = collectionId == null ? await _db.getAllFilesInDirectoryPath(dbName, path) : await _db.getAllFilesInDirectoryPath(dbName, path, collectionId);
if (filesInDir.Count() > 0)
{
await downloadFile(dbName, path.EndsWith(fileName + "/") ? path : System.IO.Path.Combine(path, fileName) + "/", filesInDir.Select(x => x.Name).ToList(), System.IO.Path.Combine(targetPath, fileName), collectionId, channelId);
}
}
else
{
Directory.CreateDirectory(currentFilePath);
if (file == null)
throw new Exception($"{targetPath} does not exist");
if (file.isSplit)
{
int i = 1;
List<string> splitPaths = new List<string>();
foreach (int messageId in file.ListMessageId)
{
string filePathPart = System.IO.Path.Combine(currentFilePath, $"({i})" + fileName);
await downloadFromTelegram(channelId == null ? dbName : channelId, messageId, filePathPart, file);
splitPaths.Add(filePathPart);
i++;
}
await mergeFileStreamAsync(splitPaths, System.IO.Path.Combine(currentFilePath, fileName));
foreach (string filePath in splitPaths)
{
File.Delete(filePath);
}
}
else
{
await downloadFromTelegram(channelId == null ? dbName : channelId, (int)file.MessageId, System.IO.Path.Combine(currentFilePath, fileName), file);
}
await wt.Sleep();
}
}
nm.sendEvent(new Notification("downloads have been completed", "Download completed", NotificationTypes.Success));
}
catch (Exception ex)
{
_logger.LogError(ex, "Error downloading files");
nm.sendEvent(new Notification("Error at download.", "Download Error", NotificationTypes.Error));
throw ex;
}
}
public virtual async Task downloadFile(string dbName, List<FileManagerDirectoryContent> files, string targetPath, string? collectionId = null, string? channelId = null)
{
NotificationModel nm = new NotificationModel();
try
{
foreach(FileManagerDirectoryContent file in files)
{
_logger.LogInformation($"Download files to {targetPath} :: {file.Name}");
}
nm.sendEvent(new Notification("Download Start", "Download", NotificationTypes.Info));
string currentTargetPath = targetPath == null ? "/" : targetPath;
// if (targetPath == null) targetPath = "/"; //path.Replace("\\", "/");
foreach (var itemFile in files)
{
var filterPath = itemFile.FilterPath == "Files/" ? "/" : itemFile.FilterPath;
BsonFileManagerModel file = null;
if (itemFile.Id != null)
file = collectionId == null ? await _db.getFileById(dbName, itemFile.Id) : await _db.getFileById(dbName, itemFile.Id, collectionId);
else
file = collectionId == null ? _db.getFileByPathSync(dbName, filterPath.Replace("\\", "/") + itemFile.Name) : _db.getFileByPathSync(dbName, filterPath.Replace("\\", "/") + itemFile.Name, collectionId);
string currentFilePath = currentTargetPath;
if (!itemFile.IsFile)
{
Directory.CreateDirectory(System.IO.Path.Combine(currentFilePath, itemFile.Name));
var filesInDir = collectionId == null ? await _db.getAllFilesInDirectoryPath(dbName, itemFile.FilterPath == "" ? "/" : itemFile.FilterPath + itemFile.Name + "/") : await _db.getAllFilesInDirectoryPath(dbName, itemFile.FilterPath == "" ? "/" : itemFile.FilterPath + itemFile.Name + "/", collectionId);
if (filesInDir.Count() > 0)
{
await downloadFile(dbName, filesInDir.Select(x => x.toFileManagerContent()).ToList(), System.IO.Path.Combine(currentTargetPath, itemFile.Name).Replace("\\", "/"), collectionId, channelId);
}
}
else
{
Directory.CreateDirectory(currentFilePath);
if (file == null)
throw new Exception($"{currentTargetPath} does not exist");
if (file.isSplit)
{
downloadSplitFiles(itemFile, file, currentFilePath, channelId == null ? dbName : channelId);
}
else
{
await downloadFromTelegram(channelId == null ? dbName : channelId, (int)file.MessageId, System.IO.Path.Combine(currentFilePath, itemFile.Name), file);
}
}
}
nm.sendEvent(new Notification("downloads have been completed", "Download completed", NotificationTypes.Success));
}
catch (Exception ex)
{
_logger.LogError(ex, "Error on downloadFile");
nm.sendEvent(new Notification("Error at download.", "Download Error", NotificationTypes.Error));
throw ex;
}
}
public virtual async Task downloadSplitFiles(FileManagerDirectoryContent itemFile, BsonFileManagerModel file, string currentFilePath, string dbName)
{
int i = 1;
List<string> splitPaths = new List<string>();
foreach (int messageId in file.ListMessageId)
{
string filePathPart = Path.Combine(currentFilePath, $"({i})" + itemFile.Name);
await downloadFromTelegram(dbName, messageId, filePathPart, file, true, Path.Combine(currentFilePath, itemFile.Name));
splitPaths.Add(filePathPart);
i++;
}
await mergeFileStreamAsync(splitPaths, Path.Combine(currentFilePath, itemFile.Name));
foreach (string filePath in splitPaths)
{
File.Delete(filePath);
}
}
private async Task<MemoryStream> downloadFromTelegramAndReturn(string dbName, int messageId, string destPath, MemoryStream ms = null)
{
TL.Message m = await _ts.getMessageFile(dbName, messageId);
ChatMessages cm = new ChatMessages();
cm.message = m;
cm.user = null;
cm.isDocument = false;
if (m.media is MessageMediaDocument { document: Document document })
{
cm.isDocument = true;
}
if (ms == null)
{
ms = new MemoryStream();
}
await _ts.DownloadFileAndReturn(cm, ms: ms);
ms.Position = 0;
return ms;
}
public static void functionCalll(string dbName, int messageId, string destPath)
{
}
public virtual async Task downloadFromTelegram(string dbName, int messageId, string destPath, BsonFileManagerModel file = null, bool shouldWait = false, string path = null)
{
_logger.LogDebug("Queueing download from Telegram - DbName: {DbName}, MessageId: {MessageId}, DestPath: {DestPath}",
dbName, messageId, destPath);
DownloadModel model = new DownloadModel();
model.path = path ?? destPath;
model.tis = _tis;
if (file != null)
{
model.name = file.Name;
model._size = file.Size;
}
model._transmitted = 0;
model.callbacks = new Callbacks();
try
{
model.channelName = _ts.getChatName(Convert.ToInt64(dbName));
} catch {
model.channelName = "Public or Shared";
}
var tcs = new TaskCompletionSource<bool>();
EventHandler handler = null;
handler = (sender, args) =>
{
if (model.state == StateTask.Completed)
{
model.EventStatechanged -= handler;
tcs.SetResult(true);
}
};
model.EventStatechanged += handler;
model.callbacks.callback = async () => await DownloadFileNow(dbName, messageId, destPath, model);
_tis.addToPendingDownloadList(model, atFirst: shouldWait);
// Espera hasta que el estado sea "Completed"
if (shouldWait)
await tcs.Task;
}
public async Task DownloadFileFromChat(ChatMessages message, string fileName = null, string folder = null, DownloadModel model = null)
{
if (model == null)
{
model = new DownloadModel();
model.tis = _tis;
}
model.name = fileName;
if (message.message.media is MessageMediaDocument { document: Document document })
{
model._size = document.size;
}
if (message.user is TL.Channel channel)
{
model.channelName = channel.Title;
}
model._transmitted = 0;
model.channel = message.user;
//model.channelName = message.user.;
model.callbacks = new Callbacks();
model.callbacks.callback = async () => await _ts.DownloadFile(message,fileName, folder, model);
_tis.addToPendingDownloadList(model);
}
public async Task DownloadFileNow(string dbName, int messageId, string destPath, DownloadModel model)
{
TL.Message m = await _ts.getMessageFile(dbName, messageId);
ChatMessages cm = new ChatMessages();
cm.message = m;
model.startDate = DateTime.Now;
cm.user = null;
cm.isDocument = false;
if (m.media is MessageMediaDocument { document: Document document })
{
cm.isDocument = true;
}
using (FileStream fs = new FileStream(destPath, FileMode.Create))
await _ts.DownloadFileAndReturn(cm, ms: fs, model: model);
}
public async Task downloadFileToServer(string dbName, string path, string destPath)
{
try
{
BsonFileManagerModel file = _db.getFileByPathSync(dbName, path);
if (file == null)
throw new Exception($"{path} does not exist");
TL.Message m = await _ts.getMessageFile(dbName, (int)file.MessageId);
ChatMessages cm = new ChatMessages();
cm.message = m;
cm.user = null;
cm.isDocument = false;
if (m.media is MessageMediaDocument { document: Document document })
{
cm.isDocument = true;
}
using (FileStream fs = new FileStream(destPath, FileMode.Create))
await _ts.DownloadFileAndReturn(cm, ms: fs);
}
catch (Exception ex)
{
_logger.LogError(ex, "Error on downloadFileToServer");
throw ex;
}
}
public async Task importData(string dbName, string path, GenericNotificationProgressModel gnp)
{
try
{
await _db.resetDatabase(dbName);
using (StreamReader r = new StreamReader(path))
{
string json = r.ReadToEnd();
List<BsonFileManagerModel> items = JsonConvert.DeserializeObject<List<BsonFileManagerModel>>(json);
int total = items.Count();
int completed = 0;
gnp.sendMessage(total, completed);
foreach (BsonFileManagerModel item in items)
{
//BsonFileManagerModel prev = await _db.getFileById(dbName, item.Id);
//if (prev != null)
//{
// if (prev.DateModified < item.DateModified || string.IsNullOrEmpty(prev.FilePath))
// {
// await _db.deleteEntry(dbName, item.Id);
// await _db.createEntry(dbName, item);
// continue;
// }
//} else
//{
// await _db.createEntry(dbName, item);
//}
await _db.createEntry(dbName, item);
gnp.sendMessage(total, ++completed);
}