BaseItem.cs 64 KB

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