BaseItem.cs 93 KB

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