BaseItem.cs 82 KB

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