TVUtils.cs 19 KB

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