BaseItem.cs 81 KB

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