BaseItem.cs 86 KB

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