BaseItem.cs 85 KB

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