BaseItem.cs 96 KB

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