BaseItem.cs 60 KB

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