2
0

BaseItem.cs 81 KB

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