-
Notifications
You must be signed in to change notification settings - Fork 74
/
Common.cs
3358 lines (3025 loc) · 130 KB
/
Common.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 System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Dynamic;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using NLog;
using Shoko.Commons.Extensions;
using Shoko.Commons.Utils;
using Shoko.Models.Client;
using Shoko.Models.Enums;
using Shoko.Models.Server;
using Shoko.Server.API.v2.Models;
using Shoko.Server.API.v2.Models.common;
using Shoko.Server.API.v2.Models.core;
using Shoko.Server.Commands;
using Shoko.Server.Extensions;
using Shoko.Server.Models;
using Shoko.Server.Repositories;
namespace Shoko.Server.API.v2.Modules
{
//As responds for this API we throw object that will be converted to json/xml
[Authorize]
[Route("/api")]
[ApiVersion("2.0")]
[ApiController]
public class Common : BaseController
{
//class will be found automagically thanks to inherits also class need to be public (or it will 404)
public Common()
{
}
#region 01. Import Folders
/// <summary>
/// Handle /api/folder/list
/// List all saved Import Folders
/// </summary>
/// <returns>List<Contract_ImportFolder></returns>
[HttpGet("folder/list")]
public ActionResult<IEnumerable<ImportFolder>> GetFolders() => new ShokoServiceImplementation().GetImportFolders();
/// <summary>
/// Handle /api/folder/count
/// </summary>
/// <returns>Counter</returns>
[HttpGet("folder/count")]
public ActionResult<Counter> CountFolders()
{
Counter count = new Counter
{
count = new ShokoServiceImplementation().GetImportFolders().Count
};
return count;
}
/// <summary>
/// Handle /api/folder/add
/// Add Folder to Import Folders Repository
/// </summary>
/// <returns>APIStatus</returns>
[HttpPost("folder/add")]
public ActionResult<ImportFolder> AddFolder(ImportFolder folder)
{
if (!ModelState.IsValid) return BadRequest(ModelState);
try
{
var result = RepoFactory.ImportFolder.SaveImportFolder(folder);
return result;
}
catch (Exception e)
{
return InternalError(e.Message);
}
}
/// <summary>
/// Handle /api/folder/edit
/// Edit folder giving fulll ImportFolder object with ID
/// </summary>
/// <returns>APIStatus</returns>
[HttpPost("folder/edit")]
public ActionResult<ImportFolder> EditFolder(ImportFolder folder)
{
if (string.IsNullOrEmpty(folder.ImportFolderLocation) || folder.ImportFolderID == 0)
return new APIMessage(StatusCodes.Status400BadRequest,
"ImportFolderLocation and ImportFolderID missing");
try
{
if (folder.IsDropDestination == 1 && folder.IsDropSource == 1)
return new APIMessage(StatusCodes.Status409Conflict,
"The Folder Can't be both Destination and Source Simultaneously");
if (folder.ImportFolderID == 0)
return new APIMessage(StatusCodes.Status409Conflict, "The Import Folder must have an ID");
ImportFolder response = RepoFactory.ImportFolder.SaveImportFolder(folder);
return response;
}
catch (Exception e)
{
return InternalError(e.Message);
}
}
/// <summary>
/// Handle /api/folder/delete
/// Delete Import Folder out of Import Folder Repo.Instance.itory
/// </summary>
/// <returns>APIStatus</returns>
[HttpPost("folder/delete")]
public ActionResult DeleteFolder(int folderId)
{
if (folderId == 0) return new APIMessage(400, "ImportFolderID missing");
string res = Importer.DeleteImportFolder(folderId);
return string.IsNullOrEmpty(res) ? Ok() : InternalError(res);
}
/// <summary>
/// Handle /api/folder/import
/// Run Import action on all Import Folders inside Import Folders Repository
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("folder/import")]
public ActionResult RunImport()
{
ShokoServer.RunImport();
return Ok();
}
/// <summary>
/// Handle /api/folder/scan
/// Scan All Drop Folders
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("folder/scan")]
public ActionResult ScanDropFolders()
{
Importer.RunImport_DropFolders();
return Ok();
}
#endregion
#region 03. Actions
/// <summary>
/// Handle /api/remove_missing_files
/// Scans your import folders and remove files from your database that are no longer in your collection.
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("remove_missing_files")]
public ActionResult RemoveMissingFiles()
{
ShokoServer.RemoveMissingFiles();
return Ok();
}
/// <summary>
/// Handle /api/stats_update
/// Updates all series stats such as watched state and missing files.
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("stats_update")]
public ActionResult UpdateStats()
{
Importer.UpdateAllStats();
return Ok();
}
/// <summary>
/// Handle /api/mediainfo_update
/// Updates all technical details about the files in your collection via running MediaInfo on them.
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("medainfo_update")]
public ActionResult UpdateMediaInfo()
{
ShokoServer.RefreshAllMediaInfo();
return Ok();
}
/// <summary>
/// Handle /api/hash/sync
/// Sync Hashes - download/upload hashes from/to webcache
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("hash/sync")]
public ActionResult HashSync()
{
ShokoServer.SyncHashes();
return Ok();
}
/// <summary>
/// Handle /api/rescan
/// Rescan ImportFolder (with given id) to recognize new episodes
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("rescan")]
public ActionResult RescanVideoLocal(int id)
{
if (id == 0) return BadRequest("missing 'id'");
try
{
SVR_VideoLocal vid = RepoFactory.VideoLocal.GetByID(id);
if (vid == null) return NotFound();
if (string.IsNullOrEmpty(vid.Hash))
return BadRequest("Could not Update a cloud file without hash, hash it locally first");
CommandRequest_ProcessFile cmd =
new CommandRequest_ProcessFile(vid.VideoLocalID, true);
cmd.Save();
return Ok();
}
catch (Exception ex)
{
return InternalError(ex.Message);
}
}
/// <summary>
/// Handle /api/rescanunlinked
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("rescanunlinked")]
public ActionResult RescanUnlinked()
{
try
{
// files which have been hashed, but don't have an associated episode
List<SVR_VideoLocal> filesWithoutEpisode = RepoFactory.VideoLocal.GetVideosWithoutEpisode();
foreach (SVR_VideoLocal vl in filesWithoutEpisode.Where(a => !string.IsNullOrEmpty(a.Hash)))
{
CommandRequest_ProcessFile cmd = new CommandRequest_ProcessFile(vl.VideoLocalID, true);
cmd.Save();
}
return Ok();
}
catch (Exception ex)
{
return InternalError(ex.Message);
}
}
/// <summary>
/// Handle /api/rescanmanuallinks
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("rescanmanuallinks")]
public ActionResult RescanManualLinks()
{
try
{
// files which have been hashed, but don't have an associated episode
List<SVR_VideoLocal> filesWithoutEpisode = RepoFactory.VideoLocal.GetManuallyLinkedVideos();
foreach (SVR_VideoLocal vl in filesWithoutEpisode.Where(a => !string.IsNullOrEmpty(a.Hash)))
{
CommandRequest_ProcessFile cmd = new CommandRequest_ProcessFile(vl.VideoLocalID, true);
cmd.Save();
}
return Ok();
}
catch (Exception ex)
{
return InternalError(ex.Message);
}
}
/// <summary>
/// Handle /api/rehash
/// Rehash given files in given VideoLocal
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("rehash")]
public ActionResult RehashVideoLocal(int id)
{
if (id == 0) return BadRequest("missing 'id'");
SVR_VideoLocal vl = RepoFactory.VideoLocal.GetByID(id);
if (vl == null) return NotFound("VideoLocal Not Found");
SVR_VideoLocal_Place pl = vl.GetBestVideoLocalPlace(true);
if (pl?.FullServerPath == null) return NotFound("videolocal_place not found");
CommandRequest_HashFile cr_hashfile = new CommandRequest_HashFile(pl.FullServerPath, true);
cr_hashfile.Save();
return Ok();
}
/// <summary>
/// Handle /api/rehashunlinked
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("rehashunlinked")]
public ActionResult RehashUnlinked()
{
try
{
// files which have been hashed, but don't have an associated episode
foreach (SVR_VideoLocal vl in RepoFactory.VideoLocal.GetVideosWithoutEpisode())
{
SVR_VideoLocal_Place pl = vl.GetBestVideoLocalPlace(true);
if (pl?.FullServerPath == null) continue;
CommandRequest_HashFile cr_hashfile = new CommandRequest_HashFile(pl.FullServerPath, true);
cr_hashfile.Save();
}
}
catch (Exception ex)
{
return InternalError(ex.Message);
}
return Ok();
}
/// <summary>
/// Handle /api/rehashmanuallinks
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("rehashmanuallinks")]
public ActionResult RehashManualLinks()
{
try
{
// files which have been hashed, but don't have an associated episode
foreach (SVR_VideoLocal vl in RepoFactory.VideoLocal.GetManuallyLinkedVideos())
{
SVR_VideoLocal_Place pl = vl.GetBestVideoLocalPlace(true);
if (pl?.FullServerPath == null) continue;
CommandRequest_HashFile cr_hashfile = new CommandRequest_HashFile(pl.FullServerPath, true);
cr_hashfile.Save();
}
}
catch (Exception ex)
{
return InternalError(ex.Message);
}
return Ok();
}
#endregion
#region 04. Misc
/// <summary>
/// Returns current user ID for use in legacy calls
/// </summary>
/// <returns>userid = int</returns>
[HttpGet("myid/get")]
public object MyID()
{
JMMUser user = HttpContext.GetUser();
dynamic x = new ExpandoObject();
if (user != null)
{
x.userid = user.JMMUserID;
return x;
}
x.userid = 0;
return x;
}
/// <summary>
/// Return newest posts from
/// </summary>
/// <returns>List<WebNews></returns>
[HttpGet("news/get")]
public List<WebNews> GetNews(int max)
{
var client = new WebClient();
client.Headers.Add("User-Agent", "jmmserver");
client.Headers.Add("Accept", "application/json");
var response = client.DownloadString(new Uri("http://shokoanime.com/wp-json/wp/v2/posts"));
List<dynamic> news_feed = JsonConvert.DeserializeObject<List<dynamic>>(response);
List<WebNews> news = new List<WebNews>();
int limit = 0;
foreach (dynamic post in news_feed)
{
limit++;
WebNews wn = new WebNews
{
author = post.author,
date = post.date,
link = post.link,
title = HttpUtility.HtmlDecode((string)post.title.rendered),
description = post.excerpt.rendered
};
news.Add(wn);
if (limit >= max) break;
}
return news;
}
/// <summary>
/// Handle /api/search
/// </summary>
/// <returns>Filter or APIStatu</returns>
[HttpGet("search")]
public ActionResult<Filter> BigSearch([FromQuery] API_Call_Parameters para)
{
JMMUser user = HttpContext.GetUser();
string query = para.query.ToLowerInvariant();
if (para.limit == 0)
{
//hardcoded
para.limit = 100;
}
if (query != string.Empty)
{
Filter search_filter = new Filter
{
name = "Search",
groups = new List<Group>()
};
Group search_group = new Group
{
name = para.query,
series = new List<Serie>()
};
search_group.series = Search(query, para.limit, para.limit_tag, (int) para.offset,
para.tags, user.JMMUserID, para.nocast != 0, para.notag != 0, para.level, para.all != 0,
para.fuzzy != 0, para.allpics != 0, para.pic, para.tagfilter).Value.ToList();
search_group.size = search_group.series.Count();
search_filter.groups.Add(search_group);
search_filter.size = search_filter.groups.Count();
return search_filter;
}
return BadRequest("missing 'query'");
}
/// <summary>
/// Handle /api/startswith
/// </summary>
/// <returns>Filter or APIStatus</returns>
[HttpGet("serie/startswith")]
public ActionResult<Filter> SearchStartsWith([FromQuery] API_Call_Parameters para)
{
JMMUser user = HttpContext.GetUser();
string query = para.query.ToLowerInvariant();
if (para.limit == 0)
{
//hardcoded
para.limit = 100;
}
if (query != string.Empty)
{
Filter search_filter = new Filter
{
name = "Search",
groups = new List<Group>()
};
Group search_group = new Group
{
name = para.query,
series = new List<Serie>()
};
search_group.series = (List<Serie>) (StartsWith(query, para.limit, user.JMMUserID, para.nocast != 0,
para.notag != 0, para.level, para.all != 0, para.allpics != 0, para.pic, para.tagfilter));
search_group.size = search_group.series.Count();
search_filter.groups.Add(search_group);
search_filter.size = search_filter.groups.Count();
return search_filter;
}
return BadRequest("missing 'query'");
}
/// <summary>
/// Handle /api/ping
/// </summary>
/// <returns>"pong" if user if valid correct - to check if connection and auth is valid without ask for real data</returns>
[HttpGet("ping")]
public ActionResult<Dictionary<string, string>> Ping()
{
// No need to check for user or anything. It won't get here if the user is invalid.
var x = new Dictionary<string, string> {["response"] = "pong"};
return x;
}
#endregion
#region 05. Queue
/// <summary>
/// Return current information about Queues (hash, general, images)
/// </summary>
/// <returns>Dictionary<string, QueueInfo></returns>
[HttpGet("queue/get")]
public ActionResult<Dictionary<string, QueueInfo>> GetQueue()
{
Dictionary<string, QueueInfo> queues = new Dictionary<string, QueueInfo>();
queues.Add("hash", GetHasherQueue().Value);
queues.Add("general", GetGeneralQueue().Value);
queues.Add("image", GetImagesQueue().Value);
return queues;
}
/// <summary>
/// Pause all running Queues
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/pause")]
public ActionResult PauseQueue()
{
ShokoService.CmdProcessorHasher.Paused = true;
ShokoService.CmdProcessorGeneral.Paused = true;
ShokoService.CmdProcessorImages.Paused = true;
return Ok();
}
/// <summary>
/// Start all queues that are pasued
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/start")]
public ActionResult StartQueue()
{
ShokoService.CmdProcessorHasher.Paused = false;
ShokoService.CmdProcessorGeneral.Paused = false;
ShokoService.CmdProcessorImages.Paused = false;
return Ok();
}
/// <summary>
/// Return information about Hasher queue
/// </summary>
/// <returns>QueueInfo</returns>
[HttpGet("queue/hasher/get")]
public ActionResult<QueueInfo> GetHasherQueue()
{
QueueInfo queue = new QueueInfo
{
count = ServerInfo.Instance.HasherQueueCount,
state = ServerInfo.Instance.HasherQueueState,
isrunning = ServerInfo.Instance.HasherQueueRunning,
ispause = ServerInfo.Instance.HasherQueuePaused
};
return queue;
}
/// <summary>
/// Return information about General queue
/// </summary>
/// <returns>QueueInfo</returns>
[HttpGet("queue/general/get")]
public ActionResult<QueueInfo> GetGeneralQueue()
{
QueueInfo queue = new QueueInfo
{
count = ServerInfo.Instance.GeneralQueueCount,
state = ServerInfo.Instance.GeneralQueueState,
isrunning = ServerInfo.Instance.GeneralQueueRunning,
ispause = ServerInfo.Instance.GeneralQueuePaused
};
return queue;
}
/// <summary>
/// Return information about Images queue
/// </summary>
/// <returns>QueueInfo</returns>
[HttpGet("queue/images/get")]
public ActionResult<QueueInfo> GetImagesQueue()
{
QueueInfo queue = new QueueInfo
{
count = ServerInfo.Instance.ImagesQueueCount,
state = ServerInfo.Instance.ImagesQueueState,
isrunning = ServerInfo.Instance.ImagesQueueRunning,
ispause = ServerInfo.Instance.ImagesQueuePaused
};
return queue;
}
/// <summary>
/// Pause Queue
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/hasher/pause")]
public ActionResult PauseHasherQueue()
{
ShokoService.CmdProcessorHasher.Paused = true;
return Ok();
}
/// <summary>
/// Pause Queue
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/general/pause")]
public ActionResult PauseGeneralQueue()
{
ShokoService.CmdProcessorGeneral.Paused = true;
return Ok();
}
/// <summary>
/// Pause Queue
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/images/pause")]
public ActionResult PauseImagesQueue()
{
ShokoService.CmdProcessorImages.Paused = true;
return Ok();
}
/// <summary>
/// Start Queue from Pause state
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/hasher/start")]
public ActionResult StartHasherQueue()
{
ShokoService.CmdProcessorHasher.Paused = false;
return Ok();
}
/// <summary>
/// Start Queue from Pause state
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/general/start")]
public ActionResult StartGeneralQueue()
{
ShokoService.CmdProcessorGeneral.Paused = false;
return Ok();
}
/// <summary>
/// Start Queue from Pause state
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/images/start")]
public ActionResult StartImagesQueue()
{
ShokoService.CmdProcessorImages.Paused = false;
return Ok();
}
/// <summary>
/// Clear Queue and Restart it
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/hasher/clear")]
public ActionResult ClearHasherQueue()
{
try
{
ShokoService.CmdProcessorHasher.Stop();
RepoFactory.CommandRequest.ClearHasherQueue();
ShokoService.CmdProcessorHasher.Init();
return Ok();
}
catch
{
return InternalError();
}
}
/// <summary>
/// Clear Queue and Restart it
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/general/clear")]
public ActionResult ClearGeneralQueue()
{
try
{
ShokoService.CmdProcessorGeneral.Stop();
RepoFactory.CommandRequest.ClearGeneralQueue();
ShokoService.CmdProcessorGeneral.Init();
return Ok();
}
catch
{
return InternalError();
}
}
/// <summary>
/// Clear Queue and Restart it
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("queue/images/clear")]
public ActionResult ClearImagesQueue()
{
try
{
ShokoService.CmdProcessorImages.Stop();
RepoFactory.CommandRequest.ClearImageQueue();
ShokoService.CmdProcessorImages.Init();
return Ok();
}
catch
{
return InternalError();
}
}
#endregion
#region 06. Files
/// <summary>
/// Handle /api/file
/// </summary>
/// <returns>List<RawFile> or RawFile or APIStatus</returns>
[HttpGet("file")]
public object GetFile(int id = 0, int limit = 0, int level = 0)
{
JMMUser user = HttpContext.GetUser();
return id == 0
? GetAllFiles(limit, level, user.JMMUserID)
: GetFileById(id, level, user.JMMUserID);
}
/// <summary>
/// Gets files whose data does not match AniDB
/// </summary>
/// <returns></returns>
[HttpGet("file/needsavdumped")]
public ActionResult<List<RawFile>> GetFilesWithMismatchedInfo(int level)
{
JMMUser user = HttpContext.GetUser();
var allvids = RepoFactory.VideoLocal.GetAll().Where(vid => !vid.IsEmpty() && vid.Media != null)
.ToDictionary(a => a, a => a.GetAniDBFile());
return allvids.Keys.Select(vid => new {vid, anidb = allvids[vid]})
.Where(_tuple => _tuple.anidb != null)
.Where(_tuple => _tuple.anidb.IsDeprecated != 1)
.Where(_tuple => _tuple.vid.Media.Chaptered != (_tuple.anidb.IsChaptered == 1))
.Select(_tuple => GetFileById(_tuple.vid.VideoLocalID, level, user.JMMUserID).Value).ToList();
}
/// <summary>
/// Gets files whose data does not match AniDB
/// </summary>
/// <returns></returns>
[HttpGet("avdumpmismatchedfiles")]
public ActionResult AVDumpMismatchedFiles()
{
var allvids = RepoFactory.VideoLocal.GetAll().Where(vid => !vid.IsEmpty() && vid.Media != null)
.ToDictionary(a => a, a => a.GetAniDBFile());
Logger logger = LogManager.GetCurrentClassLogger();
Task.Factory.StartNew(() =>
{
var list = allvids.Keys.Select(vid => new {vid, anidb = allvids[vid]})
.Where(_tuple => _tuple.anidb != null)
.Where(_tuple => _tuple.anidb.IsDeprecated != 1)
.Where(_tuple => _tuple.vid.Media.Chaptered != (_tuple.anidb.IsChaptered == 1))
.Select(_tuple => _tuple.vid.GetBestVideoLocalPlace(true)?.FullServerPath)
.Where(path => !string.IsNullOrEmpty(path)).ToList();
int index = 0;
foreach (var path in list)
{
logger.Info($"AVDump Start {index + 1}/{list.Count}: {path}");
AVDumpHelper.DumpFile(path);
logger.Info($"AVDump Finished {index + 1}/{list.Count}: {path}");
index++;
logger.Info($"AVDump Progress: {list.Count - index} remaining");
}
});
return Ok();
}
/// <summary>
/// Gets files that are deprecated on AniDB
/// </summary>
/// <returns></returns>
[HttpGet("file/deprecated")]
public ActionResult<List<RawFile>> GetDeprecatedFiles(int level)
{
JMMUser user = HttpContext.GetUser();
var allvids = RepoFactory.VideoLocal.GetAll()
.Where(a => !a.IsEmpty() && a.GetAniDBFile() != null && a.GetAniDBFile().IsDeprecated == 1).ToList();
return allvids.Select(vid => GetFileById(vid.VideoLocalID, level, user.JMMUserID).Value).ToList();
}
/// <summary>
/// handle /api/file/multiple
/// </summary>
/// <returns></returns>
[HttpGet("file/multiple")]
private object GetMultipleFiles([FromQuery] API_Call_Parameters para)
{
JMMUser user = HttpContext.GetUser();
int userID = user.JMMUserID;
Dictionary<int,Serie> results = new Dictionary<int, Serie>();
try
{
List<SVR_AnimeEpisode> list = RepoFactory.AnimeEpisode.GetEpisodesWithMultipleFiles(true).ToList();
foreach(SVR_AnimeEpisode ep in list)
{
Serie serie = null;
SVR_AnimeSeries series = ep?.GetAnimeSeries();
if (series == null) continue;
if (results.ContainsKey(series.AnimeSeriesID)) serie = results[series.AnimeSeriesID];
if (serie == null)
serie =
Serie.GenerateFromAnimeSeries(HttpContext, series, userID, para.nocast == 1,
para.notag == 1, 0,
false, para.allpics != 0, para.pic, para.tagfilter);
if (serie.eps == null) serie.eps = new List<Episode>();
Episode episode = Episode.GenerateFromAnimeEpisode(HttpContext, ep, userID, 0);
List<SVR_VideoLocal> vls = ep.GetVideoLocals();
if (vls.Count > 0)
{
episode.files = new List<RawFile>();
vls.Sort(FileQualityFilter.CompareTo);
bool first = true;
foreach (SVR_VideoLocal vl in vls)
{
RawFile file = new RawFile(HttpContext, vl, 0, userID, ep);
if (first)
{
file.is_preferred = 1;
first = false;
}
episode.files.Add(file);
}
}
serie.eps.Add(episode);
results[series.AnimeSeriesID] = serie;
}
}
catch (Exception ex)
{
LogManager.GetCurrentClassLogger().Error(ex, ex.ToString());
}
return results.Values;
}
/// <summary>
/// Handle /api/file/count
/// </summary>
/// <returns>Counter</returns>
[HttpGet("file/count")]
public Counter CountFiles()
{
return new Counter
{
count = RepoFactory.VideoLocal.GetAll().Count
};
}
/// <summary>
/// Handle /api/file/recent
/// </summary>
/// <returns>List<RawFile></returns>
[HttpGet("file/recent")]
public List<RawFile> GetRecentFiles(int limit = 0, int level = 0)
{
JMMUser user = HttpContext.GetUser();
// default 50 as that's reasonable
if (limit == 0) limit = 50;
List<RawFile> list = new List<RawFile>();
foreach (SVR_VideoLocal file in RepoFactory.VideoLocal.GetMostRecentlyAdded(limit, user.JMMUserID))
{
var allowed = !file.GetAnimeEpisodes().Any(a => a.GetAnimeSeries()?.GetAnime()?.GetAllTags()
?.FindInEnumerable(user.GetHideCategories()) ?? false);
if (allowed) list.Add(new RawFile(HttpContext, file, level, user?.JMMUserID ?? 0));
}
return list;
}
/// <summary>
/// Handle /api/file/unsort
/// </summary>
/// <returns>List<RawFile></returns>
[HttpGet("file/unsort")]
public List<RawFile> GetUnsort(int offset = 0, int level = 0, int limit = 0)
{
JMMUser user = HttpContext.GetUser();
List<RawFile> lst = new List<RawFile>();
List<SVR_VideoLocal> vids = RepoFactory.VideoLocal.GetVideosWithoutEpisode();
foreach (SVR_VideoLocal vl in vids)
{
if (offset == 0)
{
RawFile v = new RawFile(HttpContext, vl, level, user.JMMUserID);
lst.Add(v);
if (limit != 0 && lst.Count >= limit)
{
break;
}
}
else
{
offset--;
}
}
return lst;
}
/// <summary>
/// Handle /api/file/offset
/// </summary>
/// <returns>APIStatus</returns>
[HttpPost("file/offset")]
public ActionResult SetFileOffset([FromBody] API_Call_Parameters para)
{
JMMUser user = HttpContext.GetUser();
int id = para.id;
long offset = para.offset;
// allow to offset be 0 to reset position
if (id == 0 || offset < 0)
{
return BadRequest("Invalid arguments");
}
SVR_VideoLocal vlu = RepoFactory.VideoLocal.GetByID(id);
if (vlu != null)
{
vlu.SetResumePosition(offset, user.JMMUserID);
return Ok();
}
return NotFound();
}
/// <summary>
/// Handle /api/file/watch
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("file/watch")]
private object MarkFileAsWatched(int id)
{
JMMUser user = HttpContext.GetUser();
if (id != 0)
{
return MarkFile(true, id, user.JMMUserID);
}
return BadRequest("missing 'id'");
}
/// <summary>
/// Handle /api/file/unwatch
/// </summary>
/// <returns>APIStatus</returns>
[HttpGet("file/unwatch")]
private object MarkFileAsUnwatched(int id)
{
JMMUser user = HttpContext.GetUser();
if (id != 0)
{
return MarkFile(false, id, user.JMMUserID);
}
return BadRequest("missing 'id'");
}
#region internal function
/// <summary>
/// Internal function returning file with given id
/// </summary>
/// <param name="file_id">file id</param>
/// <param name="level">deep level</param>
/// <param name="uid">user id</param>
/// <returns>RawFile or APIStatus</returns>
internal ActionResult<RawFile> GetFileById(int file_id, int level, int uid)
{
SVR_VideoLocal vl = RepoFactory.VideoLocal.GetByID(file_id);
if (vl != null)
{
RawFile rawfile = new RawFile(HttpContext, vl, level, uid);
return rawfile;
}