BaseItem.cs 86 KB

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