BaseItem.cs 96 KB

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