BaseItem.cs 62 KB

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