-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
833 lines (741 loc) · 37.1 KB
/
Program.cs
File metadata and controls
833 lines (741 loc) · 37.1 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
using DataTablePrettyPrinter;
using MonoTorrent.Client;
using System.Collections.Concurrent;
using System.Data;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml.Linq;
using static AniDownloaderTerminal.SeriesDownloader.EpisodeToDownload;
namespace AniDownloaderTerminal
{
public partial class Program
{
private string CurrentlyScanningSeries = string.Empty;
private readonly SeriesDownloader CurrentSeriesDownloader = new();
private int PreviousLineCount = 0;
private int PreviousWindowHeight = 0;
private int PreviousWindowWidth = 0;
public static readonly Settings settings = new();
public static readonly Webserver webserver = new();
[GeneratedRegex(@"\d{1,3}$")]
private static partial Regex TempFolderEpisodeNumberRegex();
public static void Main()
{
settings.Init();
Program program = new();
webserver.Init();
var task = Task.Run(async () => { await program.Start(); });
task.Wait();
}
public Program()
{
LoadSeriesTable();
Console.CursorVisible = false;
}
public async Task Start()
{
Console.Clear();
bool CleanFinishedSeriesTask()
{
CleanFinishedSeries();
return true;
}
Global.TaskAdmin.NewTask("CleanFinishedSeries", "Downloader", CleanFinishedSeriesTask, 300000, true);
bool StartDownloadsTask()
{
Thread.Sleep(5000);//Delay so it doesn't crash with CleanFinishedSeriesTask at the beggining.
CurrentSeriesDownloader.StartDownloads();
return true;
}
Global.TaskAdmin.NewTask("StartDownloads", "Downloader", StartDownloadsTask, 1000, true);
bool StartConversionsTask()
{
CurrentSeriesDownloader.StartConversions();
return true;
}
Global.TaskAdmin.NewTask("StartConvertions", "Downloader", StartConversionsTask, 2000, true);
bool CleanEncodedFilesTask()
{
CurrentSeriesDownloader.CleanEncodedFiles();
return true;
};
Global.TaskAdmin.NewTask("CleanEncodedFiles", "Downloader", CleanEncodedFilesTask, 10000, true);
bool UpdateSeriesDataTableTask()
{
UpdateSeriesDataTable();
return true;
};
Global.TaskAdmin.NewTask("UpdateSeriesDataTable", "Downloader", UpdateSeriesDataTableTask, 200, true);
bool PrintUpdateTableTask()
{
PrintUpdateTable();
return true;
};
Global.TaskAdmin.NewTask("PrintUpdateTable", "Downloader", PrintUpdateTableTask, 100, true);
bool SearchForUncompletedAndNeedConvertSeriesTask()
{
SearchForUncompletedAndNeedConvertSeries();
return true;
}
Global.TaskAdmin.NewTask("SearchForNeedConvertSeriesTask", "Downloader", SearchForUncompletedAndNeedConvertSeriesTask, 300000, true);
await UpdateSeries();
}
///
/// Cleans finished series from the SeriesTable by checking if the series is marked as finished on Anilist
/// and if the local directory contains at least as many video files as the total episodes reported.
/// Removes matching rows from the DataTable and persists changes to XML if any deletions occur.
///
public void CleanFinishedSeries()
{
HashSet<(string name, string path)> seriesRows = [];
HashSet<(string name, string path)> rowsToDelete = [];
lock (Global.SeriesTable)
{
foreach (DataRow row in Global.SeriesTable.Rows)
{
string? seriesName = row["Name"]?.ToString();
string? seriesPath = row["Path"]?.ToString();
if (string.IsNullOrWhiteSpace(seriesName) || string.IsNullOrWhiteSpace(seriesPath))
{
continue;
}
seriesRows.Add((seriesName, seriesPath));
}
}
foreach ((string name, string path) row in seriesRows)
{
Global.CurrentOpsQueue.Enqueue($"Checking if {row.name} is finished.");
try
{
if (!Directory.Exists(row.path)) continue; // Directory cannot be accessed, skip.
// This program stores the episode names as 'SeriesName {episode}.ext' although the path can be specified by the user. We enforce flat directories.
// We use MKV as video container but there is the possibility the user manually downloaded some episodes so we should look for valid extensions specified in the settings.
int fileCount = Directory.EnumerateFiles(row.path, row.name + "*.*")
.Where(f => Settings.ValidExtensions.Select(x => x.ToLowerInvariant()).ToHashSet().Contains(Path.GetExtension(f).ToLowerInvariant()))
.Count();
if (fileCount == 0) continue; // New Series, don't bother to waste resources on querying.
// Since the user can specify the path (but not the file names) we try to check if the directory is following a Plex-style folder structure
// where it usually follows the '/Series Name/Season/Episode.ext' structure. We use '$' to make sure we match the end of the path.
// Matches 's00' 's-00' 's_00' 's.00' 'season00' 'season 00' 'season-00' 'season_00' 'season.00' '00' at the end of the path. Case insensitive.
Match isSeasonMatchInPath = Regex.Match(row.path.Trim(), @"(?:.+?)[/\\](?:[Ss](?:eason)?[ \-_\\.]*)*(\d{1,3})(?:$|[/\\]$)", RegexOptions.IgnoreCase);
Match isSeasonMatchInName = Regex.Match(row.name.Trim(), @"(?:(?:s|season)[ .\-_]*| )(\d{1,3})(?:nd season$|$)", RegexOptions.IgnoreCase); //We check the name too, if it matches we clean it.
string searchName = row.name; // Series name that we will use to query anilist.
if (isSeasonMatchInPath.Success)
{
if (isSeasonMatchInName.Success)
{
searchName = searchName.Replace(isSeasonMatchInName.Value, string.Empty).Trim(); // We remove the season from the name, as it will be added later.
searchName = Regex.Replace(searchName, "[ -\\._]+$", "");
}
bool success = int.TryParse(isSeasonMatchInPath.Groups[1].Value, out int season);
if (!success) continue; // Shouldn't fail since the group 1 in the regex only matches digits but we check just in case the regex is updated in the future.
// 'Series name + season {number}' should return the correct season in anilist for directories following the plex-style structure.
searchName = searchName.Trim() + " season " + season;
}
AnilistMetadataProvider.SeriesStatus? status = Global.MetadataProvider.QuerySeriesByName(searchName);
if (status == null) continue; // Can be null if an exception occurs inside the 'QuerySeriesByName' function or Anilist cannot find it by name. If so, we skip.
if (status.Episodes <= 0) continue; // No episodes yet, skip.
if (status.Finished)
{
if (fileCount >= status.Episodes)
{
rowsToDelete.Add(row);
}
}
}
catch (Exception ex)
{
Global.TaskAdmin.Logger.EX_Log($"Failed to process series '{row.name}' at '{row.path}'.", "CleanFinishedSeries");
Global.TaskAdmin.Logger.Debug_Log(ex.Message, "CleanFinishedSeries"); // Only prints if Debug == true
Global.TaskAdmin.Logger.Debug_Log(ex.StackTrace, "CleanFinishedSeries");
}
}
// Lock the table and clean finished series.
if (rowsToDelete.Count > 0)
{
Global.TaskAdmin.Logger.Log($"{rowsToDelete.Count} series finished and with all episodes downloaded are going to be renoved from the series list.", "CleanFinishedSeries");
lock (Global.SeriesTable)
{
foreach ((string name, string path) row in rowsToDelete)
{
// Use Select for efficient lookup; escapes apostrophes in queries.
var matchingRows = Global.SeriesTable.Select($"Name = '{row.name.Replace("'", "''")}' AND Path = '{row.path.Replace("'", "''")}'");
foreach (var r in matchingRows)
{
r.Delete();
}
}
Global.SeriesTable.AcceptChanges();
Global.SeriesTable.WriteXml(Global.SeriesTableFilePath, XmlWriteMode.WriteSchema);
}
foreach (string name in rowsToDelete.Select(x=> x.name))
{
Global.TaskAdmin.Logger.Log($"Removed '{name}' from the SeriesList.", "CleanFinishedSeries");
}
}
Global.CurrentOpsQueue.Enqueue($"Check for finished series Done.");
}
private async Task UpdateSeries()
{
while (true)
{
try
{
List<Series> seriesInTable = [];
lock (Global.SeriesTable)
{
foreach (DataRow row in Global.SeriesTable.Rows)
{
string? sName = row["Name"].ToString();
string? sPath = row["Path"].ToString();
string? sFilter = row["Filter"].ToString();
_ = int.TryParse(row["Offset"].ToString(), out int sOffset);
if (sName == null) { continue; }
if (sPath == null) { continue; }
if (sFilter == null) { continue; }
if (!Directory.Exists(sPath)) Directory.CreateDirectory(sPath);
Series series = new(sName, sPath, sOffset, sFilter);
seriesInTable.Add(series);
}
}
foreach (Series series in seriesInTable)
{
CurrentlyScanningSeries = "Scanning : " + series.Name;
OnlineEpisodeElement[] filteredEpisodes = FilterFoundEpisodes(await series.GetAvailableSeriesEpisodes(), series);
foreach (OnlineEpisodeElement episodeToDownload in filteredEpisodes)
{
if (episodeToDownload.ProbableEpNumber == null) continue;
int episodeNumber = (int)episodeToDownload.ProbableEpNumber;
string episodeName = series.Name + " " + episodeNumber.ToString("00");
if (CurrentSeriesDownloader.Episodes.ContainsKey(episodeName)) continue;
CurrentSeriesDownloader.AddTorrentToDictionary(episodeToDownload.TorrentUrl, series.Path, episodeName, episodeNumber);
}
}
seriesInTable.Clear();
await Task.Run(() =>
{
CurrentlyScanningSeries = "Done scanning!";
Thread.Sleep(1800000); //Task.Delay() causes a memory leak. It's only one thread so blocking it it's okay.
});
LoadSeriesTable();
}
catch (Exception ex)
{
Global.TaskAdmin.Logger.EX_Log(ex.Message, "UpdateSeries");
}
}
}
/// <summary>
/// Searches for uncompleted episodes and series that need conversion by collecting series information from the global series table and search paths,
/// then processes each series for markers requiring conversion and uncompleted temporary folders.
/// This method replaces the original SearchForUncompletedEpisodes and SearchForNeedConvertSeries methods.
/// </summary>
public void SearchForUncompletedAndNeedConvertSeries()
{
// Use HashSet to avoid duplicate series if paths overlap between table and search subdirs
HashSet<(string name, string path)> seriesRows = [];
lock (Global.SeriesTable)
{
foreach (DataRow row in Global.SeriesTable.Rows)
{
string? seriesName = row["Name"]?.ToString();
string? seriesPath = row["Path"]?.ToString();
if (string.IsNullOrWhiteSpace(seriesName) || string.IsNullOrWhiteSpace(seriesPath))
{
continue;
}
seriesRows.Add((seriesName, seriesPath));
}
}
foreach (String path in Settings.SearchPaths)
{
foreach (String subDir in Directory.EnumerateDirectories(path))
{
if (String.IsNullOrWhiteSpace(subDir)) continue;
if (!Directory.Exists(subDir)) continue;
string seriesName = new DirectoryInfo(subDir).Name;
string? seriesPath = Path.GetFullPath(subDir);
if (seriesName == null || seriesPath == null) continue;
seriesRows.Add((seriesName, seriesPath));
}
}
foreach ((string name, string path) row in seriesRows)
{
string seriesName = row.name;
string seriesPath = row.path;
Global.CurrentOpsQueue.Enqueue($"Searching unconverted files and marked series for {seriesName}");
if (!Directory.Exists(seriesPath))
{
continue;
}
SearchAndProcessDirectoryMarker(seriesName, seriesPath);
SearchAndProcessUncompleted(seriesPath);
}
UpdateSeriesDataTable();
Global.CurrentOpsQueue.Enqueue("Search for unconverted files and marked series done.");
}
/// <summary>
/// Processes a series directory if it contains a marker file indicating the need for conversion.
/// This includes probing the directory for writability, moving valid video files into per-episode temporary folders,
/// adding them as downloaded episodes, and deleting the marker file upon success.
/// </summary>
/// <param name="seriesName">The name of the series.</param>
/// <param name="seriesPath">The full path to the series directory.</param>
public void SearchAndProcessDirectoryMarker(string seriesName, string seriesPath)
{
string markerPath = Path.Combine(seriesPath, Settings.NeedsConvertFileName);
if (!File.Exists(markerPath)) return;
if (String.IsNullOrWhiteSpace(seriesName))
{
Global.TaskAdmin.Logger.Log($"Skipped '{seriesPath}'. DirectoryInfo for the path returned null or an empty string.", "SearchAndProcessDirectoryMarker");
return;
}
try
{
// Probe the directory by creating and deleting a test file to ensure writability
string probeFile = Path.Combine(seriesPath, "probe");
bool probeOk = true;
if (File.Exists(probeFile))
{
probeOk &= DeleteFileWithRetries(probeFile, 3);
}
File.Create(probeFile).Close();
probeOk = probeOk && DeleteFileWithRetries(probeFile, 3);
if (!probeOk) throw new Exception("DeleteFileWithRetries failed.");
}
catch (Exception ex)
{
Global.TaskAdmin.Logger.EX_Log($"Probing for '{seriesPath}' failed. Skipping Subdirectory. Exception: {ex.Message}.", "SearchAndProcessDirectoryMarker");
return;
}
try
{
// Get all files once
string[] videoFiles = [.. Settings.ValidExtensions.SelectMany(extension => Directory.EnumerateFiles(seriesPath, "*" + extension))]; //Settings.ValidExtensions <- lowercase hashset of extensions with dot.
if (videoFiles.Length == 0)
{
Global.TaskAdmin.Logger.Log($"Deleting marker '{markerPath}' for empty series '{seriesName}' in path '{seriesPath}'. No valid video files found!", "SearchAndProcessDirectoryMarker");
if (!DeleteFileWithRetries(markerPath, 3))
{
Global.TaskAdmin.Logger.EX_Log($"Failed to delete marker '{markerPath}'", "SearchAndProcessDirectoryMarker");
}
return;
}
int queuedCount = 0;
foreach (string file in videoFiles)
{
string episodeName = Path.GetFileNameWithoutExtension(file).Trim();
int? episodeNumber = OnlineEpisodeElement.GetEpNumberFromString(episodeName); //Method catches exceptions, always returns a number of null.
if (episodeNumber == null)
{
Global.TaskAdmin.Logger.Log($"Skipped '{file}'. No episode number found.", "SearchAndProcessDirectoryMarker");
continue;
}
// Format episode number as 00 or 000 based on total video files to ensure consistent naming (e.g., for sorting)
string epNumberString = String.Format("{0:00}", episodeNumber);
if (videoFiles.Length > 99)
{
epNumberString = String.Format("{0:000}", episodeNumber);
}
string destEpisodeExtension = Path.GetExtension(file).ToLowerInvariant();
string destEpisodeName = seriesName + " " + epNumberString;
string tempFolder = Path.Combine(seriesPath, destEpisodeName) + ".temp"; //Temp folder is per-episode, not per series. When episode processing is complete the folder is deleted.
string destEpisodePath = Path.Combine(tempFolder, destEpisodeName + destEpisodeExtension);
try
{
if (Directory.Exists(tempFolder))
{
Directory.Delete(tempFolder, true);
Global.TaskAdmin.Logger.Log($"Pre-existent temporary folder '{tempFolder}' was deleted.", "SearchAndProcessDirectoryMarker");
}
Directory.CreateDirectory(tempFolder);
}
catch (Exception ex)
{
Global.TaskAdmin.Logger.EX_Log($"Failed to delete temp dir '{tempFolder}'. Exception: {ex.Message}", "SearchAndProcessDirectoryMarker");
continue;
}
if (!MoveFileWithRetries(file, destEpisodePath, 3))
{
Global.TaskAdmin.Logger.Log($"Skipped '{file}'. Failed to move to temp folder.", "SearchAndProcessDirectoryMarker");
continue;
}
AddEpisode(destEpisodeName, seriesPath, (int)episodeNumber, State.DownloadedFound, "Downloaded-Found"); //DownloadedFound = DownloadedSeeding. Added recently.
queuedCount++;
}
if (queuedCount > 0)
{
Global.TaskAdmin.Logger.Log($"Queued {queuedCount} files of {videoFiles.Length} in '{seriesPath}' for Series '{seriesName}'.", "SearchAndProcessDirectoryMarker");
if (queuedCount != videoFiles.Length)
{
Global.TaskAdmin.Logger.Log($"Unprocessed files in '{seriesPath}' may not satisfy requirements, check filenames, extensions and Logs.", "SearchAndProcessDirectoryMarker");
}
}
if (!DeleteFileWithRetries(markerPath, 3))
{
Global.TaskAdmin.Logger.EX_Log($"Failed to delete marker '{markerPath}'", "SearchAndProcessDirectoryMarker");
return;
}
}
catch (Exception ex)
{
Global.TaskAdmin.Logger.EX_Log($"Error processing '{seriesPath}': {ex.Message}", "SearchAndProcessDirectoryMarker");
}
}
/// <summary>
/// Scans a series directory for temporary (.temp) episode folders and adds uncompleted episodes to the downloader
/// based on their state files, skipping those already in the episodes dictionary.
/// </summary>
/// <param name="seriesPath">The full path to the series directory.</param>
public void SearchAndProcessUncompleted(string seriesPath)
{
foreach (string tempDirPath in Directory.GetDirectories(seriesPath, "*.temp"))
{
string episodeName = Path.GetFileNameWithoutExtension(tempDirPath).Trim();
Match tempFolderMatch = TempFolderEpisodeNumberRegex().Match(episodeName);
if (!tempFolderMatch.Success) continue;
if (!int.TryParse(tempFolderMatch.Value, out int episodeNumber)) continue; //Value can not be null because we guarded against match success.
// Skip if episode is already being tracked in the current downloader
if (CurrentSeriesDownloader.Episodes.ContainsKey(episodeName)) continue;
// Check for episode states to determine if it's downloaded or encoded
if (File.Exists(Path.Combine(tempDirPath, "state.DownloadedSeeding")) ||
File.Exists(Path.Combine(tempDirPath, "state.ReEncoding")))
{
AddEpisode(episodeName, seriesPath, episodeNumber, State.DownloadedFound, "Downloaded-found");
}
else if (File.Exists(Path.Combine(tempDirPath, "state.EncodedSeeding")) ||
File.Exists(Path.Combine(tempDirPath, "state.EncodedFound")))
{
AddEpisode(episodeName, seriesPath, episodeNumber, State.EncodedFound, "Encoded-found");
}
}
}
public static bool MoveFileWithRetries(String source, String destination, int tries)
{
for (int retry = 0; retry < tries; retry++) // Retry on lock
{
try
{
File.Move(source, destination);
return true;
}
catch (IOException ex) when (retry < tries - 1)
{
Global.TaskAdmin.Logger.EX_Log($"Retrying move for '{source}': {ex.Message}", "MoveFileWithRetries");
Thread.Sleep(1000); // 1s delay
}
catch (IOException ex)
{
Global.TaskAdmin.Logger.EX_Log($"Failed to move '{source}': {ex.Message}", "MoveFileWithRetries");
}
}
return false;
}
public static bool DeleteFileWithRetries(String file, int tries)
{
for (int retry = 0; retry < tries; retry++) // Retry on lock
{
try
{
File.Delete(file);
return true;
}
catch (IOException ex) when (retry < tries - 1)
{
Global.TaskAdmin.Logger.EX_Log($"Retrying delete for '{file}': {ex.Message}", "DeleteFileWithRetries");
Thread.Sleep(1000); // 1s delay
}
catch (IOException ex)
{
Global.TaskAdmin.Logger.EX_Log($"Failed to delete '{file}': {ex.Message}", "DeleteFileWithRetries");
}
}
return false;
}
private void AddEpisode(string episodeName, string seriesPath, int episodeNumber, State state, string status)
{
// Clean up existing file if necessary
string episodePath = Path.Combine(seriesPath, episodeName);
string mkvFile = episodePath + ".mkv";
string mp4File = episodePath + ".mp4";
if (File.Exists(mkvFile))
{
if (!DeleteFileWithRetries(mkvFile, 3)) {
Global.TaskAdmin.Logger.EX_Log($"Could not Add '{episodeName}' because another file already exists and could not be deleted. ", "AddEpisode");
return;
}
}
if (File.Exists(mp4File))
{
if (!DeleteFileWithRetries(mp4File, 3))
{
Global.TaskAdmin.Logger.EX_Log($"Could not Add '{episodeName}' because another file already exists and could not be deleted. ", "AddEpisode");
return;
}
}
var episode = new SeriesDownloader.EpisodeToDownload("", episodeName, seriesPath, episodeNumber);
episode.SetState(state);
episode.StatusDescription = status;
CurrentSeriesDownloader.AddFoundEpisodeToDictionary(episode); //AddFoundEpisodeToDictionary has lock for Episodes dictionary inside.
}
private static OnlineEpisodeElement[] FilterFoundEpisodes(OnlineEpisodeElement[] episodes, Series series)
{
Dictionary<int, OnlineEpisodeElement> bestEpisodes = [];
List<OnlineEpisodeElement> preFilteredEpisodes = [];
int[] downloadedEpisodes = series.GetEpisodesDownloaded();
foreach (OnlineEpisodeElement episode in episodes)
{
if (episode.ProbableEpNumber == null || downloadedEpisodes.Contains((int)episode.ProbableEpNumber))
{
continue;
}
preFilteredEpisodes.Add(episode);
}
foreach (OnlineEpisodeElement episode in preFilteredEpisodes)
{
if (episode.ProbableEpNumber == null || episode.ProbableLang == Lang.RAW) continue;
episode.ProbableLang = episode.ProbableLang == Lang.Undefined ? episode.GetProbableLanguage() : episode.ProbableLang;
if (Settings.UseCustomLanguage)
{
if (episode.ProbableLang != Lang.Custom && episode.ProbableLang != Lang.CustomAndEng) continue;
}
else
{
if (episode.ProbableLang != Lang.Eng) continue;
}
int epNum = (int)episode.ProbableEpNumber;
if (!bestEpisodes.TryAdd(epNum, episode))
{
if (episode.SizeMiB > bestEpisodes[epNum].SizeMiB || Global.TrySelectUncensoredEpisode(episode, bestEpisodes[epNum]) == episode)
{
bestEpisodes[epNum] = episode;
}
}
}
return [.. bestEpisodes.Values];
}
public static void SetUpdateEpisodesStatusTable(SeriesDownloader.EpisodeToDownload episodeElement)
{
DataRow? row;
lock (Global.CurrentStatusTable)
{
row = Global.CurrentStatusTable.AsEnumerable().Where(dr => dr.Field<string>("Episode") == episodeElement.Name).FirstOrDefault();
}
if (!(row == null))
{
lock (Global.CurrentStatusTable)
{
lock (row)
{
row[1] = episodeElement.Name;
row[2] = episodeElement.StatusDescription;
if (episodeElement.GetState == State.EncodedSeeding)
{
row[3] = "R:" + episodeElement.GetTorrentRatio().ToString("0.00");
}
else
{
row[3] = episodeElement.StatusPercentage;
}
}
}
}
else
{
lock (Global.CurrentStatusTable)
{
Global.CurrentStatusTable.Rows.Add(episodeElement.TorrentName, episodeElement.Name, episodeElement.StatusDescription, episodeElement.StatusPercentage);
}
}
}
private void UpdateSeriesDataTable()
{
List<string> episodes = [];
lock (CurrentSeriesDownloader.Episodes)
{
foreach (KeyValuePair<string, SeriesDownloader.EpisodeToDownload> pair in CurrentSeriesDownloader.Episodes)
{
SeriesDownloader.EpisodeToDownload episode = pair.Value;
SetUpdateEpisodesStatusTable(episode);
episodes.Add(episode.Name);
}
}
lock (Global.CurrentStatusTable)
{
using DataTable filteredDataTable = Global.CurrentStatusTable.Clone();
foreach (DataRow row in Global.CurrentStatusTable.AsEnumerable())
{
if (row == null) continue;
string? value = row.Field<string>("Episode");
if (value == null) continue;
if (episodes.Contains(value))
{
filteredDataTable.ImportRow(row);
}
}
Global.CurrentStatusTable.Rows.Clear();
foreach (DataRow row in filteredDataTable.Rows)
{
Global.CurrentStatusTable.Rows.Add(row.ItemArray);
}
}
}
private void PrintUpdateTable()
{
string consoleText = GetConsoleText();
string currentSeries = PrepareCurrentSeries(consoleText);
string currentOpsString = GetCurrentOpsString();
currentOpsString = MatchStringLenghtWithSpaces(currentOpsString, consoleText.Split('\n')[0]);
consoleText += '\n' + currentOpsString;
if (ShouldUpdateConsole(consoleText))
{
consoleText = UpdateConsole(consoleText);
}
consoleText += string.Join('\n', Enumerable.Repeat("", 2).Select(s => MatchStringLenghtWithSpaces(s, consoleText.Split('\n')[0])));
DisplayConsoleText(consoleText);
}
private static string GetConsoleText()
{
string consoleText = string.Empty;
lock (Global.CurrentStatusTable)
{
consoleText += Global.CurrentStatusTable.ToPrettyPrintedString();
}
return consoleText;
}
private string PrepareCurrentSeries(string consoleText)
{
return MatchStringLenghtWithSpaces(CurrentlyScanningSeries, consoleText.Split('\n')[0]);
}
private static string GetCurrentOpsString()
{
var queue = Global.CurrentOpsQueue;
if (queue.Count > 5)
{
while (queue.Count > 1)
{
queue.TryDequeue(out _);
}
queue.TryPeek(out var result);
return result ?? String.Empty;
}
else
{
if (queue.Count < 2)
{
queue.TryPeek(out var result);
return result ?? String.Empty;
}
else
{
queue.TryDequeue(out var result);
return result ?? String.Empty;
}
}
}
private bool ShouldUpdateConsole(string consoleText)
{
int currentLineCount = consoleText.Split('\n').Length;
return currentLineCount != PreviousLineCount ||
Console.BufferWidth != PreviousWindowWidth ||
Console.BufferHeight != PreviousWindowHeight;
}
private string UpdateConsole(string consoleText)
{
PreviousLineCount = consoleText.Split('\n').Length;
PreviousWindowHeight = Console.BufferHeight;
PreviousWindowWidth = Console.BufferWidth;
try
{
Console.Clear();
}
catch (IOException ex)
{
consoleText += "\n[CLS EX:]" + ex.Message;
Global.TaskAdmin.Logger.EX_Log(ex.Message, "UpdateConsole");
}
return consoleText;
}
private static void DisplayConsoleText(string consoleText)
{
Console.SetCursorPosition(0, 0);
Console.CursorVisible = false;
Console.Write(consoleText);
}
public static string MatchStringLenghtWithSpaces(string stringToMatch, string stringToGetLenght)
{
if (stringToMatch.Length > stringToGetLenght.Length) return stringToMatch;
while (stringToMatch.Length < stringToGetLenght.Length)
{
stringToMatch += " ";
}
return stringToMatch;
}
public static void LoadSeriesTable()
{
Global.SeriesTable.Clear();
if (File.Exists(Global.SeriesTableFilePath))
{
lock (Global.SeriesTable)
{
try
{
Global.SeriesTable.ReadXml(Global.SeriesTableFilePath);
}
catch (Exception ex)
{
Global.TaskAdmin.Logger.EX_Log(ex.Message, "LoadSeriesTable");
}
}
}
else
{
lock (Global.SeriesTable) {
if (!Global.SeriesTable.Columns.Contains("Name"))
{
DataColumn[] keys = new DataColumn[1];
DataColumn SeriesColumn = new("Name", typeof(string));
Global.SeriesTable.Columns.Add(SeriesColumn);
keys[0] = SeriesColumn;
Global.SeriesTable.PrimaryKey = keys;
}
if (!Global.SeriesTable.Columns.Contains("Path"))
{
DataColumn SeriesPath = new("Path", typeof(string));
Global.SeriesTable.Columns.Add(SeriesPath);
}
if (!Global.SeriesTable.Columns.Contains("Offset"))
{
DataColumn Offset = new("Offset", typeof(string));
Global.SeriesTable.Columns.Add(Offset);
}
if (!Global.SeriesTable.Columns.Contains("Filter"))
{
DataColumn Filter = new("Filter", typeof(string));
Global.SeriesTable.Columns.Add(Filter);
}
}
}
lock (Global.CurrentStatusTable)
{
Global.CurrentStatusTable.Clear();
if (!Global.CurrentStatusTable.Columns.Contains("Torrent ID")){
Global.CurrentStatusTable.Columns.Add(new DataColumn("Torrent ID", typeof(string)));
}
if (!Global.CurrentStatusTable.Columns.Contains("Episode")){
Global.CurrentStatusTable.Columns.Add(new DataColumn("Episode", typeof(string)));
}
if (!Global.CurrentStatusTable.Columns.Contains("Status")){
Global.CurrentStatusTable.Columns.Add(new DataColumn("Status", typeof(string)));
}
if (!Global.CurrentStatusTable.Columns.Contains("Progress")){
Global.CurrentStatusTable.Columns.Add(new DataColumn("Progress", typeof(string)));
}
Global.CurrentStatusTable.Columns[0].SetWidth(20);
Global.CurrentStatusTable.Columns[1].SetWidth(55);
Global.CurrentStatusTable.Columns[2].SetWidth(30);
Global.CurrentStatusTable.Columns[3].SetWidth(10);
}
}
}
}