BaseItem.cs 96 KB

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