BaseItem.cs 81 KB

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