SeriesResolver.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  1. using MediaBrowser.Common.IO;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Audio;
  4. using MediaBrowser.Controller.Entities.TV;
  5. using MediaBrowser.Controller.Library;
  6. using MediaBrowser.Controller.Providers;
  7. using MediaBrowser.Controller.Resolvers;
  8. using MediaBrowser.Model.Entities;
  9. using MediaBrowser.Model.Logging;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.Globalization;
  13. using System.IO;
  14. using System.Linq;
  15. using System.Text.RegularExpressions;
  16. namespace MediaBrowser.Server.Implementations.Library.Resolvers.TV
  17. {
  18. /// <summary>
  19. /// Class SeriesResolver
  20. /// </summary>
  21. public class SeriesResolver : FolderResolver<Series>
  22. {
  23. private readonly IFileSystem _fileSystem;
  24. private readonly ILogger _logger;
  25. private readonly ILibraryManager _libraryManager;
  26. public SeriesResolver(IFileSystem fileSystem, ILogger logger, ILibraryManager libraryManager)
  27. {
  28. _fileSystem = fileSystem;
  29. _logger = logger;
  30. _libraryManager = libraryManager;
  31. }
  32. /// <summary>
  33. /// Gets the priority.
  34. /// </summary>
  35. /// <value>The priority.</value>
  36. public override ResolverPriority Priority
  37. {
  38. get
  39. {
  40. return ResolverPriority.Second;
  41. }
  42. }
  43. /// <summary>
  44. /// Resolves the specified args.
  45. /// </summary>
  46. /// <param name="args">The args.</param>
  47. /// <returns>Series.</returns>
  48. protected override Series Resolve(ItemResolveArgs args)
  49. {
  50. if (args.IsDirectory)
  51. {
  52. // Avoid expensive tests against VF's and all their children by not allowing this
  53. if (args.Parent == null || args.Parent.IsRoot)
  54. {
  55. return null;
  56. }
  57. // Optimization to avoid running these tests against Seasons
  58. if (args.Parent is Series || args.Parent is Season || args.Parent is MusicArtist || args.Parent is MusicAlbum)
  59. {
  60. return null;
  61. }
  62. var collectionType = args.GetCollectionType();
  63. var isTvShowsFolder = string.Equals(collectionType, CollectionType.TvShows,
  64. StringComparison.OrdinalIgnoreCase);
  65. // If there's a collection type and it's not tv, it can't be a series
  66. if (!string.IsNullOrEmpty(collectionType) &&
  67. !isTvShowsFolder &&
  68. !string.Equals(collectionType, CollectionType.BoxSets, StringComparison.OrdinalIgnoreCase))
  69. {
  70. return null;
  71. }
  72. if (IsSeriesFolder(args.Path, isTvShowsFolder, args.FileSystemChildren, args.DirectoryService, _fileSystem, _logger, _libraryManager))
  73. {
  74. return new Series
  75. {
  76. Path = args.Path,
  77. Name = Path.GetFileName(args.Path)
  78. };
  79. }
  80. }
  81. return null;
  82. }
  83. /// <summary>
  84. /// Determines whether [is series folder] [the specified path].
  85. /// </summary>
  86. /// <param name="path">The path.</param>
  87. /// <param name="considerSeasonlessEntries">if set to <c>true</c> [consider seasonless entries].</param>
  88. /// <param name="fileSystemChildren">The file system children.</param>
  89. /// <param name="directoryService">The directory service.</param>
  90. /// <param name="fileSystem">The file system.</param>
  91. /// <param name="logger">The logger.</param>
  92. /// <param name="libraryManager">The library manager.</param>
  93. /// <returns><c>true</c> if [is series folder] [the specified path]; otherwise, <c>false</c>.</returns>
  94. public static bool IsSeriesFolder(string path, bool considerSeasonlessEntries, IEnumerable<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService, IFileSystem fileSystem, ILogger logger, ILibraryManager libraryManager)
  95. {
  96. foreach (var child in fileSystemChildren)
  97. {
  98. var attributes = child.Attributes;
  99. if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  100. {
  101. //logger.Debug("Igoring series file or folder marked hidden: {0}", child.FullName);
  102. continue;
  103. }
  104. // Can't enforce this because files saved by Bitcasa are always marked System
  105. //if ((attributes & FileAttributes.System) == FileAttributes.System)
  106. //{
  107. // logger.Debug("Igoring series subfolder marked system: {0}", child.FullName);
  108. // continue;
  109. //}
  110. if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
  111. {
  112. if (IsSeasonFolder(child.FullName, directoryService, fileSystem))
  113. {
  114. //logger.Debug("{0} is a series because of season folder {1}.", path, child.FullName);
  115. return true;
  116. }
  117. }
  118. else
  119. {
  120. var fullName = child.FullName;
  121. if (libraryManager.IsVideoFile(fullName) || IsVideoPlaceHolder(fullName))
  122. {
  123. if (GetEpisodeNumberFromFile(fullName, considerSeasonlessEntries).HasValue)
  124. {
  125. return true;
  126. }
  127. }
  128. }
  129. }
  130. logger.Debug("{0} is not a series folder.", path);
  131. return false;
  132. }
  133. /// <summary>
  134. /// Determines whether [is place holder] [the specified path].
  135. /// </summary>
  136. /// <param name="path">The path.</param>
  137. /// <returns><c>true</c> if [is place holder] [the specified path]; otherwise, <c>false</c>.</returns>
  138. /// <exception cref="System.ArgumentNullException">path</exception>
  139. private static bool IsVideoPlaceHolder(string path)
  140. {
  141. if (string.IsNullOrEmpty(path))
  142. {
  143. throw new ArgumentNullException("path");
  144. }
  145. var extension = Path.GetExtension(path);
  146. return string.Equals(extension, ".disc", StringComparison.OrdinalIgnoreCase);
  147. }
  148. /// <summary>
  149. /// Determines whether [is season folder] [the specified path].
  150. /// </summary>
  151. /// <param name="path">The path.</param>
  152. /// <param name="directoryService">The directory service.</param>
  153. /// <param name="fileSystem">The file system.</param>
  154. /// <returns><c>true</c> if [is season folder] [the specified path]; otherwise, <c>false</c>.</returns>
  155. private static bool IsSeasonFolder(string path, IDirectoryService directoryService, IFileSystem fileSystem)
  156. {
  157. var seasonNumber = GetSeasonNumberFromPath(path);
  158. var hasSeasonNumber = seasonNumber != null;
  159. if (!hasSeasonNumber)
  160. {
  161. return false;
  162. }
  163. //// It's a season folder if it's named as such and does not contain any audio files, apart from theme.mp3
  164. //foreach (var fileSystemInfo in directoryService.GetFileSystemEntries(path))
  165. //{
  166. // var attributes = fileSystemInfo.Attributes;
  167. // if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  168. // {
  169. // continue;
  170. // }
  171. // // Can't enforce this because files saved by Bitcasa are always marked System
  172. // //if ((attributes & FileAttributes.System) == FileAttributes.System)
  173. // //{
  174. // // continue;
  175. // //}
  176. // if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
  177. // {
  178. // //if (IsBadFolder(fileSystemInfo.Name))
  179. // //{
  180. // // return false;
  181. // //}
  182. // }
  183. // else
  184. // {
  185. // if (EntityResolutionHelper.IsAudioFile(fileSystemInfo.FullName) &&
  186. // !string.Equals(fileSystem.GetFileNameWithoutExtension(fileSystemInfo), BaseItem.ThemeSongFilename))
  187. // {
  188. // return false;
  189. // }
  190. // }
  191. //}
  192. return true;
  193. }
  194. /// <summary>
  195. /// A season folder must contain one of these somewhere in the name
  196. /// </summary>
  197. private static readonly string[] SeasonFolderNames =
  198. {
  199. "season",
  200. "sæson",
  201. "temporada",
  202. "saison",
  203. "staffel",
  204. "series",
  205. "сезон"
  206. };
  207. /// <summary>
  208. /// Used to detect paths that represent episodes, need to make sure they don't also
  209. /// match movie titles like "2001 A Space..."
  210. /// Currently we limit the numbers here to 2 digits to try and avoid this
  211. /// </summary>
  212. private static readonly Regex[] EpisodeExpressions =
  213. {
  214. new Regex(
  215. @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})[^\\\/]*$",
  216. RegexOptions.Compiled),
  217. new Regex(
  218. @".*(\\|\/)[sS](?<seasonnumber>\d{1,4})[x,X]?[eE](?<epnumber>\d{1,3})[^\\\/]*$",
  219. RegexOptions.Compiled),
  220. new Regex(
  221. @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))[^\\\/]*$",
  222. RegexOptions.Compiled),
  223. new Regex(
  224. @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})[^\\\/]*$",
  225. RegexOptions.Compiled)
  226. };
  227. private static readonly Regex[] MultipleEpisodeExpressions =
  228. {
  229. new Regex(
  230. @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )\d{1,4}[eExX](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  231. RegexOptions.Compiled),
  232. new Regex(
  233. @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )\d{1,4}[xX][eE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  234. RegexOptions.Compiled),
  235. new Regex(
  236. @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  237. RegexOptions.Compiled),
  238. new Regex(
  239. @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})(-[xE]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  240. RegexOptions.Compiled),
  241. new Regex(
  242. @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))((-| - )\d{1,4}[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  243. RegexOptions.Compiled),
  244. new Regex(
  245. @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))((-| - )\d{1,4}[xX][eE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  246. RegexOptions.Compiled),
  247. new Regex(
  248. @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  249. RegexOptions.Compiled),
  250. new Regex(
  251. @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))(-[xX]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  252. RegexOptions.Compiled),
  253. new Regex(
  254. @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  255. RegexOptions.Compiled),
  256. new Regex(
  257. @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})(-[xX]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  258. RegexOptions.Compiled)
  259. };
  260. /// <summary>
  261. /// To avoid the following matching movies they are only valid when contained in a folder which has been matched as a being season, or the media type is TV series
  262. /// </summary>
  263. private static readonly Regex[] EpisodeExpressionsWithoutSeason =
  264. {
  265. new Regex(
  266. @".*[\\\/](?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\.\w+$",
  267. RegexOptions.Compiled),
  268. // "01.avi"
  269. new Regex(
  270. @".*(\\|\/)(?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\s?-\s?[^\\\/]*$",
  271. RegexOptions.Compiled),
  272. // "01 - blah.avi", "01-blah.avi"
  273. new Regex(
  274. @".*(\\|\/)(?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\.[^\\\/]+$",
  275. RegexOptions.Compiled),
  276. // "01.blah.avi"
  277. new Regex(
  278. @".*[\\\/][^\\\/]* - (?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*[^\\\/]*$",
  279. RegexOptions.Compiled),
  280. // "blah - 01.avi", "blah 2 - 01.avi", "blah - 01 blah.avi", "blah 2 - 01 blah", "blah - 01 - blah.avi", "blah 2 - 01 - blah"
  281. };
  282. /// <summary>
  283. /// Gets the season number from path.
  284. /// </summary>
  285. /// <param name="path">The path.</param>
  286. /// <returns>System.Nullable{System.Int32}.</returns>
  287. public static int? GetSeasonNumberFromPath(string path)
  288. {
  289. var filename = Path.GetFileName(path);
  290. if (string.Equals(filename, "specials", StringComparison.OrdinalIgnoreCase))
  291. {
  292. return 0;
  293. }
  294. int val;
  295. if (int.TryParse(filename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val))
  296. {
  297. return val;
  298. }
  299. if (filename.StartsWith("s", StringComparison.OrdinalIgnoreCase))
  300. {
  301. var testFilename = filename.Substring(1);
  302. if (int.TryParse(testFilename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val))
  303. {
  304. return val;
  305. }
  306. }
  307. // Look for one of the season folder names
  308. foreach (var name in SeasonFolderNames)
  309. {
  310. var index = filename.IndexOf(name, StringComparison.OrdinalIgnoreCase);
  311. if (index != -1)
  312. {
  313. return GetSeasonNumberFromPathSubstring(filename.Substring(index + name.Length));
  314. }
  315. }
  316. return null;
  317. }
  318. /// <summary>
  319. /// Extracts the season number from the second half of the Season folder name (everything after "Season", or "Staffel")
  320. /// </summary>
  321. /// <param name="path">The path.</param>
  322. /// <returns>System.Nullable{System.Int32}.</returns>
  323. private static int? GetSeasonNumberFromPathSubstring(string path)
  324. {
  325. var numericStart = -1;
  326. var length = 0;
  327. // Find out where the numbers start, and then keep going until they end
  328. for (var i = 0; i < path.Length; i++)
  329. {
  330. if (char.IsNumber(path, i))
  331. {
  332. if (numericStart == -1)
  333. {
  334. numericStart = i;
  335. }
  336. length++;
  337. }
  338. else if (numericStart != -1)
  339. {
  340. break;
  341. }
  342. }
  343. if (numericStart == -1)
  344. {
  345. return null;
  346. }
  347. return int.Parse(path.Substring(numericStart, length), CultureInfo.InvariantCulture);
  348. }
  349. /// <summary>
  350. /// Episodes the number from file.
  351. /// </summary>
  352. /// <param name="fullPath">The full path.</param>
  353. /// <param name="considerSeasonlessNames">if set to <c>true</c> [is in season].</param>
  354. /// <returns>System.String.</returns>
  355. public static int? GetEpisodeNumberFromFile(string fullPath, bool considerSeasonlessNames)
  356. {
  357. string fl = fullPath.ToLower();
  358. foreach (var r in EpisodeExpressions)
  359. {
  360. Match m = r.Match(fl);
  361. if (m.Success)
  362. return ParseEpisodeNumber(m.Groups["epnumber"].Value);
  363. }
  364. if (considerSeasonlessNames)
  365. {
  366. var match = EpisodeExpressionsWithoutSeason.Select(r => r.Match(fl))
  367. .FirstOrDefault(m => m.Success);
  368. if (match != null)
  369. {
  370. return ParseEpisodeNumber(match.Groups["epnumber"].Value);
  371. }
  372. }
  373. return null;
  374. }
  375. public static int? GetEndingEpisodeNumberFromFile(string fullPath)
  376. {
  377. var fl = fullPath.ToLower();
  378. foreach (var r in MultipleEpisodeExpressions)
  379. {
  380. var m = r.Match(fl);
  381. if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value))
  382. return ParseEpisodeNumber(m.Groups["endingepnumber"].Value);
  383. }
  384. foreach (var r in EpisodeExpressionsWithoutSeason)
  385. {
  386. var m = r.Match(fl);
  387. if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value))
  388. return ParseEpisodeNumber(m.Groups["endingepnumber"].Value);
  389. }
  390. return null;
  391. }
  392. /// <summary>
  393. /// Seasons the number from episode file.
  394. /// </summary>
  395. /// <param name="fullPath">The full path.</param>
  396. /// <returns>System.String.</returns>
  397. public static int? GetSeasonNumberFromEpisodeFile(string fullPath)
  398. {
  399. string fl = fullPath.ToLower();
  400. foreach (var r in EpisodeExpressions)
  401. {
  402. Match m = r.Match(fl);
  403. if (m.Success)
  404. {
  405. Group g = m.Groups["seasonnumber"];
  406. if (g != null)
  407. {
  408. var val = g.Value;
  409. if (!string.IsNullOrWhiteSpace(val))
  410. {
  411. int num;
  412. if (int.TryParse(val, NumberStyles.Integer, UsCulture, out num))
  413. {
  414. return num;
  415. }
  416. }
  417. }
  418. return null;
  419. }
  420. }
  421. return null;
  422. }
  423. public static string GetSeriesNameFromEpisodeFile(string fullPath)
  424. {
  425. var fl = fullPath.ToLower();
  426. foreach (var r in EpisodeExpressions)
  427. {
  428. var m = r.Match(fl);
  429. if (m.Success)
  430. {
  431. var g = m.Groups["seriesname"];
  432. if (g != null)
  433. {
  434. var val = g.Value;
  435. if (!string.IsNullOrWhiteSpace(val))
  436. {
  437. return val;
  438. }
  439. }
  440. return null;
  441. }
  442. }
  443. return null;
  444. }
  445. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  446. private static int? ParseEpisodeNumber(string val)
  447. {
  448. int num;
  449. if (!string.IsNullOrEmpty(val) && int.TryParse(val, NumberStyles.Integer, UsCulture, out num))
  450. {
  451. return num;
  452. }
  453. return null;
  454. }
  455. /// <summary>
  456. /// Sets the initial item values.
  457. /// </summary>
  458. /// <param name="item">The item.</param>
  459. /// <param name="args">The args.</param>
  460. protected override void SetInitialItemValues(Series item, ItemResolveArgs args)
  461. {
  462. base.SetInitialItemValues(item, args);
  463. SetProviderIdFromPath(item, args.Path);
  464. }
  465. /// <summary>
  466. /// Sets the provider id from path.
  467. /// </summary>
  468. /// <param name="item">The item.</param>
  469. /// <param name="path">The path.</param>
  470. private void SetProviderIdFromPath(Series item, string path)
  471. {
  472. var justName = Path.GetFileName(path);
  473. var id = justName.GetAttributeValue("tvdbid");
  474. if (!string.IsNullOrEmpty(id))
  475. {
  476. item.SetProviderId(MetadataProviders.Tvdb, id);
  477. }
  478. }
  479. }
  480. }