BaseItem.cs 91 KB

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