BaseItem.cs 62 KB

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