BaseItem.cs 57 KB

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