BaseItem.cs 92 KB

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