BaseItem.cs 83 KB

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