BaseItem.cs 94 KB

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