BaseItem.cs 57 KB

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