SeriesResolver.cs 22 KB

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