BaseItem.cs 60 KB

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