BaseItem.cs 62 KB

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