BaseItem.cs 95 KB

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