BaseItem.cs 94 KB

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