BaseItem.cs 89 KB

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