BaseItem.cs 93 KB

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