BaseItem.cs 93 KB

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