-
Notifications
You must be signed in to change notification settings - Fork 106
/
Copy pathProgram.cs
3203 lines (2912 loc) · 139 KB
/
Program.cs
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
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using OF_DL.Entities;
using OF_DL.Entities.Archived;
using OF_DL.Entities.Messages;
using OF_DL.Entities.Post;
using OF_DL.Entities.Purchased;
using OF_DL.Entities.Streams;
using OF_DL.Enumerations;
using OF_DL.Enumurations;
using OF_DL.Helpers;
using Octokit;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Spectre.Console;
using System.IO;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using static OF_DL.Entities.Messages.Messages;
using Akka.Configuration;
using System.Text;
namespace OF_DL;
public class Program
{
public int MAX_AGE = 0;
public static List<long> paid_post_ids = new();
private static bool clientIdBlobMissing = false;
private static bool devicePrivateKeyMissing = false;
private static Entities.Config? config = null;
private static Auth? auth = null;
private static LoggingLevelSwitch levelSwitch = new LoggingLevelSwitch();
private static async Task LoadAuthFromBrowser()
{
bool runningInDocker = Environment.GetEnvironmentVariable("OFDL_DOCKER") != null;
try
{
AuthHelper authHelper = new();
Task setupBrowserTask = authHelper.SetupBrowser(runningInDocker);
Task.Delay(1000).Wait();
if (!setupBrowserTask.IsCompleted)
{
AnsiConsole.MarkupLine($"[yellow]Downloading dependencies. Please wait ...[/]");
}
setupBrowserTask.Wait();
Task<Auth?> getAuthTask = authHelper.GetAuthFromBrowser();
Task.Delay(5000).Wait();
if (!getAuthTask.IsCompleted)
{
if (runningInDocker)
{
AnsiConsole.MarkupLine(
"[yellow]In your web browser, navigate to the port forwarded from your docker container.[/]");
AnsiConsole.MarkupLine(
"[yellow]For instance, if your docker run command included \"-p 8080:8080\", open your web browser to \"http://localhost:8080\".[/]");
AnsiConsole.MarkupLine("[yellow]Once on that webpage, please use it to log in to your OF account. Do not navigate away from the page.[/]");
}
else
{
AnsiConsole.MarkupLine($"[yellow]In the new window that has opened, please log in to your OF account. Do not close the window or tab. Do not navigate away from the page.[/]\n");
AnsiConsole.MarkupLine($"[yellow]Note: Some users have reported that \"Sign in with Google\" has not been working with the new authentication method.[/]");
AnsiConsole.MarkupLine($"[yellow]If you use this method or encounter other issues while logging in, use one of the legacy authentication methods documented here:[/]");
AnsiConsole.MarkupLine($"[link]https://sim0n00ps.github.io/OF-DL/docs/config/auth#legacy-methods[/]");
}
}
auth = await getAuthTask;
}
catch (Exception e)
{
AnsiConsole.MarkupLine($"\n[red]Authentication failed. Be sure to log into to OF using the new window that opened automatically.[/]");
AnsiConsole.MarkupLine($"[red]The window will close automatically when the authentication process is finished.[/]");
AnsiConsole.MarkupLine($"[red]If the problem persists, you may want to try using a legacy authentication method documented here:[/]\n");
AnsiConsole.MarkupLine($"[link]https://sim0n00ps.github.io/OF-DL/docs/config/auth#legacy-methods[/]\n");
AnsiConsole.MarkupLine($"[red]Press any key to exit.[/]");
Log.Error(e, "auth invalid after attempt to get auth from browser");
Environment.Exit(2);
}
if (auth == null)
{
AnsiConsole.MarkupLine($"\n[red]Authentication failed. Be sure to log into to OF using the new window that opened automatically.[/]");
AnsiConsole.MarkupLine($"[red]The window will close automatically when the authentication process is finished.[/]");
AnsiConsole.MarkupLine($"[red]If the problem persists, you may want to try using a legacy authentication method documented here:[/]\n");
AnsiConsole.MarkupLine($"[link]https://sim0n00ps.github.io/OF-DL/docs/config/auth#legacy-methods[/]\n");
AnsiConsole.MarkupLine($"[red]Press any key to exit.[/]");
Log.Error("auth invalid after attempt to get auth from browser");
Environment.Exit(2);
}
else
{
await File.WriteAllTextAsync("auth.json", JsonConvert.SerializeObject(auth, Formatting.Indented));
}
}
public static async Task Main(string[] args)
{
bool cliNonInteractive = false;
try
{
levelSwitch.MinimumLevel = LogEventLevel.Error; //set initial level (until we've read from config)
Log.Logger = new LoggerConfiguration()
.MinimumLevel.ControlledBy(levelSwitch)
.WriteTo.File("logs/OFDL.txt", rollingInterval: RollingInterval.Day)
.CreateLogger();
AnsiConsole.Write(new FigletText("Welcome to OF-DL").Color(Color.Red));
//Remove config.json and convert to config.conf
if (File.Exists("config.json"))
{
AnsiConsole.Markup("[green]config.json located successfully!\n[/]");
try
{
string jsonText = File.ReadAllText("config.json");
var jsonConfig = JsonConvert.DeserializeObject<Entities.Config>(jsonText);
if (jsonConfig != null)
{
var hoconConfig = new StringBuilder();
hoconConfig.AppendLine("# External Tools");
hoconConfig.AppendLine("External {");
hoconConfig.AppendLine($" FFmpegPath = \"{jsonConfig.FFmpegPath}\"");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Download Settings");
hoconConfig.AppendLine("Download {");
hoconConfig.AppendLine(" Media {");
hoconConfig.AppendLine($" DownloadAvatarHeaderPhoto = {jsonConfig.DownloadAvatarHeaderPhoto.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadPaidPosts = {jsonConfig.DownloadPaidPosts.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadPosts = {jsonConfig.DownloadPosts.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadArchived = {jsonConfig.DownloadArchived.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadStreams = {jsonConfig.DownloadStreams.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadStories = {jsonConfig.DownloadStories.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadHighlights = {jsonConfig.DownloadHighlights.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadMessages = {jsonConfig.DownloadMessages.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadPaidMessages = {jsonConfig.DownloadPaidMessages.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadImages = {jsonConfig.DownloadImages.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadVideos = {jsonConfig.DownloadVideos.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadAudios = {jsonConfig.DownloadAudios.ToString().ToLower()}");
hoconConfig.AppendLine(" }");
hoconConfig.AppendLine($" IgnoreOwnMessages = {jsonConfig.IgnoreOwnMessages.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadPostsIncrementally = {jsonConfig.DownloadPostsIncrementally.ToString().ToLower()}");
hoconConfig.AppendLine($" BypassContentForCreatorsWhoNoLongerExist = {jsonConfig.BypassContentForCreatorsWhoNoLongerExist.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadDuplicatedMedia = {jsonConfig.DownloadDuplicatedMedia.ToString().ToLower()}");
hoconConfig.AppendLine($" SkipAds = {jsonConfig.SkipAds.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadPath = \"{jsonConfig.DownloadPath}\"");
hoconConfig.AppendLine($" DownloadOnlySpecificDates = {jsonConfig.DownloadOnlySpecificDates.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadDateSelection = \"{jsonConfig.DownloadDateSelection.ToString().ToLower()}\"");
hoconConfig.AppendLine($" CustomDate = \"{jsonConfig.CustomDate?.ToString("yyyy-MM-dd")}\"");
hoconConfig.AppendLine($" ShowScrapeSize = {jsonConfig.ShowScrapeSize.ToString().ToLower()}");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# File Settings");
hoconConfig.AppendLine("File {");
hoconConfig.AppendLine($" PaidPostFileNameFormat = \"{jsonConfig.PaidPostFileNameFormat}\"");
hoconConfig.AppendLine($" PostFileNameFormat = \"{jsonConfig.PostFileNameFormat}\"");
hoconConfig.AppendLine($" PaidMessageFileNameFormat = \"{jsonConfig.PaidMessageFileNameFormat}\"");
hoconConfig.AppendLine($" MessageFileNameFormat = \"{jsonConfig.MessageFileNameFormat}\"");
hoconConfig.AppendLine($" RenameExistingFilesWhenCustomFormatIsSelected = {jsonConfig.RenameExistingFilesWhenCustomFormatIsSelected.ToString().ToLower()}");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Creator-Specific Configurations");
hoconConfig.AppendLine("CreatorConfigs {");
foreach (var creatorConfig in jsonConfig.CreatorConfigs)
{
hoconConfig.AppendLine($" \"{creatorConfig.Key}\" {{");
hoconConfig.AppendLine($" PaidPostFileNameFormat = \"{creatorConfig.Value.PaidPostFileNameFormat}\"");
hoconConfig.AppendLine($" PostFileNameFormat = \"{creatorConfig.Value.PostFileNameFormat}\"");
hoconConfig.AppendLine($" PaidMessageFileNameFormat = \"{creatorConfig.Value.PaidMessageFileNameFormat}\"");
hoconConfig.AppendLine($" MessageFileNameFormat = \"{creatorConfig.Value.MessageFileNameFormat}\"");
hoconConfig.AppendLine(" }");
}
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Folder Settings");
hoconConfig.AppendLine("Folder {");
hoconConfig.AppendLine($" FolderPerPaidPost = {jsonConfig.FolderPerPaidPost.ToString().ToLower()}");
hoconConfig.AppendLine($" FolderPerPost = {jsonConfig.FolderPerPost.ToString().ToLower()}");
hoconConfig.AppendLine($" FolderPerPaidMessage = {jsonConfig.FolderPerPaidMessage.ToString().ToLower()}");
hoconConfig.AppendLine($" FolderPerMessage = {jsonConfig.FolderPerMessage.ToString().ToLower()}");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Subscription Settings");
hoconConfig.AppendLine("Subscriptions {");
hoconConfig.AppendLine($" IncludeExpiredSubscriptions = {jsonConfig.IncludeExpiredSubscriptions.ToString().ToLower()}");
hoconConfig.AppendLine($" IncludeRestrictedSubscriptions = {jsonConfig.IncludeRestrictedSubscriptions.ToString().ToLower()}");
hoconConfig.AppendLine($" IgnoredUsersListName = \"{jsonConfig.IgnoredUsersListName}\"");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Interaction Settings");
hoconConfig.AppendLine("Interaction {");
hoconConfig.AppendLine($" NonInteractiveMode = {jsonConfig.NonInteractiveMode.ToString().ToLower()}");
hoconConfig.AppendLine($" NonInteractiveModeListName = \"{jsonConfig.NonInteractiveModeListName}\"");
hoconConfig.AppendLine($" NonInteractiveModePurchasedTab = {jsonConfig.NonInteractiveModePurchasedTab.ToString().ToLower()}");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Performance Settings");
hoconConfig.AppendLine("Performance {");
hoconConfig.AppendLine($" Timeout = {(jsonConfig.Timeout.HasValue ? jsonConfig.Timeout.Value : -1)}");
hoconConfig.AppendLine($" LimitDownloadRate = {jsonConfig.LimitDownloadRate.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadLimitInMbPerSec = {jsonConfig.DownloadLimitInMbPerSec}");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Logging/Debug Settings");
hoconConfig.AppendLine("Logging {");
hoconConfig.AppendLine($" LoggingLevel = \"{jsonConfig.LoggingLevel.ToString().ToLower()}\"");
hoconConfig.AppendLine("}");
File.WriteAllText("config.conf", hoconConfig.ToString());
File.Delete("config.json");
AnsiConsole.Markup("[green]config.conf created successfully from config.json!\n[/]");
}
}
catch (Exception e)
{
Console.WriteLine(e);
AnsiConsole.MarkupLine($"\n[red]config.conf is not valid, check your syntax![/]\n");
AnsiConsole.MarkupLine($"[red]Press any key to exit.[/]");
Log.Error("config.conf processing failed.", e.Message);
if (!cliNonInteractive)
{
Console.ReadKey();
}
Environment.Exit(3);
}
}
//I dont like it... but I needed to move config here, otherwise the logging level gets changed too late after we missed a whole bunch of important info
if (File.Exists("config.conf"))
{
AnsiConsole.Markup("[green]config.conf located successfully!\n[/]");
try
{
string hoconText = File.ReadAllText("config.conf");
var hoconConfig = ConfigurationFactory.ParseString(hoconText);
config = new Entities.Config
{
// FFmpeg Settings
FFmpegPath = hoconConfig.GetString("External.FFmpegPath"),
// Download Settings
DownloadAvatarHeaderPhoto = hoconConfig.GetBoolean("Download.Media.DownloadAvatarHeaderPhoto"),
DownloadPaidPosts = hoconConfig.GetBoolean("Download.Media.DownloadPaidPosts"),
DownloadPosts = hoconConfig.GetBoolean("Download.Media.DownloadPosts"),
DownloadArchived = hoconConfig.GetBoolean("Download.Media.DownloadArchived"),
DownloadStreams = hoconConfig.GetBoolean("Download.Media.DownloadStreams"),
DownloadStories = hoconConfig.GetBoolean("Download.Media.DownloadStories"),
DownloadHighlights = hoconConfig.GetBoolean("Download.Media.DownloadHighlights"),
DownloadMessages = hoconConfig.GetBoolean("Download.Media.DownloadMessages"),
DownloadPaidMessages = hoconConfig.GetBoolean("Download.Media.DownloadPaidMessages"),
DownloadImages = hoconConfig.GetBoolean("Download.Media.DownloadImages"),
DownloadVideos = hoconConfig.GetBoolean("Download.Media.DownloadVideos"),
DownloadAudios = hoconConfig.GetBoolean("Download.Media.DownloadAudios"),
IgnoreOwnMessages = hoconConfig.GetBoolean("Download.IgnoreOwnMessages"),
DownloadPostsIncrementally = hoconConfig.GetBoolean("Download.DownloadPostsIncrementally"),
BypassContentForCreatorsWhoNoLongerExist = hoconConfig.GetBoolean("Download.BypassContentForCreatorsWhoNoLongerExist"),
DownloadDuplicatedMedia = hoconConfig.GetBoolean("Download.DownloadDuplicatedMedia"),
SkipAds = hoconConfig.GetBoolean("Download.SkipAds"),
DownloadPath = hoconConfig.GetString("Download.DownloadPath"),
DownloadOnlySpecificDates = hoconConfig.GetBoolean("Download.DownloadOnlySpecificDates"),
DownloadDateSelection = Enum.Parse<DownloadDateSelection>(hoconConfig.GetString("Download.DownloadDateSelection"), true),
CustomDate = !string.IsNullOrWhiteSpace(hoconConfig.GetString("Download.CustomDate")) ? DateTime.Parse(hoconConfig.GetString("Download.CustomDate")) : null,
ShowScrapeSize = hoconConfig.GetBoolean("Download.ShowScrapeSize"),
// File Settings
PaidPostFileNameFormat = hoconConfig.GetString("File.PaidPostFileNameFormat"),
PostFileNameFormat = hoconConfig.GetString("File.PostFileNameFormat"),
PaidMessageFileNameFormat = hoconConfig.GetString("File.PaidMessageFileNameFormat"),
MessageFileNameFormat = hoconConfig.GetString("File.MessageFileNameFormat"),
RenameExistingFilesWhenCustomFormatIsSelected = hoconConfig.GetBoolean("File.RenameExistingFilesWhenCustomFormatIsSelected"),
// Folder Settings
FolderPerPaidPost = hoconConfig.GetBoolean("Folder.FolderPerPaidPost"),
FolderPerPost = hoconConfig.GetBoolean("Folder.FolderPerPost"),
FolderPerPaidMessage = hoconConfig.GetBoolean("Folder.FolderPerPaidMessage"),
FolderPerMessage = hoconConfig.GetBoolean("Folder.FolderPerMessage"),
// Subscription Settings
IncludeExpiredSubscriptions = hoconConfig.GetBoolean("Subscriptions.IncludeExpiredSubscriptions"),
IncludeRestrictedSubscriptions = hoconConfig.GetBoolean("Subscriptions.IncludeRestrictedSubscriptions"),
IgnoredUsersListName = hoconConfig.GetString("Subscriptions.IgnoredUsersListName"),
// Interaction Settings
NonInteractiveMode = hoconConfig.GetBoolean("Interaction.NonInteractiveMode"),
NonInteractiveModeListName = hoconConfig.GetString("Interaction.NonInteractiveModeListName"),
NonInteractiveModePurchasedTab = hoconConfig.GetBoolean("Interaction.NonInteractiveModePurchasedTab"),
// Performance Settings
Timeout = string.IsNullOrWhiteSpace(hoconConfig.GetString("Performance.Timeout")) ? -1 : hoconConfig.GetInt("Performance.Timeout"),
LimitDownloadRate = hoconConfig.GetBoolean("Performance.LimitDownloadRate"),
DownloadLimitInMbPerSec = hoconConfig.GetInt("Performance.DownloadLimitInMbPerSec"),
// Logging/Debug Settings
LoggingLevel = Enum.Parse<LoggingLevel>(hoconConfig.GetString("Logging.LoggingLevel"), true)
};
ValidateFileNameFormat(config.PaidPostFileNameFormat, "PaidPostFileNameFormat");
ValidateFileNameFormat(config.PostFileNameFormat, "PostFileNameFormat");
ValidateFileNameFormat(config.PaidMessageFileNameFormat, "PaidMessageFileNameFormat");
ValidateFileNameFormat(config.MessageFileNameFormat, "MessageFileNameFormat");
var creatorConfigsSection = hoconConfig.GetConfig("CreatorConfigs");
if (creatorConfigsSection != null)
{
foreach (var key in creatorConfigsSection.AsEnumerable())
{
var creatorKey = key.Key;
var creatorHocon = creatorConfigsSection.GetConfig(creatorKey);
if (!config.CreatorConfigs.ContainsKey(creatorKey) && creatorHocon != null)
{
config.CreatorConfigs.Add(key.Key, new CreatorConfig
{
PaidPostFileNameFormat = creatorHocon.GetString("PaidPostFileNameFormat"),
PostFileNameFormat = creatorHocon.GetString("PostFileNameFormat"),
PaidMessageFileNameFormat = creatorHocon.GetString("PaidMessageFileNameFormat"),
MessageFileNameFormat = creatorHocon.GetString("MessageFileNameFormat")
});
ValidateFileNameFormat(config.CreatorConfigs[key.Key].PaidPostFileNameFormat, $"{key.Key}.PaidPostFileNameFormat");
ValidateFileNameFormat(config.CreatorConfigs[key.Key].PostFileNameFormat, $"{key.Key}.PostFileNameFormat");
ValidateFileNameFormat(config.CreatorConfigs[key.Key].PaidMessageFileNameFormat, $"{key.Key}.PaidMessageFileNameFormat");
ValidateFileNameFormat(config.CreatorConfigs[key.Key].MessageFileNameFormat, $"{key.Key}.MessageFileNameFormat");
}
}
}
levelSwitch.MinimumLevel = (LogEventLevel)config.LoggingLevel; //set the logging level based on config
Log.Debug("Configuration:");
string configString = JsonConvert.SerializeObject(config, Formatting.Indented);
Log.Debug(configString);
}
catch (Exception e)
{
Console.WriteLine(e);
AnsiConsole.MarkupLine($"\n[red]config.conf is not valid, check your syntax![/]\n");
AnsiConsole.MarkupLine($"[red]Press any key to exit.[/]");
Log.Error("config.conf processing failed.", e.Message);
if (!cliNonInteractive)
{
Console.ReadKey();
}
Environment.Exit(3);
}
}
else
{
Entities.Config jsonConfig = new Entities.Config();
var hoconConfig = new StringBuilder();
hoconConfig.AppendLine("# External Tools");
hoconConfig.AppendLine("External {");
hoconConfig.AppendLine($" FFmpegPath = \"{jsonConfig.FFmpegPath}\"");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Download Settings");
hoconConfig.AppendLine("Download {");
hoconConfig.AppendLine(" Media {");
hoconConfig.AppendLine($" DownloadAvatarHeaderPhoto = {jsonConfig.DownloadAvatarHeaderPhoto.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadPaidPosts = {jsonConfig.DownloadPaidPosts.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadPosts = {jsonConfig.DownloadPosts.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadArchived = {jsonConfig.DownloadArchived.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadStreams = {jsonConfig.DownloadStreams.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadStories = {jsonConfig.DownloadStories.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadHighlights = {jsonConfig.DownloadHighlights.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadMessages = {jsonConfig.DownloadMessages.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadPaidMessages = {jsonConfig.DownloadPaidMessages.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadImages = {jsonConfig.DownloadImages.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadVideos = {jsonConfig.DownloadVideos.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadAudios = {jsonConfig.DownloadAudios.ToString().ToLower()}");
hoconConfig.AppendLine(" }");
hoconConfig.AppendLine($" IgnoreOwnMessages = {jsonConfig.IgnoreOwnMessages.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadPostsIncrementally = {jsonConfig.DownloadPostsIncrementally.ToString().ToLower()}");
hoconConfig.AppendLine($" BypassContentForCreatorsWhoNoLongerExist = {jsonConfig.BypassContentForCreatorsWhoNoLongerExist.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadDuplicatedMedia = {jsonConfig.DownloadDuplicatedMedia.ToString().ToLower()}");
hoconConfig.AppendLine($" SkipAds = {jsonConfig.SkipAds.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadPath = \"{jsonConfig.DownloadPath}\"");
hoconConfig.AppendLine($" DownloadOnlySpecificDates = {jsonConfig.DownloadOnlySpecificDates.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadDateSelection = \"{jsonConfig.DownloadDateSelection.ToString().ToLower()}\"");
hoconConfig.AppendLine($" CustomDate = \"{jsonConfig.CustomDate?.ToString("yyyy-MM-dd")}\"");
hoconConfig.AppendLine($" ShowScrapeSize = {jsonConfig.ShowScrapeSize.ToString().ToLower()}");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# File Settings");
hoconConfig.AppendLine("File {");
hoconConfig.AppendLine($" PaidPostFileNameFormat = \"{jsonConfig.PaidPostFileNameFormat}\"");
hoconConfig.AppendLine($" PostFileNameFormat = \"{jsonConfig.PostFileNameFormat}\"");
hoconConfig.AppendLine($" PaidMessageFileNameFormat = \"{jsonConfig.PaidMessageFileNameFormat}\"");
hoconConfig.AppendLine($" MessageFileNameFormat = \"{jsonConfig.MessageFileNameFormat}\"");
hoconConfig.AppendLine($" RenameExistingFilesWhenCustomFormatIsSelected = {jsonConfig.RenameExistingFilesWhenCustomFormatIsSelected.ToString().ToLower()}");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Creator-Specific Configurations");
hoconConfig.AppendLine("CreatorConfigs {");
foreach (var creatorConfig in jsonConfig.CreatorConfigs)
{
hoconConfig.AppendLine($" \"{creatorConfig.Key}\" {{");
hoconConfig.AppendLine($" PaidPostFileNameFormat = \"{creatorConfig.Value.PaidPostFileNameFormat}\"");
hoconConfig.AppendLine($" PostFileNameFormat = \"{creatorConfig.Value.PostFileNameFormat}\"");
hoconConfig.AppendLine($" PaidMessageFileNameFormat = \"{creatorConfig.Value.PaidMessageFileNameFormat}\"");
hoconConfig.AppendLine($" MessageFileNameFormat = \"{creatorConfig.Value.MessageFileNameFormat}\"");
hoconConfig.AppendLine(" }");
}
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Folder Settings");
hoconConfig.AppendLine("Folder {");
hoconConfig.AppendLine($" FolderPerPaidPost = {jsonConfig.FolderPerPaidPost.ToString().ToLower()}");
hoconConfig.AppendLine($" FolderPerPost = {jsonConfig.FolderPerPost.ToString().ToLower()}");
hoconConfig.AppendLine($" FolderPerPaidMessage = {jsonConfig.FolderPerPaidMessage.ToString().ToLower()}");
hoconConfig.AppendLine($" FolderPerMessage = {jsonConfig.FolderPerMessage.ToString().ToLower()}");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Subscription Settings");
hoconConfig.AppendLine("Subscriptions {");
hoconConfig.AppendLine($" IncludeExpiredSubscriptions = {jsonConfig.IncludeExpiredSubscriptions.ToString().ToLower()}");
hoconConfig.AppendLine($" IncludeRestrictedSubscriptions = {jsonConfig.IncludeRestrictedSubscriptions.ToString().ToLower()}");
hoconConfig.AppendLine($" IgnoredUsersListName = \"{jsonConfig.IgnoredUsersListName}\"");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Interaction Settings");
hoconConfig.AppendLine("Interaction {");
hoconConfig.AppendLine($" NonInteractiveMode = {jsonConfig.NonInteractiveMode.ToString().ToLower()}");
hoconConfig.AppendLine($" NonInteractiveModeListName = \"{jsonConfig.NonInteractiveModeListName}\"");
hoconConfig.AppendLine($" NonInteractiveModePurchasedTab = {jsonConfig.NonInteractiveModePurchasedTab.ToString().ToLower()}");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Performance Settings");
hoconConfig.AppendLine("Performance {");
hoconConfig.AppendLine($" Timeout = {(jsonConfig.Timeout.HasValue ? jsonConfig.Timeout.Value : -1)}");
hoconConfig.AppendLine($" LimitDownloadRate = {jsonConfig.LimitDownloadRate.ToString().ToLower()}");
hoconConfig.AppendLine($" DownloadLimitInMbPerSec = {jsonConfig.DownloadLimitInMbPerSec}");
hoconConfig.AppendLine("}");
hoconConfig.AppendLine("# Logging/Debug Settings");
hoconConfig.AppendLine("Logging {");
hoconConfig.AppendLine($" LoggingLevel = \"{jsonConfig.LoggingLevel.ToString().ToLower()}\"");
hoconConfig.AppendLine("}");
File.WriteAllText("config.conf", hoconConfig.ToString());
AnsiConsole.Markup("[red]config.conf does not exist, a default file has been created in the folder you are running the program from[/]");
Log.Error("config.conf does not exist");
if (!cliNonInteractive)
{
Console.ReadKey();
}
Environment.Exit(3);
}
if (args is not null && args.Length > 0)
{
const string NON_INTERACTIVE_ARG = "--non-interactive";
if (args.Any(a => NON_INTERACTIVE_ARG.Equals(NON_INTERACTIVE_ARG, StringComparison.OrdinalIgnoreCase)))
{
cliNonInteractive = true;
Log.Debug("NonInteractiveMode set via command line");
}
Log.Debug("Additional arguments:");
foreach (string argument in args)
{
Log.Debug(argument);
}
}
var os = Environment.OSVersion;
Log.Debug($"Operating system information: {os.VersionString}");
if (os.Platform == PlatformID.Win32NT)
{
// check if this is windows 10+
if (os.Version.Major < 10)
{
Console.Write("This appears to be running on an older version of Windows which is not supported.\n\n");
Console.Write("OF-DL requires Windows 10 or higher when being run on Windows. Your reported version is: {0}\n\n", os.VersionString);
Console.Write("Press any key to continue.\n");
Log.Error("Windows version prior to 10.x: {0}", os.VersionString);
if (!cliNonInteractive)
{
Console.ReadKey();
}
Environment.Exit(1);
}
else
{
AnsiConsole.Markup("[green]Valid version of Windows found.\n[/]");
}
}
try
{
// Only run the version check if not in DEBUG mode
#if !DEBUG
Version localVersion = Assembly.GetEntryAssembly()?.GetName().Version; //Only tested with numeric values.
// Get all releases from GitHub
GitHubClient client = new GitHubClient(new ProductHeaderValue("SomeName"));
IReadOnlyList<Release> releases = await client.Repository.Release.GetAll("sim0n00ps", "OF-DL");
// Setup the versions
Version latestGitHubVersion = new Version(releases[0].TagName.Replace("OFDLV", ""));
// Compare the Versions
int versionComparison = localVersion.CompareTo(latestGitHubVersion);
if (versionComparison < 0)
{
// The version on GitHub is more up to date than this local release.
AnsiConsole.Markup("[red]You are running OF-DL version " + $"{localVersion.Major}.{localVersion.Minor}.{localVersion.Build}\n[/]");
AnsiConsole.Markup("[red]Please update to the current release on GitHub, " + $"{latestGitHubVersion.Major}.{latestGitHubVersion.Minor}.{latestGitHubVersion.Build}: {releases[0].HtmlUrl}\n[/]");
Log.Debug("Detected outdated client running version " + $"{localVersion.Major}.{localVersion.Minor}.{localVersion.Build}");
Log.Debug("Latest GitHub release version " + $"{latestGitHubVersion.Major}.{latestGitHubVersion.Minor}.{latestGitHubVersion.Build}");
}
else
{
// This local version is greater than the release version on GitHub.
AnsiConsole.Markup("[green]You are running OF-DL version " + $"{localVersion.Major}.{localVersion.Minor}.{localVersion.Build}\n[/]");
AnsiConsole.Markup("[green]Latest GitHub Release version: " + $"{latestGitHubVersion.Major}.{latestGitHubVersion.Minor}.{latestGitHubVersion.Build}\n[/]");
Log.Debug("Detected client running version " + $"{localVersion.Major}.{localVersion.Minor}.{localVersion.Build}");
Log.Debug("Latest GitHub release version " + $"{latestGitHubVersion.Major}.{latestGitHubVersion.Minor}.{latestGitHubVersion.Build}");
}
#else
AnsiConsole.Markup("[yellow]Running in Debug/Local mode. Version check skipped.\n[/]");
Log.Debug("Running in Debug/Local mode. Version check skipped.");
#endif
}
catch (Exception e)
{
AnsiConsole.Markup("[red]Error checking latest release on GitHub:\n[/]");
Console.WriteLine(e);
Log.Error("Error checking latest release on GitHub.", e.Message);
}
if (File.Exists("auth.json"))
{
AnsiConsole.Markup("[green]auth.json located successfully!\n[/]");
Log.Debug("Auth file found");
try
{
auth = JsonConvert.DeserializeObject<Auth>(await File.ReadAllTextAsync("auth.json"));
Log.Debug("Auth file found and deserialized");
}
catch (Exception _)
{
Log.Information("Auth file found but could not be deserialized");
Log.Debug("Deleting auth.json");
File.Delete("auth.json");
if (cliNonInteractive)
{
AnsiConsole.MarkupLine($"\n[red]auth.json has invalid JSON syntax. The file can be generated automatically when OF-DL is run in the standard, interactive mode.[/]\n");
AnsiConsole.MarkupLine($"[red]You may also want to try using the browser extension which is documented here:[/]\n");
AnsiConsole.MarkupLine($"[link]https://sim0n00ps.github.io/OF-DL/docs/config/auth#browser-extension[/]\n");
AnsiConsole.MarkupLine($"[red]Press any key to exit.[/]");
Console.ReadKey();
Environment.Exit(2);
}
await LoadAuthFromBrowser();
}
}
else
{
if (cliNonInteractive)
{
AnsiConsole.MarkupLine($"\n[red]auth.json is missing. The file can be generated automatically when OF-DL is run in the standard, interactive mode.[/]\n");
AnsiConsole.MarkupLine($"[red]You may also want to try using the browser extension which is documented here:[/]\n");
AnsiConsole.MarkupLine($"[link]https://sim0n00ps.github.io/OF-DL/docs/config/auth#browser-extension[/]\n");
AnsiConsole.MarkupLine($"[red]Press any key to exit.[/]");
Console.ReadKey();
Environment.Exit(2);
}
await LoadAuthFromBrowser();
}
//Added to stop cookie being filled with un-needed headers
ValidateCookieString();
if (File.Exists("rules.json"))
{
AnsiConsole.Markup("[green]rules.json located successfully!\n[/]");
try
{
JsonConvert.DeserializeObject<DynamicRules>(File.ReadAllText("rules.json"));
Log.Debug($"Rules.json: ");
Log.Debug(JsonConvert.SerializeObject(File.ReadAllText("rules.json"), Formatting.Indented));
}
catch (Exception e)
{
Console.WriteLine(e);
AnsiConsole.MarkupLine($"\n[red]rules.json is not valid, check your JSON syntax![/]\n");
AnsiConsole.MarkupLine($"[red]Please ensure you are using the latest version of the software.[/]\n");
AnsiConsole.MarkupLine($"[red]Press any key to exit.[/]");
Log.Error("rules.json processing failed.", e.Message);
if (!cliNonInteractive)
{
Console.ReadKey();
}
Environment.Exit(2);
}
}
if(cliNonInteractive)
{
// CLI argument overrides configuration
config!.NonInteractiveMode = true;
Log.Debug("NonInteractiveMode = true");
}
if(config!.NonInteractiveMode)
{
cliNonInteractive = true; // If it was set in the config, reset the cli value so exception handling works
Log.Debug("NonInteractiveMode = true (set via config)");
}
var ffmpegFound = false;
var pathAutoDetected = false;
if (!string.IsNullOrEmpty(config!.FFmpegPath) && ValidateFilePath(config.FFmpegPath))
{
// FFmpeg path is set in config.json and is valid
ffmpegFound = true;
Log.Debug($"FFMPEG found: {config.FFmpegPath}");
Log.Debug("FFMPEG path set in config.conf");
}
else if (!string.IsNullOrEmpty(auth!.FFMPEG_PATH) && ValidateFilePath(auth.FFMPEG_PATH))
{
// FFmpeg path is set in auth.json and is valid (config.conf takes precedence and auth.json is only available for backward compatibility)
ffmpegFound = true;
config.FFmpegPath = auth.FFMPEG_PATH;
Log.Debug($"FFMPEG found: {config.FFmpegPath}");
Log.Debug("FFMPEG path set in auth.json");
}
else if (string.IsNullOrEmpty(config.FFmpegPath))
{
// FFmpeg path is not set in config.conf, so we will try to locate it in the PATH or current directory
var ffmpegPath = GetFullPath("ffmpeg");
if (ffmpegPath != null)
{
// FFmpeg is found in the PATH or current directory
ffmpegFound = true;
pathAutoDetected = true;
config.FFmpegPath = ffmpegPath;
Log.Debug($"FFMPEG found: {ffmpegPath}");
Log.Debug("FFMPEG path found via PATH or current directory");
}
else
{
// FFmpeg is not found in the PATH or current directory, so we will try to locate the windows executable
ffmpegPath = GetFullPath("ffmpeg.exe");
if (ffmpegPath != null)
{
// FFmpeg windows executable is found in the PATH or current directory
ffmpegFound = true;
pathAutoDetected = true;
config.FFmpegPath = ffmpegPath;
Log.Debug($"FFMPEG found: {ffmpegPath}");
Log.Debug("FFMPEG path found in windows excutable directory");
}
}
}
if (ffmpegFound)
{
if (pathAutoDetected)
{
AnsiConsole.Markup($"[green]FFmpeg located successfully. Path auto-detected: {config.FFmpegPath}\n[/]");
}
else
{
AnsiConsole.Markup($"[green]FFmpeg located successfully\n[/]");
}
// Escape backslashes in the path for Windows
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && config.FFmpegPath!.Contains(@":\") && !config.FFmpegPath.Contains(@":\\"))
{
config.FFmpegPath = config.FFmpegPath.Replace(@"\", @"\\");
}
}
else
{
AnsiConsole.Markup("[red]Cannot locate FFmpeg; please modify config.conf with the correct path. Press any key to exit.[/]");
Log.Error($"Cannot locate FFmpeg with path: {config.FFmpegPath}");
if (!config.NonInteractiveMode)
{
Console.ReadKey();
}
Environment.Exit(4);
}
if (!File.Exists(Path.Join(WidevineClient.Widevine.Constants.DEVICES_FOLDER, WidevineClient.Widevine.Constants.DEVICE_NAME, "device_client_id_blob")))
{
clientIdBlobMissing = true;
Log.Debug("clientIdBlobMissing missing");
}
else
{
AnsiConsole.Markup($"[green]device_client_id_blob located successfully![/]\n");
Log.Debug("clientIdBlobMissing found: " + File.Exists(Path.Join(WidevineClient.Widevine.Constants.DEVICES_FOLDER, WidevineClient.Widevine.Constants.DEVICE_NAME, "device_client_id_blob")));
}
if (!File.Exists(Path.Join(WidevineClient.Widevine.Constants.DEVICES_FOLDER, WidevineClient.Widevine.Constants.DEVICE_NAME, "device_private_key")))
{
devicePrivateKeyMissing = true;
Log.Debug("devicePrivateKeyMissing missing");
}
else
{
AnsiConsole.Markup($"[green]device_private_key located successfully![/]\n");
Log.Debug("devicePrivateKeyMissing found: " + File.Exists(Path.Join(WidevineClient.Widevine.Constants.DEVICES_FOLDER, WidevineClient.Widevine.Constants.DEVICE_NAME, "device_private_key")));
}
if (clientIdBlobMissing || devicePrivateKeyMissing)
{
AnsiConsole.Markup("[yellow]device_client_id_blob and/or device_private_key missing, https://ofdl.tools/ or https://cdrm-project.com/ will be used instead for DRM protected videos\n[/]");
}
//Check if auth is valid
var apiHelper = new APIHelper(auth, config);
Entities.User? validate = await apiHelper.GetUserInfo($"/users/me");
if (validate == null || (validate?.name == null && validate?.username == null))
{
Log.Error("Auth failed");
auth = null;
if (File.Exists("auth.json"))
{
File.Delete("auth.json");
}
if (!cliNonInteractive)
{
await LoadAuthFromBrowser();
}
if (auth == null)
{
AnsiConsole.MarkupLine($"\n[red]Auth failed. Please try again or use other authentication methods detailed here:[/]\n");
AnsiConsole.MarkupLine($"[link]https://sim0n00ps.github.io/OF-DL/docs/config/auth[/]\n");
Console.ReadKey();
Environment.Exit(2);
}
}
AnsiConsole.Markup($"[green]Logged In successfully as {validate.name} {validate.username}\n[/]");
await DownloadAllData(apiHelper, auth, config);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught: {0}\n\nStackTrace: {1}", ex.Message, ex.StackTrace);
Log.Error("Exception caught: {0}\n\nStackTrace: {1}", ex.Message, ex.StackTrace);
if (ex.InnerException != null)
{
Console.WriteLine("\nInner Exception:");
Console.WriteLine("Exception caught: {0}\n\nStackTrace: {1}", ex.InnerException.Message, ex.InnerException.StackTrace);
Log.Error("Inner Exception: {0}\n\nStackTrace: {1}", ex.InnerException.Message, ex.InnerException.StackTrace);
}
Console.WriteLine("\nPress any key to exit.");
if (!cliNonInteractive)
{
Console.ReadKey();
}
Environment.Exit(5);
}
}
private static async Task DownloadAllData(APIHelper m_ApiHelper, Auth Auth, Entities.Config Config)
{
DBHelper dBHelper = new DBHelper(Config);
Log.Debug("Calling DownloadAllData");
do
{
DateTime startTime = DateTime.Now;
Dictionary<string, int> users = new();
Dictionary<string, int> activeSubs = await m_ApiHelper.GetActiveSubscriptions("/subscriptions/subscribes", Config.IncludeRestrictedSubscriptions, Config);
Log.Debug("Subscriptions: ");
foreach (KeyValuePair<string, int> activeSub in activeSubs)
{
if (!users.ContainsKey(activeSub.Key))
{
users.Add(activeSub.Key, activeSub.Value);
Log.Debug($"Name: {activeSub.Key} ID: {activeSub.Value}");
}
}
if (Config!.IncludeExpiredSubscriptions)
{
Log.Debug("Inactive Subscriptions: ");
Dictionary<string, int> expiredSubs = await m_ApiHelper.GetExpiredSubscriptions("/subscriptions/subscribes", Config.IncludeRestrictedSubscriptions, Config);
foreach (KeyValuePair<string, int> expiredSub in expiredSubs)
{
if (!users.ContainsKey(expiredSub.Key))
{
users.Add(expiredSub.Key, expiredSub.Value);
Log.Debug($"Name: {expiredSub.Key} ID: {expiredSub.Value}");
}
}
}
Dictionary<string, int> lists = await m_ApiHelper.GetLists("/lists", Config);
// Remove users from the list if they are in the ignored list
if (!string.IsNullOrEmpty(Config.IgnoredUsersListName))
{
if (!lists.TryGetValue(Config.IgnoredUsersListName, out var ignoredUsersListId))
{
AnsiConsole.Markup($"[red]Ignored users list '{Config.IgnoredUsersListName}' not found\n[/]");
Log.Error($"Ignored users list '{Config.IgnoredUsersListName}' not found");
}
else
{
var ignoredUsernames = await m_ApiHelper.GetListUsers($"/lists/{ignoredUsersListId}/users", Config) ?? [];
users = users.Where(x => !ignoredUsernames.Contains(x.Key)).ToDictionary(x => x.Key, x => x.Value);
}
}
await dBHelper.CreateUsersDB(users);
KeyValuePair<bool, Dictionary<string, int>> hasSelectedUsersKVP;
if(Config.NonInteractiveMode && Config.NonInteractiveModePurchasedTab)
{
hasSelectedUsersKVP = new KeyValuePair<bool, Dictionary<string, int>>(true, new Dictionary<string, int> { { "PurchasedTab", 0 } });
}
else if (Config.NonInteractiveMode && string.IsNullOrEmpty(Config.NonInteractiveModeListName))
{
hasSelectedUsersKVP = new KeyValuePair<bool, Dictionary<string, int>>(true, users);
}
else if (Config.NonInteractiveMode && !string.IsNullOrEmpty(Config.NonInteractiveModeListName))
{
var listId = lists[Config.NonInteractiveModeListName];
var listUsernames = await m_ApiHelper.GetListUsers($"/lists/{listId}/users", Config) ?? [];
var selectedUsers = users.Where(x => listUsernames.Contains(x.Key)).Distinct().ToDictionary(x => x.Key, x => x.Value);
hasSelectedUsersKVP = new KeyValuePair<bool, Dictionary<string, int>>(true, selectedUsers);
}
else
{
var userSelectionResult = await HandleUserSelection(m_ApiHelper, Config, users, lists);
Config = userSelectionResult.updatedConfig;
hasSelectedUsersKVP = new KeyValuePair<bool, Dictionary<string, int>>(userSelectionResult.IsExit, userSelectionResult.selectedUsers);
}
if (hasSelectedUsersKVP.Key && hasSelectedUsersKVP.Value != null && hasSelectedUsersKVP.Value.ContainsKey("SinglePost"))
{
AnsiConsole.Markup("[red]To find an individual post URL, click on the ... at the top right corner of the post and select 'Copy link to post'.\n\nTo return to the main menu, enter 'back' or 'exit' when prompted for the URL.\n\n[/]");
string postUrl = AnsiConsole.Prompt(
new TextPrompt<string>("[red]Please enter a post URL: [/]")
.ValidationErrorMessage("[red]Please enter a valid post URL[/]")
.Validate(url =>
{
Log.Debug($"Single Post URL: {url}");
Regex regex = new Regex("https://onlyfans\\.com/[0-9]+/[A-Za-z0-9]+", RegexOptions.IgnoreCase);
if (regex.IsMatch(url))
{
return ValidationResult.Success();
}
if (url == "" || url == "exit" || url == "back") {
return ValidationResult.Success();
}
Log.Error("Post URL invalid");
return ValidationResult.Error("[red]Please enter a valid post URL[/]");
}));
if (postUrl != "" && postUrl != "exit" && postUrl != "back") {
long post_id = Convert.ToInt64(postUrl.Split("/")[3]);
string username = postUrl.Split("/")[4];
Log.Debug($"Single Post ID: {post_id.ToString()}");
Log.Debug($"Single Post Creator: {username}");
if (users.ContainsKey(username))
{
string path = "";
if (!string.IsNullOrEmpty(Config.DownloadPath))
{
path = System.IO.Path.Combine(Config.DownloadPath, username);
}
else
{
path = $"__user_data__/sites/OnlyFans/{username}";
}
Log.Debug($"Download path: {path}");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
AnsiConsole.Markup($"[red]Created folder for {username}\n[/]");
Log.Debug($"Created folder for {username}");
}
else
{
AnsiConsole.Markup($"[red]Folder for {username} already created\n[/]");
}
await dBHelper.CreateDB(path);
var downloadContext = new DownloadContext(Auth, Config, GetCreatorFileNameFormatConfig(Config, username), m_ApiHelper, dBHelper);
await DownloadSinglePost(downloadContext, post_id, path, users);
}
}
}
else if (hasSelectedUsersKVP.Key && hasSelectedUsersKVP.Value != null && hasSelectedUsersKVP.Value.ContainsKey("PurchasedTab"))
{
Dictionary<string, int> purchasedTabUsers = await m_ApiHelper.GetPurchasedTabUsers("/posts/paid", Config, users);
AnsiConsole.Markup($"[red]Checking folders for Users in Purchased Tab\n[/]");
foreach (KeyValuePair<string, int> user in purchasedTabUsers)
{
string path = "";
if (!string.IsNullOrEmpty(Config.DownloadPath))
{
path = System.IO.Path.Combine(Config.DownloadPath, user.Key);
}
else
{
path = $"__user_data__/sites/OnlyFans/{user.Key}";
}
Log.Debug($"Download path: {path}");
await dBHelper.CheckUsername(user, path);
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
AnsiConsole.Markup($"[red]Created folder for {user.Key}\n[/]");
Log.Debug($"Created folder for {user.Key}");
}
else
{
AnsiConsole.Markup($"[red]Folder for {user.Key} already created\n[/]");
Log.Debug($"Folder for {user.Key} already created");
}
Entities.User user_info = await m_ApiHelper.GetUserInfo($"/users/{user.Key}");
await dBHelper.CreateDB(path);
}
string p = "";
if (!string.IsNullOrEmpty(Config.DownloadPath))
{
p = Config.DownloadPath;
}
else
{
p = $"__user_data__/sites/OnlyFans/";
}
Log.Debug($"Download path: {p}");
List<PurchasedTabCollection> purchasedTabCollections = await m_ApiHelper.GetPurchasedTab("/posts/paid", p, Config, users);
foreach(PurchasedTabCollection purchasedTabCollection in purchasedTabCollections)
{
AnsiConsole.Markup($"[red]\nScraping Data for {purchasedTabCollection.Username}\n[/]");
string path = "";
if (!string.IsNullOrEmpty(Config.DownloadPath))
{
path = System.IO.Path.Combine(Config.DownloadPath, purchasedTabCollection.Username);
}
else
{
path = $"__user_data__/sites/OnlyFans/{purchasedTabCollection.Username}";
}
Log.Debug($"Download path: {path}");
var downloadContext = new DownloadContext(Auth, Config, GetCreatorFileNameFormatConfig(Config, purchasedTabCollection.Username), m_ApiHelper, dBHelper);
int paidPostCount = 0;
int paidMessagesCount = 0;
paidPostCount = await DownloadPaidPostsPurchasedTab(downloadContext, purchasedTabCollection.PaidPosts, users.FirstOrDefault(u => u.Value == purchasedTabCollection.UserId), paidPostCount, path, users);