BaseItem.cs 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999
  1. #pragma warning disable CS1591
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Globalization;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.Json.Serialization;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Jellyfin.Data.Entities;
  12. using Jellyfin.Data.Enums;
  13. using MediaBrowser.Common.Extensions;
  14. using MediaBrowser.Controller.Channels;
  15. using MediaBrowser.Controller.Configuration;
  16. using MediaBrowser.Controller.Dto;
  17. using MediaBrowser.Controller.Extensions;
  18. using MediaBrowser.Controller.Library;
  19. using MediaBrowser.Controller.Persistence;
  20. using MediaBrowser.Controller.Providers;
  21. using MediaBrowser.Model.Configuration;
  22. using MediaBrowser.Model.Dto;
  23. using MediaBrowser.Model.Entities;
  24. using MediaBrowser.Model.Globalization;
  25. using MediaBrowser.Model.IO;
  26. using MediaBrowser.Model.Library;
  27. using MediaBrowser.Model.LiveTv;
  28. using MediaBrowser.Model.MediaInfo;
  29. using MediaBrowser.Model.Providers;
  30. using Microsoft.Extensions.Logging;
  31. namespace MediaBrowser.Controller.Entities
  32. {
  33. /// <summary>
  34. /// Class BaseItem.
  35. /// </summary>
  36. public abstract class BaseItem : IHasProviderIds, IHasLookupInfo<ItemLookupInfo>, IEquatable<BaseItem>
  37. {
  38. /// <summary>
  39. /// The supported image extensions.
  40. /// </summary>
  41. public static readonly string[] SupportedImageExtensions
  42. = new[] { ".png", ".jpg", ".jpeg", ".tbn", ".gif" };
  43. private static readonly List<string> _supportedExtensions = new List<string>(SupportedImageExtensions)
  44. {
  45. ".nfo",
  46. ".xml",
  47. ".srt",
  48. ".vtt",
  49. ".sub",
  50. ".idx",
  51. ".txt",
  52. ".edl",
  53. ".bif",
  54. ".smi",
  55. ".ttml"
  56. };
  57. protected BaseItem()
  58. {
  59. Tags = Array.Empty<string>();
  60. Genres = Array.Empty<string>();
  61. Studios = Array.Empty<string>();
  62. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  63. LockedFields = Array.Empty<MetadataField>();
  64. ImageInfos = Array.Empty<ItemImageInfo>();
  65. ProductionLocations = Array.Empty<string>();
  66. RemoteTrailers = Array.Empty<MediaUrl>();
  67. ExtraIds = Array.Empty<Guid>();
  68. }
  69. public static readonly char[] SlugReplaceChars = { '?', '/', '&' };
  70. public static char SlugChar = '-';
  71. /// <summary>
  72. /// The trailer folder name.
  73. /// </summary>
  74. public const string TrailerFolderName = "trailers";
  75. public const string ThemeSongsFolderName = "theme-music";
  76. public const string ThemeSongFilename = "theme";
  77. public const string ThemeVideosFolderName = "backdrops";
  78. public const string ExtrasFolderName = "extras";
  79. public const string BehindTheScenesFolderName = "behind the scenes";
  80. public const string DeletedScenesFolderName = "deleted scenes";
  81. public const string InterviewFolderName = "interviews";
  82. public const string SceneFolderName = "scenes";
  83. public const string SampleFolderName = "samples";
  84. public const string ShortsFolderName = "shorts";
  85. public const string FeaturettesFolderName = "featurettes";
  86. public static readonly string[] AllExtrasTypesFolderNames = {
  87. ExtrasFolderName,
  88. BehindTheScenesFolderName,
  89. DeletedScenesFolderName,
  90. InterviewFolderName,
  91. SceneFolderName,
  92. SampleFolderName,
  93. ShortsFolderName,
  94. FeaturettesFolderName
  95. };
  96. [JsonIgnore]
  97. public Guid[] ThemeSongIds
  98. {
  99. get
  100. {
  101. return _themeSongIds ??= GetExtras()
  102. .Where(extra => extra.ExtraType == Model.Entities.ExtraType.ThemeSong)
  103. .Select(song => song.Id)
  104. .ToArray();
  105. }
  106. private set
  107. {
  108. _themeSongIds = value;
  109. }
  110. }
  111. [JsonIgnore]
  112. public Guid[] ThemeVideoIds
  113. {
  114. get
  115. {
  116. return _themeVideoIds ??= GetExtras()
  117. .Where(extra => extra.ExtraType == Model.Entities.ExtraType.ThemeVideo)
  118. .Select(song => song.Id)
  119. .ToArray();
  120. }
  121. private set
  122. {
  123. _themeVideoIds = value;
  124. }
  125. }
  126. [JsonIgnore]
  127. public string PreferredMetadataCountryCode { get; set; }
  128. [JsonIgnore]
  129. public string PreferredMetadataLanguage { get; set; }
  130. public long? Size { get; set; }
  131. public string Container { get; set; }
  132. [JsonIgnore]
  133. public string Tagline { get; set; }
  134. [JsonIgnore]
  135. public virtual ItemImageInfo[] ImageInfos { get; set; }
  136. [JsonIgnore]
  137. public bool IsVirtualItem { get; set; }
  138. /// <summary>
  139. /// Gets or sets the album.
  140. /// </summary>
  141. /// <value>The album.</value>
  142. [JsonIgnore]
  143. public string Album { get; set; }
  144. /// <summary>
  145. /// Gets or sets the channel identifier.
  146. /// </summary>
  147. /// <value>The channel identifier.</value>
  148. [JsonIgnore]
  149. public Guid ChannelId { get; set; }
  150. [JsonIgnore]
  151. public virtual bool SupportsAddingToPlaylist => false;
  152. [JsonIgnore]
  153. public virtual bool AlwaysScanInternalMetadataPath => false;
  154. /// <summary>
  155. /// Gets a value indicating whether this instance is in mixed folder.
  156. /// </summary>
  157. /// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
  158. [JsonIgnore]
  159. public bool IsInMixedFolder { get; set; }
  160. [JsonIgnore]
  161. public virtual bool SupportsPlayedStatus => false;
  162. [JsonIgnore]
  163. public virtual bool SupportsPositionTicksResume => false;
  164. [JsonIgnore]
  165. public virtual bool SupportsRemoteImageDownloading => true;
  166. private string _name;
  167. /// <summary>
  168. /// Gets or sets the name.
  169. /// </summary>
  170. /// <value>The name.</value>
  171. [JsonIgnore]
  172. public virtual string Name
  173. {
  174. get => _name;
  175. set
  176. {
  177. _name = value;
  178. // lazy load this again
  179. _sortName = null;
  180. }
  181. }
  182. [JsonIgnore]
  183. public bool IsUnaired => PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date;
  184. [JsonIgnore]
  185. public int? TotalBitrate { get; set; }
  186. [JsonIgnore]
  187. public ExtraType? ExtraType { get; set; }
  188. [JsonIgnore]
  189. public bool IsThemeMedia => ExtraType.HasValue && (ExtraType.Value == Model.Entities.ExtraType.ThemeSong || ExtraType.Value == Model.Entities.ExtraType.ThemeVideo);
  190. [JsonIgnore]
  191. public string OriginalTitle { get; set; }
  192. /// <summary>
  193. /// Gets or sets the id.
  194. /// </summary>
  195. /// <value>The id.</value>
  196. [JsonIgnore]
  197. public Guid Id { get; set; }
  198. [JsonIgnore]
  199. public Guid OwnerId { get; set; }
  200. /// <summary>
  201. /// Gets or sets the audio.
  202. /// </summary>
  203. /// <value>The audio.</value>
  204. [JsonIgnore]
  205. public ProgramAudio? Audio { get; set; }
  206. /// <summary>
  207. /// Return the id that should be used to key display prefs for this item.
  208. /// Default is based on the type for everything except actual generic folders.
  209. /// </summary>
  210. /// <value>The display prefs id.</value>
  211. [JsonIgnore]
  212. public virtual Guid DisplayPreferencesId
  213. {
  214. get
  215. {
  216. var thisType = GetType();
  217. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  218. }
  219. }
  220. /// <summary>
  221. /// Gets or sets the path.
  222. /// </summary>
  223. /// <value>The path.</value>
  224. [JsonIgnore]
  225. public virtual string Path { get; set; }
  226. [JsonIgnore]
  227. public virtual SourceType SourceType
  228. {
  229. get
  230. {
  231. if (!ChannelId.Equals(Guid.Empty))
  232. {
  233. return SourceType.Channel;
  234. }
  235. return SourceType.Library;
  236. }
  237. }
  238. /// <summary>
  239. /// Returns the folder containing the item.
  240. /// If the item is a folder, it returns the folder itself.
  241. /// </summary>
  242. [JsonIgnore]
  243. public virtual string ContainingFolderPath
  244. {
  245. get
  246. {
  247. if (IsFolder)
  248. {
  249. return Path;
  250. }
  251. return System.IO.Path.GetDirectoryName(Path);
  252. }
  253. }
  254. /// <summary>
  255. /// Gets or sets the name of the service.
  256. /// </summary>
  257. /// <value>The name of the service.</value>
  258. [JsonIgnore]
  259. public string ServiceName { get; set; }
  260. /// <summary>
  261. /// If this content came from an external service, the id of the content on that service.
  262. /// </summary>
  263. [JsonIgnore]
  264. public string ExternalId { get; set; }
  265. [JsonIgnore]
  266. public string ExternalSeriesId { get; set; }
  267. /// <summary>
  268. /// Gets or sets the etag.
  269. /// </summary>
  270. /// <value>The etag.</value>
  271. [JsonIgnore]
  272. public string ExternalEtag { get; set; }
  273. [JsonIgnore]
  274. public virtual bool IsHidden => false;
  275. public BaseItem GetOwner()
  276. {
  277. var ownerId = OwnerId;
  278. return ownerId.Equals(Guid.Empty) ? null : LibraryManager.GetItemById(ownerId);
  279. }
  280. /// <summary>
  281. /// Gets or sets the type of the location.
  282. /// </summary>
  283. /// <value>The type of the location.</value>
  284. [JsonIgnore]
  285. public virtual LocationType LocationType
  286. {
  287. get
  288. {
  289. // if (IsOffline)
  290. //{
  291. // return LocationType.Offline;
  292. //}
  293. var path = Path;
  294. if (string.IsNullOrEmpty(path))
  295. {
  296. if (SourceType == SourceType.Channel)
  297. {
  298. return LocationType.Remote;
  299. }
  300. return LocationType.Virtual;
  301. }
  302. return FileSystem.IsPathFile(path) ? LocationType.FileSystem : LocationType.Remote;
  303. }
  304. }
  305. [JsonIgnore]
  306. public MediaProtocol? PathProtocol
  307. {
  308. get
  309. {
  310. var path = Path;
  311. if (string.IsNullOrEmpty(path))
  312. {
  313. return null;
  314. }
  315. return MediaSourceManager.GetPathProtocol(path);
  316. }
  317. }
  318. public bool IsPathProtocol(MediaProtocol protocol)
  319. {
  320. var current = PathProtocol;
  321. return current.HasValue && current.Value == protocol;
  322. }
  323. [JsonIgnore]
  324. public bool IsFileProtocol => IsPathProtocol(MediaProtocol.File);
  325. [JsonIgnore]
  326. public bool HasPathProtocol => PathProtocol.HasValue;
  327. [JsonIgnore]
  328. public virtual bool SupportsLocalMetadata
  329. {
  330. get
  331. {
  332. if (SourceType == SourceType.Channel)
  333. {
  334. return false;
  335. }
  336. return IsFileProtocol;
  337. }
  338. }
  339. [JsonIgnore]
  340. public virtual string FileNameWithoutExtension
  341. {
  342. get
  343. {
  344. if (IsFileProtocol)
  345. {
  346. return System.IO.Path.GetFileNameWithoutExtension(Path);
  347. }
  348. return null;
  349. }
  350. }
  351. [JsonIgnore]
  352. public virtual bool EnableAlphaNumericSorting => true;
  353. private List<Tuple<StringBuilder, bool>> GetSortChunks(string s1)
  354. {
  355. var list = new List<Tuple<StringBuilder, bool>>();
  356. int thisMarker = 0;
  357. while (thisMarker < s1.Length)
  358. {
  359. char thisCh = s1[thisMarker];
  360. var thisChunk = new StringBuilder();
  361. bool isNumeric = char.IsDigit(thisCh);
  362. while (thisMarker < s1.Length && char.IsDigit(thisCh) == isNumeric)
  363. {
  364. thisChunk.Append(thisCh);
  365. thisMarker++;
  366. if (thisMarker < s1.Length)
  367. {
  368. thisCh = s1[thisMarker];
  369. }
  370. }
  371. list.Add(new Tuple<StringBuilder, bool>(thisChunk, isNumeric));
  372. }
  373. return list;
  374. }
  375. /// <summary>
  376. /// This is just a helper for convenience.
  377. /// </summary>
  378. /// <value>The primary image path.</value>
  379. [JsonIgnore]
  380. public string PrimaryImagePath => this.GetImagePath(ImageType.Primary);
  381. public virtual bool CanDelete()
  382. {
  383. if (SourceType == SourceType.Channel)
  384. {
  385. return ChannelManager.CanDelete(this);
  386. }
  387. return IsFileProtocol;
  388. }
  389. public virtual bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
  390. {
  391. if (user.HasPermission(PermissionKind.EnableContentDeletion))
  392. {
  393. return true;
  394. }
  395. var allowed = user.GetPreferenceValues<Guid>(PreferenceKind.EnableContentDeletionFromFolders);
  396. if (SourceType == SourceType.Channel)
  397. {
  398. return allowed.Contains(ChannelId);
  399. }
  400. else
  401. {
  402. var collectionFolders = LibraryManager.GetCollectionFolders(this, allCollectionFolders);
  403. foreach (var folder in collectionFolders)
  404. {
  405. if (allowed.Contains(folder.Id))
  406. {
  407. return true;
  408. }
  409. }
  410. }
  411. return false;
  412. }
  413. public bool CanDelete(User user, List<Folder> allCollectionFolders)
  414. {
  415. return CanDelete() && IsAuthorizedToDelete(user, allCollectionFolders);
  416. }
  417. public bool CanDelete(User user)
  418. {
  419. var allCollectionFolders = LibraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
  420. return CanDelete(user, allCollectionFolders);
  421. }
  422. public virtual bool CanDownload()
  423. {
  424. return false;
  425. }
  426. public virtual bool IsAuthorizedToDownload(User user)
  427. {
  428. return user.HasPermission(PermissionKind.EnableContentDownloading);
  429. }
  430. public bool CanDownload(User user)
  431. {
  432. return CanDownload() && IsAuthorizedToDownload(user);
  433. }
  434. /// <summary>
  435. /// Gets or sets the date created.
  436. /// </summary>
  437. /// <value>The date created.</value>
  438. [JsonIgnore]
  439. public DateTime DateCreated { get; set; }
  440. /// <summary>
  441. /// Gets or sets the date modified.
  442. /// </summary>
  443. /// <value>The date modified.</value>
  444. [JsonIgnore]
  445. public DateTime DateModified { get; set; }
  446. public DateTime DateLastSaved { get; set; }
  447. [JsonIgnore]
  448. public DateTime DateLastRefreshed { get; set; }
  449. /// <summary>
  450. /// The logger.
  451. /// </summary>
  452. public static ILogger<BaseItem> Logger { get; set; }
  453. public static ILibraryManager LibraryManager { get; set; }
  454. public static IServerConfigurationManager ConfigurationManager { get; set; }
  455. public static IProviderManager ProviderManager { get; set; }
  456. public static ILocalizationManager LocalizationManager { get; set; }
  457. public static IItemRepository ItemRepository { get; set; }
  458. public static IFileSystem FileSystem { get; set; }
  459. public static IUserDataManager UserDataManager { get; set; }
  460. public static IChannelManager ChannelManager { get; set; }
  461. public static IMediaSourceManager MediaSourceManager { get; set; }
  462. /// <summary>
  463. /// Returns a <see cref="string" /> that represents this instance.
  464. /// </summary>
  465. /// <returns>A <see cref="string" /> that represents this instance.</returns>
  466. public override string ToString()
  467. {
  468. return Name;
  469. }
  470. [JsonIgnore]
  471. public bool IsLocked { get; set; }
  472. /// <summary>
  473. /// Gets or sets the locked fields.
  474. /// </summary>
  475. /// <value>The locked fields.</value>
  476. [JsonIgnore]
  477. public MetadataField[] LockedFields { get; set; }
  478. /// <summary>
  479. /// Gets the type of the media.
  480. /// </summary>
  481. /// <value>The type of the media.</value>
  482. [JsonIgnore]
  483. public virtual string MediaType => null;
  484. [JsonIgnore]
  485. public virtual string[] PhysicalLocations
  486. {
  487. get
  488. {
  489. if (!IsFileProtocol)
  490. {
  491. return Array.Empty<string>();
  492. }
  493. return new[] { Path };
  494. }
  495. }
  496. private string _forcedSortName;
  497. /// <summary>
  498. /// Gets or sets the name of the forced sort.
  499. /// </summary>
  500. /// <value>The name of the forced sort.</value>
  501. [JsonIgnore]
  502. public string ForcedSortName
  503. {
  504. get => _forcedSortName;
  505. set { _forcedSortName = value; _sortName = null; }
  506. }
  507. private string _sortName;
  508. private Guid[] _themeSongIds;
  509. private Guid[] _themeVideoIds;
  510. /// <summary>
  511. /// Gets the name of the sort.
  512. /// </summary>
  513. /// <value>The name of the sort.</value>
  514. [JsonIgnore]
  515. public string SortName
  516. {
  517. get
  518. {
  519. if (_sortName == null)
  520. {
  521. if (!string.IsNullOrEmpty(ForcedSortName))
  522. {
  523. // Need the ToLower because that's what CreateSortName does
  524. _sortName = ModifySortChunks(ForcedSortName).ToLowerInvariant();
  525. }
  526. else
  527. {
  528. _sortName = CreateSortName();
  529. }
  530. }
  531. return _sortName;
  532. }
  533. set => _sortName = value;
  534. }
  535. public string GetInternalMetadataPath()
  536. {
  537. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  538. return GetInternalMetadataPath(basePath);
  539. }
  540. protected virtual string GetInternalMetadataPath(string basePath)
  541. {
  542. if (SourceType == SourceType.Channel)
  543. {
  544. return System.IO.Path.Combine(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), Id.ToString("N", CultureInfo.InvariantCulture));
  545. }
  546. ReadOnlySpan<char> idString = Id.ToString("N", CultureInfo.InvariantCulture);
  547. basePath = System.IO.Path.Combine(basePath, "library");
  548. return System.IO.Path.Join(basePath, idString.Slice(0, 2), idString);
  549. }
  550. /// <summary>
  551. /// Creates the name of the sort.
  552. /// </summary>
  553. /// <returns>System.String.</returns>
  554. protected virtual string CreateSortName()
  555. {
  556. if (Name == null)
  557. {
  558. return null; // some items may not have name filled in properly
  559. }
  560. if (!EnableAlphaNumericSorting)
  561. {
  562. return Name.TrimStart();
  563. }
  564. var sortable = Name.Trim().ToLowerInvariant();
  565. foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
  566. {
  567. sortable = sortable.Replace(removeChar, string.Empty, StringComparison.Ordinal);
  568. }
  569. foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
  570. {
  571. sortable = sortable.Replace(replaceChar, " ", StringComparison.Ordinal);
  572. }
  573. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  574. {
  575. // Remove from beginning if a space follows
  576. if (sortable.StartsWith(search + " ", StringComparison.Ordinal))
  577. {
  578. sortable = sortable.Remove(0, search.Length + 1);
  579. }
  580. // Remove from middle if surrounded by spaces
  581. sortable = sortable.Replace(" " + search + " ", " ", StringComparison.Ordinal);
  582. // Remove from end if followed by a space
  583. if (sortable.EndsWith(" " + search, StringComparison.Ordinal))
  584. {
  585. sortable = sortable.Remove(sortable.Length - (search.Length + 1));
  586. }
  587. }
  588. return ModifySortChunks(sortable);
  589. }
  590. private string ModifySortChunks(string name)
  591. {
  592. var chunks = GetSortChunks(name);
  593. var builder = new StringBuilder();
  594. foreach (var chunk in chunks)
  595. {
  596. var chunkBuilder = chunk.Item1;
  597. // This chunk is numeric
  598. if (chunk.Item2)
  599. {
  600. while (chunkBuilder.Length < 10)
  601. {
  602. chunkBuilder.Insert(0, '0');
  603. }
  604. }
  605. builder.Append(chunkBuilder);
  606. }
  607. // logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
  608. return builder.ToString().RemoveDiacritics();
  609. }
  610. [JsonIgnore]
  611. public bool EnableMediaSourceDisplay
  612. {
  613. get
  614. {
  615. if (SourceType == SourceType.Channel)
  616. {
  617. return ChannelManager.EnableMediaSourceDisplay(this);
  618. }
  619. return true;
  620. }
  621. }
  622. [JsonIgnore]
  623. public Guid ParentId { get; set; }
  624. /// <summary>
  625. /// Gets or sets the parent.
  626. /// </summary>
  627. /// <value>The parent.</value>
  628. [JsonIgnore]
  629. public Folder Parent
  630. {
  631. get => GetParent() as Folder;
  632. set
  633. {
  634. }
  635. }
  636. public void SetParent(Folder parent)
  637. {
  638. ParentId = parent == null ? Guid.Empty : parent.Id;
  639. }
  640. public BaseItem GetParent()
  641. {
  642. var parentId = ParentId;
  643. if (!parentId.Equals(Guid.Empty))
  644. {
  645. return LibraryManager.GetItemById(parentId);
  646. }
  647. return null;
  648. }
  649. public IEnumerable<BaseItem> GetParents()
  650. {
  651. var parent = GetParent();
  652. while (parent != null)
  653. {
  654. yield return parent;
  655. parent = parent.GetParent();
  656. }
  657. }
  658. /// <summary>
  659. /// Finds a parent of a given type.
  660. /// </summary>
  661. /// <typeparam name="T"></typeparam>
  662. /// <returns>``0.</returns>
  663. public T FindParent<T>()
  664. where T : Folder
  665. {
  666. foreach (var parent in GetParents())
  667. {
  668. var item = parent as T;
  669. if (item != null)
  670. {
  671. return item;
  672. }
  673. }
  674. return null;
  675. }
  676. [JsonIgnore]
  677. public virtual Guid DisplayParentId
  678. {
  679. get
  680. {
  681. var parentId = ParentId;
  682. return parentId;
  683. }
  684. }
  685. [JsonIgnore]
  686. public BaseItem DisplayParent
  687. {
  688. get
  689. {
  690. var id = DisplayParentId;
  691. if (id.Equals(Guid.Empty))
  692. {
  693. return null;
  694. }
  695. return LibraryManager.GetItemById(id);
  696. }
  697. }
  698. /// <summary>
  699. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  700. /// </summary>
  701. /// <value>The premiere date.</value>
  702. [JsonIgnore]
  703. public DateTime? PremiereDate { get; set; }
  704. /// <summary>
  705. /// Gets or sets the end date.
  706. /// </summary>
  707. /// <value>The end date.</value>
  708. [JsonIgnore]
  709. public DateTime? EndDate { get; set; }
  710. /// <summary>
  711. /// Gets or sets the official rating.
  712. /// </summary>
  713. /// <value>The official rating.</value>
  714. [JsonIgnore]
  715. public string OfficialRating { get; set; }
  716. [JsonIgnore]
  717. public int InheritedParentalRatingValue { get; set; }
  718. /// <summary>
  719. /// Gets or sets the critic rating.
  720. /// </summary>
  721. /// <value>The critic rating.</value>
  722. [JsonIgnore]
  723. public float? CriticRating { get; set; }
  724. /// <summary>
  725. /// Gets or sets the custom rating.
  726. /// </summary>
  727. /// <value>The custom rating.</value>
  728. [JsonIgnore]
  729. public string CustomRating { get; set; }
  730. /// <summary>
  731. /// Gets or sets the overview.
  732. /// </summary>
  733. /// <value>The overview.</value>
  734. [JsonIgnore]
  735. public string Overview { get; set; }
  736. /// <summary>
  737. /// Gets or sets the studios.
  738. /// </summary>
  739. /// <value>The studios.</value>
  740. [JsonIgnore]
  741. public string[] Studios { get; set; }
  742. /// <summary>
  743. /// Gets or sets the genres.
  744. /// </summary>
  745. /// <value>The genres.</value>
  746. [JsonIgnore]
  747. public string[] Genres { get; set; }
  748. /// <summary>
  749. /// Gets or sets the tags.
  750. /// </summary>
  751. /// <value>The tags.</value>
  752. [JsonIgnore]
  753. public string[] Tags { get; set; }
  754. [JsonIgnore]
  755. public string[] ProductionLocations { get; set; }
  756. /// <summary>
  757. /// Gets or sets the home page URL.
  758. /// </summary>
  759. /// <value>The home page URL.</value>
  760. [JsonIgnore]
  761. public string HomePageUrl { get; set; }
  762. /// <summary>
  763. /// Gets or sets the community rating.
  764. /// </summary>
  765. /// <value>The community rating.</value>
  766. [JsonIgnore]
  767. public float? CommunityRating { get; set; }
  768. /// <summary>
  769. /// Gets or sets the run time ticks.
  770. /// </summary>
  771. /// <value>The run time ticks.</value>
  772. [JsonIgnore]
  773. public long? RunTimeTicks { get; set; }
  774. /// <summary>
  775. /// Gets or sets the production year.
  776. /// </summary>
  777. /// <value>The production year.</value>
  778. [JsonIgnore]
  779. public int? ProductionYear { get; set; }
  780. /// <summary>
  781. /// If the item is part of a series, this is it's number in the series.
  782. /// This could be episode number, album track number, etc.
  783. /// </summary>
  784. /// <value>The index number.</value>
  785. [JsonIgnore]
  786. public int? IndexNumber { get; set; }
  787. /// <summary>
  788. /// For an episode this could be the season number, or for a song this could be the disc number.
  789. /// </summary>
  790. /// <value>The parent index number.</value>
  791. [JsonIgnore]
  792. public int? ParentIndexNumber { get; set; }
  793. [JsonIgnore]
  794. public virtual bool HasLocalAlternateVersions => false;
  795. [JsonIgnore]
  796. public string OfficialRatingForComparison
  797. {
  798. get
  799. {
  800. var officialRating = OfficialRating;
  801. if (!string.IsNullOrEmpty(officialRating))
  802. {
  803. return officialRating;
  804. }
  805. var parent = DisplayParent;
  806. if (parent != null)
  807. {
  808. return parent.OfficialRatingForComparison;
  809. }
  810. return null;
  811. }
  812. }
  813. [JsonIgnore]
  814. public string CustomRatingForComparison
  815. {
  816. get
  817. {
  818. var customRating = CustomRating;
  819. if (!string.IsNullOrEmpty(customRating))
  820. {
  821. return customRating;
  822. }
  823. var parent = DisplayParent;
  824. if (parent != null)
  825. {
  826. return parent.CustomRatingForComparison;
  827. }
  828. return null;
  829. }
  830. }
  831. /// <summary>
  832. /// Gets the play access.
  833. /// </summary>
  834. /// <param name="user">The user.</param>
  835. /// <returns>PlayAccess.</returns>
  836. public PlayAccess GetPlayAccess(User user)
  837. {
  838. if (!user.HasPermission(PermissionKind.EnableMediaPlayback))
  839. {
  840. return PlayAccess.None;
  841. }
  842. // if (!user.IsParentalScheduleAllowed())
  843. //{
  844. // return PlayAccess.None;
  845. //}
  846. return PlayAccess.Full;
  847. }
  848. public virtual List<MediaStream> GetMediaStreams()
  849. {
  850. return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
  851. {
  852. ItemId = Id
  853. });
  854. }
  855. protected virtual bool IsActiveRecording()
  856. {
  857. return false;
  858. }
  859. public virtual List<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  860. {
  861. if (SourceType == SourceType.Channel)
  862. {
  863. var sources = ChannelManager.GetStaticMediaSources(this, CancellationToken.None)
  864. .ToList();
  865. if (sources.Count > 0)
  866. {
  867. return sources;
  868. }
  869. }
  870. var list = GetAllItemsForMediaSources();
  871. var result = list.Select(i => GetVersionInfo(enablePathSubstitution, i.Item1, i.Item2)).ToList();
  872. if (IsActiveRecording())
  873. {
  874. foreach (var mediaSource in result)
  875. {
  876. mediaSource.Type = MediaSourceType.Placeholder;
  877. }
  878. }
  879. return result.OrderBy(i =>
  880. {
  881. if (i.VideoType == VideoType.VideoFile)
  882. {
  883. return 0;
  884. }
  885. return 1;
  886. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  887. .ThenByDescending(i =>
  888. {
  889. var stream = i.VideoStream;
  890. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  891. })
  892. .ToList();
  893. }
  894. protected virtual List<Tuple<BaseItem, MediaSourceType>> GetAllItemsForMediaSources()
  895. {
  896. return new List<Tuple<BaseItem, MediaSourceType>>();
  897. }
  898. private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type)
  899. {
  900. if (item == null)
  901. {
  902. throw new ArgumentNullException(nameof(item));
  903. }
  904. var protocol = item.PathProtocol;
  905. var info = new MediaSourceInfo
  906. {
  907. Id = item.Id.ToString("N", CultureInfo.InvariantCulture),
  908. Protocol = protocol ?? MediaProtocol.File,
  909. MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
  910. MediaAttachments = MediaSourceManager.GetMediaAttachments(item.Id),
  911. Name = GetMediaSourceName(item),
  912. Path = enablePathSubstitution ? GetMappedPath(item, item.Path, protocol) : item.Path,
  913. RunTimeTicks = item.RunTimeTicks,
  914. Container = item.Container,
  915. Size = item.Size,
  916. Type = type
  917. };
  918. if (string.IsNullOrEmpty(info.Path))
  919. {
  920. info.Type = MediaSourceType.Placeholder;
  921. }
  922. if (info.Protocol == MediaProtocol.File)
  923. {
  924. info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  925. }
  926. var video = item as Video;
  927. if (video != null)
  928. {
  929. info.IsoType = video.IsoType;
  930. info.VideoType = video.VideoType;
  931. info.Video3DFormat = video.Video3DFormat;
  932. info.Timestamp = video.Timestamp;
  933. if (video.IsShortcut)
  934. {
  935. info.IsRemote = true;
  936. info.Path = video.ShortcutPath;
  937. info.Protocol = MediaSourceManager.GetPathProtocol(info.Path);
  938. }
  939. if (string.IsNullOrEmpty(info.Container))
  940. {
  941. if (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso)
  942. {
  943. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  944. {
  945. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  946. }
  947. }
  948. }
  949. }
  950. if (string.IsNullOrEmpty(info.Container))
  951. {
  952. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  953. {
  954. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  955. }
  956. }
  957. if (info.SupportsDirectStream && !string.IsNullOrEmpty(info.Path))
  958. {
  959. info.SupportsDirectStream = MediaSourceManager.SupportsDirectStream(info.Path, info.Protocol);
  960. }
  961. if (video != null && video.VideoType != VideoType.VideoFile)
  962. {
  963. info.SupportsDirectStream = false;
  964. }
  965. info.Bitrate = item.TotalBitrate;
  966. info.InferTotalBitrate();
  967. return info;
  968. }
  969. private string GetMediaSourceName(BaseItem item)
  970. {
  971. var terms = new List<string>();
  972. var path = item.Path;
  973. if (item.IsFileProtocol && !string.IsNullOrEmpty(path))
  974. {
  975. if (HasLocalAlternateVersions)
  976. {
  977. var displayName = System.IO.Path.GetFileNameWithoutExtension(path)
  978. .Replace(System.IO.Path.GetFileName(ContainingFolderPath), string.Empty, StringComparison.OrdinalIgnoreCase)
  979. .TrimStart(new char[] { ' ', '-' });
  980. if (!string.IsNullOrEmpty(displayName))
  981. {
  982. terms.Add(displayName);
  983. }
  984. }
  985. if (terms.Count == 0)
  986. {
  987. var displayName = System.IO.Path.GetFileNameWithoutExtension(path);
  988. terms.Add(displayName);
  989. }
  990. }
  991. if (terms.Count == 0)
  992. {
  993. terms.Add(item.Name);
  994. }
  995. var video = item as Video;
  996. if (video != null)
  997. {
  998. if (video.Video3DFormat.HasValue)
  999. {
  1000. terms.Add("3D");
  1001. }
  1002. if (video.VideoType == VideoType.BluRay)
  1003. {
  1004. terms.Add("Bluray");
  1005. }
  1006. else if (video.VideoType == VideoType.Dvd)
  1007. {
  1008. terms.Add("DVD");
  1009. }
  1010. else if (video.VideoType == VideoType.Iso)
  1011. {
  1012. if (video.IsoType.HasValue)
  1013. {
  1014. if (video.IsoType.Value == IsoType.BluRay)
  1015. {
  1016. terms.Add("Bluray");
  1017. }
  1018. else if (video.IsoType.Value == IsoType.Dvd)
  1019. {
  1020. terms.Add("DVD");
  1021. }
  1022. }
  1023. else
  1024. {
  1025. terms.Add("ISO");
  1026. }
  1027. }
  1028. }
  1029. return string.Join('/', terms.ToArray());
  1030. }
  1031. /// <summary>
  1032. /// Loads the theme songs.
  1033. /// </summary>
  1034. /// <returns>List{Audio.Audio}.</returns>
  1035. private static Audio.Audio[] LoadThemeSongs(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1036. {
  1037. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1038. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  1039. .SelectMany(i => FileSystem.GetFiles(i.FullName))
  1040. .ToList();
  1041. // Support plex/xbmc convention
  1042. files.AddRange(fileSystemChildren
  1043. .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase)));
  1044. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1045. .OfType<Audio.Audio>()
  1046. .Select(audio =>
  1047. {
  1048. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1049. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  1050. if (dbItem != null)
  1051. {
  1052. audio = dbItem;
  1053. }
  1054. else
  1055. {
  1056. // item is new
  1057. audio.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeSong;
  1058. }
  1059. return audio;
  1060. // Sort them so that the list can be easily compared for changes
  1061. }).OrderBy(i => i.Path).ToArray();
  1062. }
  1063. /// <summary>
  1064. /// Loads the video backdrops.
  1065. /// </summary>
  1066. /// <returns>List{Video}.</returns>
  1067. private static Video[] LoadThemeVideos(IEnumerable<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1068. {
  1069. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1070. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  1071. .SelectMany(i => FileSystem.GetFiles(i.FullName));
  1072. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1073. .OfType<Video>()
  1074. .Select(item =>
  1075. {
  1076. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1077. if (LibraryManager.GetItemById(item.Id) is Video dbItem)
  1078. {
  1079. item = dbItem;
  1080. }
  1081. else
  1082. {
  1083. // item is new
  1084. item.ExtraType = Model.Entities.ExtraType.ThemeVideo;
  1085. }
  1086. return item;
  1087. // Sort them so that the list can be easily compared for changes
  1088. }).OrderBy(i => i.Path).ToArray();
  1089. }
  1090. protected virtual BaseItem[] LoadExtras(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1091. {
  1092. var extras = new List<Video>();
  1093. var folders = fileSystemChildren.Where(i => i.IsDirectory).ToArray();
  1094. foreach (var extraFolderName in AllExtrasTypesFolderNames)
  1095. {
  1096. var files = folders
  1097. .Where(i => string.Equals(i.Name, extraFolderName, StringComparison.OrdinalIgnoreCase))
  1098. .SelectMany(i => FileSystem.GetFiles(i.FullName));
  1099. extras.AddRange(LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1100. .OfType<Video>()
  1101. .Select(item =>
  1102. {
  1103. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1104. if (LibraryManager.GetItemById(item.Id) is Video dbItem)
  1105. {
  1106. item = dbItem;
  1107. }
  1108. // Use some hackery to get the extra type based on foldername
  1109. item.ExtraType = Enum.TryParse(extraFolderName.Replace(" ", string.Empty), true, out ExtraType extraType)
  1110. ? extraType
  1111. : Model.Entities.ExtraType.Unknown;
  1112. return item;
  1113. // Sort them so that the list can be easily compared for changes
  1114. }).OrderBy(i => i.Path));
  1115. }
  1116. return extras.ToArray();
  1117. }
  1118. public Task RefreshMetadata(CancellationToken cancellationToken)
  1119. {
  1120. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
  1121. }
  1122. protected virtual void TriggerOnRefreshStart()
  1123. {
  1124. }
  1125. protected virtual void TriggerOnRefreshComplete()
  1126. {
  1127. }
  1128. /// <summary>
  1129. /// Overrides the base implementation to refresh metadata for local trailers.
  1130. /// </summary>
  1131. /// <param name="options">The options.</param>
  1132. /// <param name="cancellationToken">The cancellation token.</param>
  1133. /// <returns>true if a provider reports we changed.</returns>
  1134. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  1135. {
  1136. TriggerOnRefreshStart();
  1137. var requiresSave = false;
  1138. if (SupportsOwnedItems)
  1139. {
  1140. try
  1141. {
  1142. var files = IsFileProtocol ?
  1143. GetFileSystemChildren(options.DirectoryService).ToList() :
  1144. new List<FileSystemMetadata>();
  1145. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  1146. await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties in DB are fresh
  1147. if (ownedItemsChanged)
  1148. {
  1149. requiresSave = true;
  1150. }
  1151. }
  1152. catch (Exception ex)
  1153. {
  1154. Logger.LogError(ex, "Error refreshing owned items for {path}", Path ?? Name);
  1155. }
  1156. }
  1157. try
  1158. {
  1159. var refreshOptions = requiresSave
  1160. ? new MetadataRefreshOptions(options)
  1161. {
  1162. ForceSave = true
  1163. }
  1164. : options;
  1165. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  1166. }
  1167. finally
  1168. {
  1169. TriggerOnRefreshComplete();
  1170. }
  1171. }
  1172. [JsonIgnore]
  1173. protected virtual bool SupportsOwnedItems => !ParentId.Equals(Guid.Empty) && IsFileProtocol;
  1174. [JsonIgnore]
  1175. public virtual bool SupportsPeople => false;
  1176. [JsonIgnore]
  1177. public virtual bool SupportsThemeMedia => false;
  1178. /// <summary>
  1179. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  1180. /// Returns true or false indicating if changes were found.
  1181. /// </summary>
  1182. /// <param name="options"></param>
  1183. /// <param name="fileSystemChildren"></param>
  1184. /// <param name="cancellationToken"></param>
  1185. /// <returns></returns>
  1186. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1187. {
  1188. var themeSongsChanged = false;
  1189. var themeVideosChanged = false;
  1190. var extrasChanged = false;
  1191. var localTrailersChanged = false;
  1192. if (IsFileProtocol && SupportsOwnedItems)
  1193. {
  1194. if (SupportsThemeMedia)
  1195. {
  1196. if (!IsInMixedFolder)
  1197. {
  1198. themeSongsChanged = await RefreshThemeSongs(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1199. themeVideosChanged = await RefreshThemeVideos(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1200. extrasChanged = await RefreshExtras(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1201. }
  1202. }
  1203. var hasTrailers = this as IHasTrailers;
  1204. if (hasTrailers != null)
  1205. {
  1206. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1207. }
  1208. }
  1209. return themeSongsChanged || themeVideosChanged || extrasChanged || localTrailersChanged;
  1210. }
  1211. protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  1212. {
  1213. var path = ContainingFolderPath;
  1214. return directoryService.GetFileSystemEntries(path);
  1215. }
  1216. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1217. {
  1218. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService);
  1219. var newItemIds = newItems.Select(i => i.Id);
  1220. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  1221. var ownerId = item.Id;
  1222. var tasks = newItems.Select(i =>
  1223. {
  1224. var subOptions = new MetadataRefreshOptions(options);
  1225. if (i.ExtraType != Model.Entities.ExtraType.Trailer ||
  1226. i.OwnerId != ownerId ||
  1227. !i.ParentId.Equals(Guid.Empty))
  1228. {
  1229. i.ExtraType = Model.Entities.ExtraType.Trailer;
  1230. i.OwnerId = ownerId;
  1231. i.ParentId = Guid.Empty;
  1232. subOptions.ForceSave = true;
  1233. }
  1234. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1235. });
  1236. await Task.WhenAll(tasks).ConfigureAwait(false);
  1237. item.LocalTrailerIds = newItemIds.ToArray();
  1238. return itemsChanged;
  1239. }
  1240. private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1241. {
  1242. var extras = LoadExtras(fileSystemChildren, options.DirectoryService);
  1243. var themeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService);
  1244. var themeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService);
  1245. var newExtras = new BaseItem[extras.Length + themeVideos.Length + themeSongs.Length];
  1246. extras.CopyTo(newExtras, 0);
  1247. themeVideos.CopyTo(newExtras, extras.Length);
  1248. themeSongs.CopyTo(newExtras, extras.Length + themeVideos.Length);
  1249. var newExtraIds = newExtras.Select(i => i.Id).ToArray();
  1250. var extrasChanged = !item.ExtraIds.SequenceEqual(newExtraIds);
  1251. if (extrasChanged)
  1252. {
  1253. var ownerId = item.Id;
  1254. var tasks = newExtras.Select(i =>
  1255. {
  1256. var subOptions = new MetadataRefreshOptions(options);
  1257. if (i.OwnerId != ownerId || i.ParentId != Guid.Empty)
  1258. {
  1259. i.OwnerId = ownerId;
  1260. i.ParentId = Guid.Empty;
  1261. subOptions.ForceSave = true;
  1262. }
  1263. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1264. });
  1265. await Task.WhenAll(tasks).ConfigureAwait(false);
  1266. item.ExtraIds = newExtraIds;
  1267. }
  1268. return extrasChanged;
  1269. }
  1270. private async Task<bool> RefreshThemeVideos(BaseItem item, MetadataRefreshOptions options, IEnumerable<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1271. {
  1272. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService);
  1273. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToArray();
  1274. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  1275. var ownerId = item.Id;
  1276. var tasks = newThemeVideos.Select(i =>
  1277. {
  1278. var subOptions = new MetadataRefreshOptions(options);
  1279. if (!i.ExtraType.HasValue ||
  1280. i.ExtraType.Value != Model.Entities.ExtraType.ThemeVideo ||
  1281. i.OwnerId != ownerId ||
  1282. !i.ParentId.Equals(Guid.Empty))
  1283. {
  1284. i.ExtraType = Model.Entities.ExtraType.ThemeVideo;
  1285. i.OwnerId = ownerId;
  1286. i.ParentId = Guid.Empty;
  1287. subOptions.ForceSave = true;
  1288. }
  1289. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1290. });
  1291. await Task.WhenAll(tasks).ConfigureAwait(false);
  1292. // They are expected to be sorted by SortName
  1293. item.ThemeVideoIds = newThemeVideos.OrderBy(i => i.SortName).Select(i => i.Id).ToArray();
  1294. return themeVideosChanged;
  1295. }
  1296. /// <summary>
  1297. /// Refreshes the theme songs.
  1298. /// </summary>
  1299. private async Task<bool> RefreshThemeSongs(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1300. {
  1301. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService);
  1302. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToArray();
  1303. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  1304. var ownerId = item.Id;
  1305. var tasks = newThemeSongs.Select(i =>
  1306. {
  1307. var subOptions = new MetadataRefreshOptions(options);
  1308. if (!i.ExtraType.HasValue ||
  1309. i.ExtraType.Value != Model.Entities.ExtraType.ThemeSong ||
  1310. i.OwnerId != ownerId ||
  1311. !i.ParentId.Equals(Guid.Empty))
  1312. {
  1313. i.ExtraType = Model.Entities.ExtraType.ThemeSong;
  1314. i.OwnerId = ownerId;
  1315. i.ParentId = Guid.Empty;
  1316. subOptions.ForceSave = true;
  1317. }
  1318. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1319. });
  1320. await Task.WhenAll(tasks).ConfigureAwait(false);
  1321. // They are expected to be sorted by SortName
  1322. item.ThemeSongIds = newThemeSongs.OrderBy(i => i.SortName).Select(i => i.Id).ToArray();
  1323. return themeSongsChanged;
  1324. }
  1325. /// <summary>
  1326. /// Gets or sets the provider ids.
  1327. /// </summary>
  1328. /// <value>The provider ids.</value>
  1329. [JsonIgnore]
  1330. public Dictionary<string, string> ProviderIds { get; set; }
  1331. [JsonIgnore]
  1332. public virtual Folder LatestItemsIndexContainer => null;
  1333. public virtual double GetDefaultPrimaryImageAspectRatio()
  1334. {
  1335. return 0;
  1336. }
  1337. public virtual string CreatePresentationUniqueKey()
  1338. {
  1339. return Id.ToString("N", CultureInfo.InvariantCulture);
  1340. }
  1341. [JsonIgnore]
  1342. public string PresentationUniqueKey { get; set; }
  1343. public string GetPresentationUniqueKey()
  1344. {
  1345. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1346. }
  1347. public virtual bool RequiresRefresh()
  1348. {
  1349. return false;
  1350. }
  1351. public virtual List<string> GetUserDataKeys()
  1352. {
  1353. var list = new List<string>();
  1354. if (SourceType == SourceType.Channel)
  1355. {
  1356. if (!string.IsNullOrEmpty(ExternalId))
  1357. {
  1358. list.Add(ExternalId);
  1359. }
  1360. }
  1361. list.Add(Id.ToString());
  1362. return list;
  1363. }
  1364. internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
  1365. {
  1366. var updateType = ItemUpdateType.None;
  1367. if (IsInMixedFolder != newItem.IsInMixedFolder)
  1368. {
  1369. IsInMixedFolder = newItem.IsInMixedFolder;
  1370. updateType |= ItemUpdateType.MetadataImport;
  1371. }
  1372. return updateType;
  1373. }
  1374. public void AfterMetadataRefresh()
  1375. {
  1376. _sortName = null;
  1377. }
  1378. /// <summary>
  1379. /// Gets the preferred metadata language.
  1380. /// </summary>
  1381. /// <returns>System.String.</returns>
  1382. public string GetPreferredMetadataLanguage()
  1383. {
  1384. string lang = PreferredMetadataLanguage;
  1385. if (string.IsNullOrEmpty(lang))
  1386. {
  1387. lang = GetParents()
  1388. .Select(i => i.PreferredMetadataLanguage)
  1389. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1390. }
  1391. if (string.IsNullOrEmpty(lang))
  1392. {
  1393. lang = LibraryManager.GetCollectionFolders(this)
  1394. .Select(i => i.PreferredMetadataLanguage)
  1395. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1396. }
  1397. if (string.IsNullOrEmpty(lang))
  1398. {
  1399. lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
  1400. }
  1401. if (string.IsNullOrEmpty(lang))
  1402. {
  1403. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1404. }
  1405. return lang;
  1406. }
  1407. /// <summary>
  1408. /// Gets the preferred metadata language.
  1409. /// </summary>
  1410. /// <returns>System.String.</returns>
  1411. public string GetPreferredMetadataCountryCode()
  1412. {
  1413. string lang = PreferredMetadataCountryCode;
  1414. if (string.IsNullOrEmpty(lang))
  1415. {
  1416. lang = GetParents()
  1417. .Select(i => i.PreferredMetadataCountryCode)
  1418. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1419. }
  1420. if (string.IsNullOrEmpty(lang))
  1421. {
  1422. lang = LibraryManager.GetCollectionFolders(this)
  1423. .Select(i => i.PreferredMetadataCountryCode)
  1424. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1425. }
  1426. if (string.IsNullOrEmpty(lang))
  1427. {
  1428. lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
  1429. }
  1430. if (string.IsNullOrEmpty(lang))
  1431. {
  1432. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1433. }
  1434. return lang;
  1435. }
  1436. public virtual bool IsSaveLocalMetadataEnabled()
  1437. {
  1438. if (SourceType == SourceType.Channel)
  1439. {
  1440. return false;
  1441. }
  1442. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  1443. return libraryOptions.SaveLocalMetadata;
  1444. }
  1445. /// <summary>
  1446. /// Determines if a given user has access to this item.
  1447. /// </summary>
  1448. /// <param name="user">The user.</param>
  1449. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1450. /// <exception cref="ArgumentNullException">user</exception>
  1451. public bool IsParentalAllowed(User user)
  1452. {
  1453. if (user == null)
  1454. {
  1455. throw new ArgumentNullException(nameof(user));
  1456. }
  1457. if (!IsVisibleViaTags(user))
  1458. {
  1459. return false;
  1460. }
  1461. var maxAllowedRating = user.MaxParentalAgeRating;
  1462. if (maxAllowedRating == null)
  1463. {
  1464. return true;
  1465. }
  1466. var rating = CustomRatingForComparison;
  1467. if (string.IsNullOrEmpty(rating))
  1468. {
  1469. rating = OfficialRatingForComparison;
  1470. }
  1471. if (string.IsNullOrEmpty(rating))
  1472. {
  1473. return !GetBlockUnratedValue(user);
  1474. }
  1475. var value = LocalizationManager.GetRatingLevel(rating);
  1476. // Could not determine the integer value
  1477. if (!value.HasValue)
  1478. {
  1479. var isAllowed = !GetBlockUnratedValue(user);
  1480. if (!isAllowed)
  1481. {
  1482. Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1483. }
  1484. return isAllowed;
  1485. }
  1486. return value.Value <= maxAllowedRating.Value;
  1487. }
  1488. public int? GetParentalRatingValue()
  1489. {
  1490. var rating = CustomRating;
  1491. if (string.IsNullOrEmpty(rating))
  1492. {
  1493. rating = OfficialRating;
  1494. }
  1495. if (string.IsNullOrEmpty(rating))
  1496. {
  1497. return null;
  1498. }
  1499. return LocalizationManager.GetRatingLevel(rating);
  1500. }
  1501. public int? GetInheritedParentalRatingValue()
  1502. {
  1503. var rating = CustomRatingForComparison;
  1504. if (string.IsNullOrEmpty(rating))
  1505. {
  1506. rating = OfficialRatingForComparison;
  1507. }
  1508. if (string.IsNullOrEmpty(rating))
  1509. {
  1510. return null;
  1511. }
  1512. return LocalizationManager.GetRatingLevel(rating);
  1513. }
  1514. public List<string> GetInheritedTags()
  1515. {
  1516. var list = new List<string>();
  1517. list.AddRange(Tags);
  1518. foreach (var parent in GetParents())
  1519. {
  1520. list.AddRange(parent.Tags);
  1521. }
  1522. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1523. }
  1524. private bool IsVisibleViaTags(User user)
  1525. {
  1526. if (user.GetPreference(PreferenceKind.BlockedTags).Any(i => Tags.Contains(i, StringComparer.OrdinalIgnoreCase)))
  1527. {
  1528. return false;
  1529. }
  1530. return true;
  1531. }
  1532. protected virtual bool IsAllowTagFilterEnforced()
  1533. {
  1534. return true;
  1535. }
  1536. public virtual UnratedItem GetBlockUnratedType()
  1537. {
  1538. if (SourceType == SourceType.Channel)
  1539. {
  1540. return UnratedItem.ChannelContent;
  1541. }
  1542. return UnratedItem.Other;
  1543. }
  1544. /// <summary>
  1545. /// Gets the block unrated value.
  1546. /// </summary>
  1547. /// <param name="user">The configuration.</param>
  1548. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1549. protected virtual bool GetBlockUnratedValue(User user)
  1550. {
  1551. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1552. // Special folders like series and albums will override this method.
  1553. if (IsFolder || this is IItemByName)
  1554. {
  1555. return false;
  1556. }
  1557. return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType());
  1558. }
  1559. /// <summary>
  1560. /// Determines if this folder should be visible to a given user.
  1561. /// Default is just parental allowed. Can be overridden for more functionality.
  1562. /// </summary>
  1563. /// <param name="user">The user.</param>
  1564. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1565. /// <exception cref="ArgumentNullException">user</exception>
  1566. public virtual bool IsVisible(User user)
  1567. {
  1568. if (user == null)
  1569. {
  1570. throw new ArgumentNullException(nameof(user));
  1571. }
  1572. return IsParentalAllowed(user);
  1573. }
  1574. public virtual bool IsVisibleStandalone(User user)
  1575. {
  1576. if (SourceType == SourceType.Channel)
  1577. {
  1578. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1579. }
  1580. return IsVisibleStandaloneInternal(user, true);
  1581. }
  1582. [JsonIgnore]
  1583. public virtual bool SupportsInheritedParentImages => false;
  1584. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1585. {
  1586. if (!IsVisible(user))
  1587. {
  1588. return false;
  1589. }
  1590. if (GetParents().Any(i => !i.IsVisible(user)))
  1591. {
  1592. return false;
  1593. }
  1594. if (checkFolders)
  1595. {
  1596. var topParent = GetParents().LastOrDefault() ?? this;
  1597. if (string.IsNullOrEmpty(topParent.Path))
  1598. {
  1599. return true;
  1600. }
  1601. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
  1602. if (itemCollectionFolders.Count > 0)
  1603. {
  1604. var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i.Id).ToList();
  1605. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1606. {
  1607. return false;
  1608. }
  1609. }
  1610. }
  1611. return true;
  1612. }
  1613. /// <summary>
  1614. /// Gets a value indicating whether this instance is folder.
  1615. /// </summary>
  1616. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  1617. [JsonIgnore]
  1618. public virtual bool IsFolder => false;
  1619. [JsonIgnore]
  1620. public virtual bool IsDisplayedAsFolder => false;
  1621. public virtual string GetClientTypeName()
  1622. {
  1623. if (IsFolder && SourceType == SourceType.Channel && !(this is Channel))
  1624. {
  1625. return "ChannelFolderItem";
  1626. }
  1627. return GetType().Name;
  1628. }
  1629. public BaseItemKind GetBaseItemKind()
  1630. {
  1631. return Enum.Parse<BaseItemKind>(GetClientTypeName());
  1632. }
  1633. /// <summary>
  1634. /// Gets the linked child.
  1635. /// </summary>
  1636. /// <param name="info">The info.</param>
  1637. /// <returns>BaseItem.</returns>
  1638. protected BaseItem GetLinkedChild(LinkedChild info)
  1639. {
  1640. // First get using the cached Id
  1641. if (info.ItemId.HasValue)
  1642. {
  1643. if (info.ItemId.Value.Equals(Guid.Empty))
  1644. {
  1645. return null;
  1646. }
  1647. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1648. if (itemById != null)
  1649. {
  1650. return itemById;
  1651. }
  1652. }
  1653. var item = FindLinkedChild(info);
  1654. // If still null, log
  1655. if (item == null)
  1656. {
  1657. // Don't keep searching over and over
  1658. info.ItemId = Guid.Empty;
  1659. }
  1660. else
  1661. {
  1662. // Cache the id for next time
  1663. info.ItemId = item.Id;
  1664. }
  1665. return item;
  1666. }
  1667. private BaseItem FindLinkedChild(LinkedChild info)
  1668. {
  1669. var path = info.Path;
  1670. if (!string.IsNullOrEmpty(path))
  1671. {
  1672. path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
  1673. var itemByPath = LibraryManager.FindByPath(path, null);
  1674. if (itemByPath == null)
  1675. {
  1676. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1677. }
  1678. return itemByPath;
  1679. }
  1680. if (!string.IsNullOrEmpty(info.LibraryItemId))
  1681. {
  1682. var item = LibraryManager.GetItemById(info.LibraryItemId);
  1683. if (item == null)
  1684. {
  1685. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1686. }
  1687. return item;
  1688. }
  1689. return null;
  1690. }
  1691. [JsonIgnore]
  1692. public virtual bool EnableRememberingTrackSelections => true;
  1693. /// <summary>
  1694. /// Adds a studio to the item.
  1695. /// </summary>
  1696. /// <param name="name">The name.</param>
  1697. /// <exception cref="ArgumentNullException"></exception>
  1698. public void AddStudio(string name)
  1699. {
  1700. if (string.IsNullOrEmpty(name))
  1701. {
  1702. throw new ArgumentNullException(nameof(name));
  1703. }
  1704. var current = Studios;
  1705. if (!current.Contains(name, StringComparer.OrdinalIgnoreCase))
  1706. {
  1707. int curLen = current.Length;
  1708. if (curLen == 0)
  1709. {
  1710. Studios = new[] { name };
  1711. }
  1712. else
  1713. {
  1714. var newArr = new string[curLen + 1];
  1715. current.CopyTo(newArr, 0);
  1716. newArr[curLen] = name;
  1717. Studios = newArr;
  1718. }
  1719. }
  1720. }
  1721. public void SetStudios(IEnumerable<string> names)
  1722. {
  1723. Studios = names.Distinct().ToArray();
  1724. }
  1725. /// <summary>
  1726. /// Adds a genre to the item.
  1727. /// </summary>
  1728. /// <param name="name">The name.</param>
  1729. /// <exception cref="ArgumentNullException"></exception>
  1730. public void AddGenre(string name)
  1731. {
  1732. if (string.IsNullOrEmpty(name))
  1733. {
  1734. throw new ArgumentNullException(nameof(name));
  1735. }
  1736. var genres = Genres;
  1737. if (!genres.Contains(name, StringComparer.OrdinalIgnoreCase))
  1738. {
  1739. var list = genres.ToList();
  1740. list.Add(name);
  1741. Genres = list.ToArray();
  1742. }
  1743. }
  1744. /// <summary>
  1745. /// Marks the played.
  1746. /// </summary>
  1747. /// <param name="user">The user.</param>
  1748. /// <param name="datePlayed">The date played.</param>
  1749. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1750. /// <returns>Task.</returns>
  1751. /// <exception cref="ArgumentNullException"></exception>
  1752. public virtual void MarkPlayed(
  1753. User user,
  1754. DateTime? datePlayed,
  1755. bool resetPosition)
  1756. {
  1757. if (user == null)
  1758. {
  1759. throw new ArgumentNullException(nameof(user));
  1760. }
  1761. var data = UserDataManager.GetUserData(user, this);
  1762. if (datePlayed.HasValue)
  1763. {
  1764. // Increment
  1765. data.PlayCount++;
  1766. }
  1767. // Ensure it's at least one
  1768. data.PlayCount = Math.Max(data.PlayCount, 1);
  1769. if (resetPosition)
  1770. {
  1771. data.PlaybackPositionTicks = 0;
  1772. }
  1773. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1774. data.Played = true;
  1775. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1776. }
  1777. /// <summary>
  1778. /// Marks the unplayed.
  1779. /// </summary>
  1780. /// <param name="user">The user.</param>
  1781. /// <returns>Task.</returns>
  1782. /// <exception cref="ArgumentNullException"></exception>
  1783. public virtual void MarkUnplayed(User user)
  1784. {
  1785. if (user == null)
  1786. {
  1787. throw new ArgumentNullException(nameof(user));
  1788. }
  1789. var data = UserDataManager.GetUserData(user, this);
  1790. // I think it is okay to do this here.
  1791. // if this is only called when a user is manually forcing something to un-played
  1792. // then it probably is what we want to do...
  1793. data.PlayCount = 0;
  1794. data.PlaybackPositionTicks = 0;
  1795. data.LastPlayedDate = null;
  1796. data.Played = false;
  1797. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1798. }
  1799. /// <summary>
  1800. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1801. /// </summary>
  1802. public virtual void ChangedExternally()
  1803. {
  1804. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriority.High);
  1805. }
  1806. /// <summary>
  1807. /// Gets an image.
  1808. /// </summary>
  1809. /// <param name="type">The type.</param>
  1810. /// <param name="imageIndex">Index of the image.</param>
  1811. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1812. /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1813. public bool HasImage(ImageType type, int imageIndex)
  1814. {
  1815. return GetImageInfo(type, imageIndex) != null;
  1816. }
  1817. public void SetImage(ItemImageInfo image, int index)
  1818. {
  1819. if (image.Type == ImageType.Chapter)
  1820. {
  1821. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1822. }
  1823. var existingImage = GetImageInfo(image.Type, index);
  1824. if (existingImage != null)
  1825. {
  1826. existingImage.Path = image.Path;
  1827. existingImage.DateModified = image.DateModified;
  1828. existingImage.Width = image.Width;
  1829. existingImage.Height = image.Height;
  1830. existingImage.BlurHash = image.BlurHash;
  1831. }
  1832. else
  1833. {
  1834. var current = ImageInfos;
  1835. var currentCount = current.Length;
  1836. var newArr = new ItemImageInfo[currentCount + 1];
  1837. current.CopyTo(newArr, 0);
  1838. newArr[currentCount] = image;
  1839. ImageInfos = newArr;
  1840. }
  1841. }
  1842. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1843. {
  1844. if (type == ImageType.Chapter)
  1845. {
  1846. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1847. }
  1848. var image = GetImageInfo(type, index);
  1849. if (image == null)
  1850. {
  1851. ImageInfos = ImageInfos.Concat(new[] { GetImageInfo(file, type) }).ToArray();
  1852. }
  1853. else
  1854. {
  1855. var imageInfo = GetImageInfo(file, type);
  1856. image.Path = file.FullName;
  1857. image.DateModified = imageInfo.DateModified;
  1858. // reset these values
  1859. image.Width = 0;
  1860. image.Height = 0;
  1861. }
  1862. }
  1863. /// <summary>
  1864. /// Deletes the image.
  1865. /// </summary>
  1866. /// <param name="type">The type.</param>
  1867. /// <param name="index">The index.</param>
  1868. public async Task DeleteImageAsync(ImageType type, int index)
  1869. {
  1870. var info = GetImageInfo(type, index);
  1871. if (info == null)
  1872. {
  1873. // Nothing to do
  1874. return;
  1875. }
  1876. // Remove it from the item
  1877. RemoveImage(info);
  1878. if (info.IsLocalFile)
  1879. {
  1880. FileSystem.DeleteFile(info.Path);
  1881. }
  1882. await UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  1883. }
  1884. public void RemoveImage(ItemImageInfo image)
  1885. {
  1886. RemoveImages(new List<ItemImageInfo> { image });
  1887. }
  1888. public void RemoveImages(List<ItemImageInfo> deletedImages)
  1889. {
  1890. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1891. }
  1892. public virtual Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1893. => LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken);
  1894. /// <summary>
  1895. /// Validates that images within the item are still on the filesystem.
  1896. /// </summary>
  1897. public bool ValidateImages(IDirectoryService directoryService)
  1898. {
  1899. var allFiles = ImageInfos
  1900. .Where(i => i.IsLocalFile)
  1901. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1902. .Distinct(StringComparer.OrdinalIgnoreCase)
  1903. .SelectMany(directoryService.GetFilePaths)
  1904. .ToList();
  1905. var deletedImages = ImageInfos
  1906. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1907. .ToList();
  1908. if (deletedImages.Count > 0)
  1909. {
  1910. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1911. }
  1912. return deletedImages.Count > 0;
  1913. }
  1914. /// <summary>
  1915. /// Gets the image path.
  1916. /// </summary>
  1917. /// <param name="imageType">Type of the image.</param>
  1918. /// <param name="imageIndex">Index of the image.</param>
  1919. /// <returns>System.String.</returns>
  1920. /// <exception cref="InvalidOperationException">
  1921. /// </exception>
  1922. /// <exception cref="ArgumentNullException">item</exception>
  1923. public string GetImagePath(ImageType imageType, int imageIndex)
  1924. => GetImageInfo(imageType, imageIndex)?.Path;
  1925. /// <summary>
  1926. /// Gets the image information.
  1927. /// </summary>
  1928. /// <param name="imageType">Type of the image.</param>
  1929. /// <param name="imageIndex">Index of the image.</param>
  1930. /// <returns>ItemImageInfo.</returns>
  1931. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1932. {
  1933. if (imageType == ImageType.Chapter)
  1934. {
  1935. var chapter = ItemRepository.GetChapter(this, imageIndex);
  1936. if (chapter == null)
  1937. {
  1938. return null;
  1939. }
  1940. var path = chapter.ImagePath;
  1941. if (string.IsNullOrEmpty(path))
  1942. {
  1943. return null;
  1944. }
  1945. return new ItemImageInfo
  1946. {
  1947. Path = path,
  1948. DateModified = chapter.ImageDateModified,
  1949. Type = imageType
  1950. };
  1951. }
  1952. return GetImages(imageType)
  1953. .ElementAtOrDefault(imageIndex);
  1954. }
  1955. /// <summary>
  1956. /// Computes image index for given image or raises if no matching image found.
  1957. /// </summary>
  1958. /// <param name="image">Image to compute index for.</param>
  1959. /// <exception cref="ArgumentException">Image index cannot be computed as no matching image found.
  1960. /// </exception>
  1961. /// <returns>Image index.</returns>
  1962. public int GetImageIndex(ItemImageInfo image)
  1963. {
  1964. if (image == null)
  1965. {
  1966. throw new ArgumentNullException(nameof(image));
  1967. }
  1968. if (image.Type == ImageType.Chapter)
  1969. {
  1970. var chapters = ItemRepository.GetChapters(this);
  1971. for (var i = 0; i < chapters.Count; i++)
  1972. {
  1973. if (chapters[i].ImagePath == image.Path)
  1974. {
  1975. return i;
  1976. }
  1977. }
  1978. throw new ArgumentException("No chapter index found for image path", image.Path);
  1979. }
  1980. var images = GetImages(image.Type).ToArray();
  1981. for (var i = 0; i < images.Length; i++)
  1982. {
  1983. if (images[i].Path == image.Path)
  1984. {
  1985. return i;
  1986. }
  1987. }
  1988. throw new ArgumentException("No image index found for image path", image.Path);
  1989. }
  1990. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1991. {
  1992. if (imageType == ImageType.Chapter)
  1993. {
  1994. throw new ArgumentException("No image info for chapter images");
  1995. }
  1996. return ImageInfos.Where(i => i.Type == imageType);
  1997. }
  1998. /// <summary>
  1999. /// Adds the images.
  2000. /// </summary>
  2001. /// <param name="imageType">Type of the image.</param>
  2002. /// <param name="images">The images.</param>
  2003. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  2004. /// <exception cref="ArgumentException">Cannot call AddImages with chapter images</exception>
  2005. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  2006. {
  2007. if (imageType == ImageType.Chapter)
  2008. {
  2009. throw new ArgumentException("Cannot call AddImages with chapter images");
  2010. }
  2011. var existingImages = GetImages(imageType)
  2012. .ToList();
  2013. var newImageList = new List<FileSystemMetadata>();
  2014. var imageAdded = false;
  2015. var imageUpdated = false;
  2016. foreach (var newImage in images)
  2017. {
  2018. if (newImage == null)
  2019. {
  2020. throw new ArgumentException("null image found in list");
  2021. }
  2022. var existing = existingImages
  2023. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  2024. if (existing == null)
  2025. {
  2026. newImageList.Add(newImage);
  2027. imageAdded = true;
  2028. }
  2029. else
  2030. {
  2031. if (existing.IsLocalFile)
  2032. {
  2033. var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  2034. // If date changed then we need to reset saved image dimensions
  2035. if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
  2036. {
  2037. existing.Width = 0;
  2038. existing.Height = 0;
  2039. imageUpdated = true;
  2040. }
  2041. existing.DateModified = newDateModified;
  2042. }
  2043. }
  2044. }
  2045. if (imageAdded || images.Count != existingImages.Count)
  2046. {
  2047. var newImagePaths = images.Select(i => i.FullName).ToList();
  2048. var deleted = existingImages
  2049. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !File.Exists(i.Path))
  2050. .ToList();
  2051. if (deleted.Count > 0)
  2052. {
  2053. ImageInfos = ImageInfos.Except(deleted).ToArray();
  2054. }
  2055. }
  2056. if (newImageList.Count > 0)
  2057. {
  2058. ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
  2059. }
  2060. return imageUpdated || newImageList.Count > 0;
  2061. }
  2062. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  2063. {
  2064. return new ItemImageInfo
  2065. {
  2066. Path = file.FullName,
  2067. Type = type,
  2068. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  2069. };
  2070. }
  2071. /// <summary>
  2072. /// Gets the file system path to delete when the item is to be deleted.
  2073. /// </summary>
  2074. /// <returns></returns>
  2075. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  2076. {
  2077. return new[] {
  2078. new FileSystemMetadata
  2079. {
  2080. FullName = Path,
  2081. IsDirectory = IsFolder
  2082. }
  2083. }.Concat(GetLocalMetadataFilesToDelete());
  2084. }
  2085. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  2086. {
  2087. if (IsFolder || !IsInMixedFolder)
  2088. {
  2089. return new List<FileSystemMetadata>();
  2090. }
  2091. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  2092. return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
  2093. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  2094. .ToList();
  2095. }
  2096. public bool AllowsMultipleImages(ImageType type)
  2097. {
  2098. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  2099. }
  2100. public Task SwapImagesAsync(ImageType type, int index1, int index2)
  2101. {
  2102. if (!AllowsMultipleImages(type))
  2103. {
  2104. throw new ArgumentException("The change index operation is only applicable to backdrops and screen shots");
  2105. }
  2106. var info1 = GetImageInfo(type, index1);
  2107. var info2 = GetImageInfo(type, index2);
  2108. if (info1 == null || info2 == null)
  2109. {
  2110. // Nothing to do
  2111. return Task.CompletedTask;
  2112. }
  2113. if (!info1.IsLocalFile || !info2.IsLocalFile)
  2114. {
  2115. // TODO: Not supported yet
  2116. return Task.CompletedTask;
  2117. }
  2118. var path1 = info1.Path;
  2119. var path2 = info2.Path;
  2120. FileSystem.SwapFiles(path1, path2);
  2121. // Refresh these values
  2122. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  2123. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  2124. info1.Width = 0;
  2125. info1.Height = 0;
  2126. info2.Width = 0;
  2127. info2.Height = 0;
  2128. return UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None);
  2129. }
  2130. public virtual bool IsPlayed(User user)
  2131. {
  2132. var userdata = UserDataManager.GetUserData(user, this);
  2133. return userdata != null && userdata.Played;
  2134. }
  2135. public bool IsFavoriteOrLiked(User user)
  2136. {
  2137. var userdata = UserDataManager.GetUserData(user, this);
  2138. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  2139. }
  2140. public virtual bool IsUnplayed(User user)
  2141. {
  2142. if (user == null)
  2143. {
  2144. throw new ArgumentNullException(nameof(user));
  2145. }
  2146. var userdata = UserDataManager.GetUserData(user, this);
  2147. return userdata == null || !userdata.Played;
  2148. }
  2149. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  2150. {
  2151. return GetItemLookupInfo<ItemLookupInfo>();
  2152. }
  2153. protected T GetItemLookupInfo<T>()
  2154. where T : ItemLookupInfo, new()
  2155. {
  2156. return new T
  2157. {
  2158. Path = Path,
  2159. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  2160. MetadataLanguage = GetPreferredMetadataLanguage(),
  2161. Name = GetNameForMetadataLookup(),
  2162. ProviderIds = ProviderIds,
  2163. IndexNumber = IndexNumber,
  2164. ParentIndexNumber = ParentIndexNumber,
  2165. Year = ProductionYear,
  2166. PremiereDate = PremiereDate
  2167. };
  2168. }
  2169. protected virtual string GetNameForMetadataLookup()
  2170. {
  2171. return Name;
  2172. }
  2173. /// <summary>
  2174. /// This is called before any metadata refresh and returns true if changes were made.
  2175. /// </summary>
  2176. public virtual bool BeforeMetadataRefresh(bool replaceAllMetdata)
  2177. {
  2178. _sortName = null;
  2179. var hasChanges = false;
  2180. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  2181. {
  2182. Name = System.IO.Path.GetFileNameWithoutExtension(Path);
  2183. hasChanges = true;
  2184. }
  2185. return hasChanges;
  2186. }
  2187. protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
  2188. {
  2189. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  2190. {
  2191. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  2192. }
  2193. return path;
  2194. }
  2195. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  2196. {
  2197. if (RunTimeTicks.HasValue)
  2198. {
  2199. double pct = RunTimeTicks.Value;
  2200. if (pct > 0)
  2201. {
  2202. pct = userData.PlaybackPositionTicks / pct;
  2203. if (pct > 0)
  2204. {
  2205. dto.PlayedPercentage = 100 * pct;
  2206. }
  2207. }
  2208. }
  2209. }
  2210. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  2211. {
  2212. var newOptions = new MetadataRefreshOptions(options);
  2213. newOptions.SearchResult = null;
  2214. var item = this;
  2215. if (copyTitleMetadata)
  2216. {
  2217. // Take some data from the main item, for querying purposes
  2218. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  2219. {
  2220. newOptions.ForceSave = true;
  2221. ownedItem.Genres = item.Genres;
  2222. }
  2223. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  2224. {
  2225. newOptions.ForceSave = true;
  2226. ownedItem.Studios = item.Studios;
  2227. }
  2228. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  2229. {
  2230. newOptions.ForceSave = true;
  2231. ownedItem.ProductionLocations = item.ProductionLocations;
  2232. }
  2233. if (item.CommunityRating != ownedItem.CommunityRating)
  2234. {
  2235. ownedItem.CommunityRating = item.CommunityRating;
  2236. newOptions.ForceSave = true;
  2237. }
  2238. if (item.CriticRating != ownedItem.CriticRating)
  2239. {
  2240. ownedItem.CriticRating = item.CriticRating;
  2241. newOptions.ForceSave = true;
  2242. }
  2243. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  2244. {
  2245. ownedItem.Overview = item.Overview;
  2246. newOptions.ForceSave = true;
  2247. }
  2248. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  2249. {
  2250. ownedItem.OfficialRating = item.OfficialRating;
  2251. newOptions.ForceSave = true;
  2252. }
  2253. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  2254. {
  2255. ownedItem.CustomRating = item.CustomRating;
  2256. newOptions.ForceSave = true;
  2257. }
  2258. }
  2259. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  2260. }
  2261. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2262. {
  2263. var newOptions = new MetadataRefreshOptions(options);
  2264. newOptions.SearchResult = null;
  2265. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2266. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2267. var video = LibraryManager.GetItemById(id) as Video;
  2268. if (video == null)
  2269. {
  2270. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2271. newOptions.ForceSave = true;
  2272. }
  2273. // var parentId = Id;
  2274. // if (!video.IsOwnedItem || video.ParentId != parentId)
  2275. //{
  2276. // video.IsOwnedItem = true;
  2277. // video.ParentId = parentId;
  2278. // newOptions.ForceSave = true;
  2279. //}
  2280. if (video == null)
  2281. {
  2282. return Task.FromResult(true);
  2283. }
  2284. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  2285. }
  2286. public string GetEtag(User user)
  2287. {
  2288. var list = GetEtagValues(user);
  2289. return string.Join('|', list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  2290. }
  2291. protected virtual List<string> GetEtagValues(User user)
  2292. {
  2293. return new List<string>
  2294. {
  2295. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2296. };
  2297. }
  2298. public virtual IEnumerable<Guid> GetAncestorIds()
  2299. {
  2300. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2301. }
  2302. public BaseItem GetTopParent()
  2303. {
  2304. if (IsTopParent)
  2305. {
  2306. return this;
  2307. }
  2308. return GetParents().FirstOrDefault(parent => parent.IsTopParent);
  2309. }
  2310. [JsonIgnore]
  2311. public virtual bool IsTopParent
  2312. {
  2313. get
  2314. {
  2315. if (this is BasePluginFolder || this is Channel)
  2316. {
  2317. return true;
  2318. }
  2319. if (this is IHasCollectionType view)
  2320. {
  2321. if (string.Equals(view.CollectionType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  2322. {
  2323. return true;
  2324. }
  2325. }
  2326. if (GetParent() is AggregateFolder)
  2327. {
  2328. return true;
  2329. }
  2330. return false;
  2331. }
  2332. }
  2333. [JsonIgnore]
  2334. public virtual bool SupportsAncestors => true;
  2335. [JsonIgnore]
  2336. public virtual bool StopRefreshIfLocalMetadataFound => true;
  2337. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2338. {
  2339. return new[] { Id };
  2340. }
  2341. public virtual List<ExternalUrl> GetRelatedUrls()
  2342. {
  2343. return new List<ExternalUrl>();
  2344. }
  2345. public virtual double? GetRefreshProgress()
  2346. {
  2347. return null;
  2348. }
  2349. public virtual ItemUpdateType OnMetadataChanged()
  2350. {
  2351. var updateType = ItemUpdateType.None;
  2352. var item = this;
  2353. var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? 0;
  2354. if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
  2355. {
  2356. item.InheritedParentalRatingValue = inheritedParentalRatingValue;
  2357. updateType |= ItemUpdateType.MetadataImport;
  2358. }
  2359. return updateType;
  2360. }
  2361. /// <summary>
  2362. /// Updates the official rating based on content and returns true or false indicating if it changed.
  2363. /// </summary>
  2364. /// <returns></returns>
  2365. public bool UpdateRatingToItems(IList<BaseItem> children)
  2366. {
  2367. var currentOfficialRating = OfficialRating;
  2368. // Gather all possible ratings
  2369. var ratings = children
  2370. .Select(i => i.OfficialRating)
  2371. .Where(i => !string.IsNullOrEmpty(i))
  2372. .Distinct(StringComparer.OrdinalIgnoreCase)
  2373. .Select(i => new Tuple<string, int?>(i, LocalizationManager.GetRatingLevel(i)))
  2374. .OrderBy(i => i.Item2 ?? 1000)
  2375. .Select(i => i.Item1);
  2376. OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
  2377. return !string.Equals(currentOfficialRating ?? string.Empty, OfficialRating ?? string.Empty,
  2378. StringComparison.OrdinalIgnoreCase);
  2379. }
  2380. public IEnumerable<BaseItem> GetThemeSongs()
  2381. {
  2382. return ThemeSongIds.Select(LibraryManager.GetItemById);
  2383. }
  2384. public IEnumerable<BaseItem> GetThemeVideos()
  2385. {
  2386. return ThemeVideoIds.Select(LibraryManager.GetItemById);
  2387. }
  2388. /// <summary>
  2389. /// Gets or sets the remote trailers.
  2390. /// </summary>
  2391. /// <value>The remote trailers.</value>
  2392. public IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
  2393. /// <summary>
  2394. /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
  2395. /// </summary>
  2396. /// <returns>An enumerable containing the items.</returns>
  2397. public IEnumerable<BaseItem> GetExtras()
  2398. {
  2399. return ExtraIds
  2400. .Select(LibraryManager.GetItemById)
  2401. .Where(i => i != null)
  2402. .OrderBy(i => i.SortName);
  2403. }
  2404. /// <summary>
  2405. /// Get all extras with specific types that are associated with this item.
  2406. /// </summary>
  2407. /// <param name="extraTypes">The types of extras to retrieve.</param>
  2408. /// <returns>An enumerable containing the extras.</returns>
  2409. public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes)
  2410. {
  2411. return ExtraIds
  2412. .Select(LibraryManager.GetItemById)
  2413. .Where(i => i != null)
  2414. .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value));
  2415. }
  2416. public IEnumerable<BaseItem> GetTrailers()
  2417. {
  2418. if (this is IHasTrailers)
  2419. {
  2420. return ((IHasTrailers)this).LocalTrailerIds.Select(LibraryManager.GetItemById).Where(i => i != null).OrderBy(i => i.SortName);
  2421. }
  2422. else
  2423. {
  2424. return Array.Empty<BaseItem>();
  2425. }
  2426. }
  2427. public virtual bool IsHD => Height >= 720;
  2428. public bool IsShortcut { get; set; }
  2429. public string ShortcutPath { get; set; }
  2430. public int Width { get; set; }
  2431. public int Height { get; set; }
  2432. public Guid[] ExtraIds { get; set; }
  2433. public virtual long GetRunTimeTicksForPlayState()
  2434. {
  2435. return RunTimeTicks ?? 0;
  2436. }
  2437. /// <summary>
  2438. /// Extra types that should be counted and displayed as "Special Features" in the UI.
  2439. /// </summary>
  2440. public static readonly IReadOnlyCollection<ExtraType> DisplayExtraTypes = new HashSet<ExtraType>
  2441. {
  2442. Model.Entities.ExtraType.Unknown,
  2443. Model.Entities.ExtraType.BehindTheScenes,
  2444. Model.Entities.ExtraType.Clip,
  2445. Model.Entities.ExtraType.DeletedScene,
  2446. Model.Entities.ExtraType.Interview,
  2447. Model.Entities.ExtraType.Sample,
  2448. Model.Entities.ExtraType.Scene
  2449. };
  2450. public virtual bool SupportsExternalTransfer => false;
  2451. /// <inheritdoc />
  2452. public override bool Equals(object obj)
  2453. {
  2454. return obj is BaseItem baseItem && this.Equals(baseItem);
  2455. }
  2456. /// <inheritdoc />
  2457. public bool Equals(BaseItem item) => Object.Equals(Id, item?.Id);
  2458. /// <inheritdoc />
  2459. public override int GetHashCode() => HashCode.Combine(Id);
  2460. }
  2461. }