2
0

BaseItem.cs 58 KB

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