BaseItem.cs 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659
  1. #nullable disable
  2. #pragma warning disable CS1591, SA1401
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Globalization;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Text.Json.Serialization;
  9. using System.Threading;
  10. using System.Threading.Tasks;
  11. using Diacritics.Extensions;
  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(Guid.Empty))
  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(Guid.Empty))
  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(Guid.Empty) && 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(Guid.Empty) ? 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. /// <summary>
  718. /// Returns a <see cref="string" /> that represents this instance.
  719. /// </summary>
  720. /// <returns>A <see cref="string" /> that represents this instance.</returns>
  721. public override string ToString()
  722. {
  723. return Name;
  724. }
  725. public string GetInternalMetadataPath()
  726. {
  727. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  728. return GetInternalMetadataPath(basePath);
  729. }
  730. protected virtual string GetInternalMetadataPath(string basePath)
  731. {
  732. if (SourceType == SourceType.Channel)
  733. {
  734. return System.IO.Path.Join(basePath, "channels", ChannelId.ToString("N", CultureInfo.InvariantCulture), Id.ToString("N", CultureInfo.InvariantCulture));
  735. }
  736. ReadOnlySpan<char> idString = Id.ToString("N", CultureInfo.InvariantCulture);
  737. return System.IO.Path.Join(basePath, "library", idString[..2], idString);
  738. }
  739. /// <summary>
  740. /// Creates the name of the sort.
  741. /// </summary>
  742. /// <returns>System.String.</returns>
  743. protected virtual string CreateSortName()
  744. {
  745. if (Name == null)
  746. {
  747. return null; // some items may not have name filled in properly
  748. }
  749. if (!EnableAlphaNumericSorting)
  750. {
  751. return Name.TrimStart();
  752. }
  753. var sortable = Name.Trim().ToLowerInvariant();
  754. foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
  755. {
  756. sortable = sortable.Replace(removeChar, string.Empty, StringComparison.Ordinal);
  757. }
  758. foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
  759. {
  760. sortable = sortable.Replace(replaceChar, " ", StringComparison.Ordinal);
  761. }
  762. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  763. {
  764. // Remove from beginning if a space follows
  765. if (sortable.StartsWith(search + " ", StringComparison.Ordinal))
  766. {
  767. sortable = sortable.Remove(0, search.Length + 1);
  768. }
  769. // Remove from middle if surrounded by spaces
  770. sortable = sortable.Replace(" " + search + " ", " ", StringComparison.Ordinal);
  771. // Remove from end if followed by a space
  772. if (sortable.EndsWith(" " + search, StringComparison.Ordinal))
  773. {
  774. sortable = sortable.Remove(sortable.Length - (search.Length + 1));
  775. }
  776. }
  777. return ModifySortChunks(sortable);
  778. }
  779. private string ModifySortChunks(string name)
  780. {
  781. var chunks = GetSortChunks(name);
  782. var builder = new StringBuilder();
  783. foreach (var chunk in chunks)
  784. {
  785. var chunkBuilder = chunk.Item1;
  786. // This chunk is numeric
  787. if (chunk.Item2)
  788. {
  789. while (chunkBuilder.Length < 10)
  790. {
  791. chunkBuilder.Insert(0, '0');
  792. }
  793. }
  794. builder.Append(chunkBuilder);
  795. }
  796. // logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
  797. return builder.ToString().RemoveDiacritics();
  798. }
  799. public BaseItem GetParent()
  800. {
  801. var parentId = ParentId;
  802. if (!parentId.Equals(Guid.Empty))
  803. {
  804. return LibraryManager.GetItemById(parentId);
  805. }
  806. return null;
  807. }
  808. public IEnumerable<BaseItem> GetParents()
  809. {
  810. var parent = GetParent();
  811. while (parent != null)
  812. {
  813. yield return parent;
  814. parent = parent.GetParent();
  815. }
  816. }
  817. /// <summary>
  818. /// Finds a parent of a given type.
  819. /// </summary>
  820. /// <typeparam name="T">Type of parent.</typeparam>
  821. /// <returns>``0.</returns>
  822. public T FindParent<T>()
  823. where T : Folder
  824. {
  825. foreach (var parent in GetParents())
  826. {
  827. if (parent is T item)
  828. {
  829. return item;
  830. }
  831. }
  832. return null;
  833. }
  834. /// <summary>
  835. /// Gets the play access.
  836. /// </summary>
  837. /// <param name="user">The user.</param>
  838. /// <returns>PlayAccess.</returns>
  839. public PlayAccess GetPlayAccess(User user)
  840. {
  841. if (!user.HasPermission(PermissionKind.EnableMediaPlayback))
  842. {
  843. return PlayAccess.None;
  844. }
  845. // if (!user.IsParentalScheduleAllowed())
  846. // {
  847. // return PlayAccess.None;
  848. // }
  849. return PlayAccess.Full;
  850. }
  851. public virtual List<MediaStream> GetMediaStreams()
  852. {
  853. return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
  854. {
  855. ItemId = Id
  856. });
  857. }
  858. protected virtual bool IsActiveRecording()
  859. {
  860. return false;
  861. }
  862. public virtual List<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  863. {
  864. if (SourceType == SourceType.Channel)
  865. {
  866. var sources = ChannelManager.GetStaticMediaSources(this, CancellationToken.None)
  867. .ToList();
  868. if (sources.Count > 0)
  869. {
  870. return sources;
  871. }
  872. }
  873. var list = GetAllItemsForMediaSources();
  874. var result = list.Select(i => GetVersionInfo(enablePathSubstitution, i.Item1, i.Item2)).ToList();
  875. if (IsActiveRecording())
  876. {
  877. foreach (var mediaSource in result)
  878. {
  879. mediaSource.Type = MediaSourceType.Placeholder;
  880. }
  881. }
  882. return result.OrderBy(i =>
  883. {
  884. if (i.VideoType == VideoType.VideoFile)
  885. {
  886. return 0;
  887. }
  888. return 1;
  889. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  890. .ThenByDescending(i =>
  891. {
  892. var stream = i.VideoStream;
  893. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  894. })
  895. .ToList();
  896. }
  897. protected virtual IEnumerable<(BaseItem, MediaSourceType)> GetAllItemsForMediaSources()
  898. {
  899. return Enumerable.Empty<(BaseItem, MediaSourceType)>();
  900. }
  901. private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type)
  902. {
  903. if (item == null)
  904. {
  905. throw new ArgumentNullException(nameof(item));
  906. }
  907. var protocol = item.PathProtocol;
  908. var info = new MediaSourceInfo
  909. {
  910. Id = item.Id.ToString("N", CultureInfo.InvariantCulture),
  911. Protocol = protocol ?? MediaProtocol.File,
  912. MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
  913. MediaAttachments = MediaSourceManager.GetMediaAttachments(item.Id),
  914. Name = GetMediaSourceName(item),
  915. Path = enablePathSubstitution ? GetMappedPath(item, item.Path, protocol) : item.Path,
  916. RunTimeTicks = item.RunTimeTicks,
  917. Container = item.Container,
  918. Size = item.Size,
  919. Type = type
  920. };
  921. if (string.IsNullOrEmpty(info.Path))
  922. {
  923. info.Type = MediaSourceType.Placeholder;
  924. }
  925. if (info.Protocol == MediaProtocol.File)
  926. {
  927. info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  928. }
  929. var video = item as Video;
  930. if (video != null)
  931. {
  932. info.IsoType = video.IsoType;
  933. info.VideoType = video.VideoType;
  934. info.Video3DFormat = video.Video3DFormat;
  935. info.Timestamp = video.Timestamp;
  936. if (video.IsShortcut)
  937. {
  938. info.IsRemote = true;
  939. info.Path = video.ShortcutPath;
  940. info.Protocol = MediaSourceManager.GetPathProtocol(info.Path);
  941. }
  942. if (string.IsNullOrEmpty(info.Container))
  943. {
  944. if (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso)
  945. {
  946. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  947. {
  948. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  949. }
  950. }
  951. }
  952. }
  953. if (string.IsNullOrEmpty(info.Container))
  954. {
  955. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  956. {
  957. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  958. }
  959. }
  960. if (info.SupportsDirectStream && !string.IsNullOrEmpty(info.Path))
  961. {
  962. info.SupportsDirectStream = MediaSourceManager.SupportsDirectStream(info.Path, info.Protocol);
  963. }
  964. if (video != null && video.VideoType != VideoType.VideoFile)
  965. {
  966. info.SupportsDirectStream = false;
  967. }
  968. info.Bitrate = item.TotalBitrate;
  969. info.InferTotalBitrate();
  970. return info;
  971. }
  972. private string GetMediaSourceName(BaseItem item)
  973. {
  974. var terms = new List<string>();
  975. var path = item.Path;
  976. if (item.IsFileProtocol && !string.IsNullOrEmpty(path))
  977. {
  978. if (HasLocalAlternateVersions)
  979. {
  980. var displayName = System.IO.Path.GetFileNameWithoutExtension(path)
  981. .Replace(System.IO.Path.GetFileName(ContainingFolderPath), string.Empty, StringComparison.OrdinalIgnoreCase)
  982. .TrimStart(new char[] { ' ', '-' });
  983. if (!string.IsNullOrEmpty(displayName))
  984. {
  985. terms.Add(displayName);
  986. }
  987. }
  988. if (terms.Count == 0)
  989. {
  990. var displayName = System.IO.Path.GetFileNameWithoutExtension(path);
  991. terms.Add(displayName);
  992. }
  993. }
  994. if (terms.Count == 0)
  995. {
  996. terms.Add(item.Name);
  997. }
  998. if (item is Video video)
  999. {
  1000. if (video.Video3DFormat.HasValue)
  1001. {
  1002. terms.Add("3D");
  1003. }
  1004. if (video.VideoType == VideoType.BluRay)
  1005. {
  1006. terms.Add("Bluray");
  1007. }
  1008. else if (video.VideoType == VideoType.Dvd)
  1009. {
  1010. terms.Add("DVD");
  1011. }
  1012. else if (video.VideoType == VideoType.Iso)
  1013. {
  1014. if (video.IsoType.HasValue)
  1015. {
  1016. if (video.IsoType.Value == IsoType.BluRay)
  1017. {
  1018. terms.Add("Bluray");
  1019. }
  1020. else if (video.IsoType.Value == IsoType.Dvd)
  1021. {
  1022. terms.Add("DVD");
  1023. }
  1024. }
  1025. else
  1026. {
  1027. terms.Add("ISO");
  1028. }
  1029. }
  1030. }
  1031. return string.Join('/', terms);
  1032. }
  1033. public Task RefreshMetadata(CancellationToken cancellationToken)
  1034. {
  1035. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(FileSystem)), cancellationToken);
  1036. }
  1037. protected virtual void TriggerOnRefreshStart()
  1038. {
  1039. }
  1040. protected virtual void TriggerOnRefreshComplete()
  1041. {
  1042. }
  1043. /// <summary>
  1044. /// Overrides the base implementation to refresh metadata for local trailers.
  1045. /// </summary>
  1046. /// <param name="options">The options.</param>
  1047. /// <param name="cancellationToken">The cancellation token.</param>
  1048. /// <returns>true if a provider reports we changed.</returns>
  1049. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  1050. {
  1051. TriggerOnRefreshStart();
  1052. var requiresSave = false;
  1053. if (SupportsOwnedItems)
  1054. {
  1055. try
  1056. {
  1057. if (IsFileProtocol)
  1058. {
  1059. requiresSave = await RefreshedOwnedItems(options, GetFileSystemChildren(options.DirectoryService).ToList(), cancellationToken).ConfigureAwait(false);
  1060. }
  1061. await LibraryManager.UpdateImagesAsync(this).ConfigureAwait(false); // ensure all image properties in DB are fresh
  1062. }
  1063. catch (Exception ex)
  1064. {
  1065. Logger.LogError(ex, "Error refreshing owned items for {Path}", Path ?? Name);
  1066. }
  1067. }
  1068. try
  1069. {
  1070. var refreshOptions = requiresSave
  1071. ? new MetadataRefreshOptions(options)
  1072. {
  1073. ForceSave = true
  1074. }
  1075. : options;
  1076. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  1077. }
  1078. finally
  1079. {
  1080. TriggerOnRefreshComplete();
  1081. }
  1082. }
  1083. protected bool IsVisibleStandaloneInternal(User user, bool checkFolders)
  1084. {
  1085. if (!IsVisible(user))
  1086. {
  1087. return false;
  1088. }
  1089. if (GetParents().Any(i => !i.IsVisible(user)))
  1090. {
  1091. return false;
  1092. }
  1093. if (checkFolders)
  1094. {
  1095. var topParent = GetParents().LastOrDefault() ?? this;
  1096. if (string.IsNullOrEmpty(topParent.Path))
  1097. {
  1098. return true;
  1099. }
  1100. var itemCollectionFolders = LibraryManager.GetCollectionFolders(this).Select(i => i.Id).ToList();
  1101. if (itemCollectionFolders.Count > 0)
  1102. {
  1103. var userCollectionFolders = LibraryManager.GetUserRootFolder().GetChildren(user, true).Select(i => i.Id).ToList();
  1104. if (!itemCollectionFolders.Any(userCollectionFolders.Contains))
  1105. {
  1106. return false;
  1107. }
  1108. }
  1109. }
  1110. return true;
  1111. }
  1112. public void SetParent(Folder parent)
  1113. {
  1114. ParentId = parent == null ? Guid.Empty : parent.Id;
  1115. }
  1116. /// <summary>
  1117. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  1118. /// Returns true or false indicating if changes were found.
  1119. /// </summary>
  1120. /// <param name="options">The metadata refresh options.</param>
  1121. /// <param name="fileSystemChildren">The list of filesystem children.</param>
  1122. /// <param name="cancellationToken">The cancellation token.</param>
  1123. /// <returns><c>true</c> if any items have changed, else <c>false</c>.</returns>
  1124. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1125. {
  1126. if (!IsFileProtocol || !SupportsOwnedItems || IsInMixedFolder || this is ICollectionFolder or UserRootFolder or AggregateFolder || this.GetType() == typeof(Folder))
  1127. {
  1128. return false;
  1129. }
  1130. return await RefreshExtras(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1131. }
  1132. protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  1133. {
  1134. var path = ContainingFolderPath;
  1135. return directoryService.GetFileSystemEntries(path);
  1136. }
  1137. private async Task<bool> RefreshExtras(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1138. {
  1139. var extras = LibraryManager.FindExtras(item, fileSystemChildren, options.DirectoryService).ToArray();
  1140. var newExtraIds = extras.Select(i => i.Id).ToArray();
  1141. var extrasChanged = !item.ExtraIds.SequenceEqual(newExtraIds);
  1142. if (!extrasChanged && !options.ReplaceAllMetadata && options.MetadataRefreshMode != MetadataRefreshMode.FullRefresh)
  1143. {
  1144. return false;
  1145. }
  1146. var ownerId = item.Id;
  1147. var tasks = extras.Select(i =>
  1148. {
  1149. var subOptions = new MetadataRefreshOptions(options);
  1150. if (i.OwnerId != ownerId || i.ParentId != Guid.Empty)
  1151. {
  1152. i.OwnerId = ownerId;
  1153. i.ParentId = Guid.Empty;
  1154. subOptions.ForceSave = true;
  1155. }
  1156. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1157. });
  1158. await Task.WhenAll(tasks).ConfigureAwait(false);
  1159. item.ExtraIds = newExtraIds;
  1160. return true;
  1161. }
  1162. public string GetPresentationUniqueKey()
  1163. {
  1164. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1165. }
  1166. public virtual bool RequiresRefresh()
  1167. {
  1168. return false;
  1169. }
  1170. public virtual List<string> GetUserDataKeys()
  1171. {
  1172. var list = new List<string>();
  1173. if (SourceType == SourceType.Channel)
  1174. {
  1175. if (!string.IsNullOrEmpty(ExternalId))
  1176. {
  1177. list.Add(ExternalId);
  1178. }
  1179. }
  1180. list.Add(Id.ToString());
  1181. return list;
  1182. }
  1183. internal virtual ItemUpdateType UpdateFromResolvedItem(BaseItem newItem)
  1184. {
  1185. var updateType = ItemUpdateType.None;
  1186. if (IsInMixedFolder != newItem.IsInMixedFolder)
  1187. {
  1188. IsInMixedFolder = newItem.IsInMixedFolder;
  1189. updateType |= ItemUpdateType.MetadataImport;
  1190. }
  1191. return updateType;
  1192. }
  1193. public void AfterMetadataRefresh()
  1194. {
  1195. _sortName = null;
  1196. }
  1197. /// <summary>
  1198. /// Gets the preferred metadata language.
  1199. /// </summary>
  1200. /// <returns>System.String.</returns>
  1201. public string GetPreferredMetadataLanguage()
  1202. {
  1203. string lang = PreferredMetadataLanguage;
  1204. if (string.IsNullOrEmpty(lang))
  1205. {
  1206. lang = GetParents()
  1207. .Select(i => i.PreferredMetadataLanguage)
  1208. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1209. }
  1210. if (string.IsNullOrEmpty(lang))
  1211. {
  1212. lang = LibraryManager.GetCollectionFolders(this)
  1213. .Select(i => i.PreferredMetadataLanguage)
  1214. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1215. }
  1216. if (string.IsNullOrEmpty(lang))
  1217. {
  1218. lang = LibraryManager.GetLibraryOptions(this).PreferredMetadataLanguage;
  1219. }
  1220. if (string.IsNullOrEmpty(lang))
  1221. {
  1222. lang = ConfigurationManager.Configuration.PreferredMetadataLanguage;
  1223. }
  1224. return lang;
  1225. }
  1226. /// <summary>
  1227. /// Gets the preferred metadata language.
  1228. /// </summary>
  1229. /// <returns>System.String.</returns>
  1230. public string GetPreferredMetadataCountryCode()
  1231. {
  1232. string lang = PreferredMetadataCountryCode;
  1233. if (string.IsNullOrEmpty(lang))
  1234. {
  1235. lang = GetParents()
  1236. .Select(i => i.PreferredMetadataCountryCode)
  1237. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1238. }
  1239. if (string.IsNullOrEmpty(lang))
  1240. {
  1241. lang = LibraryManager.GetCollectionFolders(this)
  1242. .Select(i => i.PreferredMetadataCountryCode)
  1243. .FirstOrDefault(i => !string.IsNullOrEmpty(i));
  1244. }
  1245. if (string.IsNullOrEmpty(lang))
  1246. {
  1247. lang = LibraryManager.GetLibraryOptions(this).MetadataCountryCode;
  1248. }
  1249. if (string.IsNullOrEmpty(lang))
  1250. {
  1251. lang = ConfigurationManager.Configuration.MetadataCountryCode;
  1252. }
  1253. return lang;
  1254. }
  1255. public virtual bool IsSaveLocalMetadataEnabled()
  1256. {
  1257. if (SourceType == SourceType.Channel)
  1258. {
  1259. return false;
  1260. }
  1261. var libraryOptions = LibraryManager.GetLibraryOptions(this);
  1262. return libraryOptions.SaveLocalMetadata;
  1263. }
  1264. /// <summary>
  1265. /// Determines if a given user has access to this item.
  1266. /// </summary>
  1267. /// <param name="user">The user.</param>
  1268. /// <returns><c>true</c> if [is parental allowed] [the specified user]; otherwise, <c>false</c>.</returns>
  1269. /// <exception cref="ArgumentNullException">If user is null.</exception>
  1270. public bool IsParentalAllowed(User user)
  1271. {
  1272. if (user == null)
  1273. {
  1274. throw new ArgumentNullException(nameof(user));
  1275. }
  1276. if (!IsVisibleViaTags(user))
  1277. {
  1278. return false;
  1279. }
  1280. var maxAllowedRating = user.MaxParentalAgeRating;
  1281. if (maxAllowedRating == null)
  1282. {
  1283. return true;
  1284. }
  1285. var rating = CustomRatingForComparison;
  1286. if (string.IsNullOrEmpty(rating))
  1287. {
  1288. rating = OfficialRatingForComparison;
  1289. }
  1290. if (string.IsNullOrEmpty(rating))
  1291. {
  1292. return !GetBlockUnratedValue(user);
  1293. }
  1294. var value = LocalizationManager.GetRatingLevel(rating);
  1295. // Could not determine the integer value
  1296. if (!value.HasValue)
  1297. {
  1298. var isAllowed = !GetBlockUnratedValue(user);
  1299. if (!isAllowed)
  1300. {
  1301. Logger.LogDebug("{0} has an unrecognized parental rating of {1}.", Name, rating);
  1302. }
  1303. return isAllowed;
  1304. }
  1305. return value.Value <= maxAllowedRating.Value;
  1306. }
  1307. public int? GetParentalRatingValue()
  1308. {
  1309. var rating = CustomRating;
  1310. if (string.IsNullOrEmpty(rating))
  1311. {
  1312. rating = OfficialRating;
  1313. }
  1314. if (string.IsNullOrEmpty(rating))
  1315. {
  1316. return null;
  1317. }
  1318. return LocalizationManager.GetRatingLevel(rating);
  1319. }
  1320. public int? GetInheritedParentalRatingValue()
  1321. {
  1322. var rating = CustomRatingForComparison;
  1323. if (string.IsNullOrEmpty(rating))
  1324. {
  1325. rating = OfficialRatingForComparison;
  1326. }
  1327. if (string.IsNullOrEmpty(rating))
  1328. {
  1329. return null;
  1330. }
  1331. return LocalizationManager.GetRatingLevel(rating);
  1332. }
  1333. public List<string> GetInheritedTags()
  1334. {
  1335. var list = new List<string>();
  1336. list.AddRange(Tags);
  1337. foreach (var parent in GetParents())
  1338. {
  1339. list.AddRange(parent.Tags);
  1340. }
  1341. return list.Distinct(StringComparer.OrdinalIgnoreCase).ToList();
  1342. }
  1343. private bool IsVisibleViaTags(User user)
  1344. {
  1345. if (user.GetPreference(PreferenceKind.BlockedTags).Any(i => Tags.Contains(i, StringComparison.OrdinalIgnoreCase)))
  1346. {
  1347. return false;
  1348. }
  1349. return true;
  1350. }
  1351. protected virtual bool IsAllowTagFilterEnforced()
  1352. {
  1353. return true;
  1354. }
  1355. public virtual UnratedItem GetBlockUnratedType()
  1356. {
  1357. if (SourceType == SourceType.Channel)
  1358. {
  1359. return UnratedItem.ChannelContent;
  1360. }
  1361. return UnratedItem.Other;
  1362. }
  1363. /// <summary>
  1364. /// Gets the block unrated value.
  1365. /// </summary>
  1366. /// <param name="user">The configuration.</param>
  1367. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1368. protected virtual bool GetBlockUnratedValue(User user)
  1369. {
  1370. // Don't block plain folders that are unrated. Let the media underneath get blocked
  1371. // Special folders like series and albums will override this method.
  1372. if (IsFolder || this is IItemByName)
  1373. {
  1374. return false;
  1375. }
  1376. return user.GetPreferenceValues<UnratedItem>(PreferenceKind.BlockUnratedItems).Contains(GetBlockUnratedType());
  1377. }
  1378. /// <summary>
  1379. /// Determines if this folder should be visible to a given user.
  1380. /// Default is just parental allowed. Can be overridden for more functionality.
  1381. /// </summary>
  1382. /// <param name="user">The user.</param>
  1383. /// <returns><c>true</c> if the specified user is visible; otherwise, <c>false</c>.</returns>
  1384. /// <exception cref="ArgumentNullException"><paramref name="user" /> is <c>null</c>.</exception>
  1385. public virtual bool IsVisible(User user)
  1386. {
  1387. if (user == null)
  1388. {
  1389. throw new ArgumentNullException(nameof(user));
  1390. }
  1391. return IsParentalAllowed(user);
  1392. }
  1393. public virtual bool IsVisibleStandalone(User user)
  1394. {
  1395. if (SourceType == SourceType.Channel)
  1396. {
  1397. return IsVisibleStandaloneInternal(user, false) && Channel.IsChannelVisible(this, user);
  1398. }
  1399. return IsVisibleStandaloneInternal(user, true);
  1400. }
  1401. public virtual string GetClientTypeName()
  1402. {
  1403. if (IsFolder && SourceType == SourceType.Channel && this is not Channel)
  1404. {
  1405. return "ChannelFolderItem";
  1406. }
  1407. return GetType().Name;
  1408. }
  1409. public BaseItemKind GetBaseItemKind()
  1410. {
  1411. return _baseItemKind ??= Enum.Parse<BaseItemKind>(GetClientTypeName());
  1412. }
  1413. /// <summary>
  1414. /// Gets the linked child.
  1415. /// </summary>
  1416. /// <param name="info">The info.</param>
  1417. /// <returns>BaseItem.</returns>
  1418. protected BaseItem GetLinkedChild(LinkedChild info)
  1419. {
  1420. // First get using the cached Id
  1421. if (info.ItemId.HasValue)
  1422. {
  1423. if (info.ItemId.Value.Equals(Guid.Empty))
  1424. {
  1425. return null;
  1426. }
  1427. var itemById = LibraryManager.GetItemById(info.ItemId.Value);
  1428. if (itemById != null)
  1429. {
  1430. return itemById;
  1431. }
  1432. }
  1433. var item = FindLinkedChild(info);
  1434. // If still null, log
  1435. if (item == null)
  1436. {
  1437. // Don't keep searching over and over
  1438. info.ItemId = Guid.Empty;
  1439. }
  1440. else
  1441. {
  1442. // Cache the id for next time
  1443. info.ItemId = item.Id;
  1444. }
  1445. return item;
  1446. }
  1447. private BaseItem FindLinkedChild(LinkedChild info)
  1448. {
  1449. var path = info.Path;
  1450. if (!string.IsNullOrEmpty(path))
  1451. {
  1452. path = FileSystem.MakeAbsolutePath(ContainingFolderPath, path);
  1453. var itemByPath = LibraryManager.FindByPath(path, null);
  1454. if (itemByPath == null)
  1455. {
  1456. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1457. }
  1458. return itemByPath;
  1459. }
  1460. if (!string.IsNullOrEmpty(info.LibraryItemId))
  1461. {
  1462. var item = LibraryManager.GetItemById(info.LibraryItemId);
  1463. if (item == null)
  1464. {
  1465. Logger.LogWarning("Unable to find linked item at path {0}", info.Path);
  1466. }
  1467. return item;
  1468. }
  1469. return null;
  1470. }
  1471. /// <summary>
  1472. /// Adds a studio to the item.
  1473. /// </summary>
  1474. /// <param name="name">The name.</param>
  1475. /// <exception cref="ArgumentNullException">Throws if name is null.</exception>
  1476. public void AddStudio(string name)
  1477. {
  1478. if (string.IsNullOrEmpty(name))
  1479. {
  1480. throw new ArgumentNullException(nameof(name));
  1481. }
  1482. var current = Studios;
  1483. if (!current.Contains(name, StringComparison.OrdinalIgnoreCase))
  1484. {
  1485. int curLen = current.Length;
  1486. if (curLen == 0)
  1487. {
  1488. Studios = new[] { name };
  1489. }
  1490. else
  1491. {
  1492. var newArr = new string[curLen + 1];
  1493. current.CopyTo(newArr, 0);
  1494. newArr[curLen] = name;
  1495. Studios = newArr;
  1496. }
  1497. }
  1498. }
  1499. public void SetStudios(IEnumerable<string> names)
  1500. {
  1501. Studios = names.Distinct().ToArray();
  1502. }
  1503. /// <summary>
  1504. /// Adds a genre to the item.
  1505. /// </summary>
  1506. /// <param name="name">The name.</param>
  1507. /// <exception cref="ArgumentNullException">Throwns if name is null.</exception>
  1508. public void AddGenre(string name)
  1509. {
  1510. if (string.IsNullOrEmpty(name))
  1511. {
  1512. throw new ArgumentNullException(nameof(name));
  1513. }
  1514. var genres = Genres;
  1515. if (!genres.Contains(name, StringComparison.OrdinalIgnoreCase))
  1516. {
  1517. var list = genres.ToList();
  1518. list.Add(name);
  1519. Genres = list.ToArray();
  1520. }
  1521. }
  1522. /// <summary>
  1523. /// Marks the played.
  1524. /// </summary>
  1525. /// <param name="user">The user.</param>
  1526. /// <param name="datePlayed">The date played.</param>
  1527. /// <param name="resetPosition">if set to <c>true</c> [reset position].</param>
  1528. /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
  1529. public virtual void MarkPlayed(
  1530. User user,
  1531. DateTime? datePlayed,
  1532. bool resetPosition)
  1533. {
  1534. if (user == null)
  1535. {
  1536. throw new ArgumentNullException(nameof(user));
  1537. }
  1538. var data = UserDataManager.GetUserData(user, this);
  1539. if (datePlayed.HasValue)
  1540. {
  1541. // Increment
  1542. data.PlayCount++;
  1543. }
  1544. // Ensure it's at least one
  1545. data.PlayCount = Math.Max(data.PlayCount, 1);
  1546. if (resetPosition)
  1547. {
  1548. data.PlaybackPositionTicks = 0;
  1549. }
  1550. data.LastPlayedDate = datePlayed ?? data.LastPlayedDate ?? DateTime.UtcNow;
  1551. data.Played = true;
  1552. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1553. }
  1554. /// <summary>
  1555. /// Marks the unplayed.
  1556. /// </summary>
  1557. /// <param name="user">The user.</param>
  1558. /// <exception cref="ArgumentNullException">Throws if user is null.</exception>
  1559. public virtual void MarkUnplayed(User user)
  1560. {
  1561. if (user == null)
  1562. {
  1563. throw new ArgumentNullException(nameof(user));
  1564. }
  1565. var data = UserDataManager.GetUserData(user, this);
  1566. // I think it is okay to do this here.
  1567. // if this is only called when a user is manually forcing something to un-played
  1568. // then it probably is what we want to do...
  1569. data.PlayCount = 0;
  1570. data.PlaybackPositionTicks = 0;
  1571. data.LastPlayedDate = null;
  1572. data.Played = false;
  1573. UserDataManager.SaveUserData(user.Id, this, data, UserDataSaveReason.TogglePlayed, CancellationToken.None);
  1574. }
  1575. /// <summary>
  1576. /// Do whatever refreshing is necessary when the filesystem pertaining to this item has changed.
  1577. /// </summary>
  1578. public virtual void ChangedExternally()
  1579. {
  1580. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(new DirectoryService(FileSystem)), RefreshPriority.High);
  1581. }
  1582. /// <summary>
  1583. /// Gets an image.
  1584. /// </summary>
  1585. /// <param name="type">The type.</param>
  1586. /// <param name="imageIndex">Index of the image.</param>
  1587. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1588. /// <exception cref="ArgumentException">Backdrops should be accessed using Item.Backdrops.</exception>
  1589. public bool HasImage(ImageType type, int imageIndex)
  1590. {
  1591. return GetImageInfo(type, imageIndex) != null;
  1592. }
  1593. public void SetImage(ItemImageInfo image, int index)
  1594. {
  1595. if (image.Type == ImageType.Chapter)
  1596. {
  1597. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1598. }
  1599. var existingImage = GetImageInfo(image.Type, index);
  1600. if (existingImage == null)
  1601. {
  1602. AddImage(image);
  1603. }
  1604. else
  1605. {
  1606. existingImage.Path = image.Path;
  1607. existingImage.DateModified = image.DateModified;
  1608. existingImage.Width = image.Width;
  1609. existingImage.Height = image.Height;
  1610. existingImage.BlurHash = image.BlurHash;
  1611. }
  1612. }
  1613. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1614. {
  1615. if (type == ImageType.Chapter)
  1616. {
  1617. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1618. }
  1619. var image = GetImageInfo(type, index);
  1620. if (image == null)
  1621. {
  1622. AddImage(GetImageInfo(file, type));
  1623. }
  1624. else
  1625. {
  1626. var imageInfo = GetImageInfo(file, type);
  1627. image.Path = file.FullName;
  1628. image.DateModified = imageInfo.DateModified;
  1629. // reset these values
  1630. image.Width = 0;
  1631. image.Height = 0;
  1632. }
  1633. }
  1634. /// <summary>
  1635. /// Deletes the image.
  1636. /// </summary>
  1637. /// <param name="type">The type.</param>
  1638. /// <param name="index">The index.</param>
  1639. /// <returns>A task.</returns>
  1640. public async Task DeleteImageAsync(ImageType type, int index)
  1641. {
  1642. var info = GetImageInfo(type, index);
  1643. if (info == null)
  1644. {
  1645. // Nothing to do
  1646. return;
  1647. }
  1648. // Remove it from the item
  1649. RemoveImage(info);
  1650. if (info.IsLocalFile)
  1651. {
  1652. FileSystem.DeleteFile(info.Path);
  1653. }
  1654. await UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None).ConfigureAwait(false);
  1655. }
  1656. public void RemoveImage(ItemImageInfo image)
  1657. {
  1658. RemoveImages(new[] { image });
  1659. }
  1660. public void RemoveImages(IEnumerable<ItemImageInfo> deletedImages)
  1661. {
  1662. ImageInfos = ImageInfos.Except(deletedImages).ToArray();
  1663. }
  1664. public void AddImage(ItemImageInfo image)
  1665. {
  1666. var current = ImageInfos;
  1667. var currentCount = current.Length;
  1668. var newArr = new ItemImageInfo[currentCount + 1];
  1669. current.CopyTo(newArr, 0);
  1670. newArr[currentCount] = image;
  1671. ImageInfos = newArr;
  1672. }
  1673. public virtual Task UpdateToRepositoryAsync(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1674. => LibraryManager.UpdateItemAsync(this, GetParent(), updateReason, cancellationToken);
  1675. /// <summary>
  1676. /// Validates that images within the item are still on the filesystem.
  1677. /// </summary>
  1678. /// <param name="directoryService">The directory service to use.</param>
  1679. /// <returns><c>true</c> if the images validate, <c>false</c> if not.</returns>
  1680. public bool ValidateImages(IDirectoryService directoryService)
  1681. {
  1682. var allFiles = ImageInfos
  1683. .Where(i => i.IsLocalFile)
  1684. .Select(i => System.IO.Path.GetDirectoryName(i.Path))
  1685. .Distinct(StringComparer.OrdinalIgnoreCase)
  1686. .SelectMany(path => directoryService.GetFilePaths(path))
  1687. .ToList();
  1688. var deletedImages = ImageInfos
  1689. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparison.OrdinalIgnoreCase))
  1690. .ToList();
  1691. if (deletedImages.Count > 0)
  1692. {
  1693. RemoveImages(deletedImages);
  1694. }
  1695. return deletedImages.Count > 0;
  1696. }
  1697. /// <summary>
  1698. /// Gets the image path.
  1699. /// </summary>
  1700. /// <param name="imageType">Type of the image.</param>
  1701. /// <param name="imageIndex">Index of the image.</param>
  1702. /// <returns>System.String.</returns>
  1703. /// <exception cref="ArgumentNullException">Item is null.</exception>
  1704. public string GetImagePath(ImageType imageType, int imageIndex)
  1705. => GetImageInfo(imageType, imageIndex)?.Path;
  1706. /// <summary>
  1707. /// Gets the image information.
  1708. /// </summary>
  1709. /// <param name="imageType">Type of the image.</param>
  1710. /// <param name="imageIndex">Index of the image.</param>
  1711. /// <returns>ItemImageInfo.</returns>
  1712. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1713. {
  1714. if (imageType == ImageType.Chapter)
  1715. {
  1716. var chapter = ItemRepository.GetChapter(this, imageIndex);
  1717. if (chapter == null)
  1718. {
  1719. return null;
  1720. }
  1721. var path = chapter.ImagePath;
  1722. if (string.IsNullOrEmpty(path))
  1723. {
  1724. return null;
  1725. }
  1726. return new ItemImageInfo
  1727. {
  1728. Path = path,
  1729. DateModified = chapter.ImageDateModified,
  1730. Type = imageType
  1731. };
  1732. }
  1733. // Music albums usually don't have dedicated backdrops, so return one from the artist instead
  1734. if (GetType() == typeof(MusicAlbum) && imageType == ImageType.Backdrop)
  1735. {
  1736. var artist = FindParent<MusicArtist>();
  1737. if (artist != null)
  1738. {
  1739. return artist.GetImages(imageType).ElementAtOrDefault(imageIndex);
  1740. }
  1741. }
  1742. return GetImages(imageType)
  1743. .ElementAtOrDefault(imageIndex);
  1744. }
  1745. /// <summary>
  1746. /// Computes image index for given image or raises if no matching image found.
  1747. /// </summary>
  1748. /// <param name="image">Image to compute index for.</param>
  1749. /// <exception cref="ArgumentException">Image index cannot be computed as no matching image found.
  1750. /// </exception>
  1751. /// <returns>Image index.</returns>
  1752. public int GetImageIndex(ItemImageInfo image)
  1753. {
  1754. if (image == null)
  1755. {
  1756. throw new ArgumentNullException(nameof(image));
  1757. }
  1758. if (image.Type == ImageType.Chapter)
  1759. {
  1760. var chapters = ItemRepository.GetChapters(this);
  1761. for (var i = 0; i < chapters.Count; i++)
  1762. {
  1763. if (chapters[i].ImagePath == image.Path)
  1764. {
  1765. return i;
  1766. }
  1767. }
  1768. throw new ArgumentException("No chapter index found for image path", image.Path);
  1769. }
  1770. var images = GetImages(image.Type).ToArray();
  1771. for (var i = 0; i < images.Length; i++)
  1772. {
  1773. if (images[i].Path == image.Path)
  1774. {
  1775. return i;
  1776. }
  1777. }
  1778. throw new ArgumentException("No image index found for image path", image.Path);
  1779. }
  1780. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1781. {
  1782. if (imageType == ImageType.Chapter)
  1783. {
  1784. throw new ArgumentException("No image info for chapter images");
  1785. }
  1786. // Yield return is more performant than LINQ Where on an Array
  1787. for (var i = 0; i < ImageInfos.Length; i++)
  1788. {
  1789. var imageInfo = ImageInfos[i];
  1790. if (imageInfo.Type == imageType)
  1791. {
  1792. yield return imageInfo;
  1793. }
  1794. }
  1795. }
  1796. /// <summary>
  1797. /// Adds the images, updating metadata if they already are part of this item.
  1798. /// </summary>
  1799. /// <param name="imageType">Type of the image.</param>
  1800. /// <param name="images">The images.</param>
  1801. /// <returns><c>true</c> if images were added or updated, <c>false</c> otherwise.</returns>
  1802. /// <exception cref="ArgumentException">Cannot call AddImages with chapter images.</exception>
  1803. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1804. {
  1805. if (imageType == ImageType.Chapter)
  1806. {
  1807. throw new ArgumentException("Cannot call AddImages with chapter images");
  1808. }
  1809. var existingImages = GetImages(imageType)
  1810. .ToList();
  1811. var newImageList = new List<FileSystemMetadata>();
  1812. var imageUpdated = false;
  1813. foreach (var newImage in images)
  1814. {
  1815. if (newImage == null)
  1816. {
  1817. throw new ArgumentException("null image found in list");
  1818. }
  1819. var existing = existingImages
  1820. .Find(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1821. if (existing == null)
  1822. {
  1823. newImageList.Add(newImage);
  1824. }
  1825. else
  1826. {
  1827. if (existing.IsLocalFile)
  1828. {
  1829. var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1830. // If date changed then we need to reset saved image dimensions
  1831. if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
  1832. {
  1833. existing.Width = 0;
  1834. existing.Height = 0;
  1835. imageUpdated = true;
  1836. }
  1837. existing.DateModified = newDateModified;
  1838. }
  1839. }
  1840. }
  1841. if (newImageList.Count > 0)
  1842. {
  1843. ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
  1844. }
  1845. return imageUpdated || newImageList.Count > 0;
  1846. }
  1847. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1848. {
  1849. return new ItemImageInfo
  1850. {
  1851. Path = file.FullName,
  1852. Type = type,
  1853. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1854. };
  1855. }
  1856. /// <summary>
  1857. /// Gets the file system path to delete when the item is to be deleted.
  1858. /// </summary>
  1859. /// <returns>The metadata for the deleted paths.</returns>
  1860. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  1861. {
  1862. return new[]
  1863. {
  1864. new FileSystemMetadata
  1865. {
  1866. FullName = Path,
  1867. IsDirectory = IsFolder
  1868. }
  1869. }.Concat(GetLocalMetadataFilesToDelete());
  1870. }
  1871. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  1872. {
  1873. if (IsFolder || !IsInMixedFolder)
  1874. {
  1875. return new List<FileSystemMetadata>();
  1876. }
  1877. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  1878. return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), _supportedExtensions, false, false)
  1879. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  1880. .ToList();
  1881. }
  1882. public bool AllowsMultipleImages(ImageType type)
  1883. {
  1884. return type == ImageType.Backdrop || type == ImageType.Chapter;
  1885. }
  1886. public Task SwapImagesAsync(ImageType type, int index1, int index2)
  1887. {
  1888. if (!AllowsMultipleImages(type))
  1889. {
  1890. throw new ArgumentException("The change index operation is only applicable to backdrops and screen shots");
  1891. }
  1892. var info1 = GetImageInfo(type, index1);
  1893. var info2 = GetImageInfo(type, index2);
  1894. if (info1 == null || info2 == null)
  1895. {
  1896. // Nothing to do
  1897. return Task.CompletedTask;
  1898. }
  1899. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1900. {
  1901. // TODO: Not supported yet
  1902. return Task.CompletedTask;
  1903. }
  1904. var path1 = info1.Path;
  1905. var path2 = info2.Path;
  1906. FileSystem.SwapFiles(path1, path2);
  1907. // Refresh these values
  1908. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1909. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1910. info1.Width = 0;
  1911. info1.Height = 0;
  1912. info2.Width = 0;
  1913. info2.Height = 0;
  1914. return UpdateToRepositoryAsync(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1915. }
  1916. public virtual bool IsPlayed(User user)
  1917. {
  1918. var userdata = UserDataManager.GetUserData(user, this);
  1919. return userdata != null && userdata.Played;
  1920. }
  1921. public bool IsFavoriteOrLiked(User user)
  1922. {
  1923. var userdata = UserDataManager.GetUserData(user, this);
  1924. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1925. }
  1926. public virtual bool IsUnplayed(User user)
  1927. {
  1928. if (user == null)
  1929. {
  1930. throw new ArgumentNullException(nameof(user));
  1931. }
  1932. var userdata = UserDataManager.GetUserData(user, this);
  1933. return userdata == null || !userdata.Played;
  1934. }
  1935. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1936. {
  1937. return GetItemLookupInfo<ItemLookupInfo>();
  1938. }
  1939. protected T GetItemLookupInfo<T>()
  1940. where T : ItemLookupInfo, new()
  1941. {
  1942. return new T
  1943. {
  1944. Path = Path,
  1945. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1946. MetadataLanguage = GetPreferredMetadataLanguage(),
  1947. Name = GetNameForMetadataLookup(),
  1948. OriginalTitle = OriginalTitle,
  1949. ProviderIds = ProviderIds,
  1950. IndexNumber = IndexNumber,
  1951. ParentIndexNumber = ParentIndexNumber,
  1952. Year = ProductionYear,
  1953. PremiereDate = PremiereDate
  1954. };
  1955. }
  1956. protected virtual string GetNameForMetadataLookup()
  1957. {
  1958. return Name;
  1959. }
  1960. /// <summary>
  1961. /// This is called before any metadata refresh and returns true if changes were made.
  1962. /// </summary>
  1963. /// <param name="replaceAllMetadata">Whether to replace all metadata.</param>
  1964. /// <returns>true if the item has change, else false.</returns>
  1965. public virtual bool BeforeMetadataRefresh(bool replaceAllMetadata)
  1966. {
  1967. _sortName = null;
  1968. var hasChanges = false;
  1969. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1970. {
  1971. Name = System.IO.Path.GetFileNameWithoutExtension(Path);
  1972. hasChanges = true;
  1973. }
  1974. return hasChanges;
  1975. }
  1976. protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
  1977. {
  1978. if (protocol == MediaProtocol.File)
  1979. {
  1980. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  1981. }
  1982. return path;
  1983. }
  1984. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  1985. {
  1986. if (RunTimeTicks.HasValue)
  1987. {
  1988. double pct = RunTimeTicks.Value;
  1989. if (pct > 0)
  1990. {
  1991. pct = userData.PlaybackPositionTicks / pct;
  1992. if (pct > 0)
  1993. {
  1994. dto.PlayedPercentage = 100 * pct;
  1995. }
  1996. }
  1997. }
  1998. }
  1999. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  2000. {
  2001. var newOptions = new MetadataRefreshOptions(options)
  2002. {
  2003. SearchResult = null
  2004. };
  2005. var item = this;
  2006. if (copyTitleMetadata)
  2007. {
  2008. // Take some data from the main item, for querying purposes
  2009. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  2010. {
  2011. newOptions.ForceSave = true;
  2012. ownedItem.Genres = item.Genres;
  2013. }
  2014. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  2015. {
  2016. newOptions.ForceSave = true;
  2017. ownedItem.Studios = item.Studios;
  2018. }
  2019. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  2020. {
  2021. newOptions.ForceSave = true;
  2022. ownedItem.ProductionLocations = item.ProductionLocations;
  2023. }
  2024. if (item.CommunityRating != ownedItem.CommunityRating)
  2025. {
  2026. ownedItem.CommunityRating = item.CommunityRating;
  2027. newOptions.ForceSave = true;
  2028. }
  2029. if (item.CriticRating != ownedItem.CriticRating)
  2030. {
  2031. ownedItem.CriticRating = item.CriticRating;
  2032. newOptions.ForceSave = true;
  2033. }
  2034. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  2035. {
  2036. ownedItem.Overview = item.Overview;
  2037. newOptions.ForceSave = true;
  2038. }
  2039. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  2040. {
  2041. ownedItem.OfficialRating = item.OfficialRating;
  2042. newOptions.ForceSave = true;
  2043. }
  2044. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  2045. {
  2046. ownedItem.CustomRating = item.CustomRating;
  2047. newOptions.ForceSave = true;
  2048. }
  2049. }
  2050. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  2051. }
  2052. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2053. {
  2054. var newOptions = new MetadataRefreshOptions(options)
  2055. {
  2056. SearchResult = null
  2057. };
  2058. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2059. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2060. var video = LibraryManager.GetItemById(id) as Video;
  2061. if (video == null)
  2062. {
  2063. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2064. newOptions.ForceSave = true;
  2065. }
  2066. if (video == null)
  2067. {
  2068. return Task.FromResult(true);
  2069. }
  2070. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  2071. }
  2072. public string GetEtag(User user)
  2073. {
  2074. var list = GetEtagValues(user);
  2075. return string.Join('|', list).GetMD5().ToString("N", CultureInfo.InvariantCulture);
  2076. }
  2077. protected virtual List<string> GetEtagValues(User user)
  2078. {
  2079. return new List<string>
  2080. {
  2081. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2082. };
  2083. }
  2084. public virtual IEnumerable<Guid> GetAncestorIds()
  2085. {
  2086. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2087. }
  2088. public BaseItem GetTopParent()
  2089. {
  2090. if (IsTopParent)
  2091. {
  2092. return this;
  2093. }
  2094. return GetParents().FirstOrDefault(parent => parent.IsTopParent);
  2095. }
  2096. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2097. {
  2098. return new[] { Id };
  2099. }
  2100. public virtual List<ExternalUrl> GetRelatedUrls()
  2101. {
  2102. return new List<ExternalUrl>();
  2103. }
  2104. public virtual double? GetRefreshProgress()
  2105. {
  2106. return null;
  2107. }
  2108. public virtual ItemUpdateType OnMetadataChanged()
  2109. {
  2110. var updateType = ItemUpdateType.None;
  2111. var item = this;
  2112. var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? 0;
  2113. if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
  2114. {
  2115. item.InheritedParentalRatingValue = inheritedParentalRatingValue;
  2116. updateType |= ItemUpdateType.MetadataImport;
  2117. }
  2118. return updateType;
  2119. }
  2120. /// <summary>
  2121. /// Updates the official rating based on content and returns true or false indicating if it changed.
  2122. /// </summary>
  2123. /// <param name="children">Media children.</param>
  2124. /// <returns><c>true</c> if the rating was updated; otherwise <c>false</c>.</returns>
  2125. public bool UpdateRatingToItems(IList<BaseItem> children)
  2126. {
  2127. var currentOfficialRating = OfficialRating;
  2128. // Gather all possible ratings
  2129. var ratings = children
  2130. .Select(i => i.OfficialRating)
  2131. .Where(i => !string.IsNullOrEmpty(i))
  2132. .Distinct(StringComparer.OrdinalIgnoreCase)
  2133. .Select(rating => (rating, LocalizationManager.GetRatingLevel(rating)))
  2134. .OrderBy(i => i.Item2 ?? 1000)
  2135. .Select(i => i.rating);
  2136. OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
  2137. return !string.Equals(
  2138. currentOfficialRating ?? string.Empty,
  2139. OfficialRating ?? string.Empty,
  2140. StringComparison.OrdinalIgnoreCase);
  2141. }
  2142. public IReadOnlyList<BaseItem> GetThemeSongs()
  2143. {
  2144. return GetExtras().Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeSong).ToArray();
  2145. }
  2146. public IReadOnlyList<BaseItem> GetThemeVideos()
  2147. {
  2148. return GetExtras().Where(e => e.ExtraType == Model.Entities.ExtraType.ThemeVideo).ToArray();
  2149. }
  2150. /// <summary>
  2151. /// Get all extras associated with this item, sorted by <see cref="SortName"/>.
  2152. /// </summary>
  2153. /// <returns>An enumerable containing the items.</returns>
  2154. public IEnumerable<BaseItem> GetExtras()
  2155. {
  2156. return ExtraIds
  2157. .Select(LibraryManager.GetItemById)
  2158. .Where(i => i != null)
  2159. .OrderBy(i => i.SortName);
  2160. }
  2161. /// <summary>
  2162. /// Get all extras with specific types that are associated with this item.
  2163. /// </summary>
  2164. /// <param name="extraTypes">The types of extras to retrieve.</param>
  2165. /// <returns>An enumerable containing the extras.</returns>
  2166. public IEnumerable<BaseItem> GetExtras(IReadOnlyCollection<ExtraType> extraTypes)
  2167. {
  2168. return ExtraIds
  2169. .Select(LibraryManager.GetItemById)
  2170. .Where(i => i != null)
  2171. .Where(i => i.ExtraType.HasValue && extraTypes.Contains(i.ExtraType.Value));
  2172. }
  2173. public virtual long GetRunTimeTicksForPlayState()
  2174. {
  2175. return RunTimeTicks ?? 0;
  2176. }
  2177. /// <inheritdoc />
  2178. public override bool Equals(object obj)
  2179. {
  2180. return obj is BaseItem baseItem && this.Equals(baseItem);
  2181. }
  2182. /// <inheritdoc />
  2183. public bool Equals(BaseItem other) => Id == other?.Id;
  2184. /// <inheritdoc />
  2185. public override int GetHashCode() => HashCode.Combine(Id);
  2186. }
  2187. }