BaseItem.cs 61 KB

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