BaseItem.cs 81 KB

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