BaseItem.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Configuration;
  4. using MediaBrowser.Controller.Entities.TV;
  5. using MediaBrowser.Controller.IO;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.Localization;
  8. using MediaBrowser.Controller.Persistence;
  9. using MediaBrowser.Controller.Providers;
  10. using MediaBrowser.Controller.Resolvers;
  11. using MediaBrowser.Model.Entities;
  12. using MediaBrowser.Model.Logging;
  13. using System;
  14. using System.Collections.Generic;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Runtime.Serialization;
  18. using System.Threading;
  19. using System.Threading.Tasks;
  20. namespace MediaBrowser.Controller.Entities
  21. {
  22. /// <summary>
  23. /// Class BaseItem
  24. /// </summary>
  25. public abstract class BaseItem : IHasProviderIds, ILibraryItem
  26. {
  27. protected BaseItem()
  28. {
  29. Genres = new List<string>();
  30. Studios = new List<string>();
  31. People = new List<PersonInfo>();
  32. ScreenshotImagePaths = new List<string>();
  33. BackdropImagePaths = new List<string>();
  34. ProductionLocations = new List<string>();
  35. Images = new Dictionary<ImageType, string>();
  36. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  37. Tags = new List<string>();
  38. ThemeSongIds = new List<Guid>();
  39. ThemeVideoIds = new List<Guid>();
  40. LocalTrailerIds = new List<Guid>();
  41. LockedFields = new List<MetadataFields>();
  42. Taglines = new List<string>();
  43. RemoteTrailers = new List<MediaUrl>();
  44. ImageSources = new List<ImageSourceInfo>();
  45. }
  46. /// <summary>
  47. /// The supported image extensions
  48. /// </summary>
  49. public static readonly string[] SupportedImageExtensions = new[] { ".png", ".jpg", ".jpeg", ".tbn" };
  50. /// <summary>
  51. /// The trailer folder name
  52. /// </summary>
  53. public const string TrailerFolderName = "trailers";
  54. public const string ThemeSongsFolderName = "theme-music";
  55. public const string ThemeSongFilename = "theme";
  56. public const string ThemeVideosFolderName = "backdrops";
  57. public const string XbmcTrailerFileSuffix = "-trailer";
  58. public bool IsInMixedFolder { get; set; }
  59. private string _name;
  60. /// <summary>
  61. /// Gets or sets the name.
  62. /// </summary>
  63. /// <value>The name.</value>
  64. public string Name
  65. {
  66. get
  67. {
  68. return _name;
  69. }
  70. set
  71. {
  72. _name = value;
  73. // lazy load this again
  74. _sortName = null;
  75. }
  76. }
  77. /// <summary>
  78. /// Gets or sets the id.
  79. /// </summary>
  80. /// <value>The id.</value>
  81. public Guid Id { get; set; }
  82. /// <summary>
  83. /// Gets or sets the budget.
  84. /// </summary>
  85. /// <value>The budget.</value>
  86. public double? Budget { get; set; }
  87. /// <summary>
  88. /// Gets or sets the taglines.
  89. /// </summary>
  90. /// <value>The taglines.</value>
  91. public List<string> Taglines { get; set; }
  92. /// <summary>
  93. /// Gets or sets the revenue.
  94. /// </summary>
  95. /// <value>The revenue.</value>
  96. public double? Revenue { get; set; }
  97. /// <summary>
  98. /// Gets or sets the trailer URL.
  99. /// </summary>
  100. /// <value>The trailer URL.</value>
  101. public List<MediaUrl> RemoteTrailers { get; set; }
  102. /// <summary>
  103. /// Return the id that should be used to key display prefs for this item.
  104. /// Default is based on the type for everything except actual generic folders.
  105. /// </summary>
  106. /// <value>The display prefs id.</value>
  107. [IgnoreDataMember]
  108. public virtual Guid DisplayPreferencesId
  109. {
  110. get
  111. {
  112. var thisType = GetType();
  113. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  114. }
  115. }
  116. /// <summary>
  117. /// Gets or sets the path.
  118. /// </summary>
  119. /// <value>The path.</value>
  120. public virtual string Path { get; set; }
  121. [IgnoreDataMember]
  122. protected internal bool IsOffline { get; set; }
  123. /// <summary>
  124. /// Gets or sets the type of the location.
  125. /// </summary>
  126. /// <value>The type of the location.</value>
  127. public virtual LocationType LocationType
  128. {
  129. get
  130. {
  131. if (IsOffline)
  132. {
  133. return LocationType.Offline;
  134. }
  135. if (string.IsNullOrEmpty(Path))
  136. {
  137. return LocationType.Virtual;
  138. }
  139. return System.IO.Path.IsPathRooted(Path) ? LocationType.FileSystem : LocationType.Remote;
  140. }
  141. }
  142. /// <summary>
  143. /// This is just a helper for convenience
  144. /// </summary>
  145. /// <value>The primary image path.</value>
  146. [IgnoreDataMember]
  147. public string PrimaryImagePath
  148. {
  149. get { return GetImage(ImageType.Primary); }
  150. set { SetImage(ImageType.Primary, value); }
  151. }
  152. /// <summary>
  153. /// Gets or sets the images.
  154. /// </summary>
  155. /// <value>The images.</value>
  156. public Dictionary<ImageType, string> Images { get; set; }
  157. /// <summary>
  158. /// Gets or sets the date created.
  159. /// </summary>
  160. /// <value>The date created.</value>
  161. public DateTime DateCreated { get; set; }
  162. /// <summary>
  163. /// Gets or sets the date modified.
  164. /// </summary>
  165. /// <value>The date modified.</value>
  166. public DateTime DateModified { get; set; }
  167. /// <summary>
  168. /// The logger
  169. /// </summary>
  170. public static ILogger Logger { get; set; }
  171. public static ILibraryManager LibraryManager { get; set; }
  172. public static IServerConfigurationManager ConfigurationManager { get; set; }
  173. public static IProviderManager ProviderManager { get; set; }
  174. public static ILocalizationManager LocalizationManager { get; set; }
  175. public static IItemRepository ItemRepository { get; set; }
  176. public static IFileSystem FileSystem { get; set; }
  177. /// <summary>
  178. /// Returns a <see cref="System.String" /> that represents this instance.
  179. /// </summary>
  180. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  181. public override string ToString()
  182. {
  183. return Name;
  184. }
  185. /// <summary>
  186. /// Returns true if this item should not attempt to fetch metadata
  187. /// </summary>
  188. /// <value><c>true</c> if [dont fetch meta]; otherwise, <c>false</c>.</value>
  189. public bool DontFetchMeta { get; set; }
  190. /// <summary>
  191. /// Gets or sets the locked fields.
  192. /// </summary>
  193. /// <value>The locked fields.</value>
  194. public List<MetadataFields> LockedFields { get; set; }
  195. /// <summary>
  196. /// Should be overridden to return the proper folder where metadata lives
  197. /// </summary>
  198. /// <value>The meta location.</value>
  199. [IgnoreDataMember]
  200. public virtual string MetaLocation
  201. {
  202. get
  203. {
  204. return Path ?? "";
  205. }
  206. }
  207. /// <summary>
  208. /// The _provider data
  209. /// </summary>
  210. private Dictionary<Guid, BaseProviderInfo> _providerData;
  211. /// <summary>
  212. /// Holds persistent data for providers like last refresh date.
  213. /// Providers can use this to determine if they need to refresh.
  214. /// The BaseProviderInfo class can be extended to hold anything a provider may need.
  215. /// Keyed by a unique provider ID.
  216. /// </summary>
  217. /// <value>The provider data.</value>
  218. public Dictionary<Guid, BaseProviderInfo> ProviderData
  219. {
  220. get
  221. {
  222. return _providerData ?? (_providerData = new Dictionary<Guid, BaseProviderInfo>());
  223. }
  224. set
  225. {
  226. _providerData = value;
  227. }
  228. }
  229. /// <summary>
  230. /// Gets the type of the media.
  231. /// </summary>
  232. /// <value>The type of the media.</value>
  233. [IgnoreDataMember]
  234. public virtual string MediaType
  235. {
  236. get
  237. {
  238. return null;
  239. }
  240. }
  241. /// <summary>
  242. /// The _resolve args
  243. /// </summary>
  244. private ItemResolveArgs _resolveArgs;
  245. /// <summary>
  246. /// We attach these to the item so that we only ever have to hit the file system once
  247. /// (this includes the children of the containing folder)
  248. /// </summary>
  249. /// <value>The resolve args.</value>
  250. [IgnoreDataMember]
  251. public ItemResolveArgs ResolveArgs
  252. {
  253. get
  254. {
  255. if (_resolveArgs == null)
  256. {
  257. try
  258. {
  259. _resolveArgs = CreateResolveArgs();
  260. }
  261. catch (IOException ex)
  262. {
  263. Logger.ErrorException("Error creating resolve args for {0}", ex, Path);
  264. IsOffline = true;
  265. throw;
  266. }
  267. }
  268. return _resolveArgs;
  269. }
  270. set
  271. {
  272. _resolveArgs = value;
  273. }
  274. }
  275. /// <summary>
  276. /// Resets the resolve args.
  277. /// </summary>
  278. /// <param name="pathInfo">The path info.</param>
  279. public void ResetResolveArgs(FileSystemInfo pathInfo)
  280. {
  281. ResetResolveArgs(CreateResolveArgs(pathInfo));
  282. }
  283. /// <summary>
  284. /// Resets the resolve args.
  285. /// </summary>
  286. public void ResetResolveArgs()
  287. {
  288. _resolveArgs = null;
  289. }
  290. /// <summary>
  291. /// Resets the resolve args.
  292. /// </summary>
  293. /// <param name="args">The args.</param>
  294. public void ResetResolveArgs(ItemResolveArgs args)
  295. {
  296. _resolveArgs = args;
  297. }
  298. /// <summary>
  299. /// Creates ResolveArgs on demand
  300. /// </summary>
  301. /// <param name="pathInfo">The path info.</param>
  302. /// <returns>ItemResolveArgs.</returns>
  303. /// <exception cref="System.IO.IOException">Unable to retrieve file system info for + path</exception>
  304. protected internal virtual ItemResolveArgs CreateResolveArgs(FileSystemInfo pathInfo = null)
  305. {
  306. var path = Path;
  307. var locationType = LocationType;
  308. if (locationType == LocationType.Remote ||
  309. locationType == LocationType.Virtual)
  310. {
  311. return new ItemResolveArgs(ConfigurationManager.ApplicationPaths, LibraryManager);
  312. }
  313. var isDirectory = false;
  314. if (UseParentPathToCreateResolveArgs)
  315. {
  316. path = System.IO.Path.GetDirectoryName(path);
  317. isDirectory = true;
  318. }
  319. pathInfo = pathInfo ?? (isDirectory ? new DirectoryInfo(path) : FileSystem.GetFileSystemInfo(path));
  320. if (pathInfo == null || !pathInfo.Exists)
  321. {
  322. throw new IOException("Unable to retrieve file system info for " + path);
  323. }
  324. var args = new ItemResolveArgs(ConfigurationManager.ApplicationPaths, LibraryManager)
  325. {
  326. FileInfo = pathInfo,
  327. Path = path,
  328. Parent = Parent
  329. };
  330. // Gather child folder and files
  331. if (args.IsDirectory)
  332. {
  333. var isPhysicalRoot = args.IsPhysicalRoot;
  334. // When resolving the root, we need it's grandchildren (children of user views)
  335. var flattenFolderDepth = isPhysicalRoot ? 2 : 0;
  336. args.FileSystemDictionary = FileData.GetFilteredFileSystemEntries(args.Path, FileSystem, Logger, args, flattenFolderDepth: flattenFolderDepth, resolveShortcuts: isPhysicalRoot || args.IsVf);
  337. // Need to remove subpaths that may have been resolved from shortcuts
  338. // Example: if \\server\movies exists, then strip out \\server\movies\action
  339. if (isPhysicalRoot)
  340. {
  341. var paths = args.FileSystemDictionary.Keys.ToList();
  342. foreach (var subPath in paths
  343. .Where(subPath => !subPath.EndsWith(":\\", StringComparison.OrdinalIgnoreCase) && paths.Any(i => subPath.StartsWith(i.TrimEnd(System.IO.Path.DirectorySeparatorChar) + System.IO.Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase))))
  344. {
  345. Logger.Info("Ignoring duplicate path: {0}", subPath);
  346. args.FileSystemDictionary.Remove(subPath);
  347. }
  348. }
  349. }
  350. //update our dates
  351. EntityResolutionHelper.EnsureDates(FileSystem, this, args, false);
  352. IsOffline = false;
  353. return args;
  354. }
  355. /// <summary>
  356. /// Some subclasses will stop resolving at a directory and point their Path to a file within. This will help ensure the on-demand resolve args are identical to the
  357. /// original ones.
  358. /// </summary>
  359. /// <value><c>true</c> if [use parent path to create resolve args]; otherwise, <c>false</c>.</value>
  360. [IgnoreDataMember]
  361. protected virtual bool UseParentPathToCreateResolveArgs
  362. {
  363. get
  364. {
  365. return false;
  366. }
  367. }
  368. /// <summary>
  369. /// Gets or sets the name of the forced sort.
  370. /// </summary>
  371. /// <value>The name of the forced sort.</value>
  372. public string ForcedSortName { get; set; }
  373. private string _sortName;
  374. /// <summary>
  375. /// Gets or sets the name of the sort.
  376. /// </summary>
  377. /// <value>The name of the sort.</value>
  378. [IgnoreDataMember]
  379. public string SortName
  380. {
  381. get
  382. {
  383. if (!string.IsNullOrEmpty(ForcedSortName))
  384. {
  385. return ForcedSortName;
  386. }
  387. return _sortName ?? (_sortName = CreateSortName());
  388. }
  389. }
  390. /// <summary>
  391. /// Creates the name of the sort.
  392. /// </summary>
  393. /// <returns>System.String.</returns>
  394. protected virtual string CreateSortName()
  395. {
  396. if (Name == null) return null; //some items may not have name filled in properly
  397. var sortable = Name.Trim().ToLower();
  398. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  399. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  400. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  401. {
  402. var searchLower = search.ToLower();
  403. // Remove from beginning if a space follows
  404. if (sortable.StartsWith(searchLower + " "))
  405. {
  406. sortable = sortable.Remove(0, searchLower.Length + 1);
  407. }
  408. // Remove from middle if surrounded by spaces
  409. sortable = sortable.Replace(" " + searchLower + " ", " ");
  410. // Remove from end if followed by a space
  411. if (sortable.EndsWith(" " + searchLower))
  412. {
  413. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  414. }
  415. }
  416. return sortable;
  417. }
  418. /// <summary>
  419. /// Gets or sets the parent.
  420. /// </summary>
  421. /// <value>The parent.</value>
  422. [IgnoreDataMember]
  423. public Folder Parent { get; set; }
  424. /// <summary>
  425. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  426. /// </summary>
  427. /// <value>The premiere date.</value>
  428. public DateTime? PremiereDate { get; set; }
  429. /// <summary>
  430. /// Gets or sets the end date.
  431. /// </summary>
  432. /// <value>The end date.</value>
  433. public DateTime? EndDate { get; set; }
  434. /// <summary>
  435. /// Gets or sets the display type of the media.
  436. /// </summary>
  437. /// <value>The display type of the media.</value>
  438. public string DisplayMediaType { get; set; }
  439. /// <summary>
  440. /// Gets or sets the backdrop image paths.
  441. /// </summary>
  442. /// <value>The backdrop image paths.</value>
  443. public List<string> BackdropImagePaths { get; set; }
  444. /// <summary>
  445. /// Gets or sets the backdrop image sources.
  446. /// </summary>
  447. /// <value>The backdrop image sources.</value>
  448. public List<ImageSourceInfo> ImageSources { get; set; }
  449. /// <summary>
  450. /// Gets or sets the screenshot image paths.
  451. /// </summary>
  452. /// <value>The screenshot image paths.</value>
  453. public List<string> ScreenshotImagePaths { get; set; }
  454. /// <summary>
  455. /// Gets or sets the official rating.
  456. /// </summary>
  457. /// <value>The official rating.</value>
  458. public string OfficialRating { get; set; }
  459. /// <summary>
  460. /// Gets or sets the official rating description.
  461. /// </summary>
  462. /// <value>The official rating description.</value>
  463. public string OfficialRatingDescription { get; set; }
  464. /// <summary>
  465. /// Gets or sets the custom rating.
  466. /// </summary>
  467. /// <value>The custom rating.</value>
  468. public string CustomRating { get; set; }
  469. /// <summary>
  470. /// Gets or sets the language.
  471. /// </summary>
  472. /// <value>The language.</value>
  473. public string Language { get; set; }
  474. /// <summary>
  475. /// Gets or sets the overview.
  476. /// </summary>
  477. /// <value>The overview.</value>
  478. public string Overview { get; set; }
  479. /// <summary>
  480. /// Gets or sets the people.
  481. /// </summary>
  482. /// <value>The people.</value>
  483. public List<PersonInfo> People { get; set; }
  484. /// <summary>
  485. /// Gets or sets the tags.
  486. /// </summary>
  487. /// <value>The tags.</value>
  488. public List<string> Tags { get; set; }
  489. /// <summary>
  490. /// Override this if you need to combine/collapse person information
  491. /// </summary>
  492. /// <value>All people.</value>
  493. [IgnoreDataMember]
  494. public virtual IEnumerable<PersonInfo> AllPeople
  495. {
  496. get { return People; }
  497. }
  498. [IgnoreDataMember]
  499. public virtual IEnumerable<string> AllStudios
  500. {
  501. get { return Studios; }
  502. }
  503. [IgnoreDataMember]
  504. public virtual IEnumerable<string> AllGenres
  505. {
  506. get { return Genres; }
  507. }
  508. /// <summary>
  509. /// Gets or sets the studios.
  510. /// </summary>
  511. /// <value>The studios.</value>
  512. public List<string> Studios { get; set; }
  513. /// <summary>
  514. /// Gets or sets the genres.
  515. /// </summary>
  516. /// <value>The genres.</value>
  517. public List<string> Genres { get; set; }
  518. /// <summary>
  519. /// Gets or sets the home page URL.
  520. /// </summary>
  521. /// <value>The home page URL.</value>
  522. public string HomePageUrl { get; set; }
  523. /// <summary>
  524. /// Gets or sets the production locations.
  525. /// </summary>
  526. /// <value>The production locations.</value>
  527. public List<string> ProductionLocations { get; set; }
  528. /// <summary>
  529. /// Gets or sets the community rating.
  530. /// </summary>
  531. /// <value>The community rating.</value>
  532. public float? CommunityRating { get; set; }
  533. /// <summary>
  534. /// Gets or sets the community rating vote count.
  535. /// </summary>
  536. /// <value>The community rating vote count.</value>
  537. public int? VoteCount { get; set; }
  538. /// <summary>
  539. /// Gets or sets the run time ticks.
  540. /// </summary>
  541. /// <value>The run time ticks.</value>
  542. public long? RunTimeTicks { get; set; }
  543. /// <summary>
  544. /// Gets or sets the original run time ticks.
  545. /// </summary>
  546. /// <value>The original run time ticks.</value>
  547. public long? OriginalRunTimeTicks { get; set; }
  548. /// <summary>
  549. /// Gets or sets the aspect ratio.
  550. /// </summary>
  551. /// <value>The aspect ratio.</value>
  552. public string AspectRatio { get; set; }
  553. /// <summary>
  554. /// Gets or sets the production year.
  555. /// </summary>
  556. /// <value>The production year.</value>
  557. public int? ProductionYear { get; set; }
  558. /// <summary>
  559. /// If the item is part of a series, this is it's number in the series.
  560. /// This could be episode number, album track number, etc.
  561. /// </summary>
  562. /// <value>The index number.</value>
  563. public int? IndexNumber { get; set; }
  564. /// <summary>
  565. /// For an episode this could be the season number, or for a song this could be the disc number.
  566. /// </summary>
  567. /// <value>The parent index number.</value>
  568. public int? ParentIndexNumber { get; set; }
  569. public List<Guid> ThemeSongIds { get; set; }
  570. public List<Guid> ThemeVideoIds { get; set; }
  571. public List<Guid> LocalTrailerIds { get; set; }
  572. [IgnoreDataMember]
  573. public virtual string OfficialRatingForComparison
  574. {
  575. get { return OfficialRating; }
  576. }
  577. [IgnoreDataMember]
  578. public virtual string CustomRatingForComparison
  579. {
  580. get { return CustomRating; }
  581. }
  582. /// <summary>
  583. /// Loads local trailers from the file system
  584. /// </summary>
  585. /// <returns>List{Video}.</returns>
  586. private IEnumerable<Trailer> LoadLocalTrailers()
  587. {
  588. ItemResolveArgs resolveArgs;
  589. try
  590. {
  591. resolveArgs = ResolveArgs;
  592. if (!resolveArgs.IsDirectory)
  593. {
  594. return new List<Trailer>();
  595. }
  596. }
  597. catch (IOException ex)
  598. {
  599. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  600. return new List<Trailer>();
  601. }
  602. var files = new List<FileSystemInfo>();
  603. var folder = resolveArgs.GetFileSystemEntryByName(TrailerFolderName);
  604. // Path doesn't exist. No biggie
  605. if (folder != null)
  606. {
  607. try
  608. {
  609. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  610. }
  611. catch (IOException ex)
  612. {
  613. Logger.ErrorException("Error loading trailers for {0}", ex, Name);
  614. }
  615. }
  616. // Support xbmc trailers (-trailer suffix on video file names)
  617. files.AddRange(resolveArgs.FileSystemChildren.Where(i =>
  618. {
  619. try
  620. {
  621. if ((i.Attributes & FileAttributes.Directory) != FileAttributes.Directory)
  622. {
  623. if (System.IO.Path.GetFileNameWithoutExtension(i.Name).EndsWith(XbmcTrailerFileSuffix, StringComparison.OrdinalIgnoreCase) && !string.Equals(Path, i.FullName, StringComparison.OrdinalIgnoreCase))
  624. {
  625. return true;
  626. }
  627. }
  628. }
  629. catch (IOException ex)
  630. {
  631. Logger.ErrorException("Error accessing path {0}", ex, i.FullName);
  632. }
  633. return false;
  634. }));
  635. return LibraryManager.ResolvePaths<Trailer>(files, null).Select(video =>
  636. {
  637. // Try to retrieve it from the db. If we don't find it, use the resolved version
  638. var dbItem = LibraryManager.RetrieveItem(video.Id) as Trailer;
  639. if (dbItem != null)
  640. {
  641. dbItem.ResetResolveArgs(video.ResolveArgs);
  642. video = dbItem;
  643. }
  644. return video;
  645. }).ToList();
  646. }
  647. /// <summary>
  648. /// Loads the theme songs.
  649. /// </summary>
  650. /// <returns>List{Audio.Audio}.</returns>
  651. private IEnumerable<Audio.Audio> LoadThemeSongs()
  652. {
  653. ItemResolveArgs resolveArgs;
  654. try
  655. {
  656. resolveArgs = ResolveArgs;
  657. if (!resolveArgs.IsDirectory)
  658. {
  659. return new List<Audio.Audio>();
  660. }
  661. }
  662. catch (IOException ex)
  663. {
  664. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  665. return new List<Audio.Audio>();
  666. }
  667. var files = new List<FileSystemInfo>();
  668. var folder = resolveArgs.GetFileSystemEntryByName(ThemeSongsFolderName);
  669. // Path doesn't exist. No biggie
  670. if (folder != null)
  671. {
  672. try
  673. {
  674. files.AddRange(new DirectoryInfo(folder.FullName).EnumerateFiles());
  675. }
  676. catch (IOException ex)
  677. {
  678. Logger.ErrorException("Error loading theme songs for {0}", ex, Name);
  679. }
  680. }
  681. // Support plex/xbmc convention
  682. files.AddRange(resolveArgs.FileSystemChildren
  683. .Where(i => string.Equals(System.IO.Path.GetFileNameWithoutExtension(i.Name), ThemeSongFilename, StringComparison.OrdinalIgnoreCase) && EntityResolutionHelper.IsAudioFile(i.Name))
  684. );
  685. return LibraryManager.ResolvePaths<Audio.Audio>(files, null).Select(audio =>
  686. {
  687. // Try to retrieve it from the db. If we don't find it, use the resolved version
  688. var dbItem = LibraryManager.RetrieveItem(audio.Id) as Audio.Audio;
  689. if (dbItem != null)
  690. {
  691. dbItem.ResetResolveArgs(audio.ResolveArgs);
  692. audio = dbItem;
  693. }
  694. return audio;
  695. }).ToList();
  696. }
  697. /// <summary>
  698. /// Loads the video backdrops.
  699. /// </summary>
  700. /// <returns>List{Video}.</returns>
  701. private IEnumerable<Video> LoadThemeVideos()
  702. {
  703. ItemResolveArgs resolveArgs;
  704. try
  705. {
  706. resolveArgs = ResolveArgs;
  707. if (!resolveArgs.IsDirectory)
  708. {
  709. return new List<Video>();
  710. }
  711. }
  712. catch (IOException ex)
  713. {
  714. Logger.ErrorException("Error getting ResolveArgs for {0}", ex, Path);
  715. return new List<Video>();
  716. }
  717. var folder = resolveArgs.GetFileSystemEntryByName(ThemeVideosFolderName);
  718. // Path doesn't exist. No biggie
  719. if (folder == null)
  720. {
  721. return new List<Video>();
  722. }
  723. IEnumerable<FileSystemInfo> files;
  724. try
  725. {
  726. files = new DirectoryInfo(folder.FullName).EnumerateFiles();
  727. }
  728. catch (IOException ex)
  729. {
  730. Logger.ErrorException("Error loading video backdrops for {0}", ex, Name);
  731. return new List<Video>();
  732. }
  733. return LibraryManager.ResolvePaths<Video>(files, null).Select(item =>
  734. {
  735. // Try to retrieve it from the db. If we don't find it, use the resolved version
  736. var dbItem = LibraryManager.RetrieveItem(item.Id) as Video;
  737. if (dbItem != null)
  738. {
  739. dbItem.ResetResolveArgs(item.ResolveArgs);
  740. item = dbItem;
  741. }
  742. return item;
  743. }).ToList();
  744. }
  745. /// <summary>
  746. /// Overrides the base implementation to refresh metadata for local trailers
  747. /// </summary>
  748. /// <param name="cancellationToken">The cancellation token.</param>
  749. /// <param name="forceSave">if set to <c>true</c> [is new item].</param>
  750. /// <param name="forceRefresh">if set to <c>true</c> [force].</param>
  751. /// <param name="allowSlowProviders">if set to <c>true</c> [allow slow providers].</param>
  752. /// <param name="resetResolveArgs">if set to <c>true</c> [reset resolve args].</param>
  753. /// <returns>true if a provider reports we changed</returns>
  754. public virtual async Task<bool> RefreshMetadata(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true, bool resetResolveArgs = true)
  755. {
  756. if (resetResolveArgs || ResolveArgs == null)
  757. {
  758. // Reload this
  759. ResetResolveArgs();
  760. }
  761. // Refresh for the item
  762. var itemRefreshTask = ProviderManager.ExecuteMetadataProviders(this, cancellationToken, forceRefresh, allowSlowProviders);
  763. cancellationToken.ThrowIfCancellationRequested();
  764. var themeSongsChanged = false;
  765. var themeVideosChanged = false;
  766. var localTrailersChanged = false;
  767. if (LocationType == LocationType.FileSystem && Parent != null)
  768. {
  769. themeSongsChanged = await RefreshThemeSongs(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  770. themeVideosChanged = await RefreshThemeVideos(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  771. localTrailersChanged = await RefreshLocalTrailers(cancellationToken, forceSave, forceRefresh, allowSlowProviders).ConfigureAwait(false);
  772. }
  773. cancellationToken.ThrowIfCancellationRequested();
  774. // Get the result from the item task
  775. var updateReason = await itemRefreshTask.ConfigureAwait(false);
  776. var changed = updateReason.HasValue;
  777. if (changed || forceSave || themeSongsChanged || themeVideosChanged || localTrailersChanged)
  778. {
  779. cancellationToken.ThrowIfCancellationRequested();
  780. await LibraryManager.UpdateItem(this, updateReason ?? ItemUpdateType.Unspecified, cancellationToken).ConfigureAwait(false);
  781. }
  782. return changed;
  783. }
  784. private async Task<bool> RefreshLocalTrailers(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  785. {
  786. var newItems = LoadLocalTrailers().ToList();
  787. var newItemIds = newItems.Select(i => i.Id).ToList();
  788. var itemsChanged = !LocalTrailerIds.SequenceEqual(newItemIds);
  789. var tasks = newItems.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  790. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  791. LocalTrailerIds = newItemIds;
  792. return itemsChanged || results.Contains(true);
  793. }
  794. private async Task<bool> RefreshThemeVideos(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  795. {
  796. var newThemeVideos = LoadThemeVideos().ToList();
  797. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  798. var themeVideosChanged = !ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  799. var tasks = newThemeVideos.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  800. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  801. ThemeVideoIds = newThemeVideoIds;
  802. return themeVideosChanged || results.Contains(true);
  803. }
  804. /// <summary>
  805. /// Refreshes the theme songs.
  806. /// </summary>
  807. private async Task<bool> RefreshThemeSongs(CancellationToken cancellationToken, bool forceSave = false, bool forceRefresh = false, bool allowSlowProviders = true)
  808. {
  809. var newThemeSongs = LoadThemeSongs().ToList();
  810. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  811. var themeSongsChanged = !ThemeSongIds.SequenceEqual(newThemeSongIds);
  812. var tasks = newThemeSongs.Select(i => i.RefreshMetadata(cancellationToken, forceSave, forceRefresh, allowSlowProviders, resetResolveArgs: false));
  813. var results = await Task.WhenAll(tasks).ConfigureAwait(false);
  814. ThemeSongIds = newThemeSongIds;
  815. return themeSongsChanged || results.Contains(true);
  816. }
  817. /// <summary>
  818. /// Gets or sets the provider ids.
  819. /// </summary>
  820. /// <value>The provider ids.</value>
  821. public Dictionary<string, string> ProviderIds { get; set; }
  822. /// <summary>
  823. /// Override this to false if class should be ignored for indexing purposes
  824. /// </summary>
  825. /// <value><c>true</c> if [include in index]; otherwise, <c>false</c>.</value>
  826. [IgnoreDataMember]
  827. public virtual bool IncludeInIndex
  828. {
  829. get { return true; }
  830. }
  831. /// <summary>
  832. /// Override this to true if class should be grouped under a container in indicies
  833. /// The container class should be defined via IndexContainer
  834. /// </summary>
  835. /// <value><c>true</c> if [group in index]; otherwise, <c>false</c>.</value>
  836. [IgnoreDataMember]
  837. public virtual bool GroupInIndex
  838. {
  839. get { return false; }
  840. }
  841. /// <summary>
  842. /// Override this to return the folder that should be used to construct a container
  843. /// for this item in an index. GroupInIndex should be true as well.
  844. /// </summary>
  845. /// <value>The index container.</value>
  846. [IgnoreDataMember]
  847. public virtual Folder IndexContainer
  848. {
  849. get { return null; }
  850. }
  851. /// <summary>
  852. /// Gets the user data key.
  853. /// </summary>
  854. /// <returns>System.String.</returns>
  855. public virtual string GetUserDataKey()
  856. {
  857. return Id.ToString();
  858. }
  859. /// <summary>
  860. /// Determines if a given user has access to this item
  861. /// </summary>
  862. /// <param name="user">The user.</param>
  863. /// <param name="localizationManager">The localization manager.</param>
  864. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  865. /// <exception cref="System.ArgumentNullException">user</exception>
  866. public bool IsParentalAllowed(User user, ILocalizationManager localizationManager)
  867. {
  868. if (user == null)
  869. {
  870. throw new ArgumentNullException("user");
  871. }
  872. var maxAllowedRating = user.Configuration.MaxParentalRating;
  873. if (maxAllowedRating == null)
  874. {
  875. return true;
  876. }
  877. var rating = CustomRatingForComparison;
  878. if (string.IsNullOrEmpty(rating))
  879. {
  880. rating = OfficialRatingForComparison;
  881. }
  882. if (string.IsNullOrEmpty(rating))
  883. {
  884. return !user.Configuration.BlockNotRated;
  885. }
  886. var value = localizationManager.GetRatingLevel(rating);
  887. // Could not determine the integer value
  888. if (!value.HasValue)
  889. {
  890. return true;
  891. }
  892. return value.Value <= maxAllowedRating.Value;
  893. }
  894. /// <summary>
  895. /// Determines if this folder should be visible to a given user.
  896. /// Default is just parental allowed. Can be overridden for more functionality.
  897. /// </summary>
  898. /// <param name="user">The user.</param>
  899. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  900. /// <exception cref="System.ArgumentNullException">user</exception>
  901. public virtual bool IsVisible(User user)
  902. {
  903. if (user == null)
  904. {
  905. throw new ArgumentNullException("user");
  906. }
  907. return IsParentalAllowed(user, LocalizationManager);
  908. }
  909. /// <summary>
  910. /// Finds the particular item by searching through our parents and, if not found there, loading from repo
  911. /// </summary>
  912. /// <param name="id">The id.</param>
  913. /// <returns>BaseItem.</returns>
  914. /// <exception cref="System.ArgumentException"></exception>
  915. protected BaseItem FindParentItem(Guid id)
  916. {
  917. if (id == Guid.Empty)
  918. {
  919. throw new ArgumentException();
  920. }
  921. var parent = Parent;
  922. while (parent != null && !parent.IsRoot)
  923. {
  924. if (parent.Id == id) return parent;
  925. parent = parent.Parent;
  926. }
  927. return null;
  928. }
  929. /// <summary>
  930. /// Gets a value indicating whether this instance is folder.
  931. /// </summary>
  932. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  933. [IgnoreDataMember]
  934. public virtual bool IsFolder
  935. {
  936. get
  937. {
  938. return false;
  939. }
  940. }
  941. /// <summary>
  942. /// Determine if we have changed vs the passed in copy
  943. /// </summary>
  944. /// <param name="copy">The copy.</param>
  945. /// <returns><c>true</c> if the specified copy has changed; otherwise, <c>false</c>.</returns>
  946. /// <exception cref="System.ArgumentNullException"></exception>
  947. public virtual bool HasChanged(BaseItem copy)
  948. {
  949. if (copy == null)
  950. {
  951. throw new ArgumentNullException();
  952. }
  953. var changed = copy.DateModified != DateModified;
  954. if (changed)
  955. {
  956. Logger.Debug(Name + " changed - original creation: " + DateCreated + " new creation: " + copy.DateCreated + " original modified: " + DateModified + " new modified: " + copy.DateModified);
  957. }
  958. return changed;
  959. }
  960. /// <summary>
  961. /// Determines if the item is considered new based on user settings
  962. /// </summary>
  963. /// <returns><c>true</c> if [is recently added] [the specified user]; otherwise, <c>false</c>.</returns>
  964. /// <exception cref="System.ArgumentNullException"></exception>
  965. public bool IsRecentlyAdded()
  966. {
  967. return (DateTime.UtcNow - DateCreated).TotalDays < ConfigurationManager.Configuration.RecentItemDays;
  968. }
  969. /// <summary>
  970. /// Adds a person to the item
  971. /// </summary>
  972. /// <param name="person">The person.</param>
  973. /// <exception cref="System.ArgumentNullException"></exception>
  974. public void AddPerson(PersonInfo person)
  975. {
  976. if (person == null)
  977. {
  978. throw new ArgumentNullException("person");
  979. }
  980. if (string.IsNullOrWhiteSpace(person.Name))
  981. {
  982. throw new ArgumentNullException();
  983. }
  984. // Normalize
  985. if (string.Equals(person.Role, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  986. {
  987. person.Type = PersonType.GuestStar;
  988. }
  989. else if (string.Equals(person.Role, PersonType.Director, StringComparison.OrdinalIgnoreCase))
  990. {
  991. person.Type = PersonType.Director;
  992. }
  993. else if (string.Equals(person.Role, PersonType.Producer, StringComparison.OrdinalIgnoreCase))
  994. {
  995. person.Type = PersonType.Producer;
  996. }
  997. else if (string.Equals(person.Role, PersonType.Writer, StringComparison.OrdinalIgnoreCase))
  998. {
  999. person.Type = PersonType.Writer;
  1000. }
  1001. // If the type is GuestStar and there's already an Actor entry, then update it to avoid dupes
  1002. if (string.Equals(person.Type, PersonType.GuestStar, StringComparison.OrdinalIgnoreCase))
  1003. {
  1004. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase));
  1005. if (existing != null)
  1006. {
  1007. existing.Type = PersonType.GuestStar;
  1008. return;
  1009. }
  1010. }
  1011. if (string.Equals(person.Type, PersonType.Actor, StringComparison.OrdinalIgnoreCase))
  1012. {
  1013. // If the actor already exists without a role and we have one, fill it in
  1014. var existing = People.FirstOrDefault(p => p.Name.Equals(person.Name, StringComparison.OrdinalIgnoreCase) && (p.Type.Equals(PersonType.Actor, StringComparison.OrdinalIgnoreCase) || p.Type.Equals(PersonType.GuestStar, StringComparison.OrdinalIgnoreCase)));
  1015. if (existing == null)
  1016. {
  1017. // Wasn't there - add it
  1018. People.Add(person);
  1019. }
  1020. else
  1021. {
  1022. // Was there, if no role and we have one - fill it in
  1023. if (string.IsNullOrWhiteSpace(existing.Role) && !string.IsNullOrWhiteSpace(person.Role)) existing.Role = person.Role;
  1024. }
  1025. }
  1026. else
  1027. {
  1028. // Check for dupes based on the combination of Name and Type
  1029. if (!People.Any(p => string.Equals(p.Name, person.Name, StringComparison.OrdinalIgnoreCase) && string.Equals(p.Type, person.Type, StringComparison.OrdinalIgnoreCase)))
  1030. {
  1031. People.Add(person);
  1032. }
  1033. }
  1034. }
  1035. /// <summary>
  1036. /// Adds the tagline.
  1037. /// </summary>
  1038. /// <param name="item">The item.</param>
  1039. /// <param name="tagline">The tagline.</param>
  1040. /// <exception cref="System.ArgumentNullException">tagline</exception>
  1041. public void AddTagline(string tagline)
  1042. {
  1043. if (string.IsNullOrWhiteSpace(tagline))
  1044. {
  1045. throw new ArgumentNullException("tagline");
  1046. }
  1047. if (!Taglines.Contains(tagline, StringComparer.OrdinalIgnoreCase))
  1048. {
  1049. Taglines.Add(tagline);
  1050. }
  1051. }
  1052. /// <summary>
  1053. /// Adds a studio to the item
  1054. /// </summary>
  1055. /// <param name="name">The name.</param>
  1056. /// <exception cref="System.ArgumentNullException"></exception>
  1057. public void AddStudio(string name)
  1058. {
  1059. if (string.IsNullOrWhiteSpace(name))
  1060. {
  1061. throw new ArgumentNullException("name");
  1062. }
  1063. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1064. {
  1065. Studios.Add(name);
  1066. }
  1067. }
  1068. public void AddTag(string name)
  1069. {
  1070. if (string.IsNullOrWhiteSpace(name))
  1071. {
  1072. throw new ArgumentNullException("name");
  1073. }
  1074. if (!Tags.Contains(name, StringComparer.OrdinalIgnoreCase))
  1075. {
  1076. Tags.Add(name);
  1077. }
  1078. }
  1079. /// <summary>
  1080. /// Adds a genre to the item
  1081. /// </summary>
  1082. /// <param name="name">The name.</param>
  1083. /// <exception cref="System.ArgumentNullException"></exception>
  1084. public void AddGenre(string name)
  1085. {
  1086. if (string.IsNullOrWhiteSpace(name))
  1087. {
  1088. throw new ArgumentNullException("name");
  1089. }
  1090. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1091. {
  1092. Genres.Add(name);
  1093. }
  1094. }
  1095. /// <summary>
  1096. /// Adds the production location.
  1097. /// </summary>
  1098. /// <param name="location">The location.</param>
  1099. /// <exception cref="System.ArgumentNullException">location</exception>
  1100. public void AddProductionLocation(string location)
  1101. {
  1102. if (string.IsNullOrWhiteSpace(location))
  1103. {
  1104. throw new ArgumentNullException("location");
  1105. }
  1106. if (!ProductionLocations.Contains(location, StringComparer.OrdinalIgnoreCase))
  1107. {
  1108. ProductionLocations.Add(location);
  1109. }
  1110. }
  1111. /// <summary>
  1112. /// Marks the played.
  1113. /// </summary>
  1114. /// <param name="user">The user.</param>
  1115. /// <param name="datePlayed">The date played.</param>
  1116. /// <param name="userManager">The user manager.</param>
  1117. /// <returns>Task.</returns>
  1118. /// <exception cref="System.ArgumentNullException"></exception>
  1119. public virtual async Task MarkPlayed(User user, DateTime? datePlayed, IUserDataManager userManager)
  1120. {
  1121. if (user == null)
  1122. {
  1123. throw new ArgumentNullException();
  1124. }
  1125. var key = GetUserDataKey();
  1126. var data = userManager.GetUserData(user.Id, key);
  1127. if (datePlayed.HasValue)
  1128. {
  1129. // Incremenet
  1130. data.PlayCount++;
  1131. }
  1132. // Ensure it's at least one
  1133. data.PlayCount = Math.Max(data.PlayCount, 1);
  1134. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1135. data.Played = true;
  1136. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1137. }
  1138. /// <summary>
  1139. /// Marks the unplayed.
  1140. /// </summary>
  1141. /// <param name="user">The user.</param>
  1142. /// <param name="userManager">The user manager.</param>
  1143. /// <returns>Task.</returns>
  1144. /// <exception cref="System.ArgumentNullException"></exception>
  1145. public virtual async Task MarkUnplayed(User user, IUserDataManager userManager)
  1146. {
  1147. if (user == null)
  1148. {
  1149. throw new ArgumentNullException();
  1150. }
  1151. var key = GetUserDataKey();
  1152. var data = userManager.GetUserData(user.Id, key);
  1153. //I think it is okay to do this here.
  1154. // if this is only called when a user is manually forcing something to un-played
  1155. // then it probably is what we want to do...
  1156. data.PlayCount = 0;
  1157. data.PlaybackPositionTicks = 0;
  1158. data.LastPlayedDate = null;
  1159. data.Played = false;
  1160. await userManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1161. }
  1162. /// <summary>
  1163. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1164. /// </summary>
  1165. /// <returns>Task.</returns>
  1166. public virtual Task ChangedExternally()
  1167. {
  1168. return RefreshMetadata(CancellationToken.None);
  1169. }
  1170. /// <summary>
  1171. /// Finds a parent of a given type
  1172. /// </summary>
  1173. /// <typeparam name="T"></typeparam>
  1174. /// <returns>``0.</returns>
  1175. public T FindParent<T>()
  1176. where T : Folder
  1177. {
  1178. var parent = Parent;
  1179. while (parent != null)
  1180. {
  1181. var result = parent as T;
  1182. if (result != null)
  1183. {
  1184. return result;
  1185. }
  1186. parent = parent.Parent;
  1187. }
  1188. return null;
  1189. }
  1190. /// <summary>
  1191. /// Gets an image
  1192. /// </summary>
  1193. /// <param name="type">The type.</param>
  1194. /// <returns>System.String.</returns>
  1195. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1196. public string GetImage(ImageType type)
  1197. {
  1198. if (type == ImageType.Backdrop)
  1199. {
  1200. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1201. }
  1202. if (type == ImageType.Screenshot)
  1203. {
  1204. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1205. }
  1206. string val;
  1207. Images.TryGetValue(type, out val);
  1208. return val;
  1209. }
  1210. /// <summary>
  1211. /// Gets an image
  1212. /// </summary>
  1213. /// <param name="type">The type.</param>
  1214. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1215. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1216. public bool HasImage(ImageType type)
  1217. {
  1218. if (type == ImageType.Backdrop)
  1219. {
  1220. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1221. }
  1222. if (type == ImageType.Screenshot)
  1223. {
  1224. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1225. }
  1226. return !string.IsNullOrEmpty(GetImage(type));
  1227. }
  1228. /// <summary>
  1229. /// Sets an image
  1230. /// </summary>
  1231. /// <param name="type">The type.</param>
  1232. /// <param name="path">The path.</param>
  1233. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1234. public void SetImage(ImageType type, string path)
  1235. {
  1236. if (type == ImageType.Backdrop)
  1237. {
  1238. throw new ArgumentException("Backdrops should be accessed using Item.Backdrops");
  1239. }
  1240. if (type == ImageType.Screenshot)
  1241. {
  1242. throw new ArgumentException("Screenshots should be accessed using Item.Screenshots");
  1243. }
  1244. var typeKey = type;
  1245. // If it's null remove the key from the dictionary
  1246. if (string.IsNullOrEmpty(path))
  1247. {
  1248. if (Images.ContainsKey(typeKey))
  1249. {
  1250. Images.Remove(typeKey);
  1251. }
  1252. }
  1253. else
  1254. {
  1255. Images[typeKey] = path;
  1256. }
  1257. }
  1258. /// <summary>
  1259. /// Deletes the image.
  1260. /// </summary>
  1261. /// <param name="type">The type.</param>
  1262. /// <param name="index">The index.</param>
  1263. /// <returns>Task.</returns>
  1264. public Task DeleteImage(ImageType type, int? index)
  1265. {
  1266. if (type == ImageType.Backdrop)
  1267. {
  1268. if (!index.HasValue)
  1269. {
  1270. throw new ArgumentException("Please specify a backdrop image index to delete.");
  1271. }
  1272. var file = BackdropImagePaths[index.Value];
  1273. BackdropImagePaths.Remove(file);
  1274. RemoveImageSourceForPath(file);
  1275. // Delete the source file
  1276. DeleteImagePath(file);
  1277. }
  1278. else if (type == ImageType.Screenshot)
  1279. {
  1280. if (!index.HasValue)
  1281. {
  1282. throw new ArgumentException("Please specify a screenshot image index to delete.");
  1283. }
  1284. var file = ScreenshotImagePaths[index.Value];
  1285. ScreenshotImagePaths.Remove(file);
  1286. // Delete the source file
  1287. DeleteImagePath(file);
  1288. }
  1289. else
  1290. {
  1291. // Delete the source file
  1292. DeleteImagePath(GetImage(type));
  1293. // Remove it from the item
  1294. SetImage(type, null);
  1295. }
  1296. // Refresh metadata
  1297. // Need to disable slow providers or the image might get re-downloaded
  1298. return RefreshMetadata(CancellationToken.None, forceSave: true, allowSlowProviders: false);
  1299. }
  1300. /// <summary>
  1301. /// Deletes the image path.
  1302. /// </summary>
  1303. /// <param name="path">The path.</param>
  1304. private void DeleteImagePath(string path)
  1305. {
  1306. var currentFile = new FileInfo(path);
  1307. // This will fail if the file is hidden
  1308. if (currentFile.Exists)
  1309. {
  1310. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1311. {
  1312. currentFile.Attributes &= ~FileAttributes.Hidden;
  1313. }
  1314. currentFile.Delete();
  1315. }
  1316. }
  1317. /// <summary>
  1318. /// Validates that images within the item are still on the file system
  1319. /// </summary>
  1320. public void ValidateImages()
  1321. {
  1322. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1323. var deletedKeys = Images
  1324. .Where(image => !File.Exists(image.Value))
  1325. .Select(i => i.Key)
  1326. .ToList();
  1327. // Now remove them from the dictionary
  1328. foreach (var key in deletedKeys)
  1329. {
  1330. Images.Remove(key);
  1331. }
  1332. }
  1333. /// <summary>
  1334. /// Validates that backdrops within the item are still on the file system
  1335. /// </summary>
  1336. public void ValidateBackdrops()
  1337. {
  1338. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1339. var deletedImages = BackdropImagePaths
  1340. .Where(path => !File.Exists(path))
  1341. .ToList();
  1342. // Now remove them from the dictionary
  1343. foreach (var path in deletedImages)
  1344. {
  1345. BackdropImagePaths.Remove(path);
  1346. RemoveImageSourceForPath(path);
  1347. }
  1348. }
  1349. /// <summary>
  1350. /// Adds the image source.
  1351. /// </summary>
  1352. /// <param name="path">The path.</param>
  1353. /// <param name="url">The URL.</param>
  1354. public void AddImageSource(string path, string url)
  1355. {
  1356. RemoveImageSourceForPath(path);
  1357. var pathMd5 = path.ToLower().GetMD5();
  1358. ImageSources.Add(new ImageSourceInfo
  1359. {
  1360. ImagePathMD5 = pathMd5,
  1361. ImageUrlMD5 = url.ToLower().GetMD5()
  1362. });
  1363. }
  1364. /// <summary>
  1365. /// Gets the image source info.
  1366. /// </summary>
  1367. /// <param name="path">The path.</param>
  1368. /// <returns>ImageSourceInfo.</returns>
  1369. public ImageSourceInfo GetImageSourceInfo(string path)
  1370. {
  1371. if (ImageSources.Count == 0)
  1372. {
  1373. return null;
  1374. }
  1375. var pathMd5 = path.ToLower().GetMD5();
  1376. return ImageSources.FirstOrDefault(i => i.ImagePathMD5 == pathMd5);
  1377. }
  1378. /// <summary>
  1379. /// Removes the image source for path.
  1380. /// </summary>
  1381. /// <param name="path">The path.</param>
  1382. public void RemoveImageSourceForPath(string path)
  1383. {
  1384. if (ImageSources.Count == 0)
  1385. {
  1386. return;
  1387. }
  1388. var pathMd5 = path.ToLower().GetMD5();
  1389. // Remove existing
  1390. foreach (var entry in ImageSources
  1391. .Where(i => i.ImagePathMD5 == pathMd5)
  1392. .ToList())
  1393. {
  1394. ImageSources.Remove(entry);
  1395. }
  1396. }
  1397. /// <summary>
  1398. /// Determines whether [contains image with source URL] [the specified URL].
  1399. /// </summary>
  1400. /// <param name="url">The URL.</param>
  1401. /// <returns><c>true</c> if [contains image with source URL] [the specified URL]; otherwise, <c>false</c>.</returns>
  1402. public bool ContainsImageWithSourceUrl(string url)
  1403. {
  1404. if (ImageSources.Count == 0)
  1405. {
  1406. return false;
  1407. }
  1408. var md5 = url.ToLower().GetMD5();
  1409. return ImageSources.Any(i => i.ImageUrlMD5 == md5);
  1410. }
  1411. /// <summary>
  1412. /// Validates the screenshots.
  1413. /// </summary>
  1414. public void ValidateScreenshots()
  1415. {
  1416. // Only validate paths from the same directory - need to copy to a list because we are going to potentially modify the collection below
  1417. var deletedImages = ScreenshotImagePaths
  1418. .Where(path => !File.Exists(path))
  1419. .ToList();
  1420. // Now remove them from the dictionary
  1421. foreach (var path in deletedImages)
  1422. {
  1423. ScreenshotImagePaths.Remove(path);
  1424. }
  1425. }
  1426. /// <summary>
  1427. /// Gets the image path.
  1428. /// </summary>
  1429. /// <param name="imageType">Type of the image.</param>
  1430. /// <param name="imageIndex">Index of the image.</param>
  1431. /// <returns>System.String.</returns>
  1432. /// <exception cref="System.InvalidOperationException">
  1433. /// </exception>
  1434. /// <exception cref="System.ArgumentNullException">item</exception>
  1435. public string GetImagePath(ImageType imageType, int imageIndex)
  1436. {
  1437. if (imageType == ImageType.Backdrop)
  1438. {
  1439. return BackdropImagePaths[imageIndex];
  1440. }
  1441. if (imageType == ImageType.Screenshot)
  1442. {
  1443. return ScreenshotImagePaths[imageIndex];
  1444. }
  1445. if (imageType == ImageType.Chapter)
  1446. {
  1447. return ItemRepository.GetChapter(Id, imageIndex).ImagePath;
  1448. }
  1449. return GetImage(imageType);
  1450. }
  1451. /// <summary>
  1452. /// Gets the image date modified.
  1453. /// </summary>
  1454. /// <param name="imagePath">The image path.</param>
  1455. /// <returns>DateTime.</returns>
  1456. /// <exception cref="System.ArgumentNullException">item</exception>
  1457. public DateTime GetImageDateModified(string imagePath)
  1458. {
  1459. if (string.IsNullOrEmpty(imagePath))
  1460. {
  1461. throw new ArgumentNullException("imagePath");
  1462. }
  1463. var locationType = LocationType;
  1464. if (locationType == LocationType.Remote ||
  1465. locationType == LocationType.Virtual)
  1466. {
  1467. return FileSystem.GetLastWriteTimeUtc(imagePath);
  1468. }
  1469. var metaFileEntry = ResolveArgs.GetMetaFileByPath(imagePath);
  1470. // If we didn't the metafile entry, check the Season
  1471. if (metaFileEntry == null)
  1472. {
  1473. var episode = this as Episode;
  1474. if (episode != null && episode.Season != null)
  1475. {
  1476. episode.Season.ResolveArgs.GetMetaFileByPath(imagePath);
  1477. }
  1478. }
  1479. // See if we can avoid a file system lookup by looking for the file in ResolveArgs
  1480. return metaFileEntry == null ? FileSystem.GetLastWriteTimeUtc(imagePath) : FileSystem.GetLastWriteTimeUtc(metaFileEntry);
  1481. }
  1482. }
  1483. }