BaseItem.cs 59 KB

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