SeriesResolver.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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.HasParent<Series>() || args.HasParent<Season>() || args.HasParent<MusicArtist>() || args.HasParent<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, collectionType, 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="collectionType">Type of the collection.</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, string collectionType, 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, collectionType, 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. var isTvShowsFolder = string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase);
  124. if (GetEpisodeNumberFromFile(fullName, isTvShowsFolder).HasValue)
  125. {
  126. return true;
  127. }
  128. }
  129. }
  130. }
  131. logger.Debug("{0} is not a series folder.", path);
  132. return false;
  133. }
  134. /// <summary>
  135. /// Determines whether [is place holder] [the specified path].
  136. /// </summary>
  137. /// <param name="path">The path.</param>
  138. /// <returns><c>true</c> if [is place holder] [the specified path]; otherwise, <c>false</c>.</returns>
  139. /// <exception cref="System.ArgumentNullException">path</exception>
  140. private static bool IsVideoPlaceHolder(string path)
  141. {
  142. if (string.IsNullOrEmpty(path))
  143. {
  144. throw new ArgumentNullException("path");
  145. }
  146. var extension = Path.GetExtension(path);
  147. return string.Equals(extension, ".disc", StringComparison.OrdinalIgnoreCase);
  148. }
  149. /// <summary>
  150. /// Determines whether [is season folder] [the specified path].
  151. /// </summary>
  152. /// <param name="path">The path.</param>
  153. /// <param name="collectionType">Type of the collection.</param>
  154. /// <param name="directoryService">The directory service.</param>
  155. /// <param name="fileSystem">The file system.</param>
  156. /// <returns><c>true</c> if [is season folder] [the specified path]; otherwise, <c>false</c>.</returns>
  157. private static bool IsSeasonFolder(string path, string collectionType, IDirectoryService directoryService, IFileSystem fileSystem)
  158. {
  159. var seasonNumber = GetSeasonNumberFromPath(path, collectionType);
  160. var hasSeasonNumber = seasonNumber != null;
  161. if (!hasSeasonNumber)
  162. {
  163. return false;
  164. }
  165. //// It's a season folder if it's named as such and does not contain any audio files, apart from theme.mp3
  166. //foreach (var fileSystemInfo in directoryService.GetFileSystemEntries(path))
  167. //{
  168. // var attributes = fileSystemInfo.Attributes;
  169. // if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  170. // {
  171. // continue;
  172. // }
  173. // // Can't enforce this because files saved by Bitcasa are always marked System
  174. // //if ((attributes & FileAttributes.System) == FileAttributes.System)
  175. // //{
  176. // // continue;
  177. // //}
  178. // if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
  179. // {
  180. // //if (IsBadFolder(fileSystemInfo.Name))
  181. // //{
  182. // // return false;
  183. // //}
  184. // }
  185. // else
  186. // {
  187. // if (EntityResolutionHelper.IsAudioFile(fileSystemInfo.FullName) &&
  188. // !string.Equals(fileSystem.GetFileNameWithoutExtension(fileSystemInfo), BaseItem.ThemeSongFilename))
  189. // {
  190. // return false;
  191. // }
  192. // }
  193. //}
  194. return true;
  195. }
  196. /// <summary>
  197. /// A season folder must contain one of these somewhere in the name
  198. /// </summary>
  199. private static readonly string[] SeasonFolderNames =
  200. {
  201. "season",
  202. "sæson",
  203. "temporada",
  204. "saison",
  205. "staffel",
  206. "series",
  207. "сезон"
  208. };
  209. /// <summary>
  210. /// Used to detect paths that represent episodes, need to make sure they don't also
  211. /// match movie titles like "2001 A Space..."
  212. /// Currently we limit the numbers here to 2 digits to try and avoid this
  213. /// </summary>
  214. private static readonly Regex[] EpisodeExpressions =
  215. {
  216. new Regex(
  217. @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})[^\\\/]*$",
  218. RegexOptions.Compiled),
  219. new Regex(
  220. @".*(\\|\/)[sS](?<seasonnumber>\d{1,4})[x,X]?[eE](?<epnumber>\d{1,3})[^\\\/]*$",
  221. RegexOptions.Compiled),
  222. new Regex(
  223. @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))[^\\\/]*$",
  224. RegexOptions.Compiled),
  225. new Regex(
  226. @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})[^\\\/]*$",
  227. RegexOptions.Compiled)
  228. };
  229. private static readonly Regex[] MultipleEpisodeExpressions =
  230. {
  231. new Regex(
  232. @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )\d{1,4}[eExX](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  233. RegexOptions.Compiled),
  234. new Regex(
  235. @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )\d{1,4}[xX][eE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  236. RegexOptions.Compiled),
  237. new Regex(
  238. @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  239. RegexOptions.Compiled),
  240. new Regex(
  241. @".*(\\|\/)[sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3})(-[xE]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  242. RegexOptions.Compiled),
  243. new Regex(
  244. @".*(\\|\/)(?<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}))+[^\\\/]*$",
  245. RegexOptions.Compiled),
  246. new Regex(
  247. @".*(\\|\/)(?<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}))+[^\\\/]*$",
  248. RegexOptions.Compiled),
  249. new Regex(
  250. @".*(\\|\/)(?<seriesname>((?![sS]?\d{1,4}[xX]\d{1,3})[^\\\/])*)?([sS]?(?<seasonnumber>\d{1,4})[xX](?<epnumber>\d{1,3}))((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  251. RegexOptions.Compiled),
  252. new Regex(
  253. @".*(\\|\/)(?<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}))+[^\\\/]*$",
  254. RegexOptions.Compiled),
  255. new Regex(
  256. @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})((-| - )?[xXeE](?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  257. RegexOptions.Compiled),
  258. new Regex(
  259. @".*(\\|\/)(?<seriesname>[^\\\/]*)[sS](?<seasonnumber>\d{1,4})[xX\.]?[eE](?<epnumber>\d{1,3})(-[xX]?[eE]?(?<endingepnumber>\d{1,3}))+[^\\\/]*$",
  260. RegexOptions.Compiled)
  261. };
  262. /// <summary>
  263. /// 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
  264. /// </summary>
  265. private static readonly Regex[] EpisodeExpressionsWithoutSeason =
  266. {
  267. new Regex(
  268. @".*[\\\/](?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\.\w+$",
  269. RegexOptions.Compiled),
  270. // "01.avi"
  271. new Regex(
  272. @".*(\\|\/)(?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\s?-\s?[^\\\/]*$",
  273. RegexOptions.Compiled),
  274. // "01 - blah.avi", "01-blah.avi"
  275. new Regex(
  276. @".*(\\|\/)(?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*\.[^\\\/]+$",
  277. RegexOptions.Compiled),
  278. // "01.blah.avi"
  279. new Regex(
  280. @".*[\\\/][^\\\/]* - (?<epnumber>\d{1,3})(-(?<endingepnumber>\d{2,3}))*[^\\\/]*$",
  281. RegexOptions.Compiled),
  282. // "blah - 01.avi", "blah 2 - 01.avi", "blah - 01 blah.avi", "blah 2 - 01 blah", "blah - 01 - blah.avi", "blah 2 - 01 - blah"
  283. };
  284. public static int? GetSeasonNumberFromPath(string path)
  285. {
  286. return GetSeasonNumberFromPath(path, CollectionType.TvShows);
  287. }
  288. /// <summary>
  289. /// Gets the season number from path.
  290. /// </summary>
  291. /// <param name="path">The path.</param>
  292. /// <param name="collectionType">Type of the collection.</param>
  293. /// <returns>System.Nullable{System.Int32}.</returns>
  294. public static int? GetSeasonNumberFromPath(string path, string collectionType)
  295. {
  296. var filename = Path.GetFileName(path);
  297. if (string.Equals(collectionType, CollectionType.TvShows, StringComparison.OrdinalIgnoreCase))
  298. {
  299. if (string.Equals(filename, "specials", StringComparison.OrdinalIgnoreCase))
  300. {
  301. return 0;
  302. }
  303. }
  304. int val;
  305. if (int.TryParse(filename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val))
  306. {
  307. return val;
  308. }
  309. if (filename.StartsWith("s", StringComparison.OrdinalIgnoreCase))
  310. {
  311. var testFilename = filename.Substring(1);
  312. if (int.TryParse(testFilename, NumberStyles.Integer, CultureInfo.InvariantCulture, out val))
  313. {
  314. return val;
  315. }
  316. }
  317. // Look for one of the season folder names
  318. foreach (var name in SeasonFolderNames)
  319. {
  320. var index = filename.IndexOf(name, StringComparison.OrdinalIgnoreCase);
  321. if (index != -1)
  322. {
  323. return GetSeasonNumberFromPathSubstring(filename.Substring(index + name.Length));
  324. }
  325. }
  326. return null;
  327. }
  328. /// <summary>
  329. /// Extracts the season number from the second half of the Season folder name (everything after "Season", or "Staffel")
  330. /// </summary>
  331. /// <param name="path">The path.</param>
  332. /// <returns>System.Nullable{System.Int32}.</returns>
  333. private static int? GetSeasonNumberFromPathSubstring(string path)
  334. {
  335. var numericStart = -1;
  336. var length = 0;
  337. // Find out where the numbers start, and then keep going until they end
  338. for (var i = 0; i < path.Length; i++)
  339. {
  340. if (char.IsNumber(path, i))
  341. {
  342. if (numericStart == -1)
  343. {
  344. numericStart = i;
  345. }
  346. length++;
  347. }
  348. else if (numericStart != -1)
  349. {
  350. break;
  351. }
  352. }
  353. if (numericStart == -1)
  354. {
  355. return null;
  356. }
  357. return int.Parse(path.Substring(numericStart, length), CultureInfo.InvariantCulture);
  358. }
  359. /// <summary>
  360. /// Episodes the number from file.
  361. /// </summary>
  362. /// <param name="fullPath">The full path.</param>
  363. /// <param name="considerSeasonlessNames">if set to <c>true</c> [is in season].</param>
  364. /// <returns>System.String.</returns>
  365. public static int? GetEpisodeNumberFromFile(string fullPath, bool considerSeasonlessNames)
  366. {
  367. string fl = fullPath.ToLower();
  368. foreach (var r in EpisodeExpressions)
  369. {
  370. Match m = r.Match(fl);
  371. if (m.Success)
  372. return ParseEpisodeNumber(m.Groups["epnumber"].Value);
  373. }
  374. if (considerSeasonlessNames)
  375. {
  376. var match = EpisodeExpressionsWithoutSeason.Select(r => r.Match(fl))
  377. .FirstOrDefault(m => m.Success);
  378. if (match != null)
  379. {
  380. return ParseEpisodeNumber(match.Groups["epnumber"].Value);
  381. }
  382. }
  383. return null;
  384. }
  385. public static int? GetEndingEpisodeNumberFromFile(string fullPath)
  386. {
  387. var fl = fullPath.ToLower();
  388. foreach (var r in MultipleEpisodeExpressions)
  389. {
  390. var m = r.Match(fl);
  391. if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value))
  392. return ParseEpisodeNumber(m.Groups["endingepnumber"].Value);
  393. }
  394. foreach (var r in EpisodeExpressionsWithoutSeason)
  395. {
  396. var m = r.Match(fl);
  397. if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value))
  398. return ParseEpisodeNumber(m.Groups["endingepnumber"].Value);
  399. }
  400. return null;
  401. }
  402. /// <summary>
  403. /// Seasons the number from episode file.
  404. /// </summary>
  405. /// <param name="fullPath">The full path.</param>
  406. /// <returns>System.String.</returns>
  407. public static int? GetSeasonNumberFromEpisodeFile(string fullPath)
  408. {
  409. string fl = fullPath.ToLower();
  410. foreach (var r in EpisodeExpressions)
  411. {
  412. Match m = r.Match(fl);
  413. if (m.Success)
  414. {
  415. Group g = m.Groups["seasonnumber"];
  416. if (g != null)
  417. {
  418. var val = g.Value;
  419. if (!string.IsNullOrWhiteSpace(val))
  420. {
  421. int num;
  422. if (int.TryParse(val, NumberStyles.Integer, UsCulture, out num))
  423. {
  424. return num;
  425. }
  426. }
  427. }
  428. return null;
  429. }
  430. }
  431. return null;
  432. }
  433. public static string GetSeriesNameFromEpisodeFile(string fullPath)
  434. {
  435. var fl = fullPath.ToLower();
  436. foreach (var r in EpisodeExpressions)
  437. {
  438. var m = r.Match(fl);
  439. if (m.Success)
  440. {
  441. var g = m.Groups["seriesname"];
  442. if (g != null)
  443. {
  444. var val = g.Value;
  445. if (!string.IsNullOrWhiteSpace(val))
  446. {
  447. return val;
  448. }
  449. }
  450. return null;
  451. }
  452. }
  453. return null;
  454. }
  455. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  456. private static int? ParseEpisodeNumber(string val)
  457. {
  458. int num;
  459. if (!string.IsNullOrEmpty(val) && int.TryParse(val, NumberStyles.Integer, UsCulture, out num))
  460. {
  461. return num;
  462. }
  463. return null;
  464. }
  465. /// <summary>
  466. /// Sets the initial item values.
  467. /// </summary>
  468. /// <param name="item">The item.</param>
  469. /// <param name="args">The args.</param>
  470. protected override void SetInitialItemValues(Series item, ItemResolveArgs args)
  471. {
  472. base.SetInitialItemValues(item, args);
  473. SetProviderIdFromPath(item, args.Path);
  474. }
  475. /// <summary>
  476. /// Sets the provider id from path.
  477. /// </summary>
  478. /// <param name="item">The item.</param>
  479. /// <param name="path">The path.</param>
  480. private void SetProviderIdFromPath(Series item, string path)
  481. {
  482. var justName = Path.GetFileName(path);
  483. var id = justName.GetAttributeValue("tvdbid");
  484. if (!string.IsNullOrEmpty(id))
  485. {
  486. item.SetProviderId(MetadataProviders.Tvdb, id);
  487. }
  488. }
  489. }
  490. }