BaseItem.cs 62 KB

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