BaseItem.cs 81 KB

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