BaseItem.cs 95 KB

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