BaseItem.cs 63 KB

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