BaseItem.cs 67 KB

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