BaseItem.cs 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Common.IO;
  3. using MediaBrowser.Controller.Channels;
  4. using MediaBrowser.Controller.Collections;
  5. using MediaBrowser.Controller.Configuration;
  6. using MediaBrowser.Controller.Drawing;
  7. using MediaBrowser.Controller.Library;
  8. using MediaBrowser.Controller.LiveTv;
  9. using MediaBrowser.Controller.Localization;
  10. using MediaBrowser.Controller.Persistence;
  11. using MediaBrowser.Controller.Providers;
  12. using MediaBrowser.Model.Configuration;
  13. using MediaBrowser.Model.Dto;
  14. using MediaBrowser.Model.Entities;
  15. using MediaBrowser.Model.Library;
  16. using MediaBrowser.Model.Logging;
  17. using MediaBrowser.Model.Users;
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Globalization;
  21. using System.IO;
  22. using System.Linq;
  23. using System.Runtime.Serialization;
  24. using System.Threading;
  25. using System.Threading.Tasks;
  26. using CommonIO;
  27. namespace MediaBrowser.Controller.Entities
  28. {
  29. /// <summary>
  30. /// Class BaseItem
  31. /// </summary>
  32. public abstract class BaseItem : IHasProviderIds, ILibraryItem, IHasImages, IHasUserData, IHasMetadata, IHasLookupInfo<ItemLookupInfo>
  33. {
  34. protected BaseItem()
  35. {
  36. Tags = new List<string>();
  37. Genres = new List<string>();
  38. Studios = new List<string>();
  39. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  40. LockedFields = new List<MetadataFields>();
  41. ImageInfos = new List<ItemImageInfo>();
  42. }
  43. /// <summary>
  44. /// The supported image extensions
  45. /// </summary>
  46. public static readonly string[] SupportedImageExtensions = { ".png", ".jpg", ".jpeg" };
  47. public static readonly List<string> SupportedImageExtensionsList = SupportedImageExtensions.ToList();
  48. /// <summary>
  49. /// The trailer folder name
  50. /// </summary>
  51. public static string TrailerFolderName = "trailers";
  52. public static string ThemeSongsFolderName = "theme-music";
  53. public static string ThemeSongFilename = "theme";
  54. public static string ThemeVideosFolderName = "backdrops";
  55. public string PreferredMetadataCountryCode { get; set; }
  56. public string PreferredMetadataLanguage { get; set; }
  57. public List<ItemImageInfo> ImageInfos { get; set; }
  58. /// <summary>
  59. /// Gets or sets the channel identifier.
  60. /// </summary>
  61. /// <value>The channel identifier.</value>
  62. [IgnoreDataMember]
  63. public string ChannelId { get; set; }
  64. [IgnoreDataMember]
  65. public virtual bool SupportsAddingToPlaylist
  66. {
  67. get
  68. {
  69. return false;
  70. }
  71. }
  72. [IgnoreDataMember]
  73. public virtual bool AlwaysScanInternalMetadataPath
  74. {
  75. get { return false; }
  76. }
  77. /// <summary>
  78. /// Gets a value indicating whether this instance is in mixed folder.
  79. /// </summary>
  80. /// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
  81. public bool IsInMixedFolder { get; set; }
  82. [IgnoreDataMember]
  83. public virtual bool SupportsRemoteImageDownloading
  84. {
  85. get
  86. {
  87. return true;
  88. }
  89. }
  90. private string _name;
  91. /// <summary>
  92. /// Gets or sets the name.
  93. /// </summary>
  94. /// <value>The name.</value>
  95. [IgnoreDataMember]
  96. public virtual string Name
  97. {
  98. get
  99. {
  100. return _name;
  101. }
  102. set
  103. {
  104. _name = value;
  105. // lazy load this again
  106. _sortName = null;
  107. }
  108. }
  109. /// <summary>
  110. /// Gets or sets the id.
  111. /// </summary>
  112. /// <value>The id.</value>
  113. [IgnoreDataMember]
  114. public Guid Id { get; set; }
  115. /// <summary>
  116. /// Gets or sets a value indicating whether this instance is hd.
  117. /// </summary>
  118. /// <value><c>true</c> if this instance is hd; otherwise, <c>false</c>.</value>
  119. [IgnoreDataMember]
  120. public bool? IsHD { get; set; }
  121. /// <summary>
  122. /// Return the id that should be used to key display prefs for this item.
  123. /// Default is based on the type for everything except actual generic folders.
  124. /// </summary>
  125. /// <value>The display prefs id.</value>
  126. [IgnoreDataMember]
  127. public virtual Guid DisplayPreferencesId
  128. {
  129. get
  130. {
  131. var thisType = GetType();
  132. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  133. }
  134. }
  135. /// <summary>
  136. /// Gets or sets the path.
  137. /// </summary>
  138. /// <value>The path.</value>
  139. [IgnoreDataMember]
  140. public virtual string Path { get; set; }
  141. [IgnoreDataMember]
  142. public bool IsOffline { get; set; }
  143. /// <summary>
  144. /// Returns the folder containing the item.
  145. /// If the item is a folder, it returns the folder itself
  146. /// </summary>
  147. [IgnoreDataMember]
  148. public virtual string ContainingFolderPath
  149. {
  150. get
  151. {
  152. if (IsFolder)
  153. {
  154. return Path;
  155. }
  156. return System.IO.Path.GetDirectoryName(Path);
  157. }
  158. }
  159. /// <summary>
  160. /// Id of the program.
  161. /// </summary>
  162. [IgnoreDataMember]
  163. public string ExternalId
  164. {
  165. get { return this.GetProviderId("ProviderExternalId"); }
  166. set
  167. {
  168. this.SetProviderId("ProviderExternalId", value);
  169. }
  170. }
  171. /// <summary>
  172. /// Gets or sets the etag.
  173. /// </summary>
  174. /// <value>The etag.</value>
  175. [IgnoreDataMember]
  176. public string ExternalEtag { get; set; }
  177. [IgnoreDataMember]
  178. public virtual bool IsHidden
  179. {
  180. get
  181. {
  182. return false;
  183. }
  184. }
  185. public virtual bool IsHiddenFromUser(User user)
  186. {
  187. return false;
  188. }
  189. [IgnoreDataMember]
  190. public virtual bool IsOwnedItem
  191. {
  192. get
  193. {
  194. // Local trailer, special feature, theme video, etc.
  195. // An item that belongs to another item but is not part of the Parent-Child tree
  196. return !IsFolder && ParentId == Guid.Empty && LocationType == LocationType.FileSystem;
  197. }
  198. }
  199. /// <summary>
  200. /// Gets or sets the type of the location.
  201. /// </summary>
  202. /// <value>The type of the location.</value>
  203. [IgnoreDataMember]
  204. public virtual LocationType LocationType
  205. {
  206. get
  207. {
  208. if (IsOffline)
  209. {
  210. return LocationType.Offline;
  211. }
  212. if (string.IsNullOrWhiteSpace(Path))
  213. {
  214. return LocationType.Virtual;
  215. }
  216. return FileSystem.IsPathFile(Path) ? LocationType.FileSystem : LocationType.Remote;
  217. }
  218. }
  219. [IgnoreDataMember]
  220. public virtual bool SupportsLocalMetadata
  221. {
  222. get
  223. {
  224. var locationType = LocationType;
  225. return locationType != LocationType.Remote && locationType != LocationType.Virtual;
  226. }
  227. }
  228. [IgnoreDataMember]
  229. public virtual string FileNameWithoutExtension
  230. {
  231. get
  232. {
  233. if (LocationType == LocationType.FileSystem)
  234. {
  235. return System.IO.Path.GetFileNameWithoutExtension(Path);
  236. }
  237. return null;
  238. }
  239. }
  240. [IgnoreDataMember]
  241. public virtual bool EnableAlphaNumericSorting
  242. {
  243. get
  244. {
  245. return true;
  246. }
  247. }
  248. /// <summary>
  249. /// This is just a helper for convenience
  250. /// </summary>
  251. /// <value>The primary image path.</value>
  252. [IgnoreDataMember]
  253. public string PrimaryImagePath
  254. {
  255. get { return this.GetImagePath(ImageType.Primary); }
  256. }
  257. public virtual bool IsInternetMetadataEnabled()
  258. {
  259. return ConfigurationManager.Configuration.EnableInternetProviders;
  260. }
  261. public virtual bool CanDelete()
  262. {
  263. var locationType = LocationType;
  264. return locationType != LocationType.Remote &&
  265. locationType != LocationType.Virtual;
  266. }
  267. public virtual bool IsAuthorizedToDelete(User user)
  268. {
  269. return user.Policy.EnableContentDeletion;
  270. }
  271. public bool CanDelete(User user)
  272. {
  273. return CanDelete() && IsAuthorizedToDelete(user);
  274. }
  275. public virtual bool CanDownload()
  276. {
  277. return false;
  278. }
  279. public virtual bool IsAuthorizedToDownload(User user)
  280. {
  281. return user.Policy.EnableContentDownloading;
  282. }
  283. public bool CanDownload(User user)
  284. {
  285. return CanDownload() && IsAuthorizedToDownload(user);
  286. }
  287. /// <summary>
  288. /// Gets or sets the date created.
  289. /// </summary>
  290. /// <value>The date created.</value>
  291. [IgnoreDataMember]
  292. public DateTime DateCreated { get; set; }
  293. /// <summary>
  294. /// Gets or sets the date modified.
  295. /// </summary>
  296. /// <value>The date modified.</value>
  297. [IgnoreDataMember]
  298. public DateTime DateModified { get; set; }
  299. public DateTime DateLastSaved { get; set; }
  300. [IgnoreDataMember]
  301. public DateTime DateLastRefreshed { get; set; }
  302. /// <summary>
  303. /// The logger
  304. /// </summary>
  305. public static ILogger Logger { get; set; }
  306. public static ILibraryManager LibraryManager { get; set; }
  307. public static IServerConfigurationManager ConfigurationManager { get; set; }
  308. public static IProviderManager ProviderManager { get; set; }
  309. public static ILocalizationManager LocalizationManager { get; set; }
  310. public static IItemRepository ItemRepository { get; set; }
  311. public static IFileSystem FileSystem { get; set; }
  312. public static IUserDataManager UserDataManager { get; set; }
  313. public static ILiveTvManager LiveTvManager { get; set; }
  314. public static IChannelManager ChannelManager { get; set; }
  315. public static ICollectionManager CollectionManager { get; set; }
  316. public static IImageProcessor ImageProcessor { get; set; }
  317. public static IMediaSourceManager MediaSourceManager { get; set; }
  318. /// <summary>
  319. /// Returns a <see cref="System.String" /> that represents this instance.
  320. /// </summary>
  321. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  322. public override string ToString()
  323. {
  324. return Name;
  325. }
  326. [IgnoreDataMember]
  327. public bool IsLocked { get; set; }
  328. /// <summary>
  329. /// Gets or sets the locked fields.
  330. /// </summary>
  331. /// <value>The locked fields.</value>
  332. public List<MetadataFields> LockedFields { get; set; }
  333. /// <summary>
  334. /// Gets the type of the media.
  335. /// </summary>
  336. /// <value>The type of the media.</value>
  337. [IgnoreDataMember]
  338. public virtual string MediaType
  339. {
  340. get
  341. {
  342. return null;
  343. }
  344. }
  345. [IgnoreDataMember]
  346. public virtual IEnumerable<string> PhysicalLocations
  347. {
  348. get
  349. {
  350. var locationType = LocationType;
  351. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  352. {
  353. return new string[] { };
  354. }
  355. return new[] { Path };
  356. }
  357. }
  358. private string _forcedSortName;
  359. /// <summary>
  360. /// Gets or sets the name of the forced sort.
  361. /// </summary>
  362. /// <value>The name of the forced sort.</value>
  363. [IgnoreDataMember]
  364. public string ForcedSortName
  365. {
  366. get { return _forcedSortName; }
  367. set { _forcedSortName = value; _sortName = null; }
  368. }
  369. private string _sortName;
  370. /// <summary>
  371. /// Gets the name of the sort.
  372. /// </summary>
  373. /// <value>The name of the sort.</value>
  374. [IgnoreDataMember]
  375. public string SortName
  376. {
  377. get
  378. {
  379. if (!string.IsNullOrWhiteSpace(ForcedSortName))
  380. {
  381. return ForcedSortName;
  382. }
  383. return _sortName ?? (_sortName = CreateSortName());
  384. }
  385. set
  386. {
  387. _sortName = value;
  388. }
  389. }
  390. public string GetInternalMetadataPath()
  391. {
  392. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  393. return GetInternalMetadataPath(basePath);
  394. }
  395. protected virtual string GetInternalMetadataPath(string basePath)
  396. {
  397. var idString = Id.ToString("N");
  398. if (ConfigurationManager.Configuration.EnableLibraryMetadataSubFolder)
  399. {
  400. basePath = System.IO.Path.Combine(basePath, "library");
  401. }
  402. return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString);
  403. }
  404. /// <summary>
  405. /// Creates the name of the sort.
  406. /// </summary>
  407. /// <returns>System.String.</returns>
  408. protected virtual string CreateSortName()
  409. {
  410. if (Name == null) return null; //some items may not have name filled in properly
  411. if (!EnableAlphaNumericSorting)
  412. {
  413. return Name.TrimStart();
  414. }
  415. var sortable = Name.Trim().ToLower();
  416. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  417. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  418. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  419. {
  420. var searchLower = search.ToLower();
  421. // Remove from beginning if a space follows
  422. if (sortable.StartsWith(searchLower + " "))
  423. {
  424. sortable = sortable.Remove(0, searchLower.Length + 1);
  425. }
  426. // Remove from middle if surrounded by spaces
  427. sortable = sortable.Replace(" " + searchLower + " ", " ");
  428. // Remove from end if followed by a space
  429. if (sortable.EndsWith(" " + searchLower))
  430. {
  431. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  432. }
  433. }
  434. return sortable;
  435. }
  436. [IgnoreDataMember]
  437. public Guid ParentId { get; set; }
  438. /// <summary>
  439. /// Gets or sets the parent.
  440. /// </summary>
  441. /// <value>The parent.</value>
  442. [IgnoreDataMember]
  443. public Folder Parent
  444. {
  445. get
  446. {
  447. if (ParentId != Guid.Empty)
  448. {
  449. return LibraryManager.GetItemById(ParentId) as Folder;
  450. }
  451. return null;
  452. }
  453. set
  454. {
  455. }
  456. }
  457. public void SetParent(Folder parent)
  458. {
  459. ParentId = parent == null ? Guid.Empty : parent.Id;
  460. }
  461. [IgnoreDataMember]
  462. public IEnumerable<Folder> Parents
  463. {
  464. get
  465. {
  466. var parent = Parent;
  467. while (parent != null)
  468. {
  469. yield return parent;
  470. parent = parent.Parent;
  471. }
  472. }
  473. }
  474. /// <summary>
  475. /// Finds a parent of a given type
  476. /// </summary>
  477. /// <typeparam name="T"></typeparam>
  478. /// <returns>``0.</returns>
  479. public T FindParent<T>()
  480. where T : Folder
  481. {
  482. return Parents.OfType<T>().FirstOrDefault();
  483. }
  484. [IgnoreDataMember]
  485. public virtual BaseItem DisplayParent
  486. {
  487. get { return Parent; }
  488. }
  489. /// <summary>
  490. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  491. /// </summary>
  492. /// <value>The premiere date.</value>
  493. [IgnoreDataMember]
  494. public DateTime? PremiereDate { get; set; }
  495. /// <summary>
  496. /// Gets or sets the end date.
  497. /// </summary>
  498. /// <value>The end date.</value>
  499. [IgnoreDataMember]
  500. public DateTime? EndDate { get; set; }
  501. /// <summary>
  502. /// Gets or sets the display type of the media.
  503. /// </summary>
  504. /// <value>The display type of the media.</value>
  505. [IgnoreDataMember]
  506. public string DisplayMediaType { get; set; }
  507. /// <summary>
  508. /// Gets or sets the official rating.
  509. /// </summary>
  510. /// <value>The official rating.</value>
  511. [IgnoreDataMember]
  512. public string OfficialRating { get; set; }
  513. /// <summary>
  514. /// Gets or sets the official rating description.
  515. /// </summary>
  516. /// <value>The official rating description.</value>
  517. [IgnoreDataMember]
  518. public string OfficialRatingDescription { get; set; }
  519. /// <summary>
  520. /// Gets or sets the custom rating.
  521. /// </summary>
  522. /// <value>The custom rating.</value>
  523. [IgnoreDataMember]
  524. public string CustomRating { get; set; }
  525. /// <summary>
  526. /// Gets or sets the overview.
  527. /// </summary>
  528. /// <value>The overview.</value>
  529. [IgnoreDataMember]
  530. public string Overview { get; set; }
  531. /// <summary>
  532. /// Gets or sets the studios.
  533. /// </summary>
  534. /// <value>The studios.</value>
  535. public List<string> Studios { get; set; }
  536. /// <summary>
  537. /// Gets or sets the genres.
  538. /// </summary>
  539. /// <value>The genres.</value>
  540. [IgnoreDataMember]
  541. public List<string> Genres { get; set; }
  542. /// <summary>
  543. /// Gets or sets the tags.
  544. /// </summary>
  545. /// <value>The tags.</value>
  546. public List<string> Tags { get; set; }
  547. /// <summary>
  548. /// Gets or sets the home page URL.
  549. /// </summary>
  550. /// <value>The home page URL.</value>
  551. [IgnoreDataMember]
  552. public string HomePageUrl { get; set; }
  553. /// <summary>
  554. /// Gets or sets the community rating.
  555. /// </summary>
  556. /// <value>The community rating.</value>
  557. [IgnoreDataMember]
  558. public float? CommunityRating { get; set; }
  559. /// <summary>
  560. /// Gets or sets the community rating vote count.
  561. /// </summary>
  562. /// <value>The community rating vote count.</value>
  563. [IgnoreDataMember]
  564. public int? VoteCount { get; set; }
  565. /// <summary>
  566. /// Gets or sets the run time ticks.
  567. /// </summary>
  568. /// <value>The run time ticks.</value>
  569. [IgnoreDataMember]
  570. public long? RunTimeTicks { get; set; }
  571. /// <summary>
  572. /// Gets or sets the production year.
  573. /// </summary>
  574. /// <value>The production year.</value>
  575. [IgnoreDataMember]
  576. public int? ProductionYear { get; set; }
  577. /// <summary>
  578. /// If the item is part of a series, this is it's number in the series.
  579. /// This could be episode number, album track number, etc.
  580. /// </summary>
  581. /// <value>The index number.</value>
  582. [IgnoreDataMember]
  583. public int? IndexNumber { get; set; }
  584. /// <summary>
  585. /// For an episode this could be the season number, or for a song this could be the disc number.
  586. /// </summary>
  587. /// <value>The parent index number.</value>
  588. [IgnoreDataMember]
  589. public int? ParentIndexNumber { get; set; }
  590. [IgnoreDataMember]
  591. public virtual string OfficialRatingForComparison
  592. {
  593. get { return OfficialRating; }
  594. }
  595. [IgnoreDataMember]
  596. public string CustomRatingForComparison
  597. {
  598. get
  599. {
  600. if (!string.IsNullOrWhiteSpace(CustomRating))
  601. {
  602. return CustomRating;
  603. }
  604. var parent = DisplayParent;
  605. if (parent != null)
  606. {
  607. return parent.CustomRatingForComparison;
  608. }
  609. return null;
  610. }
  611. }
  612. /// <summary>
  613. /// Gets the play access.
  614. /// </summary>
  615. /// <param name="user">The user.</param>
  616. /// <returns>PlayAccess.</returns>
  617. public PlayAccess GetPlayAccess(User user)
  618. {
  619. if (!user.Policy.EnableMediaPlayback)
  620. {
  621. return PlayAccess.None;
  622. }
  623. //if (!user.IsParentalScheduleAllowed())
  624. //{
  625. // return PlayAccess.None;
  626. //}
  627. return PlayAccess.Full;
  628. }
  629. /// <summary>
  630. /// Loads the theme songs.
  631. /// </summary>
  632. /// <returns>List{Audio.Audio}.</returns>
  633. private IEnumerable<Audio.Audio> LoadThemeSongs(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  634. {
  635. var files = fileSystemChildren.Where(i => i.IsDirectory)
  636. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  637. .SelectMany(i => directoryService.GetFiles(i.FullName))
  638. .ToList();
  639. // Support plex/xbmc convention
  640. files.AddRange(fileSystemChildren
  641. .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
  642. );
  643. return LibraryManager.ResolvePaths(files, directoryService, null)
  644. .OfType<Audio.Audio>()
  645. .Select(audio =>
  646. {
  647. // Try to retrieve it from the db. If we don't find it, use the resolved version
  648. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  649. if (dbItem != null)
  650. {
  651. audio = dbItem;
  652. }
  653. audio.ExtraType = ExtraType.ThemeSong;
  654. return audio;
  655. // Sort them so that the list can be easily compared for changes
  656. }).OrderBy(i => i.Path).ToList();
  657. }
  658. /// <summary>
  659. /// Loads the video backdrops.
  660. /// </summary>
  661. /// <returns>List{Video}.</returns>
  662. private IEnumerable<Video> LoadThemeVideos(IEnumerable<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  663. {
  664. var files = fileSystemChildren.Where(i => i.IsDirectory)
  665. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  666. .SelectMany(i => directoryService.GetFiles(i.FullName));
  667. return LibraryManager.ResolvePaths(files, directoryService, null)
  668. .OfType<Video>()
  669. .Select(item =>
  670. {
  671. // Try to retrieve it from the db. If we don't find it, use the resolved version
  672. var dbItem = LibraryManager.GetItemById(item.Id) as Video;
  673. if (dbItem != null)
  674. {
  675. item = dbItem;
  676. }
  677. item.ExtraType = ExtraType.ThemeVideo;
  678. return item;
  679. // Sort them so that the list can be easily compared for changes
  680. }).OrderBy(i => i.Path).ToList();
  681. }
  682. public Task RefreshMetadata(CancellationToken cancellationToken)
  683. {
  684. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
  685. }
  686. /// <summary>
  687. /// Overrides the base implementation to refresh metadata for local trailers
  688. /// </summary>
  689. /// <param name="options">The options.</param>
  690. /// <param name="cancellationToken">The cancellation token.</param>
  691. /// <returns>true if a provider reports we changed</returns>
  692. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  693. {
  694. var locationType = LocationType;
  695. var requiresSave = false;
  696. if (SupportsOwnedItems)
  697. {
  698. try
  699. {
  700. var files = locationType != LocationType.Remote && locationType != LocationType.Virtual ?
  701. GetFileSystemChildren(options.DirectoryService).ToList() :
  702. new List<FileSystemMetadata>();
  703. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  704. if (ownedItemsChanged)
  705. {
  706. requiresSave = true;
  707. }
  708. }
  709. catch (Exception ex)
  710. {
  711. Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name);
  712. }
  713. }
  714. var refreshOptions = requiresSave
  715. ? new MetadataRefreshOptions(options)
  716. {
  717. ForceSave = true
  718. }
  719. : options;
  720. var result = await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  721. return result;
  722. }
  723. [IgnoreDataMember]
  724. protected virtual bool SupportsOwnedItems
  725. {
  726. get { return IsFolder || Parent != null; }
  727. }
  728. [IgnoreDataMember]
  729. public virtual bool SupportsPeople
  730. {
  731. get { return true; }
  732. }
  733. /// <summary>
  734. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  735. /// Returns true or false indicating if changes were found.
  736. /// </summary>
  737. /// <param name="options"></param>
  738. /// <param name="fileSystemChildren"></param>
  739. /// <param name="cancellationToken"></param>
  740. /// <returns></returns>
  741. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  742. {
  743. var themeSongsChanged = false;
  744. var themeVideosChanged = false;
  745. var localTrailersChanged = false;
  746. if (LocationType == LocationType.FileSystem && Parent != null)
  747. {
  748. var hasThemeMedia = this as IHasThemeMedia;
  749. if (hasThemeMedia != null)
  750. {
  751. if (!IsInMixedFolder)
  752. {
  753. themeSongsChanged = await RefreshThemeSongs(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  754. themeVideosChanged = await RefreshThemeVideos(hasThemeMedia, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  755. }
  756. }
  757. var hasTrailers = this as IHasTrailers;
  758. if (hasTrailers != null)
  759. {
  760. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  761. }
  762. }
  763. return themeSongsChanged || themeVideosChanged || localTrailersChanged;
  764. }
  765. protected virtual IEnumerable<FileSystemMetadata> GetFileSystemChildren(IDirectoryService directoryService)
  766. {
  767. var path = ContainingFolderPath;
  768. return directoryService.GetFileSystemEntries(path);
  769. }
  770. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  771. {
  772. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService).ToList();
  773. var newItemIds = newItems.Select(i => i.Id).ToList();
  774. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  775. var tasks = newItems.Select(i => i.RefreshMetadata(options, cancellationToken));
  776. await Task.WhenAll(tasks).ConfigureAwait(false);
  777. item.LocalTrailerIds = newItemIds;
  778. return itemsChanged;
  779. }
  780. private async Task<bool> RefreshThemeVideos(IHasThemeMedia item, MetadataRefreshOptions options, IEnumerable<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  781. {
  782. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService).ToList();
  783. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  784. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  785. var tasks = newThemeVideos.Select(i =>
  786. {
  787. var subOptions = new MetadataRefreshOptions(options);
  788. if (!i.IsThemeMedia)
  789. {
  790. i.ExtraType = ExtraType.ThemeVideo;
  791. subOptions.ForceSave = true;
  792. }
  793. return i.RefreshMetadata(subOptions, cancellationToken);
  794. });
  795. await Task.WhenAll(tasks).ConfigureAwait(false);
  796. item.ThemeVideoIds = newThemeVideoIds;
  797. return themeVideosChanged;
  798. }
  799. /// <summary>
  800. /// Refreshes the theme songs.
  801. /// </summary>
  802. private async Task<bool> RefreshThemeSongs(IHasThemeMedia item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  803. {
  804. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService).ToList();
  805. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  806. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  807. var tasks = newThemeSongs.Select(i =>
  808. {
  809. var subOptions = new MetadataRefreshOptions(options);
  810. if (!i.IsThemeMedia)
  811. {
  812. i.ExtraType = ExtraType.ThemeSong;
  813. subOptions.ForceSave = true;
  814. }
  815. return i.RefreshMetadata(subOptions, cancellationToken);
  816. });
  817. await Task.WhenAll(tasks).ConfigureAwait(false);
  818. item.ThemeSongIds = newThemeSongIds;
  819. return themeSongsChanged;
  820. }
  821. /// <summary>
  822. /// Gets or sets the provider ids.
  823. /// </summary>
  824. /// <value>The provider ids.</value>
  825. public Dictionary<string, string> ProviderIds { get; set; }
  826. [IgnoreDataMember]
  827. public virtual Folder LatestItemsIndexContainer
  828. {
  829. get { return null; }
  830. }
  831. private string _userDataKey;
  832. /// <summary>
  833. /// Gets the user data key.
  834. /// </summary>
  835. /// <returns>System.String.</returns>
  836. public string GetUserDataKey()
  837. {
  838. if (string.IsNullOrWhiteSpace(_userDataKey))
  839. {
  840. var key = CreateUserDataKey();
  841. _userDataKey = key;
  842. return key;
  843. }
  844. return _userDataKey;
  845. }
  846. protected virtual string CreateUserDataKey()
  847. {
  848. return Id.ToString();
  849. }
  850. internal virtual bool IsValidFromResolver(BaseItem newItem)
  851. {
  852. var current = this;
  853. return current.IsInMixedFolder == newItem.IsInMixedFolder;
  854. }
  855. public void AfterMetadataRefresh()
  856. {
  857. _sortName = null;
  858. _userDataKey = null;
  859. }
  860. /// <summary>
  861. /// Gets the preferred metadata language.
  862. /// </summary>
  863. /// <returns>System.String.</returns>
  864. public string GetPreferredMetadataLanguage()
  865. {
  866. string lang = PreferredMetadataLanguage;
  867. if (string.IsNullOrWhiteSpace(lang))
  868. {
  869. lang = Parents
  870. .Select(i => i.PreferredMetadataLanguage)
  871. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  872. }
  873. if (string.IsNullOrWhiteSpace(lang))
  874. {
  875. lang = LibraryManager.GetCollectionFolders(this)
  876. .Select(i => i.PreferredMetadataLanguage)
  877. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  878. }
  879. if (string.IsNullOrWhiteSpace(lang))
  880. {
  881. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  882. }
  883. return lang;
  884. }
  885. /// <summary>
  886. /// Gets the preferred metadata language.
  887. /// </summary>
  888. /// <returns>System.String.</returns>
  889. public string GetPreferredMetadataCountryCode()
  890. {
  891. string lang = PreferredMetadataCountryCode;
  892. if (string.IsNullOrWhiteSpace(lang))
  893. {
  894. lang = Parents
  895. .Select(i => i.PreferredMetadataCountryCode)
  896. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  897. }
  898. if (string.IsNullOrWhiteSpace(lang))
  899. {
  900. lang = LibraryManager.GetCollectionFolders(this)
  901. .Select(i => i.PreferredMetadataCountryCode)
  902. .FirstOrDefault(i => !string.IsNullOrWhiteSpace(i));
  903. }
  904. if (string.IsNullOrWhiteSpace(lang))
  905. {
  906. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  907. }
  908. return lang;
  909. }
  910. public virtual bool IsSaveLocalMetadataEnabled()
  911. {
  912. return ConfigurationManager.Configuration.SaveLocalMeta;
  913. }
  914. /// <summary>
  915. /// Determines if a given user has access to this item
  916. /// </summary>
  917. /// <param name="user">The user.</param>
  918. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  919. /// <exception cref="System.ArgumentNullException">user</exception>
  920. public bool IsParentalAllowed(User user)
  921. {
  922. if (user == null)
  923. {
  924. throw new ArgumentNullException("user");
  925. }
  926. if (!IsVisibleViaTags(user))
  927. {
  928. return false;
  929. }
  930. var maxAllowedRating = user.Policy.MaxParentalRating;
  931. if (maxAllowedRating == null)
  932. {
  933. return true;
  934. }
  935. var rating = CustomRatingForComparison;
  936. if (string.IsNullOrWhiteSpace(rating))
  937. {
  938. rating = OfficialRatingForComparison;
  939. }
  940. if (string.IsNullOrWhiteSpace(rating))
  941. {
  942. return !GetBlockUnratedValue(user.Policy);
  943. }
  944. var value = LocalizationManager.GetRatingLevel(rating);
  945. // Could not determine the integer value
  946. if (!value.HasValue)
  947. {
  948. var isAllowed = !GetBlockUnratedValue(user.Policy);
  949. if (!isAllowed)
  950. {
  951. Logger.Debug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  952. }
  953. return isAllowed;
  954. }
  955. return value.Value <= maxAllowedRating.Value;
  956. }
  957. public int? GetParentalRatingValue()
  958. {
  959. var rating = CustomRatingForComparison;
  960. if (string.IsNullOrWhiteSpace(rating))
  961. {
  962. rating = OfficialRatingForComparison;
  963. }
  964. if (string.IsNullOrWhiteSpace(rating))
  965. {
  966. return null;
  967. }
  968. return LocalizationManager.GetRatingLevel(rating);
  969. }
  970. private bool IsVisibleViaTags(User user)
  971. {
  972. var hasTags = this as IHasTags;
  973. if (hasTags != null)
  974. {
  975. var policy = user.Policy;
  976. if (policy.BlockedTags.Any(i => hasTags.Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  977. {
  978. return false;
  979. }
  980. }
  981. return true;
  982. }
  983. protected virtual bool IsAllowTagFilterEnforced()
  984. {
  985. return true;
  986. }
  987. /// <summary>
  988. /// Gets the block unrated value.
  989. /// </summary>
  990. /// <param name="config">The configuration.</param>
  991. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  992. protected virtual bool GetBlockUnratedValue(UserPolicy config)
  993. {
  994. // Don't block plain folders that are unrated. Let the media underneath get blocked
  995. // Special folders like series and albums will override this method.
  996. if (IsFolder)
  997. {
  998. return false;
  999. }
  1000. if (this is IItemByName)
  1001. {
  1002. return false;
  1003. }
  1004. return config.BlockUnratedItems.Contains(UnratedItem.Other);
  1005. }
  1006. /// <summary>
  1007. /// Determines if this folder should be visible to a given user.
  1008. /// Default is just parental allowed. Can be overridden for more functionality.
  1009. /// </summary>
  1010. /// <param name="user">The user.</param>
  1011. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1012. /// <exception cref="System.ArgumentNullException">user</exception>
  1013. public virtual bool IsVisible(User user)
  1014. {
  1015. if (user == null)
  1016. {
  1017. throw new ArgumentNullException("user");
  1018. }
  1019. return IsParentalAllowed(user);
  1020. }
  1021. public virtual bool IsVisibleStandalone(User user)
  1022. {
  1023. return IsVisibleStandaloneInternal(user, true);
  1024. }
  1025. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1026. {
  1027. if (!IsVisible(user))
  1028. {
  1029. return false;
  1030. }
  1031. if (Parents.Any(i => !i.IsVisible(user)))
  1032. {
  1033. return false;
  1034. }
  1035. if (checkFolders)
  1036. {
  1037. var topParent = Parents.LastOrDefault() ?? this;
  1038. if (string.IsNullOrWhiteSpace(topParent.Path))
  1039. {
  1040. return true;
  1041. }
  1042. var userCollectionFolders = user.RootFolder.GetChildren(user, true).Select(i => i.Id).ToList();
  1043. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id);
  1044. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1045. {
  1046. return false;
  1047. }
  1048. }
  1049. return true;
  1050. }
  1051. /// <summary>
  1052. /// Gets a value indicating whether this instance is folder.
  1053. /// </summary>
  1054. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1055. [IgnoreDataMember]
  1056. public virtual bool IsFolder
  1057. {
  1058. get
  1059. {
  1060. return false;
  1061. }
  1062. }
  1063. public virtual string GetClientTypeName()
  1064. {
  1065. return GetType().Name;
  1066. }
  1067. /// <summary>
  1068. /// Gets the linked child.
  1069. /// </summary>
  1070. /// <param name="info">The info.</param>
  1071. /// <returns>BaseItem.</returns>
  1072. protected BaseItem GetLinkedChild(LinkedChild info)
  1073. {
  1074. // First get using the cached Id
  1075. if (info.ItemId.HasValue)
  1076. {
  1077. if (info.ItemId.Value == Guid.Empty)
  1078. {
  1079. return null;
  1080. }
  1081. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1082. if (itemById != null)
  1083. {
  1084. return itemById;
  1085. }
  1086. }
  1087. var item = FindLinkedChild(info);
  1088. // If still null, log
  1089. if (item == null)
  1090. {
  1091. // Don't keep searching over and over
  1092. info.ItemId = Guid.Empty;
  1093. }
  1094. else
  1095. {
  1096. // Cache the id for next time
  1097. info.ItemId = item.Id;
  1098. }
  1099. return item;
  1100. }
  1101. private BaseItem FindLinkedChild(LinkedChild info)
  1102. {
  1103. if (!string.IsNullOrEmpty(info.Path))
  1104. {
  1105. var itemByPath = LibraryManager.RootFolder.FindByPath(info.Path);
  1106. if (itemByPath == null)
  1107. {
  1108. Logger.Warn("Unable to find linked item at path {0}", info.Path);
  1109. }
  1110. return itemByPath;
  1111. }
  1112. return null;
  1113. }
  1114. /// <summary>
  1115. /// Adds a studio to the item
  1116. /// </summary>
  1117. /// <param name="name">The name.</param>
  1118. /// <exception cref="System.ArgumentNullException"></exception>
  1119. public void AddStudio(string name)
  1120. {
  1121. if (string.IsNullOrWhiteSpace(name))
  1122. {
  1123. throw new ArgumentNullException("name");
  1124. }
  1125. if (!Studios.Contains(name, StringComparer.OrdinalIgnoreCase))
  1126. {
  1127. Studios.Add(name);
  1128. }
  1129. }
  1130. /// <summary>
  1131. /// Adds a genre to the item
  1132. /// </summary>
  1133. /// <param name="name">The name.</param>
  1134. /// <exception cref="System.ArgumentNullException"></exception>
  1135. public void AddGenre(string name)
  1136. {
  1137. if (string.IsNullOrWhiteSpace(name))
  1138. {
  1139. throw new ArgumentNullException("name");
  1140. }
  1141. if (!Genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1142. {
  1143. Genres.Add(name);
  1144. }
  1145. }
  1146. /// <summary>
  1147. /// Marks the played.
  1148. /// </summary>
  1149. /// <param name="user">The user.</param>
  1150. /// <param name="datePlayed">The date played.</param>
  1151. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1152. /// <returns>Task.</returns>
  1153. /// <exception cref="System.ArgumentNullException"></exception>
  1154. public virtual async Task MarkPlayed(User user,
  1155. DateTime? datePlayed,
  1156. bool resetPosition)
  1157. {
  1158. if (user == null)
  1159. {
  1160. throw new ArgumentNullException();
  1161. }
  1162. var key = GetUserDataKey();
  1163. var data = UserDataManager.GetUserData(user.Id, key);
  1164. if (datePlayed.HasValue)
  1165. {
  1166. // Incremenet
  1167. data.PlayCount++;
  1168. }
  1169. // Ensure it's at least one
  1170. data.PlayCount = Math.Max(data.PlayCount, 1);
  1171. if (resetPosition)
  1172. {
  1173. data.PlaybackPositionTicks = 0;
  1174. }
  1175. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate;
  1176. data.Played = true;
  1177. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1178. }
  1179. /// <summary>
  1180. /// Marks the unplayed.
  1181. /// </summary>
  1182. /// <param name="user">The user.</param>
  1183. /// <returns>Task.</returns>
  1184. /// <exception cref="System.ArgumentNullException"></exception>
  1185. public virtual async Task MarkUnplayed(User user)
  1186. {
  1187. if (user == null)
  1188. {
  1189. throw new ArgumentNullException();
  1190. }
  1191. var key = GetUserDataKey();
  1192. var data = UserDataManager.GetUserData(user.Id, key);
  1193. //I think it is okay to do this here.
  1194. // if this is only called when a user is manually forcing something to un-played
  1195. // then it probably is what we want to do...
  1196. data.PlayCount = 0;
  1197. data.PlaybackPositionTicks = 0;
  1198. data.LastPlayedDate = null;
  1199. data.Played = false;
  1200. await UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None).ConfigureAwait(false);
  1201. }
  1202. /// <summary>
  1203. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1204. /// </summary>
  1205. /// <returns>Task.</returns>
  1206. public virtual Task ChangedExternally()
  1207. {
  1208. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem));
  1209. return Task.FromResult(true);
  1210. }
  1211. /// <summary>
  1212. /// Gets an image
  1213. /// </summary>
  1214. /// <param name="type">The type.</param>
  1215. /// <param name="imageIndex">Index of the image.</param>
  1216. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1217. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1218. public bool HasImage(ImageType type, int imageIndex)
  1219. {
  1220. return GetImageInfo(type, imageIndex) != null;
  1221. }
  1222. public void SetImage(ItemImageInfo image, int index)
  1223. {
  1224. if (image.Type == ImageType.Chapter)
  1225. {
  1226. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1227. }
  1228. var existingImage = GetImageInfo(image.Type, index);
  1229. if (existingImage != null)
  1230. {
  1231. ImageInfos.Remove(existingImage);
  1232. }
  1233. ImageInfos.Add(image);
  1234. }
  1235. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1236. {
  1237. if (type == ImageType.Chapter)
  1238. {
  1239. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1240. }
  1241. var image = GetImageInfo(type, index);
  1242. if (image == null)
  1243. {
  1244. ImageInfos.Add(GetImageInfo(file, type));
  1245. }
  1246. else
  1247. {
  1248. var imageInfo = GetImageInfo(file, type);
  1249. image.Path = file.FullName;
  1250. image.DateModified = imageInfo.DateModified;
  1251. }
  1252. }
  1253. /// <summary>
  1254. /// Deletes the image.
  1255. /// </summary>
  1256. /// <param name="type">The type.</param>
  1257. /// <param name="index">The index.</param>
  1258. /// <returns>Task.</returns>
  1259. public Task DeleteImage(ImageType type, int index)
  1260. {
  1261. var info = GetImageInfo(type, index);
  1262. if (info == null)
  1263. {
  1264. // Nothing to do
  1265. return Task.FromResult(true);
  1266. }
  1267. // Remove it from the item
  1268. RemoveImage(info);
  1269. if (info.IsLocalFile)
  1270. {
  1271. // Delete the source file
  1272. var currentFile = new FileInfo(info.Path);
  1273. // Deletion will fail if the file is hidden so remove the attribute first
  1274. if (currentFile.Exists)
  1275. {
  1276. if ((currentFile.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
  1277. {
  1278. currentFile.Attributes &= ~FileAttributes.Hidden;
  1279. }
  1280. FileSystem.DeleteFile(currentFile.FullName);
  1281. }
  1282. }
  1283. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1284. }
  1285. public void RemoveImage(ItemImageInfo image)
  1286. {
  1287. ImageInfos.Remove(image);
  1288. }
  1289. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1290. {
  1291. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1292. }
  1293. /// <summary>
  1294. /// Validates that images within the item are still on the file system
  1295. /// </summary>
  1296. public bool ValidateImages(IDirectoryService directoryService)
  1297. {
  1298. var allFiles = ImageInfos
  1299. .Where(i => i.IsLocalFile)
  1300. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1301. .Distinct(StringComparer.OrdinalIgnoreCase)
  1302. .SelectMany(directoryService.GetFiles)
  1303. .Select(i => i.FullName)
  1304. .ToList();
  1305. var deletedImages = ImageInfos
  1306. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1307. .ToList();
  1308. if (deletedImages.Count > 0)
  1309. {
  1310. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1311. }
  1312. return deletedImages.Count > 0;
  1313. }
  1314. /// <summary>
  1315. /// Gets the image path.
  1316. /// </summary>
  1317. /// <param name="imageType">Type of the image.</param>
  1318. /// <param name="imageIndex">Index of the image.</param>
  1319. /// <returns>System.String.</returns>
  1320. /// <exception cref="System.InvalidOperationException">
  1321. /// </exception>
  1322. /// <exception cref="System.ArgumentNullException">item</exception>
  1323. public string GetImagePath(ImageType imageType, int imageIndex)
  1324. {
  1325. var info = GetImageInfo(imageType, imageIndex);
  1326. return info == null ? null : info.Path;
  1327. }
  1328. /// <summary>
  1329. /// Gets the image information.
  1330. /// </summary>
  1331. /// <param name="imageType">Type of the image.</param>
  1332. /// <param name="imageIndex">Index of the image.</param>
  1333. /// <returns>ItemImageInfo.</returns>
  1334. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1335. {
  1336. if (imageType == ImageType.Chapter)
  1337. {
  1338. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1339. if (chapter == null)
  1340. {
  1341. return null;
  1342. }
  1343. var path = chapter.ImagePath;
  1344. if (string.IsNullOrWhiteSpace(path))
  1345. {
  1346. return null;
  1347. }
  1348. return new ItemImageInfo
  1349. {
  1350. Path = path,
  1351. DateModified = FileSystem.GetLastWriteTimeUtc(path),
  1352. Type = imageType
  1353. };
  1354. }
  1355. return GetImages(imageType)
  1356. .ElementAtOrDefault(imageIndex);
  1357. }
  1358. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1359. {
  1360. if (imageType == ImageType.Chapter)
  1361. {
  1362. throw new ArgumentException("No image info for chapter images");
  1363. }
  1364. return ImageInfos.Where(i => i.Type == imageType);
  1365. }
  1366. /// <summary>
  1367. /// Adds the images.
  1368. /// </summary>
  1369. /// <param name="imageType">Type of the image.</param>
  1370. /// <param name="images">The images.</param>
  1371. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1372. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1373. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1374. {
  1375. if (imageType == ImageType.Chapter)
  1376. {
  1377. throw new ArgumentException("Cannot call AddImages with chapter images");
  1378. }
  1379. var existingImages = GetImages(imageType)
  1380. .ToList();
  1381. var newImageList = new List<FileSystemMetadata>();
  1382. var imageAdded = false;
  1383. foreach (var newImage in images)
  1384. {
  1385. if (newImage == null)
  1386. {
  1387. throw new ArgumentException("null image found in list");
  1388. }
  1389. var existing = existingImages
  1390. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1391. if (existing == null)
  1392. {
  1393. newImageList.Add(newImage);
  1394. imageAdded = true;
  1395. }
  1396. else
  1397. {
  1398. if (existing.IsLocalFile)
  1399. {
  1400. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1401. }
  1402. }
  1403. }
  1404. if (imageAdded || images.Count != existingImages.Count)
  1405. {
  1406. var newImagePaths = images.Select(i => i.FullName).ToList();
  1407. var deleted = existingImages
  1408. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !FileSystem.FileExists(i.Path))
  1409. .ToList();
  1410. ImageInfos = ImageInfos.Except(deleted).ToList();
  1411. }
  1412. ImageInfos.AddRange(newImageList.Select(i => GetImageInfo(i, imageType)));
  1413. return newImageList.Count > 0;
  1414. }
  1415. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1416. {
  1417. return new ItemImageInfo
  1418. {
  1419. Path = file.FullName,
  1420. Type = type,
  1421. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1422. };
  1423. }
  1424. /// <summary>
  1425. /// Gets the file system path to delete when the item is to be deleted
  1426. /// </summary>
  1427. /// <returns></returns>
  1428. public virtual IEnumerable<string> GetDeletePaths()
  1429. {
  1430. return new[] { Path };
  1431. }
  1432. public bool AllowsMultipleImages(ImageType type)
  1433. {
  1434. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1435. }
  1436. public Task SwapImages(ImageType type, int index1, int index2)
  1437. {
  1438. if (!AllowsMultipleImages(type))
  1439. {
  1440. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1441. }
  1442. var info1 = GetImageInfo(type, index1);
  1443. var info2 = GetImageInfo(type, index2);
  1444. if (info1 == null || info2 == null)
  1445. {
  1446. // Nothing to do
  1447. return Task.FromResult(true);
  1448. }
  1449. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1450. {
  1451. // TODO: Not supported yet
  1452. return Task.FromResult(true);
  1453. }
  1454. var path1 = info1.Path;
  1455. var path2 = info2.Path;
  1456. FileSystem.SwapFiles(path1, path2);
  1457. // Refresh these values
  1458. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1459. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1460. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1461. }
  1462. public virtual bool IsPlayed(User user)
  1463. {
  1464. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1465. return userdata != null && userdata.Played;
  1466. }
  1467. public bool IsFavoriteOrLiked(User user)
  1468. {
  1469. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1470. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1471. }
  1472. public virtual bool IsUnplayed(User user)
  1473. {
  1474. if (user == null)
  1475. {
  1476. throw new ArgumentNullException("user");
  1477. }
  1478. var userdata = UserDataManager.GetUserData(user.Id, GetUserDataKey());
  1479. return userdata == null || !userdata.Played;
  1480. }
  1481. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1482. {
  1483. return GetItemLookupInfo<ItemLookupInfo>();
  1484. }
  1485. protected T GetItemLookupInfo<T>()
  1486. where T : ItemLookupInfo, new()
  1487. {
  1488. return new T
  1489. {
  1490. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1491. MetadataLanguage = GetPreferredMetadataLanguage(),
  1492. Name = Name,
  1493. ProviderIds = ProviderIds,
  1494. IndexNumber = IndexNumber,
  1495. ParentIndexNumber = ParentIndexNumber,
  1496. Year = ProductionYear
  1497. };
  1498. }
  1499. /// <summary>
  1500. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1501. /// </summary>
  1502. public virtual bool BeforeMetadataRefresh()
  1503. {
  1504. _userDataKey = null;
  1505. _sortName = null;
  1506. var hasChanges = false;
  1507. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1508. {
  1509. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1510. hasChanges = true;
  1511. }
  1512. return hasChanges;
  1513. }
  1514. protected static string GetMappedPath(string path, LocationType locationType)
  1515. {
  1516. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1517. {
  1518. foreach (var map in ConfigurationManager.Configuration.PathSubstitutions)
  1519. {
  1520. path = LibraryManager.SubstitutePath(path, map.From, map.To);
  1521. }
  1522. }
  1523. return path;
  1524. }
  1525. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, User user)
  1526. {
  1527. if (RunTimeTicks.HasValue)
  1528. {
  1529. double pct = RunTimeTicks.Value;
  1530. if (pct > 0)
  1531. {
  1532. pct = userData.PlaybackPositionTicks / pct;
  1533. if (pct > 0)
  1534. {
  1535. dto.PlayedPercentage = 100 * pct;
  1536. }
  1537. }
  1538. }
  1539. }
  1540. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, string path, CancellationToken cancellationToken)
  1541. {
  1542. var newOptions = new MetadataRefreshOptions(options.DirectoryService)
  1543. {
  1544. ImageRefreshMode = options.ImageRefreshMode,
  1545. MetadataRefreshMode = options.MetadataRefreshMode,
  1546. ReplaceAllMetadata = options.ReplaceAllMetadata
  1547. };
  1548. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1549. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1550. var video = LibraryManager.GetItemById(id) as Video;
  1551. if (video == null)
  1552. {
  1553. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  1554. newOptions.ForceSave = true;
  1555. }
  1556. if (video == null)
  1557. {
  1558. return Task.FromResult(true);
  1559. }
  1560. return video.RefreshMetadata(newOptions, cancellationToken);
  1561. }
  1562. public string GetEtag(User user)
  1563. {
  1564. return string.Join("|", GetEtagValues(user).ToArray()).GetMD5().ToString("N");
  1565. }
  1566. protected virtual List<string> GetEtagValues(User user)
  1567. {
  1568. return new List<string>
  1569. {
  1570. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  1571. };
  1572. }
  1573. }
  1574. }