BaseItem.cs 59 KB

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