PageRenderTime 58ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/JMMServer/JMMServer/Importer.cs

https://bitbucket.org/gibwar/jmm-test
C# | 1143 lines | 876 code | 188 blank | 79 comment | 174 complexity | 8b686622780c52daed477e2aebf67902 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using JMMServer.Repositories;
  6. using JMMServer.Entities;
  7. using JMMServer.Commands;
  8. using NLog;
  9. using System.IO;
  10. using JMMFileHelper;
  11. using JMMServer.Providers.TvDB;
  12. using JMMServer.Providers.MovieDB;
  13. using JMMServer.Providers.TraktTV;
  14. using System.Threading;
  15. using JMMServer.Providers.MyAnimeList;
  16. using JMMServer.Commands.AniDB;
  17. namespace JMMServer
  18. {
  19. public class Importer
  20. {
  21. private static Logger logger = LogManager.GetCurrentClassLogger();
  22. public static void RunImport_IntegrityCheck()
  23. {
  24. VideoLocalRepository repVidLocals = new VideoLocalRepository();
  25. AniDB_FileRepository repAniFile = new AniDB_FileRepository();
  26. AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
  27. AniDB_AnimeRepository repAniAnime = new AniDB_AnimeRepository();
  28. // files which don't have a valid import folder
  29. List<VideoLocal> filesToDelete = repVidLocals.GetVideosWithoutImportFolder();
  30. foreach (VideoLocal vl in filesToDelete)
  31. repVidLocals.Delete(vl.VideoLocalID);
  32. // files which have not been hashed yet
  33. // or files which do not have a VideoInfo record
  34. List<VideoLocal> filesToHash = repVidLocals.GetVideosWithoutHash();
  35. Dictionary<int, VideoLocal> dictFilesToHash = new Dictionary<int, VideoLocal>();
  36. foreach (VideoLocal vl in filesToHash)
  37. {
  38. dictFilesToHash[vl.VideoLocalID] = vl;
  39. CommandRequest_HashFile cmd = new CommandRequest_HashFile(vl.FullServerPath, false);
  40. cmd.Save();
  41. }
  42. List<VideoLocal> filesToRehash = repVidLocals.GetVideosWithoutVideoInfo();
  43. Dictionary<int, VideoLocal> dictFilesToRehash = new Dictionary<int, VideoLocal>();
  44. foreach (VideoLocal vl in filesToHash)
  45. {
  46. dictFilesToRehash[vl.VideoLocalID] = vl;
  47. // don't use if it is in the previous list
  48. if (!dictFilesToHash.ContainsKey(vl.VideoLocalID))
  49. {
  50. try
  51. {
  52. CommandRequest_HashFile cmd = new CommandRequest_HashFile(vl.FullServerPath, false);
  53. cmd.Save();
  54. }
  55. catch (Exception ex)
  56. {
  57. string msg = string.Format("Error RunImport_IntegrityCheck XREF: {0} - {1}", vl.ToStringDetailed(), ex.ToString());
  58. logger.Info(msg);
  59. }
  60. }
  61. }
  62. // files which have been hashed, but don't have an associated episode
  63. List<VideoLocal> filesWithoutEpisode = repVidLocals.GetVideosWithoutEpisode();
  64. Dictionary<int, VideoLocal> dictFilesWithoutEpisode = new Dictionary<int, VideoLocal>();
  65. foreach (VideoLocal vl in filesWithoutEpisode)
  66. dictFilesWithoutEpisode[vl.VideoLocalID] = vl;
  67. // check that all the episode data is populated
  68. List<VideoLocal> filesAll = repVidLocals.GetAll();
  69. Dictionary<string, VideoLocal> dictFilesAllExisting = new Dictionary<string, VideoLocal>();
  70. foreach (VideoLocal vl in filesAll)
  71. {
  72. try
  73. {
  74. dictFilesAllExisting[vl.FullServerPath] = vl;
  75. }
  76. catch (Exception ex)
  77. {
  78. string msg = string.Format("Error RunImport_IntegrityCheck XREF: {0} - {1}", vl.ToStringDetailed(), ex.ToString());
  79. logger.Error(msg);
  80. continue;
  81. }
  82. // check if it has an episode
  83. if (dictFilesWithoutEpisode.ContainsKey(vl.VideoLocalID))
  84. {
  85. CommandRequest_ProcessFile cmd = new CommandRequest_ProcessFile(vl.VideoLocalID, false);
  86. cmd.Save();
  87. continue;
  88. }
  89. // if the file is not manually associated, then check for AniDB_File info
  90. AniDB_File aniFile = repAniFile.GetByHash(vl.Hash);
  91. foreach (CrossRef_File_Episode xref in vl.EpisodeCrossRefs)
  92. {
  93. if (xref.CrossRefSource != (int)CrossRefSource.AniDB) continue;
  94. if (aniFile == null)
  95. {
  96. CommandRequest_ProcessFile cmd = new CommandRequest_ProcessFile(vl.VideoLocalID, false);
  97. cmd.Save();
  98. continue;
  99. }
  100. }
  101. if (aniFile == null) continue;
  102. // the cross ref is created before the actually episode data is downloaded
  103. // so lets check for that
  104. bool missingEpisodes = false;
  105. foreach (CrossRef_File_Episode xref in aniFile.EpisodeCrossRefs)
  106. {
  107. AniDB_Episode ep = repAniEps.GetByEpisodeID(xref.EpisodeID);
  108. if (ep == null) missingEpisodes = true;
  109. }
  110. if (missingEpisodes)
  111. {
  112. // this will then download the anime etc
  113. CommandRequest_ProcessFile cmd = new CommandRequest_ProcessFile(vl.VideoLocalID, false);
  114. cmd.Save();
  115. continue;
  116. }
  117. }
  118. }
  119. public static void RunImport_ScanFolder(int importFolderID)
  120. {
  121. // get a complete list of files
  122. List<string> fileList = new List<string>();
  123. ImportFolderRepository repFolders = new ImportFolderRepository();
  124. int filesFound = 0, videosFound = 0;
  125. int i = 0;
  126. try
  127. {
  128. ImportFolder fldr = repFolders.GetByID(importFolderID);
  129. if (fldr == null) return;
  130. VideoLocalRepository repVidLocals = new VideoLocalRepository();
  131. // first build a list of files that we already know about, as we don't want to process them again
  132. List<VideoLocal> filesAll = repVidLocals.GetAll();
  133. Dictionary<string, VideoLocal> dictFilesExisting = new Dictionary<string, VideoLocal>();
  134. foreach (VideoLocal vl in filesAll)
  135. {
  136. try
  137. {
  138. dictFilesExisting[vl.FullServerPath] = vl;
  139. }
  140. catch (Exception ex)
  141. {
  142. string msg = string.Format("Error RunImport_ScanFolder XREF: {0} - {1}", vl.ToStringDetailed(), ex.ToString());
  143. logger.Info(msg);
  144. }
  145. }
  146. logger.Debug("ImportFolder: {0} || {1}", fldr.ImportFolderName, fldr.ImportFolderLocation);
  147. Utils.GetFilesForImportFolder(fldr.ImportFolderLocation, ref fileList);
  148. // get a list of all files in the share
  149. foreach (string fileName in fileList)
  150. {
  151. i++;
  152. if (dictFilesExisting.ContainsKey(fileName)) continue;
  153. filesFound++;
  154. logger.Info("Processing File {0}/{1} --- {2}", i, fileList.Count, fileName);
  155. if (!FileHashHelper.IsVideo(fileName)) continue;
  156. videosFound++;
  157. CommandRequest_HashFile cr_hashfile = new CommandRequest_HashFile(fileName, false);
  158. cr_hashfile.Save();
  159. }
  160. logger.Debug("Found {0} new files", filesFound);
  161. logger.Debug("Found {0} videos", videosFound);
  162. }
  163. catch (Exception ex)
  164. {
  165. logger.ErrorException(ex.ToString(), ex);
  166. }
  167. }
  168. public static void RunImport_DropFolders()
  169. {
  170. // get a complete list of files
  171. List<string> fileList = new List<string>();
  172. ImportFolderRepository repNetShares = new ImportFolderRepository();
  173. foreach (ImportFolder share in repNetShares.GetAll())
  174. {
  175. if (!share.FolderIsDropSource) continue;
  176. logger.Debug("ImportFolder: {0} || {1}", share.ImportFolderName, share.ImportFolderLocation);
  177. Utils.GetFilesForImportFolder(share.ImportFolderLocation, ref fileList);
  178. }
  179. // get a list of all the shares we are looking at
  180. int filesFound = 0, videosFound = 0;
  181. int i = 0;
  182. // get a list of all files in the share
  183. foreach (string fileName in fileList)
  184. {
  185. i++;
  186. filesFound++;
  187. logger.Info("Processing File {0}/{1} --- {2}", i, fileList.Count, fileName);
  188. if (!FileHashHelper.IsVideo(fileName)) continue;
  189. videosFound++;
  190. CommandRequest_HashFile cr_hashfile = new CommandRequest_HashFile(fileName, false);
  191. cr_hashfile.Save();
  192. }
  193. logger.Debug("Found {0} files", filesFound);
  194. logger.Debug("Found {0} videos", videosFound);
  195. }
  196. public static void RunImport_NewFiles()
  197. {
  198. VideoLocalRepository repVidLocals = new VideoLocalRepository();
  199. // first build a list of files that we already know about, as we don't want to process them again
  200. List<VideoLocal> filesAll = repVidLocals.GetAll();
  201. Dictionary<string, VideoLocal> dictFilesExisting = new Dictionary<string, VideoLocal>();
  202. foreach (VideoLocal vl in filesAll)
  203. {
  204. try
  205. {
  206. dictFilesExisting[vl.FullServerPath] = vl;
  207. }
  208. catch (Exception ex)
  209. {
  210. string msg = string.Format("Error RunImport_NewFiles XREF: {0} - {1}", vl.ToStringDetailed(), ex.ToString());
  211. logger.Info(msg);
  212. //throw;
  213. }
  214. }
  215. // Steps for processing a file
  216. // 1. Check if it is a video file
  217. // 2. Check if we have a VideoLocal record for that file
  218. // .........
  219. // get a complete list of files
  220. List<string> fileList = new List<string>();
  221. ImportFolderRepository repNetShares = new ImportFolderRepository();
  222. foreach (ImportFolder share in repNetShares.GetAll())
  223. {
  224. logger.Debug("ImportFolder: {0} || {1}", share.ImportFolderName, share.ImportFolderLocation);
  225. try
  226. {
  227. Utils.GetFilesForImportFolder(share.ImportFolderLocation, ref fileList);
  228. }
  229. catch (Exception ex)
  230. {
  231. logger.ErrorException(ex.ToString(), ex);
  232. }
  233. }
  234. // get a list fo files that we haven't processed before
  235. List<string> fileListNew = new List<string>();
  236. foreach (string fileName in fileList)
  237. {
  238. if (!dictFilesExisting.ContainsKey(fileName))
  239. fileListNew.Add(fileName);
  240. }
  241. // get a list of all the shares we are looking at
  242. int filesFound = 0, videosFound = 0;
  243. int i = 0;
  244. // get a list of all files in the share
  245. foreach (string fileName in fileListNew)
  246. {
  247. i++;
  248. filesFound++;
  249. logger.Info("Processing File {0}/{1} --- {2}", i, fileList.Count, fileName);
  250. if (!FileHashHelper.IsVideo(fileName)) continue;
  251. videosFound++;
  252. CommandRequest_HashFile cr_hashfile = new CommandRequest_HashFile(fileName, false);
  253. cr_hashfile.Save();
  254. }
  255. logger.Debug("Found {0} files", filesFound);
  256. logger.Debug("Found {0} videos", videosFound);
  257. }
  258. public static void RunImport_GetImages()
  259. {
  260. // AniDB posters
  261. AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
  262. foreach (AniDB_Anime anime in repAnime.GetAll())
  263. {
  264. if (anime.AnimeID == 8580)
  265. Console.Write("");
  266. if (string.IsNullOrEmpty(anime.PosterPath)) continue;
  267. bool fileExists = File.Exists(anime.PosterPath);
  268. if (!fileExists)
  269. {
  270. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(anime.AniDB_AnimeID, JMMImageType.AniDB_Cover, false);
  271. cmd.Save();
  272. }
  273. }
  274. // TvDB Posters
  275. if (ServerSettings.TvDB_AutoPosters)
  276. {
  277. TvDB_ImagePosterRepository repTvPosters = new TvDB_ImagePosterRepository();
  278. Dictionary<int, int> postersCount = new Dictionary<int, int>();
  279. // build a dictionary of series and how many images exist
  280. List<TvDB_ImagePoster> allPosters = repTvPosters.GetAll();
  281. foreach (TvDB_ImagePoster tvPoster in allPosters)
  282. {
  283. if (string.IsNullOrEmpty(tvPoster.FullImagePath)) continue;
  284. bool fileExists = File.Exists(tvPoster.FullImagePath);
  285. if (fileExists)
  286. {
  287. if (postersCount.ContainsKey(tvPoster.SeriesID))
  288. postersCount[tvPoster.SeriesID] = postersCount[tvPoster.SeriesID] + 1;
  289. else
  290. postersCount[tvPoster.SeriesID] = 1;
  291. }
  292. }
  293. foreach (TvDB_ImagePoster tvPoster in allPosters)
  294. {
  295. if (string.IsNullOrEmpty(tvPoster.FullImagePath)) continue;
  296. bool fileExists = File.Exists(tvPoster.FullImagePath);
  297. int postersAvailable = 0;
  298. if (postersCount.ContainsKey(tvPoster.SeriesID))
  299. postersAvailable = postersCount[tvPoster.SeriesID];
  300. if (!fileExists && postersAvailable < ServerSettings.TvDB_AutoPostersAmount)
  301. {
  302. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(tvPoster.TvDB_ImagePosterID, JMMImageType.TvDB_Cover, false);
  303. cmd.Save();
  304. }
  305. }
  306. }
  307. // TvDB Fanart
  308. if (ServerSettings.TvDB_AutoFanart)
  309. {
  310. Dictionary<int, int> fanartCount = new Dictionary<int, int>();
  311. TvDB_ImageFanartRepository repTvFanart = new TvDB_ImageFanartRepository();
  312. List<TvDB_ImageFanart> allFanart = repTvFanart.GetAll();
  313. foreach (TvDB_ImageFanart tvFanart in allFanart)
  314. {
  315. // build a dictionary of series and how many images exist
  316. if (string.IsNullOrEmpty(tvFanart.FullImagePath)) continue;
  317. bool fileExists = File.Exists(tvFanart.FullImagePath);
  318. if (fileExists)
  319. {
  320. if (fanartCount.ContainsKey(tvFanart.SeriesID))
  321. fanartCount[tvFanart.SeriesID] = fanartCount[tvFanart.SeriesID] + 1;
  322. else
  323. fanartCount[tvFanart.SeriesID] = 1;
  324. }
  325. }
  326. foreach (TvDB_ImageFanart tvFanart in allFanart)
  327. {
  328. if (string.IsNullOrEmpty(tvFanart.FullImagePath)) continue;
  329. bool fileExists = File.Exists(tvFanart.FullImagePath);
  330. int fanartAvailable = 0;
  331. if (fanartCount.ContainsKey(tvFanart.SeriesID))
  332. fanartAvailable = fanartCount[tvFanart.SeriesID];
  333. if (!fileExists && fanartAvailable < ServerSettings.TvDB_AutoFanartAmount)
  334. {
  335. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(tvFanart.TvDB_ImageFanartID, JMMImageType.TvDB_FanArt, false);
  336. cmd.Save();
  337. fanartCount[tvFanart.SeriesID] = fanartAvailable + 1;
  338. }
  339. }
  340. }
  341. // TvDB Wide Banners
  342. if (ServerSettings.TvDB_AutoWideBanners)
  343. {
  344. TvDB_ImageWideBannerRepository repTvBanners = new TvDB_ImageWideBannerRepository();
  345. Dictionary<int, int> fanartCount = new Dictionary<int, int>();
  346. // build a dictionary of series and how many images exist
  347. List<TvDB_ImageWideBanner> allBanners = repTvBanners.GetAll();
  348. foreach (TvDB_ImageWideBanner tvBanner in allBanners)
  349. {
  350. if (string.IsNullOrEmpty(tvBanner.FullImagePath)) continue;
  351. bool fileExists = File.Exists(tvBanner.FullImagePath);
  352. if (fileExists)
  353. {
  354. if (fanartCount.ContainsKey(tvBanner.SeriesID))
  355. fanartCount[tvBanner.SeriesID] = fanartCount[tvBanner.SeriesID] + 1;
  356. else
  357. fanartCount[tvBanner.SeriesID] = 1;
  358. }
  359. }
  360. foreach (TvDB_ImageWideBanner tvBanner in allBanners)
  361. {
  362. if (string.IsNullOrEmpty(tvBanner.FullImagePath)) continue;
  363. bool fileExists = File.Exists(tvBanner.FullImagePath);
  364. int bannersAvailable = 0;
  365. if (fanartCount.ContainsKey(tvBanner.SeriesID))
  366. bannersAvailable = fanartCount[tvBanner.SeriesID];
  367. if (!fileExists && bannersAvailable < ServerSettings.TvDB_AutoWideBannersAmount)
  368. {
  369. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(tvBanner.TvDB_ImageWideBannerID, JMMImageType.TvDB_Banner, false);
  370. cmd.Save();
  371. }
  372. }
  373. }
  374. // TvDB Episodes
  375. TvDB_EpisodeRepository repTvEpisodes = new TvDB_EpisodeRepository();
  376. foreach (TvDB_Episode tvEpisode in repTvEpisodes.GetAll())
  377. {
  378. if (string.IsNullOrEmpty(tvEpisode.FullImagePath)) continue;
  379. bool fileExists = File.Exists(tvEpisode.FullImagePath);
  380. if (!fileExists)
  381. {
  382. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(tvEpisode.TvDB_EpisodeID, JMMImageType.TvDB_Episode, false);
  383. cmd.Save();
  384. }
  385. }
  386. // MovieDB Posters
  387. if (ServerSettings.MovieDB_AutoPosters)
  388. {
  389. MovieDB_PosterRepository repMoviePosters = new MovieDB_PosterRepository();
  390. Dictionary<int, int> postersCount = new Dictionary<int, int>();
  391. // build a dictionary of series and how many images exist
  392. List<MovieDB_Poster> allPosters = repMoviePosters.GetAll();
  393. foreach (MovieDB_Poster moviePoster in allPosters)
  394. {
  395. if (string.IsNullOrEmpty(moviePoster.FullImagePath)) continue;
  396. bool fileExists = File.Exists(moviePoster.FullImagePath);
  397. if (fileExists)
  398. {
  399. if (postersCount.ContainsKey(moviePoster.MovieId))
  400. postersCount[moviePoster.MovieId] = postersCount[moviePoster.MovieId] + 1;
  401. else
  402. postersCount[moviePoster.MovieId] = 1;
  403. }
  404. }
  405. foreach (MovieDB_Poster moviePoster in allPosters)
  406. {
  407. if (string.IsNullOrEmpty(moviePoster.FullImagePath)) continue;
  408. bool fileExists = File.Exists(moviePoster.FullImagePath);
  409. int postersAvailable = 0;
  410. if (postersCount.ContainsKey(moviePoster.MovieId))
  411. postersAvailable = postersCount[moviePoster.MovieId];
  412. if (!fileExists && postersAvailable < ServerSettings.MovieDB_AutoPostersAmount)
  413. {
  414. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(moviePoster.MovieDB_PosterID, JMMImageType.MovieDB_Poster, false);
  415. cmd.Save();
  416. }
  417. }
  418. }
  419. // MovieDB Fanart
  420. if (ServerSettings.MovieDB_AutoFanart)
  421. {
  422. MovieDB_FanartRepository repMovieFanarts = new MovieDB_FanartRepository();
  423. Dictionary<int, int> fanartCount = new Dictionary<int, int>();
  424. // build a dictionary of series and how many images exist
  425. List<MovieDB_Fanart> allFanarts = repMovieFanarts.GetAll();
  426. foreach (MovieDB_Fanart movieFanart in allFanarts)
  427. {
  428. if (string.IsNullOrEmpty(movieFanart.FullImagePath)) continue;
  429. bool fileExists = File.Exists(movieFanart.FullImagePath);
  430. if (fileExists)
  431. {
  432. if (fanartCount.ContainsKey(movieFanart.MovieId))
  433. fanartCount[movieFanart.MovieId] = fanartCount[movieFanart.MovieId] + 1;
  434. else
  435. fanartCount[movieFanart.MovieId] = 1;
  436. }
  437. }
  438. foreach (MovieDB_Fanart movieFanart in repMovieFanarts.GetAll())
  439. {
  440. if (string.IsNullOrEmpty(movieFanart.FullImagePath)) continue;
  441. bool fileExists = File.Exists(movieFanart.FullImagePath);
  442. int fanartAvailable = 0;
  443. if (fanartCount.ContainsKey(movieFanart.MovieId))
  444. fanartAvailable = fanartCount[movieFanart.MovieId];
  445. if (!fileExists && fanartAvailable < ServerSettings.MovieDB_AutoFanartAmount)
  446. {
  447. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(movieFanart.MovieDB_FanartID, JMMImageType.MovieDB_FanArt, false);
  448. cmd.Save();
  449. }
  450. }
  451. }
  452. // Trakt Posters
  453. if (ServerSettings.Trakt_DownloadPosters)
  454. {
  455. Trakt_ImagePosterRepository repTraktPosters = new Trakt_ImagePosterRepository();
  456. foreach (Trakt_ImagePoster traktPoster in repTraktPosters.GetAll())
  457. {
  458. if (string.IsNullOrEmpty(traktPoster.FullImagePath)) continue;
  459. bool fileExists = File.Exists(traktPoster.FullImagePath);
  460. if (!fileExists)
  461. {
  462. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(traktPoster.Trakt_ImagePosterID, JMMImageType.Trakt_Poster, false);
  463. cmd.Save();
  464. }
  465. }
  466. }
  467. // Trakt Fanart
  468. if (ServerSettings.Trakt_DownloadFanart)
  469. {
  470. Trakt_ImageFanartRepository repTraktFanarts = new Trakt_ImageFanartRepository();
  471. foreach (Trakt_ImageFanart traktFanart in repTraktFanarts.GetAll())
  472. {
  473. if (string.IsNullOrEmpty(traktFanart.FullImagePath)) continue;
  474. bool fileExists = File.Exists(traktFanart.FullImagePath);
  475. if (!fileExists)
  476. {
  477. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(traktFanart.Trakt_ImageFanartID, JMMImageType.Trakt_Fanart, false);
  478. cmd.Save();
  479. }
  480. }
  481. }
  482. // Trakt Episode
  483. if (ServerSettings.Trakt_DownloadEpisodes)
  484. {
  485. Trakt_EpisodeRepository repTraktEpisodes = new Trakt_EpisodeRepository();
  486. foreach (Trakt_Episode traktEp in repTraktEpisodes.GetAll())
  487. {
  488. if (string.IsNullOrEmpty(traktEp.FullImagePath)) continue;
  489. bool fileExists = File.Exists(traktEp.FullImagePath);
  490. if (!fileExists)
  491. {
  492. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(traktEp.Trakt_EpisodeID, JMMImageType.Trakt_Episode, false);
  493. cmd.Save();
  494. }
  495. }
  496. }
  497. // AniDB Characters
  498. if (ServerSettings.AniDB_DownloadCharacters)
  499. {
  500. AniDB_CharacterRepository repChars = new AniDB_CharacterRepository();
  501. foreach (AniDB_Character chr in repChars.GetAll())
  502. {
  503. if (string.IsNullOrEmpty(chr.PosterPath)) continue;
  504. bool fileExists = File.Exists(chr.PosterPath);
  505. if (!fileExists)
  506. {
  507. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(chr.AniDB_CharacterID, JMMImageType.AniDB_Character, false);
  508. cmd.Save();
  509. }
  510. }
  511. }
  512. // AniDB Creators
  513. if (ServerSettings.AniDB_DownloadCreators)
  514. {
  515. AniDB_SeiyuuRepository repSeiyuu = new AniDB_SeiyuuRepository();
  516. foreach (AniDB_Seiyuu seiyuu in repSeiyuu.GetAll())
  517. {
  518. if (string.IsNullOrEmpty(seiyuu.PosterPath)) continue;
  519. bool fileExists = File.Exists(seiyuu.PosterPath);
  520. if (!fileExists)
  521. {
  522. CommandRequest_DownloadImage cmd = new CommandRequest_DownloadImage(seiyuu.AniDB_SeiyuuID, JMMImageType.AniDB_Creator, false);
  523. cmd.Save();
  524. }
  525. }
  526. }
  527. }
  528. public static void RunImport_ScanTvDB()
  529. {
  530. TvDBHelper.ScanForMatches();
  531. }
  532. public static void RunImport_ScanTrakt()
  533. {
  534. TraktTVHelper.ScanForMatches();
  535. }
  536. public static void RunImport_ScanMovieDB()
  537. {
  538. MovieDBHelper.ScanForMatches();
  539. }
  540. public static void RunImport_ScanMAL()
  541. {
  542. MALHelper.ScanForMatches();
  543. }
  544. public static void RunImport_UpdateTvDB(bool forced)
  545. {
  546. TvDBHelper.UpdateAllInfo(forced);
  547. }
  548. public static void RunImport_UpdateAllAniDB()
  549. {
  550. AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
  551. foreach (AniDB_Anime anime in repAnime.GetAll())
  552. {
  553. CommandRequest_GetAnimeHTTP cmd = new CommandRequest_GetAnimeHTTP(anime.AnimeID, true, false);
  554. cmd.Save();
  555. }
  556. }
  557. public static void RemoveRecordsWithoutPhysicalFiles()
  558. {
  559. VideoLocalRepository repVidLocals = new VideoLocalRepository();
  560. CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();
  561. // get a full list of files
  562. List<VideoLocal> filesAll = repVidLocals.GetAll();
  563. foreach (VideoLocal vl in filesAll)
  564. {
  565. if (!File.Exists(vl.FullServerPath))
  566. {
  567. // delete video local record
  568. logger.Info("RemoveRecordsWithoutPhysicalFiles : {0}", vl.FullServerPath);
  569. repVidLocals.Delete(vl.VideoLocalID);
  570. CommandRequest_DeleteFileFromMyList cmdDel = new CommandRequest_DeleteFileFromMyList(vl.Hash, vl.FileSize);
  571. cmdDel.Save();
  572. }
  573. }
  574. UpdateAllStats();
  575. }
  576. public static string DeleteImportFolder(int importFolderID)
  577. {
  578. try
  579. {
  580. ImportFolderRepository repNS = new ImportFolderRepository();
  581. ImportFolder ns = repNS.GetByID(importFolderID);
  582. if (ns == null) return "Could not find Import Folder ID: " + importFolderID;
  583. // first delete all the files attached to this import folder
  584. Dictionary<int, AnimeSeries> affectedSeries = new Dictionary<int, AnimeSeries>();
  585. VideoLocalRepository repVids = new VideoLocalRepository();
  586. foreach (VideoLocal vid in repVids.GetByImportFolder(importFolderID))
  587. {
  588. //Thread.Sleep(5000);
  589. logger.Info("Deleting video local record: {0}", vid.FullServerPath);
  590. AnimeSeries ser = null;
  591. List<AnimeEpisode> animeEpisodes = vid.GetAnimeEpisodes();
  592. if (animeEpisodes.Count > 0)
  593. {
  594. ser = animeEpisodes[0].GetAnimeSeries();
  595. if (ser != null && !affectedSeries.ContainsKey(ser.AnimeSeriesID))
  596. affectedSeries.Add(ser.AnimeSeriesID, ser);
  597. }
  598. repVids.Delete(vid.VideoLocalID);
  599. }
  600. // delete any duplicate file records which reference this folder
  601. DuplicateFileRepository repDupFiles = new DuplicateFileRepository();
  602. foreach (DuplicateFile df in repDupFiles.GetByImportFolder1(importFolderID))
  603. repDupFiles.Delete(df.DuplicateFileID);
  604. foreach (DuplicateFile df in repDupFiles.GetByImportFolder2(importFolderID))
  605. repDupFiles.Delete(df.DuplicateFileID);
  606. // delete the import folder
  607. repNS.Delete(importFolderID);
  608. ServerInfo.Instance.RefreshImportFolders();
  609. foreach (AnimeSeries ser in affectedSeries.Values)
  610. {
  611. ser.UpdateStats(true, true, true);
  612. StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID);
  613. }
  614. return "";
  615. }
  616. catch (Exception ex)
  617. {
  618. logger.ErrorException(ex.ToString(), ex);
  619. return ex.Message;
  620. }
  621. }
  622. public static void UpdateAllStats()
  623. {
  624. AnimeGroupRepository repGroups = new AnimeGroupRepository();
  625. foreach (AnimeGroup grp in repGroups.GetAllTopLevelGroups())
  626. {
  627. grp.UpdateStatsFromTopLevel(true, true);
  628. }
  629. }
  630. public static int UpdateAniDBFileData(bool missingInfo, bool outOfDate, bool countOnly)
  631. {
  632. List<int> vidsToUpdate = new List<int>();
  633. try
  634. {
  635. AniDB_FileRepository repFiles = new AniDB_FileRepository();
  636. VideoLocalRepository repVids = new VideoLocalRepository();
  637. if (missingInfo)
  638. {
  639. List<VideoLocal> vids = repVids.GetByAniDBResolution("0x0");
  640. foreach (VideoLocal vid in vids)
  641. {
  642. if (!vidsToUpdate.Contains(vid.VideoLocalID))
  643. vidsToUpdate.Add(vid.VideoLocalID);
  644. }
  645. }
  646. if (outOfDate)
  647. {
  648. List<VideoLocal> vids = repVids.GetByInternalVersion(1);
  649. foreach (VideoLocal vid in vids)
  650. {
  651. if (!vidsToUpdate.Contains(vid.VideoLocalID))
  652. vidsToUpdate.Add(vid.VideoLocalID);
  653. }
  654. }
  655. if (!countOnly)
  656. {
  657. foreach (int id in vidsToUpdate)
  658. {
  659. CommandRequest_GetFile cmd = new CommandRequest_GetFile(id, true);
  660. cmd.Save();
  661. }
  662. }
  663. }
  664. catch (Exception ex)
  665. {
  666. logger.ErrorException(ex.ToString(), ex);
  667. }
  668. return vidsToUpdate.Count;
  669. }
  670. public static void CheckForTvDBUpdates(bool forceRefresh)
  671. {
  672. if (ServerSettings.TvDB_UpdateFrequency == ScheduledUpdateFrequency.Never && !forceRefresh) return;
  673. int freqHours = Utils.GetScheduledHours(ServerSettings.TvDB_UpdateFrequency);
  674. // update tvdb info every 12 hours
  675. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  676. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.TvDBInfo);
  677. if (sched != null)
  678. {
  679. // if we have run this in the last 12 hours and are not forcing it, then exit
  680. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  681. if (tsLastRun.TotalHours < freqHours)
  682. {
  683. if (!forceRefresh) return;
  684. }
  685. }
  686. List<int> tvDBIDs = new List<int>();
  687. bool tvDBOnline = false;
  688. string serverTime = JMMService.TvdbHelper.IncrementalTvDBUpdate(ref tvDBIDs, ref tvDBOnline);
  689. if (tvDBOnline)
  690. {
  691. foreach (int tvid in tvDBIDs)
  692. {
  693. // download and update series info, episode info and episode images
  694. // will also download fanart, posters and wide banners
  695. CommandRequest_TvDBUpdateSeriesAndEpisodes cmdSeriesEps = new CommandRequest_TvDBUpdateSeriesAndEpisodes(tvid, false);
  696. cmdSeriesEps.Save();
  697. }
  698. }
  699. if (sched == null)
  700. {
  701. sched = new ScheduledUpdate();
  702. sched.UpdateType = (int)ScheduledUpdateType.TvDBInfo;
  703. }
  704. sched.LastUpdate = DateTime.Now;
  705. sched.UpdateDetails = serverTime;
  706. repSched.Save(sched);
  707. TvDBHelper.ScanForMatches();
  708. }
  709. public static void CheckForCalendarUpdate(bool forceRefresh)
  710. {
  711. if (ServerSettings.AniDB_Calendar_UpdateFrequency == ScheduledUpdateFrequency.Never && !forceRefresh) return;
  712. int freqHours = Utils.GetScheduledHours(ServerSettings.AniDB_Calendar_UpdateFrequency);
  713. // update the calendar every 12 hours
  714. // we will always assume that an anime was downloaded via http first
  715. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  716. AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
  717. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.AniDBCalendar);
  718. if (sched != null)
  719. {
  720. // if we have run this in the last 12 hours and are not forcing it, then exit
  721. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  722. if (tsLastRun.TotalHours < freqHours)
  723. {
  724. if (!forceRefresh) return;
  725. }
  726. }
  727. CommandRequest_GetCalendar cmd = new CommandRequest_GetCalendar(forceRefresh);
  728. cmd.Save();
  729. }
  730. public static void CheckForAnimeUpdate(bool forceRefresh)
  731. {
  732. if (ServerSettings.AniDB_Anime_UpdateFrequency == ScheduledUpdateFrequency.Never && !forceRefresh) return;
  733. int freqHours = Utils.GetScheduledHours(ServerSettings.AniDB_Anime_UpdateFrequency);
  734. // check for any updated anime info every 12 hours
  735. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  736. AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
  737. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.AniDBUpdates);
  738. if (sched != null)
  739. {
  740. // if we have run this in the last 12 hours and are not forcing it, then exit
  741. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  742. if (tsLastRun.TotalHours < freqHours)
  743. {
  744. if (!forceRefresh) return;
  745. }
  746. }
  747. CommandRequest_GetUpdated cmd = new CommandRequest_GetUpdated(true);
  748. cmd.Save();
  749. }
  750. public static void CheckForMALUpdate(bool forceRefresh)
  751. {
  752. if (ServerSettings.AniDB_Anime_UpdateFrequency == ScheduledUpdateFrequency.Never && !forceRefresh) return;
  753. int freqHours = Utils.GetScheduledHours(ServerSettings.MAL_UpdateFrequency);
  754. // check for any updated anime info every 12 hours
  755. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  756. AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
  757. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.MALUpdate);
  758. if (sched != null)
  759. {
  760. // if we have run this in the last 12 hours and are not forcing it, then exit
  761. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  762. if (tsLastRun.TotalHours < freqHours)
  763. {
  764. if (!forceRefresh) return;
  765. }
  766. }
  767. RunImport_ScanMAL();
  768. if (sched == null)
  769. {
  770. sched = new ScheduledUpdate();
  771. sched.UpdateType = (int)ScheduledUpdateType.MALUpdate;
  772. sched.UpdateDetails = "";
  773. }
  774. sched.LastUpdate = DateTime.Now;
  775. repSched.Save(sched);
  776. }
  777. public static void CheckForMyListStatsUpdate(bool forceRefresh)
  778. {
  779. if (ServerSettings.AniDB_MyListStats_UpdateFrequency == ScheduledUpdateFrequency.Never && !forceRefresh) return;
  780. int freqHours = Utils.GetScheduledHours(ServerSettings.AniDB_MyListStats_UpdateFrequency);
  781. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  782. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.AniDBMylistStats);
  783. if (sched != null)
  784. {
  785. // if we have run this in the last 24 hours and are not forcing it, then exit
  786. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  787. logger.Trace("Last AniDB MyList Stats Update: {0} minutes ago", tsLastRun.TotalMinutes);
  788. if (tsLastRun.TotalHours < freqHours)
  789. {
  790. if (!forceRefresh) return;
  791. }
  792. }
  793. CommandRequest_UpdateMylistStats cmd = new CommandRequest_UpdateMylistStats(forceRefresh);
  794. cmd.Save();
  795. }
  796. public static void CheckForMyListSyncUpdate(bool forceRefresh)
  797. {
  798. if (ServerSettings.AniDB_MyList_UpdateFrequency == ScheduledUpdateFrequency.Never && !forceRefresh) return;
  799. int freqHours = Utils.GetScheduledHours(ServerSettings.AniDB_MyList_UpdateFrequency);
  800. // update the calendar every 24 hours
  801. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  802. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.AniDBMyListSync);
  803. if (sched != null)
  804. {
  805. // if we have run this in the last 24 hours and are not forcing it, then exit
  806. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  807. logger.Trace("Last AniDB MyList Sync: {0} minutes ago", tsLastRun.TotalMinutes);
  808. if (tsLastRun.TotalHours < freqHours)
  809. {
  810. if (!forceRefresh) return;
  811. }
  812. }
  813. CommandRequest_SyncMyList cmd = new CommandRequest_SyncMyList(forceRefresh);
  814. cmd.Save();
  815. }
  816. public static void CheckForTraktSyncUpdate(bool forceRefresh)
  817. {
  818. if (ServerSettings.Trakt_SyncFrequency == ScheduledUpdateFrequency.Never && !forceRefresh) return;
  819. int freqHours = Utils.GetScheduledHours(ServerSettings.Trakt_SyncFrequency);
  820. // update the calendar every xxx hours
  821. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  822. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.TraktSync);
  823. if (sched != null)
  824. {
  825. // if we have run this in the last xxx hours and are not forcing it, then exit
  826. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  827. logger.Trace("Last Trakt Sync: {0} minutes ago", tsLastRun.TotalMinutes);
  828. if (tsLastRun.TotalHours < freqHours)
  829. {
  830. if (!forceRefresh) return;
  831. }
  832. }
  833. CommandRequest_TraktSyncCollection cmd = new CommandRequest_TraktSyncCollection(false);
  834. cmd.Save();
  835. }
  836. public static void CheckForTraktAllSeriesUpdate(bool forceRefresh)
  837. {
  838. if (ServerSettings.Trakt_UpdateFrequency == ScheduledUpdateFrequency.Never && !forceRefresh) return;
  839. int freqHours = Utils.GetScheduledHours(ServerSettings.Trakt_UpdateFrequency);
  840. // update the calendar every xxx hours
  841. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  842. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.TraktUpdate);
  843. if (sched != null)
  844. {
  845. // if we have run this in the last xxx hours and are not forcing it, then exit
  846. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  847. logger.Trace("Last Trakt Update: {0} minutes ago", tsLastRun.TotalMinutes);
  848. if (tsLastRun.TotalHours < freqHours)
  849. {
  850. if (!forceRefresh) return;
  851. }
  852. }
  853. CommandRequest_TraktUpdateAllSeries cmd = new CommandRequest_TraktUpdateAllSeries(false);
  854. cmd.Save();
  855. }
  856. public static void CheckForAniDBFileUpdate(bool forceRefresh)
  857. {
  858. if (ServerSettings.AniDB_File_UpdateFrequency == ScheduledUpdateFrequency.Never && !forceRefresh) return;
  859. int freqHours = Utils.GetScheduledHours(ServerSettings.AniDB_File_UpdateFrequency);
  860. // check for any updated anime info every 12 hours
  861. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  862. AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
  863. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.AniDBFileUpdates);
  864. if (sched != null)
  865. {
  866. // if we have run this in the last 12 hours and are not forcing it, then exit
  867. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  868. if (tsLastRun.TotalHours < freqHours)
  869. {
  870. if (!forceRefresh) return;
  871. }
  872. }
  873. UpdateAniDBFileData(true, false, false);
  874. // files which have been hashed, but don't have an associated episode
  875. VideoLocalRepository repVidLocals = new VideoLocalRepository();
  876. List<VideoLocal> filesWithoutEpisode = repVidLocals.GetVideosWithoutEpisode();
  877. foreach (VideoLocal vl in filesWithoutEpisode)
  878. {
  879. CommandRequest_ProcessFile cmd = new CommandRequest_ProcessFile(vl.VideoLocalID, true);
  880. cmd.Save();
  881. }
  882. // now check for any files which have been manually linked and are less than 30 days old
  883. if (sched == null)
  884. {
  885. sched = new ScheduledUpdate();
  886. sched.UpdateType = (int)ScheduledUpdateType.AniDBFileUpdates;
  887. sched.UpdateDetails = "";
  888. }
  889. sched.LastUpdate = DateTime.Now;
  890. repSched.Save(sched);
  891. }
  892. public static void CheckForLogClean()
  893. {
  894. int freqHours = 24;
  895. // check for any updated anime info every 12 hours
  896. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  897. AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
  898. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.LogClean);
  899. if (sched != null)
  900. {
  901. // if we have run this in the last 24 hours and are not forcing it, then exit
  902. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  903. if (tsLastRun.TotalHours < freqHours) return;
  904. }
  905. // files which have been hashed, but don't have an associated episode
  906. LogMessageRepository repVidLocals = new LogMessageRepository();
  907. DateTime logCutoff = DateTime.Now.AddDays(-30);
  908. //DateTime logCutoff = DateTime.Now.AddMinutes(-45);
  909. using (var session = JMMService.SessionFactory.OpenSession())
  910. {
  911. foreach (LogMessage log in repVidLocals.GetAll(session))
  912. {
  913. if (log.LogDate < logCutoff)
  914. repVidLocals.Delete(session, log.LogMessageID);
  915. }
  916. }
  917. // now check for any files which have been manually linked and are less than 30 days old
  918. if (sched == null)
  919. {
  920. sched = new ScheduledUpdate();
  921. sched.UpdateType = (int)ScheduledUpdateType.LogClean;
  922. sched.UpdateDetails = "";
  923. }
  924. sched.LastUpdate = DateTime.Now;
  925. repSched.Save(sched);
  926. }
  927. public static void UpdateAniDBTitles()
  928. {
  929. int freqHours = 100;
  930. bool process = (ServerSettings.AniDB_Username.Equals("jonbaby", StringComparison.InvariantCultureIgnoreCase) ||
  931. ServerSettings.AniDB_Username.Equals("jmediamanager", StringComparison.InvariantCultureIgnoreCase));
  932. if (!process) return;
  933. // check for any updated anime info every 100 hours
  934. ScheduledUpdateRepository repSched = new ScheduledUpdateRepository();
  935. AniDB_AnimeRepository repAnime = new AniDB_AnimeRepository();
  936. ScheduledUpdate sched = repSched.GetByUpdateType((int)ScheduledUpdateType.AniDBTitles);
  937. if (sched != null)
  938. {
  939. // if we have run this in the last 100 hours and are not forcing it, then exit
  940. TimeSpan tsLastRun = DateTime.Now - sched.LastUpdate;
  941. if (tsLastRun.TotalHours < freqHours) return;
  942. }
  943. if (sched == null)
  944. {
  945. sched = new ScheduledUpdate();
  946. sched.UpdateType = (int)ScheduledUpdateType.AniDBTitles;
  947. sched.UpdateDetails = "";
  948. }
  949. sched.LastUpdate = DateTime.Now;
  950. repSched.Save(sched);
  951. CommandRequest_GetAniDBTitles cmd = new CommandRequest_GetAniDBTitles();
  952. cmd.Save();
  953. }
  954. }
  955. }