BaseItem.cs 82 KB

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