BaseItem.cs 96 KB

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