BaseItem.cs 96 KB

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