TVUtils.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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. if ((attributes & FileAttributes.System) == FileAttributes.System)
  206. {
  207. continue;
  208. }
  209. if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
  210. {
  211. //if (IsBadFolder(fileSystemInfo.Name))
  212. //{
  213. // return false;
  214. //}
  215. }
  216. else
  217. {
  218. if (EntityResolutionHelper.IsAudioFile(fileSystemInfo.FullName) &&
  219. !string.Equals(fileSystem.GetFileNameWithoutExtension(fileSystemInfo), BaseItem.ThemeSongFilename))
  220. {
  221. return false;
  222. }
  223. }
  224. }
  225. return true;
  226. }
  227. /// <summary>
  228. /// Determines whether [is series folder] [the specified path].
  229. /// </summary>
  230. /// <param name="path">The path.</param>
  231. /// <param name="considerSeasonlessEntries">if set to <c>true</c> [consider seasonless entries].</param>
  232. /// <param name="fileSystemChildren">The file system children.</param>
  233. /// <param name="directoryService">The directory service.</param>
  234. /// <param name="fileSystem">The file system.</param>
  235. /// <returns><c>true</c> if [is series folder] [the specified path]; otherwise, <c>false</c>.</returns>
  236. public static bool IsSeriesFolder(string path, bool considerSeasonlessEntries, IEnumerable<FileSystemInfo> fileSystemChildren, IDirectoryService directoryService, IFileSystem fileSystem, ILogger logger)
  237. {
  238. // A folder with more than 3 non-season folders in will not becounted as a series
  239. var nonSeriesFolders = 0;
  240. foreach (var child in fileSystemChildren)
  241. {
  242. var attributes = child.Attributes;
  243. if ((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  244. {
  245. continue;
  246. }
  247. if ((attributes & FileAttributes.System) == FileAttributes.System)
  248. {
  249. continue;
  250. }
  251. if ((attributes & FileAttributes.Directory) == FileAttributes.Directory)
  252. {
  253. if (IsSeasonFolder(child.FullName, directoryService, fileSystem))
  254. {
  255. logger.Debug("{0} is a series because of season folder {1}.", path, child.FullName);
  256. return true;
  257. }
  258. if (IsBadFolder(child.Name))
  259. {
  260. logger.Debug("Invalid folder under series: {0}", child.FullName);
  261. nonSeriesFolders++;
  262. }
  263. if (nonSeriesFolders >= 3)
  264. {
  265. logger.Debug("{0} not a series due to 3 or more invalid folders.", path);
  266. return false;
  267. }
  268. }
  269. else
  270. {
  271. var fullName = child.FullName;
  272. if (EntityResolutionHelper.IsVideoFile(fullName) || EntityResolutionHelper.IsVideoPlaceHolder(fullName))
  273. {
  274. if (GetEpisodeNumberFromFile(fullName, considerSeasonlessEntries).HasValue)
  275. {
  276. return true;
  277. }
  278. }
  279. }
  280. }
  281. logger.Debug("{0} is not a series folder.", path);
  282. return false;
  283. }
  284. private static bool IsBadFolder(string name)
  285. {
  286. if (string.Equals(name, BaseItem.ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  287. {
  288. return false;
  289. }
  290. if (string.Equals(name, BaseItem.ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  291. {
  292. return false;
  293. }
  294. if (string.Equals(name, BaseItem.TrailerFolderName, StringComparison.OrdinalIgnoreCase))
  295. {
  296. return false;
  297. }
  298. return !EntityResolutionHelper.IgnoreFolders.Contains(name, StringComparer.OrdinalIgnoreCase);
  299. }
  300. /// <summary>
  301. /// Episodes the number from file.
  302. /// </summary>
  303. /// <param name="fullPath">The full path.</param>
  304. /// <param name="considerSeasonlessNames">if set to <c>true</c> [is in season].</param>
  305. /// <returns>System.String.</returns>
  306. public static int? GetEpisodeNumberFromFile(string fullPath, bool considerSeasonlessNames)
  307. {
  308. string fl = fullPath.ToLower();
  309. foreach (var r in EpisodeExpressions)
  310. {
  311. Match m = r.Match(fl);
  312. if (m.Success)
  313. return ParseEpisodeNumber(m.Groups["epnumber"].Value);
  314. }
  315. if (considerSeasonlessNames)
  316. {
  317. var match = EpisodeExpressionsWithoutSeason.Select(r => r.Match(fl))
  318. .FirstOrDefault(m => m.Success);
  319. if (match != null)
  320. {
  321. return ParseEpisodeNumber(match.Groups["epnumber"].Value);
  322. }
  323. }
  324. return null;
  325. }
  326. public static int? GetEndingEpisodeNumberFromFile(string fullPath)
  327. {
  328. var fl = fullPath.ToLower();
  329. foreach (var r in MultipleEpisodeExpressions)
  330. {
  331. var m = r.Match(fl);
  332. if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value))
  333. return ParseEpisodeNumber(m.Groups["endingepnumber"].Value);
  334. }
  335. foreach (var r in EpisodeExpressionsWithoutSeason)
  336. {
  337. var m = r.Match(fl);
  338. if (m.Success && !string.IsNullOrEmpty(m.Groups["endingepnumber"].Value))
  339. return ParseEpisodeNumber(m.Groups["endingepnumber"].Value);
  340. }
  341. return null;
  342. }
  343. private static readonly CultureInfo UsCulture = new CultureInfo("en-US");
  344. private static int? ParseEpisodeNumber(string val)
  345. {
  346. int num;
  347. if (!string.IsNullOrEmpty(val) && int.TryParse(val, NumberStyles.Integer, UsCulture, out num))
  348. {
  349. return num;
  350. }
  351. return null;
  352. }
  353. /// <summary>
  354. /// Seasons the number from episode file.
  355. /// </summary>
  356. /// <param name="fullPath">The full path.</param>
  357. /// <returns>System.String.</returns>
  358. public static int? GetSeasonNumberFromEpisodeFile(string fullPath)
  359. {
  360. string fl = fullPath.ToLower();
  361. foreach (var r in EpisodeExpressions)
  362. {
  363. Match m = r.Match(fl);
  364. if (m.Success)
  365. {
  366. Group g = m.Groups["seasonnumber"];
  367. if (g != null)
  368. {
  369. var val = g.Value;
  370. if (!string.IsNullOrWhiteSpace(val))
  371. {
  372. int num;
  373. if (int.TryParse(val, NumberStyles.Integer, UsCulture, out num))
  374. {
  375. return num;
  376. }
  377. }
  378. }
  379. return null;
  380. }
  381. }
  382. return null;
  383. }
  384. public static string GetSeriesNameFromEpisodeFile(string fullPath)
  385. {
  386. var fl = fullPath.ToLower();
  387. foreach (var r in EpisodeExpressions)
  388. {
  389. var m = r.Match(fl);
  390. if (m.Success)
  391. {
  392. var g = m.Groups["seriesname"];
  393. if (g != null)
  394. {
  395. var val = g.Value;
  396. if (!string.IsNullOrWhiteSpace(val))
  397. {
  398. return val;
  399. }
  400. }
  401. return null;
  402. }
  403. }
  404. return null;
  405. }
  406. /// <summary>
  407. /// Gets the air days.
  408. /// </summary>
  409. /// <param name="day">The day.</param>
  410. /// <returns>List{DayOfWeek}.</returns>
  411. public static List<DayOfWeek> GetAirDays(string day)
  412. {
  413. if (!string.IsNullOrWhiteSpace(day))
  414. {
  415. if (day.Equals("Daily", StringComparison.OrdinalIgnoreCase))
  416. {
  417. return new List<DayOfWeek>
  418. {
  419. DayOfWeek.Sunday,
  420. DayOfWeek.Monday,
  421. DayOfWeek.Tuesday,
  422. DayOfWeek.Wednesday,
  423. DayOfWeek.Thursday,
  424. DayOfWeek.Friday,
  425. DayOfWeek.Saturday
  426. };
  427. }
  428. DayOfWeek value;
  429. if (Enum.TryParse(day, true, out value))
  430. {
  431. return new List<DayOfWeek>
  432. {
  433. value
  434. };
  435. }
  436. return new List<DayOfWeek>();
  437. }
  438. return null;
  439. }
  440. }
  441. }