BaseItem.cs 82 KB

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