BaseItem.cs 95 KB

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