BaseItem.cs 81 KB

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