2
0

BaseItem.cs 94 KB

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