BaseItem.cs 60 KB

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