BaseItem.cs 57 KB

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