BaseItem.cs 97 KB

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