TVUtils.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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(filename, "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. var fullName = child.FullName;
  276. if (EntityResolutionHelper.IsVideoFile(fullName) || EntityResolutionHelper.IsVideoPlaceHolder(fullName))
  277. {
  278. if (GetEpisodeNumberFromFile(fullName, considerSeasonlessEntries).HasValue)
  279. {
  280. return true;
  281. }
  282. }
  283. }
  284. }
  285. logger.Debug("{0} is not a series folder.", path);
  286. return false;
  287. }
  288. private static bool IsBadFolder(string name)
  289. {
  290. if (string.Equals(name, BaseItem.ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  291. {
  292. return false;
  293. }
  294. if (string.Equals(name, BaseItem.ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  295. {
  296. return false;
  297. }
  298. if (string.Equals(name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase))
  299. {
  300. return false;
  301. }
  302. return !EntityResolutionHelper.IgnoreFolders.Contains(name, StringComparer.OrdinalIgnoreCase);
  303. }
  304. /// <summary>
  305. /// Episodes the number from file.
  306. /// </summary>
  307. /// <param name="fullPath">The full path.</param>
  308. /// <param name="considerSeasonlessNames">if set to <c>true</c> [is in season].</param>
  309. /// <returns>System.String.</returns>
  310. public static int? GetEpisodeNumberFromFile(string fullPath, bool considerSeasonlessNames)
  311. {
  312. string fl = fullPath.ToLower();
  313. foreach (var r in EpisodeExpressions)
  314. {
  315. Match m = r.Match(fl);
  316. if (m.Success)
  317. return ParseEpisodeNumber(m.Groups["epnumber"].Value);
  318. }
  319. if (considerSeasonlessNames)
  320. {
  321. var match = EpisodeExpressionsWithoutSeason.Select(r => r.Match(fl))
  322. .FirstOrDefault(m => m.Success);
  323. if (match != null)
  324. {
  325. return ParseEpisodeNumber(match.Groups["epnumber"].Value);
  326. }
  327. }
  328. return null;
  329. }
  330. public static int? GetEndingEpisodeNumberFromFile(string fullPath)
  331. {
  332. var fl = fullPath.ToLower();
  333. foreach (var r in MultipleEpisodeExpressions)
  334. {
  335. var m = r.Match(fl);
  336. if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value))
  337. return ParseEpisodeNumber(m.Groups["endingepnumber"].Value);
  338. }
  339. foreach (var r in EpisodeExpressionsWithoutSeason)
  340. {
  341. var m = r.Match(fl);
  342. if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value))
  343. return ParseEpisodeNumber(m.Groups["endingepnumber"].Value);
  344. }
  345. return null;
  346. }
  347. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  348. private static int? ParseEpisodeNumber(string val)
  349. {
  350. int num;
  351. if (!string.IsNullOrEmpty(val) && int.TryParse(val, NumberStyles.Integer, UsCulture, out num))
  352. {
  353. return num;
  354. }
  355. return null;
  356. }
  357. /// <summary>
  358. /// Seasons the number from episode file.
  359. /// </summary>
  360. /// <param name="fullPath">The full path.</param>
  361. /// <returns>System.String.</returns>
  362. public static int? GetSeasonNumberFromEpisodeFile(string fullPath)
  363. {
  364. string fl = fullPath.ToLower();
  365. foreach (var r in EpisodeExpressions)
  366. {
  367. Match m = r.Match(fl);
  368. if (m.Success)
  369. {
  370. Group g = m.Groups["seasonnumber"];
  371. if (g != null)
  372. {
  373. var val = g.Value;
  374. if (!string.IsNullOrWhiteSpace(val))
  375. {
  376. int num;
  377. if (int.TryParse(val, NumberStyles.Integer, UsCulture, out num))
  378. {
  379. return num;
  380. }
  381. }
  382. }
  383. return null;
  384. }
  385. }
  386. return null;
  387. }
  388. public static string GetSeriesNameFromEpisodeFile(string fullPath)
  389. {
  390. var fl = fullPath.ToLower();
  391. foreach (var r in EpisodeExpressions)
  392. {
  393. var m = r.Match(fl);
  394. if (m.Success)
  395. {
  396. var g = m.Groups["seriesname"];
  397. if (g != null)
  398. {
  399. var val = g.Value;
  400. if (!string.IsNullOrWhiteSpace(val))
  401. {
  402. return val;
  403. }
  404. }
  405. return null;
  406. }
  407. }
  408. return null;
  409. }
  410. /// <summary>
  411. /// Gets the air days.
  412. /// </summary>
  413. /// <param name="day">The day.</param>
  414. /// <returns>List{DayOfWeek}.</returns>
  415. public static List<DayOfWeek> GetAirDays(string day)
  416. {
  417. if (!string.IsNullOrWhiteSpace(day))
  418. {
  419. if (day.Equals("Daily", StringComparison.OrdinalIgnoreCase))
  420. {
  421. return new List<DayOfWeek>
  422. {
  423. DayOfWeek.Sunday,
  424. DayOfWeek.Monday,
  425. DayOfWeek.Tuesday,
  426. DayOfWeek.Wednesday,
  427. DayOfWeek.Thursday,
  428. DayOfWeek.Friday,
  429. DayOfWeek.Saturday
  430. };
  431. }
  432. DayOfWeek value;
  433. if (Enum.TryParse(day, true, out value))
  434. {
  435. return new List<DayOfWeek>
  436. {
  437. value
  438. };
  439. }
  440. return new List<DayOfWeek>();
  441. }
  442. return null;
  443. }
  444. }
  445. }