BaseItem.cs 89 KB

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