BaseItem.cs 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648
  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.Persistence;
  27. using MediaBrowser.Controller.Providers;
  28. using MediaBrowser.Model.Dto;
  29. using MediaBrowser.Model.Entities;
  30. using MediaBrowser.Model.Globalization;
  31. using MediaBrowser.Model.IO;
  32. using MediaBrowser.Model.Library;
  33. using MediaBrowser.Model.LiveTv;
  34. using MediaBrowser.Model.MediaInfo;
  35. using MediaBrowser.Model.Providers;
  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. = new[] { ".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 new[] { 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 IChapterRepository ChapterRepository { 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. var customRating = CustomRating;
  582. if (!string.IsNullOrEmpty(customRating))
  583. {
  584. return customRating;
  585. }
  586. var parent = DisplayParent;
  587. if (parent is not null)
  588. {
  589. return parent.CustomRatingForComparison;
  590. }
  591. return null;
  592. }
  593. }
  594. /// <summary>
  595. /// Gets or sets the provider ids.
  596. /// </summary>
  597. /// <value>The provider ids.</value>
  598. [JsonIgnore]
  599. public Dictionary<string, string> ProviderIds { get; set; }
  600. [JsonIgnore]
  601. public virtual Folder LatestItemsIndexContainer => null;
  602. [JsonIgnore]
  603. public string PresentationUniqueKey { get; set; }
  604. [JsonIgnore]
  605. public virtual bool EnableRememberingTrackSelections => true;
  606. [JsonIgnore]
  607. public virtual bool IsTopParent
  608. {
  609. get
  610. {
  611. if (this is BasePluginFolder || this is Channel)
  612. {
  613. return true;
  614. }
  615. if (this is IHasCollectionType view)
  616. {
  617. if (view.CollectionType == CollectionType.livetv)
  618. {
  619. return true;
  620. }
  621. }
  622. if (GetParent() is AggregateFolder)
  623. {
  624. return true;
  625. }
  626. return false;
  627. }
  628. }
  629. [JsonIgnore]
  630. public virtual bool SupportsAncestors => true;
  631. [JsonIgnore]
  632. protected virtual bool SupportsOwnedItems => !ParentId.IsEmpty() && IsFileProtocol;
  633. [JsonIgnore]
  634. public virtual bool SupportsPeople => false;
  635. [JsonIgnore]
  636. public virtual bool SupportsThemeMedia => false;
  637. [JsonIgnore]
  638. public virtual bool SupportsInheritedParentImages => false;
  639. /// <summary>
  640. /// Gets a value indicating whether this instance is folder.
  641. /// </summary>
  642. /// <value><c>true</c> if this instance is folder; otherwise, <c>false</c>.</value>
  643. [JsonIgnore]
  644. public virtual bool IsFolder => false;
  645. [JsonIgnore]
  646. public virtual bool IsDisplayedAsFolder => false;
  647. /// <summary>
  648. /// Gets or sets the remote trailers.
  649. /// </summary>
  650. /// <value>The remote trailers.</value>
  651. public IReadOnlyList<MediaUrl> RemoteTrailers { get; set; }
  652. public virtual double GetDefaultPrimaryImageAspectRatio()
  653. {
  654. return 0;
  655. }
  656. public virtual string CreatePresentationUniqueKey()
  657. {
  658. return Id.ToString("N", CultureInfo.InvariantCulture);
  659. }
  660. public virtual bool CanDelete()
  661. {
  662. if (SourceType == SourceType.Channel)
  663. {
  664. return ChannelManager.CanDelete(this);
  665. }
  666. return IsFileProtocol;
  667. }
  668. public virtual bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
  669. {
  670. if (user.HasPermission(PermissionKind.EnableContentDeletion))
  671. {
  672. return true;
  673. }
  674. var allowed = user.GetPreferenceValues<Guid>(PreferenceKind.EnableContentDeletionFromFolders);
  675. if (SourceType == SourceType.Channel)
  676. {
  677. return allowed.Contains(ChannelId);
  678. }
  679. var collectionFolders = LibraryManager.GetCollectionFolders(this, allCollectionFolders);
  680. foreach (var folder in collectionFolders)
  681. {
  682. if (allowed.Contains(folder.Id))
  683. {
  684. return true;
  685. }
  686. }
  687. return false;
  688. }
  689. public BaseItem GetOwner()
  690. {
  691. var ownerId = OwnerId;
  692. return ownerId.IsEmpty() ? null : LibraryManager.GetItemById(ownerId);
  693. }
  694. public bool CanDelete(User user, List<Folder> allCollectionFolders)
  695. {
  696. return CanDelete() && IsAuthorizedToDelete(user, allCollectionFolders);
  697. }
  698. public virtual bool CanDelete(User user)
  699. {
  700. var allCollectionFolders = LibraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
  701. return CanDelete(user, allCollectionFolders);
  702. }
  703. public virtual bool CanDownload()
  704. {
  705. return false;
  706. }
  707. public virtual bool IsAuthorizedToDownload(User user)
  708. {
  709. return user.HasPermission(PermissionKind.EnableContentDownloading);
  710. }
  711. public bool CanDownload(User user)
  712. {
  713. return CanDownload() && IsAuthorizedToDownload(user);
  714. }
  715. /// <inheritdoc />
  716. public override string ToString()
  717. {
  718. return Name;
  719. }
  720. public virtual string GetInternalMetadataPath()
  721. {
  722. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  723. return GetInternalMetadataPath(basePath);
  724. }
  725. protected virtual string GetInternalMetadataPath(string basePath)
  726. {
  727. if (SourceType == SourceType.Channel)
  728. {
  729. return System.IO.Path.Join(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), Id.ToString("N", CultureInfo.InvariantCulture));
  730. }
  731. ReadOnlySpan<char> idString = Id.ToString("N", CultureInfo.InvariantCulture);
  732. return System.IO.Path.Join(basePath, "library", idString[..2], idString);
  733. }
  734. /// <summary>
  735. /// Creates the name of the sort.
  736. /// </summary>
  737. /// <returns>System.String.</returns>
  738. protected virtual string CreateSortName()
  739. {
  740. if (Name is null)
  741. {
  742. return null; // some items may not have name filled in properly
  743. }
  744. if (!EnableAlphaNumericSorting)
  745. {
  746. return Name.TrimStart();
  747. }
  748. var sortable = Name.Trim().ToLowerInvariant();
  749. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  750. {
  751. // Remove from beginning if a space follows
  752. if (sortable.StartsWith(search + " ", StringComparison.Ordinal))
  753. {
  754. sortable = sortable.Remove(0, search.Length + 1);
  755. }
  756. // Remove from middle if surrounded by spaces
  757. sortable = sortable.Replace(" " + search + " ", " ", StringComparison.Ordinal);
  758. // Remove from end if preceeded by a space
  759. if (sortable.EndsWith(" " + search, StringComparison.Ordinal))
  760. {
  761. sortable = sortable.Remove(sortable.Length - (search.Length + 1));
  762. }
  763. }
  764. foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
  765. {
  766. sortable = sortable.Replace(removeChar, string.Empty, StringComparison.Ordinal);
  767. }
  768. foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
  769. {
  770. sortable = sortable.Replace(replaceChar, " ", StringComparison.Ordinal);
  771. }
  772. return ModifySortChunks(sortable);
  773. }
  774. internal static string ModifySortChunks(ReadOnlySpan<char> name)
  775. {
  776. static void AppendChunk(StringBuilder builder, bool isDigitChunk, ReadOnlySpan<char> chunk)
  777. {
  778. if (isDigitChunk && chunk.Length < 10)
  779. {
  780. builder.Append('0', 10 - chunk.Length);
  781. }
  782. builder.Append(chunk);
  783. }
  784. if (name.IsEmpty)
  785. {
  786. return string.Empty;
  787. }
  788. var builder = new StringBuilder(name.Length);
  789. int chunkStart = 0;
  790. bool isDigitChunk = char.IsDigit(name[0]);
  791. for (int i = 0; i < name.Length; i++)
  792. {
  793. var isDigit = char.IsDigit(name[i]);
  794. if (isDigit != isDigitChunk)
  795. {
  796. AppendChunk(builder, isDigitChunk, name.Slice(chunkStart, i - chunkStart));
  797. chunkStart = i;
  798. isDigitChunk = isDigit;
  799. }
  800. }
  801. AppendChunk(builder, isDigitChunk, name.Slice(chunkStart));
  802. // logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
  803. var result = builder.ToString().RemoveDiacritics();
  804. if (!result.All(char.IsAscii))
  805. {
  806. result = result.Transliterated();
  807. }
  808. return result;
  809. }
  810. public BaseItem GetParent()
  811. {
  812. var parentId = ParentId;
  813. if (parentId.IsEmpty())
  814. {
  815. return null;
  816. }
  817. return LibraryManager.GetItemById(parentId);
  818. }
  819. public IEnumerable<BaseItem> GetParents()
  820. {
  821. var parent = GetParent();
  822. while (parent is not null)
  823. {
  824. yield return parent;
  825. parent = parent.GetParent();
  826. }
  827. }
  828. /// <summary>
  829. /// Finds a parent of a given type.
  830. /// </summary>
  831. /// <typeparam name="T">Type of parent.</typeparam>
  832. /// <returns>``0.</returns>
  833. public T FindParent<T>()
  834. where T : Folder
  835. {
  836. foreach (var parent in GetParents())
  837. {
  838. if (parent is T item)
  839. {
  840. return item;
  841. }
  842. }
  843. return null;
  844. }
  845. /// <summary>
  846. /// Gets the play access.
  847. /// </summary>
  848. /// <param name="user">The user.</param>
  849. /// <returns>PlayAccess.</returns>
  850. public PlayAccess GetPlayAccess(User user)
  851. {
  852. if (!user.HasPermission(PermissionKind.EnableMediaPlayback))
  853. {
  854. return PlayAccess.None;
  855. }
  856. // if (!user.IsParentalScheduleAllowed())
  857. // {
  858. // return PlayAccess.None;
  859. // }
  860. return PlayAccess.Full;
  861. }
  862. public virtual IReadOnlyList<MediaStream> GetMediaStreams()
  863. {
  864. return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
  865. {
  866. ItemId = Id
  867. });
  868. }
  869. protected virtual bool IsActiveRecording()
  870. {
  871. return false;
  872. }
  873. public virtual IReadOnlyList<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  874. {
  875. if (SourceType == SourceType.Channel)
  876. {
  877. var sources = ChannelManager.GetStaticMediaSources(this, CancellationToken.None)
  878. .ToList();
  879. if (sources.Count > 0)
  880. {
  881. return sources;
  882. }
  883. }
  884. var list = GetAllItemsForMediaSources();
  885. var result = list.Select(i => GetVersionInfo(enablePathSubstitution, i.Item, i.MediaSourceType)).ToList();
  886. if (IsActiveRecording())
  887. {
  888. foreach (var mediaSource in result)
  889. {
  890. mediaSource.Type = MediaSourceType.Placeholder;
  891. }
  892. }
  893. return result.OrderBy(i =>
  894. {
  895. if (i.VideoType == VideoType.VideoFile)
  896. {
  897. return 0;
  898. }
  899. return 1;
  900. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  901. .ThenByDescending(i => i, new MediaSourceWidthComparator())
  902. .ToArray();
  903. }
  904. protected virtual IEnumerable<(BaseItem Item, MediaSourceType MediaSourceType)> GetAllItemsForMediaSources()
  905. {
  906. return Enumerable.Empty<(BaseItem, MediaSourceType)>();
  907. }
  908. private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type)
  909. {
  910. ArgumentNullException.ThrowIfNull(item);
  911. var protocol = item.PathProtocol;
  912. var info = new MediaSourceInfo
  913. {
  914. Id = item.Id.ToString("N", CultureInfo.InvariantCulture),
  915. Protocol = protocol ?? MediaProtocol.File,
  916. MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
  917. MediaAttachments = MediaSourceManager.GetMediaAttachments(item.Id),
  918. Name = GetMediaSourceName(item),
  919. Path = enablePathSubstitution ? GetMappedPath(item, item.Path, protocol) : item.Path,
  920. RunTimeTicks = item.RunTimeTicks,
  921. Container = item.Container,
  922. Size = item.Size,
  923. Type = type,
  924. HasSegments = MediaSegmentManager.IsTypeSupported(item)
  925. && (protocol is null or MediaProtocol.File)
  926. && MediaSegmentManager.HasSegments(item.Id)
  927. };
  928. if (string.IsNullOrEmpty(info.Path))
  929. {
  930. info.Type = MediaSourceType.Placeholder;
  931. }
  932. if (info.Protocol == MediaProtocol.File)
  933. {
  934. info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  935. }
  936. var video = item as Video;
  937. if (video is not null)
  938. {
  939. info.IsoType = video.IsoType;
  940. info.VideoType = video.VideoType;
  941. info.Video3DFormat = video.Video3DFormat;
  942. info.Timestamp = video.Timestamp;
  943. if (video.IsShortcut)
  944. {
  945. info.IsRemote = true;
  946. info.Path = video.ShortcutPath;
  947. info.Protocol = MediaSourceManager.GetPathProtocol(info.Path);
  948. }
  949. if (string.IsNullOrEmpty(info.Container))
  950. {
  951. if (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso)
  952. {
  953. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  954. {
  955. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  956. }
  957. }
  958. }
  959. }
  960. if (string.IsNullOrEmpty(info.Container))
  961. {
  962. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  963. {
  964. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  965. }
  966. }
  967. if (info.SupportsDirectStream && !string.IsNullOrEmpty(info.Path))
  968. {
  969. info.SupportsDirectStream = MediaSourceManager.SupportsDirectStream(info.Path, info.Protocol);
  970. }
  971. if (video is not null && video.VideoType != VideoType.VideoFile)
  972. {
  973. info.SupportsDirectStream = false;
  974. }
  975. info.Bitrate = item.TotalBitrate;
  976. info.InferTotalBitrate();
  977. return info;
  978. }
  979. internal string GetMediaSourceName(BaseItem item)
  980. {
  981. var terms = new List<string>();
  982. var path = item.Path;
  983. if (item.IsFileProtocol && !string.IsNullOrEmpty(path))
  984. {
  985. var displayName = System.IO.Path.GetFileNameWithoutExtension(path);
  986. if (HasLocalAlternateVersions)
  987. {
  988. var containingFolderName = System.IO.Path.GetFileName(ContainingFolderPath);
  989. if (displayName.Length > containingFolderName.Length && displayName.StartsWith(containingFolderName, StringComparison.OrdinalIgnoreCase))
  990. {
  991. var name = displayName.AsSpan(containingFolderName.Length).TrimStart([' ', '-']);
  992. if (!name.IsWhiteSpace())
  993. {
  994. terms.Add(name.ToString());
  995. }
  996. }
  997. }
  998. if (terms.Count == 0)
  999. {
  1000. terms.Add(displayName);
  1001. }
  1002. }
  1003. if (terms.Count == 0)
  1004. {
  1005. terms.Add(item.Name);
  1006. }
  1007. if (item is Video video)
  1008. {
  1009. if (video.Video3DFormat.HasValue)
  1010. {
  1011. terms.Add("3D");
  1012. }
  1013. if (video.VideoType == VideoType.BluRay)
  1014. {
  1015. terms.Add("Bluray");
  1016. }
  1017. else if (video.VideoType == VideoType.Dvd)
  1018. {
  1019. terms.Add("DVD");
  1020. }
  1021. else if (video.VideoType == VideoType.Iso)
  1022. {
  1023. if (video.IsoType.HasValue)
  1024. {
  1025. if (video.IsoType.Value == IsoType.BluRay)
  1026. {
  1027. terms.Add("Bluray");
  1028. }
  1029. else if (video.IsoType.Value == IsoType.Dvd)
  1030. {
  1031. terms.Add("DVD");
  1032. }
  1033. }
  1034. else
  1035. {
  1036. terms.Add("ISO");
  1037. }
  1038. }
  1039. }
  1040. return string.Join('/', terms);
  1041. }
  1042. public Task RefreshMetadata(CancellationToken cancellationToken)
  1043. {
  1044. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
  1045. }
  1046. /// <summary>
  1047. /// Overrides the base implementation to refresh metadata for local trailers.
  1048. /// </summary>
  1049. /// <param name="options">The options.</param>
  1050. /// <param name="cancellationToken">The cancellation token.</param>
  1051. /// <returns>true if a provider reports we changed.</returns>
  1052. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  1053. {
  1054. var requiresSave = false;
  1055. if (SupportsOwnedItems)
  1056. {
  1057. try
  1058. {
  1059. if (IsFileProtocol)
  1060. {
  1061. requiresSave = await RefreshedOwnedItems(options, GetFileSystemChildren(options.DirectoryService), cancellationToken).ConfigureAwait(false);
  1062. }
  1063. await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties in DB are fresh
  1064. }
  1065. catch (Exception ex)
  1066. {
  1067. Logger.LogError(ex, "Error refreshing owned items for {Path}", Path ?? Name);
  1068. }
  1069. }
  1070. var refreshOptions = requiresSave
  1071. ? new MetadataRefreshOptions(options)
  1072. {
  1073. ForceSave = true
  1074. }
  1075. : options;
  1076. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  1077. }
  1078. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1079. {
  1080. if (!IsVisible(user))
  1081. {
  1082. return false;
  1083. }
  1084. if (GetParents().Any(i => !i.IsVisible(user, true)))
  1085. {
  1086. return false;
  1087. }
  1088. if (checkFolders)
  1089. {
  1090. var topParent = GetParents().LastOrDefault() ?? this;
  1091. if (string.IsNullOrEmpty(topParent.Path))
  1092. {
  1093. return true;
  1094. }
  1095. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
  1096. if (itemCollectionFolders.Count > 0)
  1097. {
  1098. var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i.Id).ToList();
  1099. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1100. {
  1101. return false;
  1102. }
  1103. }
  1104. }
  1105. return true;
  1106. }
  1107. public void SetParent(Folder parent)
  1108. {
  1109. ParentId = parent is null ? Guid.Empty : parent.Id;
  1110. }
  1111. /// <summary>
  1112. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  1113. /// Returns true or false indicating if changes were found.
  1114. /// </summary>
  1115. /// <param name="options">The metadata refresh options.</param>
  1116. /// <param name="fileSystemChildren">The list of filesystem children.</param>
  1117. /// <param name="cancellationToken">The cancellation token.</param>
  1118. /// <returns><c>true</c> if any items have changed, else <c>false</c>.</returns>
  1119. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, IReadOnlyList<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1120. {
  1121. if (!IsFileProtocol || !SupportsOwnedItems || IsInMixedFolder || this is ICollectionFolder or UserRootFolder or AggregateFolder || this.GetType() == typeof(Folder))
  1122. {
  1123. return false;
  1124. }
  1125. return await RefreshExtras(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1126. }
  1127. protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  1128. {
  1129. var path = ContainingFolderPath;
  1130. return directoryService.GetFileSystemEntries(path);
  1131. }
  1132. private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, IReadOnlyList<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1133. {
  1134. var extras = LibraryManager.FindExtras(item, fileSystemChildren, options.DirectoryService).ToArray();
  1135. var newExtraIds = Array.ConvertAll(extras, x => x.Id);
  1136. var extrasChanged = !item.ExtraIds.SequenceEqual(newExtraIds);
  1137. if (!extrasChanged && !options.ReplaceAllMetadata && options.MetadataRefreshMode != MetadataRefreshMode.FullRefresh)
  1138. {
  1139. return false;
  1140. }
  1141. var ownerId = item.Id;
  1142. var tasks = extras.Select(i =>
  1143. {
  1144. var subOptions = new MetadataRefreshOptions(options);
  1145. if (!i.OwnerId.Equals(ownerId) || !i.ParentId.IsEmpty())
  1146. {
  1147. i.OwnerId = ownerId;
  1148. i.ParentId = Guid.Empty;
  1149. subOptions.ForceSave = true;
  1150. }
  1151. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1152. });
  1153. await Task.WhenAll(tasks).ConfigureAwait(false);
  1154. item.ExtraIds = newExtraIds;
  1155. return true;
  1156. }
  1157. public string GetPresentationUniqueKey()
  1158. {
  1159. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1160. }
  1161. public virtual bool RequiresRefresh()
  1162. {
  1163. return false;
  1164. }
  1165. public virtual List<string> GetUserDataKeys()
  1166. {
  1167. var list = new List<string>();
  1168. if (SourceType == SourceType.Channel)
  1169. {
  1170. if (!string.IsNullOrEmpty(ExternalId))
  1171. {
  1172. list.Add(ExternalId);
  1173. }
  1174. }
  1175. list.Add(Id.ToString());
  1176. return list;
  1177. }
  1178. internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
  1179. {
  1180. var updateType = ItemUpdateType.None;
  1181. if (IsInMixedFolder != newItem.IsInMixedFolder)
  1182. {
  1183. IsInMixedFolder = newItem.IsInMixedFolder;
  1184. updateType |= ItemUpdateType.MetadataImport;
  1185. }
  1186. return updateType;
  1187. }
  1188. public void AfterMetadataRefresh()
  1189. {
  1190. _sortName = null;
  1191. }
  1192. /// <summary>
  1193. /// Gets the preferred metadata language.
  1194. /// </summary>
  1195. /// <returns>System.String.</returns>
  1196. public string GetPreferredMetadataLanguage()
  1197. {
  1198. string lang = PreferredMetadataLanguage;
  1199. if (string.IsNullOrEmpty(lang))
  1200. {
  1201. lang = GetParents()
  1202. .Select(i => i.PreferredMetadataLanguage)
  1203. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1204. }
  1205. if (string.IsNullOrEmpty(lang))
  1206. {
  1207. lang = LibraryManager.GetCollectionFolders(this)
  1208. .Select(i => i.PreferredMetadataLanguage)
  1209. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1210. }
  1211. if (string.IsNullOrEmpty(lang))
  1212. {
  1213. lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
  1214. }
  1215. if (string.IsNullOrEmpty(lang))
  1216. {
  1217. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1218. }
  1219. return lang;
  1220. }
  1221. /// <summary>
  1222. /// Gets the preferred metadata language.
  1223. /// </summary>
  1224. /// <returns>System.String.</returns>
  1225. public string GetPreferredMetadataCountryCode()
  1226. {
  1227. string lang = PreferredMetadataCountryCode;
  1228. if (string.IsNullOrEmpty(lang))
  1229. {
  1230. lang = GetParents()
  1231. .Select(i => i.PreferredMetadataCountryCode)
  1232. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1233. }
  1234. if (string.IsNullOrEmpty(lang))
  1235. {
  1236. lang = LibraryManager.GetCollectionFolders(this)
  1237. .Select(i => i.PreferredMetadataCountryCode)
  1238. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1239. }
  1240. if (string.IsNullOrEmpty(lang))
  1241. {
  1242. lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
  1243. }
  1244. if (string.IsNullOrEmpty(lang))
  1245. {
  1246. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1247. }
  1248. return lang;
  1249. }
  1250. public virtual bool IsSaveLocalMetadataEnabled()
  1251. {
  1252. if (SourceType == SourceType.Channel)
  1253. {
  1254. return false;
  1255. }
  1256. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  1257. return libraryOptions.SaveLocalMetadata;
  1258. }
  1259. /// <summary>
  1260. /// Determines if a given user has access to this item.
  1261. /// </summary>
  1262. /// <param name="user">The user.</param>
  1263. /// <param name="skipAllowedTagsCheck">Don't check for allowed tags.</param>
  1264. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1265. /// <exception cref="ArgumentNullException">If user is null.</exception>
  1266. public bool IsParentalAllowed(User user, bool skipAllowedTagsCheck)
  1267. {
  1268. ArgumentNullException.ThrowIfNull(user);
  1269. if (!IsVisibleViaTags(user, skipAllowedTagsCheck))
  1270. {
  1271. return false;
  1272. }
  1273. var maxAllowedRating = user.MaxParentalRatingScore;
  1274. var maxAllowedSubRating = user.MaxParentalRatingSubScore;
  1275. var rating = CustomRatingForComparison;
  1276. if (string.IsNullOrEmpty(rating))
  1277. {
  1278. rating = OfficialRatingForComparison;
  1279. }
  1280. if (string.IsNullOrEmpty(rating))
  1281. {
  1282. Logger.LogDebug("{0} has no parental rating set.", Name);
  1283. return !GetBlockUnratedValue(user);
  1284. }
  1285. var ratingScore = LocalizationManager.GetRatingScore(rating);
  1286. // Could not determine rating level
  1287. if (ratingScore is null)
  1288. {
  1289. var isAllowed = !GetBlockUnratedValue(user);
  1290. if (!isAllowed)
  1291. {
  1292. Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1293. }
  1294. return isAllowed;
  1295. }
  1296. if (maxAllowedSubRating is not null)
  1297. {
  1298. return (ratingScore.SubScore ?? 0) <= maxAllowedSubRating && ratingScore.Score <= maxAllowedRating.Value;
  1299. }
  1300. return !maxAllowedRating.HasValue || ratingScore.Score <= maxAllowedRating.Value;
  1301. }
  1302. public ParentalRatingScore GetParentalRatingScore()
  1303. {
  1304. var rating = CustomRatingForComparison;
  1305. if (string.IsNullOrEmpty(rating))
  1306. {
  1307. rating = OfficialRatingForComparison;
  1308. }
  1309. if (string.IsNullOrEmpty(rating))
  1310. {
  1311. return null;
  1312. }
  1313. return LocalizationManager.GetRatingScore(rating);
  1314. }
  1315. public List<string> GetInheritedTags()
  1316. {
  1317. var list = new List<string>();
  1318. list.AddRange(Tags);
  1319. foreach (var parent in GetParents())
  1320. {
  1321. list.AddRange(parent.Tags);
  1322. }
  1323. foreach (var folder in LibraryManager.GetCollectionFolders(this))
  1324. {
  1325. list.AddRange(folder.Tags);
  1326. }
  1327. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1328. }
  1329. private bool IsVisibleViaTags(User user, bool skipAllowedTagsCheck)
  1330. {
  1331. var allTags = GetInheritedTags();
  1332. if (user.GetPreference(PreferenceKind.BlockedTags).Any(i => allTags.Contains(i, StringComparison.OrdinalIgnoreCase)))
  1333. {
  1334. return false;
  1335. }
  1336. var parent = GetParents().FirstOrDefault() ?? this;
  1337. if (parent is UserRootFolder or AggregateFolder or UserView)
  1338. {
  1339. return true;
  1340. }
  1341. var allowedTagsPreference = user.GetPreference(PreferenceKind.AllowedTags);
  1342. if (!skipAllowedTagsCheck && allowedTagsPreference.Length != 0 && !allowedTagsPreference.Any(i => allTags.Contains(i, StringComparison.OrdinalIgnoreCase)))
  1343. {
  1344. return false;
  1345. }
  1346. return true;
  1347. }
  1348. public virtual UnratedItem GetBlockUnratedType()
  1349. {
  1350. if (SourceType == SourceType.Channel)
  1351. {
  1352. return UnratedItem.ChannelContent;
  1353. }
  1354. return UnratedItem.Other;
  1355. }
  1356. /// <summary>
  1357. /// Gets a bool indicating if access to the unrated item is blocked or not.
  1358. /// </summary>
  1359. /// <param name="user">The configuration.</param>
  1360. /// <returns><c>true</c> if blocked, <c>false</c> otherwise.</returns>
  1361. protected virtual bool GetBlockUnratedValue(User user)
  1362. {
  1363. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1364. // Special folders like series and albums will override this method.
  1365. if (IsFolder || this is IItemByName)
  1366. {
  1367. return false;
  1368. }
  1369. return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType());
  1370. }
  1371. /// <summary>
  1372. /// Determines if this folder should be visible to a given user.
  1373. /// Default is just parental allowed. Can be overridden for more functionality.
  1374. /// </summary>
  1375. /// <param name="user">The user.</param>
  1376. /// <param name="skipAllowedTagsCheck">Don't check for allowed tags.</param>
  1377. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1378. /// <exception cref="ArgumentNullException"><paramref name="user" /> is <c>null</c>.</exception>
  1379. public virtual bool IsVisible(User user, bool skipAllowedTagsCheck = false)
  1380. {
  1381. ArgumentNullException.ThrowIfNull(user);
  1382. return IsParentalAllowed(user, skipAllowedTagsCheck);
  1383. }
  1384. public virtual bool IsVisibleStandalone(User user)
  1385. {
  1386. if (SourceType == SourceType.Channel)
  1387. {
  1388. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1389. }
  1390. return IsVisibleStandaloneInternal(user, true);
  1391. }
  1392. public virtual string GetClientTypeName()
  1393. {
  1394. if (IsFolder && SourceType == SourceType.Channel && this is not Channel && this is not Season && this is not Series)
  1395. {
  1396. return "ChannelFolderItem";
  1397. }
  1398. return GetType().Name;
  1399. }
  1400. public BaseItemKind GetBaseItemKind()
  1401. {
  1402. return _baseItemKind ??= Enum.Parse<BaseItemKind>(GetClientTypeName());
  1403. }
  1404. /// <summary>
  1405. /// Gets the linked child.
  1406. /// </summary>
  1407. /// <param name="info">The info.</param>
  1408. /// <returns>BaseItem.</returns>
  1409. protected BaseItem GetLinkedChild(LinkedChild info)
  1410. {
  1411. // First get using the cached Id
  1412. if (info.ItemId.HasValue)
  1413. {
  1414. if (info.ItemId.Value.IsEmpty())
  1415. {
  1416. return null;
  1417. }
  1418. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1419. if (itemById is not null)
  1420. {
  1421. return itemById;
  1422. }
  1423. }
  1424. var item = FindLinkedChild(info);
  1425. // If still null, log
  1426. if (item is null)
  1427. {
  1428. // Don't keep searching over and over
  1429. info.ItemId = Guid.Empty;
  1430. }
  1431. else
  1432. {
  1433. // Cache the id for next time
  1434. info.ItemId = item.Id;
  1435. }
  1436. return item;
  1437. }
  1438. private BaseItem FindLinkedChild(LinkedChild info)
  1439. {
  1440. var path = info.Path;
  1441. if (!string.IsNullOrEmpty(path))
  1442. {
  1443. path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
  1444. var itemByPath = LibraryManager.FindByPath(path, null);
  1445. if (itemByPath is null)
  1446. {
  1447. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1448. }
  1449. return itemByPath;
  1450. }
  1451. if (!string.IsNullOrEmpty(info.LibraryItemId))
  1452. {
  1453. var item = LibraryManager.GetItemById(info.LibraryItemId);
  1454. if (item is null)
  1455. {
  1456. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1457. }
  1458. return item;
  1459. }
  1460. return null;
  1461. }
  1462. /// <summary>
  1463. /// Adds a studio to the item.
  1464. /// </summary>
  1465. /// <param name="name">The name.</param>
  1466. /// <exception cref="ArgumentNullException">Throws if name is null.</exception>
  1467. public void AddStudio(string name)
  1468. {
  1469. ArgumentException.ThrowIfNullOrEmpty(name);
  1470. var current = Studios;
  1471. if (!current.Contains(name, StringComparison.OrdinalIgnoreCase))
  1472. {
  1473. int curLen = current.Length;
  1474. if (curLen == 0)
  1475. {
  1476. Studios = [name];
  1477. }
  1478. else
  1479. {
  1480. Studios = [.. current, name];
  1481. }
  1482. }
  1483. }
  1484. public void SetStudios(IEnumerable<string> names)
  1485. {
  1486. Studios = names.Trimmed().Distinct().ToArray();
  1487. }
  1488. /// <summary>
  1489. /// Adds a genre 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 AddGenre(string name)
  1494. {
  1495. ArgumentException.ThrowIfNullOrEmpty(name);
  1496. var genres = Genres;
  1497. if (!genres.Contains(name, StringComparison.OrdinalIgnoreCase))
  1498. {
  1499. Genres = [.. genres, name];
  1500. }
  1501. }
  1502. /// <summary>
  1503. /// Marks the played.
  1504. /// </summary>
  1505. /// <param name="user">The user.</param>
  1506. /// <param name="datePlayed">The date played.</param>
  1507. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1508. /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
  1509. public virtual void MarkPlayed(
  1510. User user,
  1511. DateTime? datePlayed,
  1512. bool resetPosition)
  1513. {
  1514. ArgumentNullException.ThrowIfNull(user);
  1515. var data = UserDataManager.GetUserData(user, this) ?? new UserItemData()
  1516. {
  1517. Key = GetUserDataKeys().First(),
  1518. };
  1519. if (datePlayed.HasValue)
  1520. {
  1521. // Increment
  1522. data.PlayCount++;
  1523. }
  1524. // Ensure it's at least one
  1525. data.PlayCount = Math.Max(data.PlayCount, 1);
  1526. if (resetPosition)
  1527. {
  1528. data.PlaybackPositionTicks = 0;
  1529. }
  1530. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1531. data.Played = true;
  1532. UserDataManager.SaveUserData(user, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1533. }
  1534. /// <summary>
  1535. /// Marks the unplayed.
  1536. /// </summary>
  1537. /// <param name="user">The user.</param>
  1538. /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
  1539. public virtual void MarkUnplayed(User user)
  1540. {
  1541. ArgumentNullException.ThrowIfNull(user);
  1542. var data = UserDataManager.GetUserData(user, this);
  1543. // I think it is okay to do this here.
  1544. // if this is only called when a user is manually forcing something to un-played
  1545. // then it probably is what we want to do...
  1546. data.PlayCount = 0;
  1547. data.PlaybackPositionTicks = 0;
  1548. data.LastPlayedDate = null;
  1549. data.Played = false;
  1550. UserDataManager.SaveUserData(user, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1551. }
  1552. /// <summary>
  1553. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1554. /// </summary>
  1555. public virtual void ChangedExternally()
  1556. {
  1557. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriority.High);
  1558. }
  1559. /// <summary>
  1560. /// Gets an image.
  1561. /// </summary>
  1562. /// <param name="type">The type.</param>
  1563. /// <param name="imageIndex">Index of the image.</param>
  1564. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1565. /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops.</exception>
  1566. public bool HasImage(ImageType type, int imageIndex)
  1567. {
  1568. return GetImageInfo(type, imageIndex) is not null;
  1569. }
  1570. public void SetImage(ItemImageInfo image, int index)
  1571. {
  1572. if (image.Type == ImageType.Chapter)
  1573. {
  1574. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1575. }
  1576. var existingImage = GetImageInfo(image.Type, index);
  1577. if (existingImage is null)
  1578. {
  1579. AddImage(image);
  1580. }
  1581. else
  1582. {
  1583. existingImage.Path = image.Path;
  1584. existingImage.DateModified = image.DateModified;
  1585. existingImage.Width = image.Width;
  1586. existingImage.Height = image.Height;
  1587. existingImage.BlurHash = image.BlurHash;
  1588. }
  1589. }
  1590. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1591. {
  1592. if (type == ImageType.Chapter)
  1593. {
  1594. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1595. }
  1596. var image = GetImageInfo(type, index);
  1597. if (image is null)
  1598. {
  1599. AddImage(GetImageInfo(file, type));
  1600. }
  1601. else
  1602. {
  1603. var imageInfo = GetImageInfo(file, type);
  1604. image.Path = file.FullName;
  1605. image.DateModified = imageInfo.DateModified;
  1606. // reset these values
  1607. image.Width = 0;
  1608. image.Height = 0;
  1609. }
  1610. }
  1611. /// <summary>
  1612. /// Deletes the image.
  1613. /// </summary>
  1614. /// <param name="type">The type.</param>
  1615. /// <param name="index">The index.</param>
  1616. /// <returns>A task.</returns>
  1617. public async Task DeleteImageAsync(ImageType type, int index)
  1618. {
  1619. var info = GetImageInfo(type, index);
  1620. if (info is null)
  1621. {
  1622. // Nothing to do
  1623. return;
  1624. }
  1625. // Remove from file system
  1626. if (info.IsLocalFile)
  1627. {
  1628. FileSystem.DeleteFile(info.Path);
  1629. }
  1630. // Remove from item
  1631. RemoveImage(info);
  1632. await UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  1633. }
  1634. public void RemoveImage(ItemImageInfo image)
  1635. {
  1636. RemoveImages(new[] { image });
  1637. }
  1638. public void RemoveImages(IEnumerable<ItemImageInfo> deletedImages)
  1639. {
  1640. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1641. }
  1642. public void AddImage(ItemImageInfo image)
  1643. {
  1644. ImageInfos = [.. ImageInfos, image];
  1645. }
  1646. public virtual async Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1647. => await LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken).ConfigureAwait(false);
  1648. /// <summary>
  1649. /// Validates that images within the item are still on the filesystem.
  1650. /// </summary>
  1651. /// <returns><c>true</c> if the images validate, <c>false</c> if not.</returns>
  1652. public bool ValidateImages()
  1653. {
  1654. List<ItemImageInfo> deletedImages = null;
  1655. foreach (var imageInfo in ImageInfos)
  1656. {
  1657. if (!imageInfo.IsLocalFile)
  1658. {
  1659. continue;
  1660. }
  1661. if (File.Exists(imageInfo.Path))
  1662. {
  1663. continue;
  1664. }
  1665. (deletedImages ??= new List<ItemImageInfo>()).Add(imageInfo);
  1666. }
  1667. var anyImagesRemoved = deletedImages?.Count > 0;
  1668. if (anyImagesRemoved)
  1669. {
  1670. RemoveImages(deletedImages);
  1671. }
  1672. return anyImagesRemoved;
  1673. }
  1674. /// <summary>
  1675. /// Gets the image path.
  1676. /// </summary>
  1677. /// <param name="imageType">Type of the image.</param>
  1678. /// <param name="imageIndex">Index of the image.</param>
  1679. /// <returns>System.String.</returns>
  1680. /// <exception cref="ArgumentNullException">Item is null.</exception>
  1681. public string GetImagePath(ImageType imageType, int imageIndex)
  1682. => GetImageInfo(imageType, imageIndex)?.Path;
  1683. /// <summary>
  1684. /// Gets the image information.
  1685. /// </summary>
  1686. /// <param name="imageType">Type of the image.</param>
  1687. /// <param name="imageIndex">Index of the image.</param>
  1688. /// <returns>ItemImageInfo.</returns>
  1689. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1690. {
  1691. if (imageType == ImageType.Chapter)
  1692. {
  1693. var chapter = ChapterRepository.GetChapter(this.Id, imageIndex);
  1694. if (chapter is null)
  1695. {
  1696. return null;
  1697. }
  1698. var path = chapter.ImagePath;
  1699. if (string.IsNullOrEmpty(path))
  1700. {
  1701. return null;
  1702. }
  1703. return new ItemImageInfo
  1704. {
  1705. Path = path,
  1706. DateModified = chapter.ImageDateModified,
  1707. Type = imageType
  1708. };
  1709. }
  1710. // Music albums usually don't have dedicated backdrops, so return one from the artist instead
  1711. if (GetType() == typeof(MusicAlbum) && imageType == ImageType.Backdrop)
  1712. {
  1713. var artist = FindParent<MusicArtist>();
  1714. if (artist is not null)
  1715. {
  1716. return artist.GetImages(imageType).ElementAtOrDefault(imageIndex);
  1717. }
  1718. }
  1719. return GetImages(imageType)
  1720. .ElementAtOrDefault(imageIndex);
  1721. }
  1722. /// <summary>
  1723. /// Computes image index for given image or raises if no matching image found.
  1724. /// </summary>
  1725. /// <param name="image">Image to compute index for.</param>
  1726. /// <exception cref="ArgumentException">Image index cannot be computed as no matching image found.
  1727. /// </exception>
  1728. /// <returns>Image index.</returns>
  1729. public int GetImageIndex(ItemImageInfo image)
  1730. {
  1731. ArgumentNullException.ThrowIfNull(image);
  1732. if (image.Type == ImageType.Chapter)
  1733. {
  1734. var chapters = ChapterRepository.GetChapters(this.Id);
  1735. for (var i = 0; i < chapters.Count; i++)
  1736. {
  1737. if (chapters[i].ImagePath == image.Path)
  1738. {
  1739. return i;
  1740. }
  1741. }
  1742. throw new ArgumentException("No chapter index found for image path", image.Path);
  1743. }
  1744. var images = GetImages(image.Type).ToArray();
  1745. for (var i = 0; i < images.Length; i++)
  1746. {
  1747. if (images[i].Path == image.Path)
  1748. {
  1749. return i;
  1750. }
  1751. }
  1752. throw new ArgumentException("No image index found for image path", image.Path);
  1753. }
  1754. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1755. {
  1756. if (imageType == ImageType.Chapter)
  1757. {
  1758. throw new ArgumentException("No image info for chapter images");
  1759. }
  1760. // Yield return is more performant than LINQ Where on an Array
  1761. for (var i = 0; i < ImageInfos.Length; i++)
  1762. {
  1763. var imageInfo = ImageInfos[i];
  1764. if (imageInfo.Type == imageType)
  1765. {
  1766. yield return imageInfo;
  1767. }
  1768. }
  1769. }
  1770. /// <summary>
  1771. /// Adds the images, updating metadata if they already are part of this item.
  1772. /// </summary>
  1773. /// <param name="imageType">Type of the image.</param>
  1774. /// <param name="images">The images.</param>
  1775. /// <returns><c>true</c> if images were added or updated, <c>false</c> otherwise.</returns>
  1776. /// <exception cref="ArgumentException">Cannot call AddImages with chapter images.</exception>
  1777. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1778. {
  1779. if (imageType == ImageType.Chapter)
  1780. {
  1781. throw new ArgumentException("Cannot call AddImages with chapter images");
  1782. }
  1783. var existingImages = GetImages(imageType)
  1784. .ToList();
  1785. var newImageList = new List<FileSystemMetadata>();
  1786. var imageUpdated = false;
  1787. foreach (var newImage in images)
  1788. {
  1789. if (newImage is null)
  1790. {
  1791. throw new ArgumentException("null image found in list");
  1792. }
  1793. var existing = existingImages
  1794. .Find(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1795. if (existing is null)
  1796. {
  1797. newImageList.Add(newImage);
  1798. }
  1799. else
  1800. {
  1801. if (existing.IsLocalFile)
  1802. {
  1803. var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1804. // If date changed then we need to reset saved image dimensions
  1805. if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
  1806. {
  1807. existing.Width = 0;
  1808. existing.Height = 0;
  1809. imageUpdated = true;
  1810. }
  1811. existing.DateModified = newDateModified;
  1812. }
  1813. }
  1814. }
  1815. if (newImageList.Count > 0)
  1816. {
  1817. ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
  1818. }
  1819. return imageUpdated || newImageList.Count > 0;
  1820. }
  1821. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1822. {
  1823. return new ItemImageInfo
  1824. {
  1825. Path = file.FullName,
  1826. Type = type,
  1827. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1828. };
  1829. }
  1830. /// <summary>
  1831. /// Gets the file system path to delete when the item is to be deleted.
  1832. /// </summary>
  1833. /// <returns>The metadata for the deleted paths.</returns>
  1834. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  1835. {
  1836. return new[]
  1837. {
  1838. new FileSystemMetadata
  1839. {
  1840. FullName = Path,
  1841. IsDirectory = IsFolder
  1842. }
  1843. }.Concat(GetLocalMetadataFilesToDelete());
  1844. }
  1845. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  1846. {
  1847. if (IsFolder || !IsInMixedFolder)
  1848. {
  1849. return new List<FileSystemMetadata>();
  1850. }
  1851. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  1852. return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
  1853. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  1854. .ToList();
  1855. }
  1856. public bool AllowsMultipleImages(ImageType type)
  1857. {
  1858. return type == ImageType.Backdrop || type == ImageType.Chapter;
  1859. }
  1860. public Task SwapImagesAsync(ImageType type, int index1, int index2)
  1861. {
  1862. if (!AllowsMultipleImages(type))
  1863. {
  1864. throw new ArgumentException("The change index operation is only applicable to backdrops and screen shots");
  1865. }
  1866. var info1 = GetImageInfo(type, index1);
  1867. var info2 = GetImageInfo(type, index2);
  1868. if (info1 is null || info2 is null)
  1869. {
  1870. // Nothing to do
  1871. return Task.CompletedTask;
  1872. }
  1873. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1874. {
  1875. // TODO: Not supported yet
  1876. return Task.CompletedTask;
  1877. }
  1878. var path1 = info1.Path;
  1879. var path2 = info2.Path;
  1880. FileSystem.SwapFiles(path1, path2);
  1881. // Refresh these values
  1882. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1883. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1884. info1.Width = 0;
  1885. info1.Height = 0;
  1886. info2.Width = 0;
  1887. info2.Height = 0;
  1888. return UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1889. }
  1890. public virtual bool IsPlayed(User user)
  1891. {
  1892. var userdata = UserDataManager.GetUserData(user, this);
  1893. return userdata is not null && userdata.Played;
  1894. }
  1895. public bool IsFavoriteOrLiked(User user)
  1896. {
  1897. var userdata = UserDataManager.GetUserData(user, this);
  1898. return userdata is not null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1899. }
  1900. public virtual bool IsUnplayed(User user)
  1901. {
  1902. ArgumentNullException.ThrowIfNull(user);
  1903. var userdata = UserDataManager.GetUserData(user, this);
  1904. return userdata is null || !userdata.Played;
  1905. }
  1906. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1907. {
  1908. return GetItemLookupInfo<ItemLookupInfo>();
  1909. }
  1910. protected T GetItemLookupInfo<T>()
  1911. where T : ItemLookupInfo, new()
  1912. {
  1913. return new T
  1914. {
  1915. Path = Path,
  1916. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1917. MetadataLanguage = GetPreferredMetadataLanguage(),
  1918. Name = GetNameForMetadataLookup(),
  1919. OriginalTitle = OriginalTitle,
  1920. ProviderIds = ProviderIds,
  1921. IndexNumber = IndexNumber,
  1922. ParentIndexNumber = ParentIndexNumber,
  1923. Year = ProductionYear,
  1924. PremiereDate = PremiereDate
  1925. };
  1926. }
  1927. protected virtual string GetNameForMetadataLookup()
  1928. {
  1929. return Name;
  1930. }
  1931. /// <summary>
  1932. /// This is called before any metadata refresh and returns true if changes were made.
  1933. /// </summary>
  1934. /// <param name="replaceAllMetadata">Whether to replace all metadata.</param>
  1935. /// <returns>true if the item has change, else false.</returns>
  1936. public virtual bool BeforeMetadataRefresh(bool replaceAllMetadata)
  1937. {
  1938. _sortName = null;
  1939. var hasChanges = false;
  1940. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1941. {
  1942. Name = System.IO.Path.GetFileNameWithoutExtension(Path);
  1943. hasChanges = true;
  1944. }
  1945. return hasChanges;
  1946. }
  1947. protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
  1948. {
  1949. if (protocol == MediaProtocol.File)
  1950. {
  1951. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  1952. }
  1953. return path;
  1954. }
  1955. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  1956. {
  1957. if (RunTimeTicks.HasValue)
  1958. {
  1959. double pct = RunTimeTicks.Value;
  1960. if (pct > 0)
  1961. {
  1962. pct = userData.PlaybackPositionTicks / pct;
  1963. if (pct > 0)
  1964. {
  1965. dto.PlayedPercentage = 100 * pct;
  1966. }
  1967. }
  1968. }
  1969. }
  1970. protected async Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  1971. {
  1972. var newOptions = new MetadataRefreshOptions(options)
  1973. {
  1974. SearchResult = null
  1975. };
  1976. var item = this;
  1977. if (copyTitleMetadata)
  1978. {
  1979. // Take some data from the main item, for querying purposes
  1980. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  1981. {
  1982. newOptions.ForceSave = true;
  1983. ownedItem.Genres = item.Genres;
  1984. }
  1985. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  1986. {
  1987. newOptions.ForceSave = true;
  1988. ownedItem.Studios = item.Studios;
  1989. }
  1990. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  1991. {
  1992. newOptions.ForceSave = true;
  1993. ownedItem.ProductionLocations = item.ProductionLocations;
  1994. }
  1995. if (item.CommunityRating != ownedItem.CommunityRating)
  1996. {
  1997. ownedItem.CommunityRating = item.CommunityRating;
  1998. newOptions.ForceSave = true;
  1999. }
  2000. if (item.CriticRating != ownedItem.CriticRating)
  2001. {
  2002. ownedItem.CriticRating = item.CriticRating;
  2003. newOptions.ForceSave = true;
  2004. }
  2005. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  2006. {
  2007. ownedItem.Overview = item.Overview;
  2008. newOptions.ForceSave = true;
  2009. }
  2010. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  2011. {
  2012. ownedItem.OfficialRating = item.OfficialRating;
  2013. newOptions.ForceSave = true;
  2014. }
  2015. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  2016. {
  2017. ownedItem.CustomRating = item.CustomRating;
  2018. newOptions.ForceSave = true;
  2019. }
  2020. }
  2021. await ownedItem.RefreshMetadata(newOptions, cancellationToken).ConfigureAwait(false);
  2022. }
  2023. protected async Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2024. {
  2025. var newOptions = new MetadataRefreshOptions(options)
  2026. {
  2027. SearchResult = null
  2028. };
  2029. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2030. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2031. if (LibraryManager.GetItemById(id) is not Video video)
  2032. {
  2033. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2034. newOptions.ForceSave = true;
  2035. }
  2036. if (video is null)
  2037. {
  2038. return;
  2039. }
  2040. if (video.OwnerId.IsEmpty())
  2041. {
  2042. video.OwnerId = Id;
  2043. }
  2044. await RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken).ConfigureAwait(false);
  2045. }
  2046. public string GetEtag(User user)
  2047. {
  2048. var list = GetEtagValues(user);
  2049. return string.Join('|', list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  2050. }
  2051. protected virtual List<string> GetEtagValues(User user)
  2052. {
  2053. return new List<string>
  2054. {
  2055. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2056. };
  2057. }
  2058. public virtual IEnumerable<Guid> GetAncestorIds()
  2059. {
  2060. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2061. }
  2062. public BaseItem GetTopParent()
  2063. {
  2064. if (IsTopParent)
  2065. {
  2066. return this;
  2067. }
  2068. return GetParents().FirstOrDefault(parent => parent.IsTopParent);
  2069. }
  2070. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2071. {
  2072. return new[] { Id };
  2073. }
  2074. public virtual double? GetRefreshProgress()
  2075. {
  2076. return null;
  2077. }
  2078. public virtual ItemUpdateType OnMetadataChanged()
  2079. {
  2080. var updateType = ItemUpdateType.None;
  2081. var item = this;
  2082. var rating = item.GetParentalRatingScore();
  2083. if (rating is not null)
  2084. {
  2085. if (rating.Score != item.InheritedParentalRatingValue)
  2086. {
  2087. item.InheritedParentalRatingValue = rating.Score;
  2088. updateType |= ItemUpdateType.MetadataImport;
  2089. }
  2090. if (rating.SubScore != item.InheritedParentalRatingSubValue)
  2091. {
  2092. item.InheritedParentalRatingSubValue = rating.SubScore;
  2093. updateType |= ItemUpdateType.MetadataImport;
  2094. }
  2095. }
  2096. else
  2097. {
  2098. if (item.InheritedParentalRatingValue is not null)
  2099. {
  2100. item.InheritedParentalRatingValue = null;
  2101. item.InheritedParentalRatingSubValue = null;
  2102. updateType |= ItemUpdateType.MetadataImport;
  2103. }
  2104. }
  2105. return updateType;
  2106. }
  2107. /// <summary>
  2108. /// Updates the official rating based on content and returns true or false indicating if it changed.
  2109. /// </summary>
  2110. /// <param name="children">Media children.</param>
  2111. /// <returns><c>true</c> if the rating was updated; otherwise <c>false</c>.</returns>
  2112. public bool UpdateRatingToItems(IReadOnlyList<BaseItem> children)
  2113. {
  2114. var currentOfficialRating = OfficialRating;
  2115. // Gather all possible ratings
  2116. var ratings = children
  2117. .Select(i => i.OfficialRating)
  2118. .Where(i => !string.IsNullOrEmpty(i))
  2119. .Distinct(StringComparer.OrdinalIgnoreCase)
  2120. .Select(rating => (rating, LocalizationManager.GetRatingScore(rating)))
  2121. .OrderBy(i => i.Item2 is null ? 1001 : i.Item2.Score)
  2122. .ThenBy(i => i.Item2 is null ? 1001 : i.Item2.SubScore)
  2123. .Select(i => i.rating);
  2124. OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
  2125. return !string.Equals(
  2126. currentOfficialRating ?? string.Empty,
  2127. OfficialRating ?? string.Empty,
  2128. StringComparison.OrdinalIgnoreCase);
  2129. }
  2130. public IReadOnlyList<BaseItem> GetThemeSongs(User user = null)
  2131. {
  2132. return GetThemeSongs(user, Array.Empty<(ItemSortBy, SortOrder)>());
  2133. }
  2134. public IReadOnlyList<BaseItem> GetThemeSongs(User user, IEnumerable<(ItemSortBy SortBy, SortOrder SortOrder)> orderBy)
  2135. {
  2136. return LibraryManager.Sort(GetExtras().Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeSong), user, orderBy).ToArray();
  2137. }
  2138. public IReadOnlyList<BaseItem> GetThemeVideos(User user = null)
  2139. {
  2140. return GetThemeVideos(user, Array.Empty<(ItemSortBy, SortOrder)>());
  2141. }
  2142. public IReadOnlyList<BaseItem> GetThemeVideos(User user, IEnumerable<(ItemSortBy SortBy, SortOrder SortOrder)> orderBy)
  2143. {
  2144. return LibraryManager.Sort(GetExtras().Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeVideo), user, orderBy).ToArray();
  2145. }
  2146. /// <summary>
  2147. /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
  2148. /// </summary>
  2149. /// <returns>An enumerable containing the items.</returns>
  2150. public IEnumerable<BaseItem> GetExtras()
  2151. {
  2152. return ExtraIds
  2153. .Select(LibraryManager.GetItemById)
  2154. .Where(i => i is not null)
  2155. .OrderBy(i => i.SortName);
  2156. }
  2157. /// <summary>
  2158. /// Get all extras with specific types that are associated with this item.
  2159. /// </summary>
  2160. /// <param name="extraTypes">The types of extras to retrieve.</param>
  2161. /// <returns>An enumerable containing the extras.</returns>
  2162. public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes)
  2163. {
  2164. return ExtraIds
  2165. .Select(LibraryManager.GetItemById)
  2166. .Where(i => i is not null)
  2167. .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value))
  2168. .OrderBy(i => i.SortName);
  2169. }
  2170. public virtual long GetRunTimeTicksForPlayState()
  2171. {
  2172. return RunTimeTicks ?? 0;
  2173. }
  2174. /// <inheritdoc />
  2175. public override bool Equals(object obj)
  2176. {
  2177. return obj is BaseItem baseItem && this.Equals(baseItem);
  2178. }
  2179. /// <inheritdoc />
  2180. public bool Equals(BaseItem other) => other is not null && other.Id.Equals(Id);
  2181. /// <inheritdoc />
  2182. public override int GetHashCode() => HashCode.Combine(Id);
  2183. }
  2184. }