BaseItem.cs 60 KB

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