BaseItem.cs 94 KB

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