BaseItem.cs 59 KB

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