BaseItem.cs 95 KB

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