BaseItem.cs 95 KB

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