BaseItem.cs 57 KB

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