BaseItem.cs 83 KB

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