BaseItem.cs 59 KB

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