BaseItem.cs 81 KB

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