BaseItem.cs 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Threading.Tasks;
  9. using MediaBrowser.Common.Extensions;
  10. using MediaBrowser.Controller.Channels;
  11. using MediaBrowser.Controller.Configuration;
  12. using MediaBrowser.Controller.Dto;
  13. using MediaBrowser.Controller.Extensions;
  14. using MediaBrowser.Controller.Library;
  15. using MediaBrowser.Controller.Persistence;
  16. using MediaBrowser.Controller.Providers;
  17. using MediaBrowser.Controller.Sorting;
  18. using MediaBrowser.Model.Configuration;
  19. using MediaBrowser.Model.Dto;
  20. using MediaBrowser.Model.Entities;
  21. using MediaBrowser.Model.Extensions;
  22. using MediaBrowser.Model.Globalization;
  23. using MediaBrowser.Model.IO;
  24. using MediaBrowser.Model.Library;
  25. using MediaBrowser.Model.LiveTv;
  26. using MediaBrowser.Model.MediaInfo;
  27. using MediaBrowser.Model.Providers;
  28. using MediaBrowser.Model.Serialization;
  29. using MediaBrowser.Model.Users;
  30. using Microsoft.Extensions.Logging;
  31. namespace MediaBrowser.Controller.Entities
  32. {
  33. /// <summary>
  34. /// Class BaseItem
  35. /// </summary>
  36. public abstract class BaseItem : IHasProviderIds, IHasLookupInfo<ItemLookupInfo>
  37. {
  38. protected static MetadataFields[] EmptyMetadataFieldsArray = Array.Empty<MetadataFields>();
  39. protected static MediaUrl[] EmptyMediaUrlArray = Array.Empty<MediaUrl>();
  40. protected static ItemImageInfo[] EmptyItemImageInfoArray = Array.Empty<ItemImageInfo>();
  41. public static readonly LinkedChild[] EmptyLinkedChildArray = Array.Empty<LinkedChild>();
  42. protected BaseItem()
  43. {
  44. ThemeSongIds = Array.Empty<Guid>();
  45. ThemeVideoIds = Array.Empty<Guid>();
  46. Tags = Array.Empty<string>();
  47. Genres = Array.Empty<string>();
  48. Studios = Array.Empty<string>();
  49. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  50. LockedFields = EmptyMetadataFieldsArray;
  51. ImageInfos = EmptyItemImageInfoArray;
  52. ProductionLocations = Array.Empty<string>();
  53. RemoteTrailers = Array.Empty<MediaUrl>();
  54. ExtraIds = Array.Empty<Guid>();
  55. }
  56. public static readonly char[] SlugReplaceChars = { '?', '/', '&' };
  57. public static char SlugChar = '-';
  58. /// <summary>
  59. /// The supported image extensions
  60. /// </summary>
  61. public static readonly string[] SupportedImageExtensions = { ".png", ".jpg", ".jpeg", ".tbn", ".gif" };
  62. /// <summary>
  63. /// The trailer folder name
  64. /// </summary>
  65. public static string TrailerFolderName = "trailers";
  66. public static string ThemeSongsFolderName = "theme-music";
  67. public static string ThemeSongFilename = "theme";
  68. public static string ThemeVideosFolderName = "backdrops";
  69. [IgnoreDataMember]
  70. public Guid[] ThemeSongIds { get; set; }
  71. [IgnoreDataMember]
  72. public Guid[] ThemeVideoIds { get; set; }
  73. [IgnoreDataMember]
  74. public string PreferredMetadataCountryCode { get; set; }
  75. [IgnoreDataMember]
  76. public string PreferredMetadataLanguage { get; set; }
  77. public long? Size { get; set; }
  78. public string Container { get; set; }
  79. [IgnoreDataMember]
  80. public string Tagline { get; set; }
  81. [IgnoreDataMember]
  82. public virtual ItemImageInfo[] ImageInfos { get; set; }
  83. [IgnoreDataMember]
  84. public bool IsVirtualItem { get; set; }
  85. /// <summary>
  86. /// Gets or sets the album.
  87. /// </summary>
  88. /// <value>The album.</value>
  89. [IgnoreDataMember]
  90. public string Album { get; set; }
  91. /// <summary>
  92. /// Gets or sets the channel identifier.
  93. /// </summary>
  94. /// <value>The channel identifier.</value>
  95. [IgnoreDataMember]
  96. public Guid ChannelId { get; set; }
  97. [IgnoreDataMember]
  98. public virtual bool SupportsAddingToPlaylist => false;
  99. [IgnoreDataMember]
  100. public virtual bool AlwaysScanInternalMetadataPath => false;
  101. /// <summary>
  102. /// Gets a value indicating whether this instance is in mixed folder.
  103. /// </summary>
  104. /// <value><c>true</c> if this instance is in mixed folder; otherwise, <c>false</c>.</value>
  105. [IgnoreDataMember]
  106. public bool IsInMixedFolder { get; set; }
  107. [IgnoreDataMember]
  108. public virtual bool SupportsPlayedStatus => false;
  109. [IgnoreDataMember]
  110. public virtual bool SupportsPositionTicksResume => false;
  111. [IgnoreDataMember]
  112. public virtual bool SupportsRemoteImageDownloading => true;
  113. private string _name;
  114. /// <summary>
  115. /// Gets or sets the name.
  116. /// </summary>
  117. /// <value>The name.</value>
  118. [IgnoreDataMember]
  119. public virtual string Name
  120. {
  121. get => _name;
  122. set
  123. {
  124. _name = value;
  125. // lazy load this again
  126. _sortName = null;
  127. }
  128. }
  129. [IgnoreDataMember]
  130. public bool IsUnaired => PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date;
  131. [IgnoreDataMember]
  132. public int? TotalBitrate { get; set; }
  133. [IgnoreDataMember]
  134. public ExtraType? ExtraType { get; set; }
  135. [IgnoreDataMember]
  136. public bool IsThemeMedia => ExtraType.HasValue && (ExtraType.Value == Model.Entities.ExtraType.ThemeSong || ExtraType.Value == Model.Entities.ExtraType.ThemeVideo);
  137. [IgnoreDataMember]
  138. public string OriginalTitle { get; set; }
  139. /// <summary>
  140. /// Gets or sets the id.
  141. /// </summary>
  142. /// <value>The id.</value>
  143. [IgnoreDataMember]
  144. public Guid Id { get; set; }
  145. [IgnoreDataMember]
  146. public Guid OwnerId { get; set; }
  147. /// <summary>
  148. /// Gets or sets the audio.
  149. /// </summary>
  150. /// <value>The audio.</value>
  151. [IgnoreDataMember]
  152. public ProgramAudio? Audio { get; set; }
  153. /// <summary>
  154. /// Return the id that should be used to key display prefs for this item.
  155. /// Default is based on the type for everything except actual generic folders.
  156. /// </summary>
  157. /// <value>The display prefs id.</value>
  158. [IgnoreDataMember]
  159. public virtual Guid DisplayPreferencesId
  160. {
  161. get
  162. {
  163. var thisType = GetType();
  164. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  165. }
  166. }
  167. /// <summary>
  168. /// Gets or sets the path.
  169. /// </summary>
  170. /// <value>The path.</value>
  171. [IgnoreDataMember]
  172. public virtual string Path { get; set; }
  173. [IgnoreDataMember]
  174. public virtual SourceType SourceType
  175. {
  176. get
  177. {
  178. if (!ChannelId.Equals(Guid.Empty))
  179. {
  180. return SourceType.Channel;
  181. }
  182. return SourceType.Library;
  183. }
  184. }
  185. /// <summary>
  186. /// Returns the folder containing the item.
  187. /// If the item is a folder, it returns the folder itself
  188. /// </summary>
  189. [IgnoreDataMember]
  190. public virtual string ContainingFolderPath
  191. {
  192. get
  193. {
  194. if (IsFolder)
  195. {
  196. return Path;
  197. }
  198. return System.IO.Path.GetDirectoryName(Path);
  199. }
  200. }
  201. /// <summary>
  202. /// Gets or sets the name of the service.
  203. /// </summary>
  204. /// <value>The name of the service.</value>
  205. [IgnoreDataMember]
  206. public string ServiceName { get; set; }
  207. /// <summary>
  208. /// If this content came from an external service, the id of the content on that service
  209. /// </summary>
  210. [IgnoreDataMember]
  211. public string ExternalId { get; set; }
  212. [IgnoreDataMember]
  213. public string ExternalSeriesId { get; set; }
  214. /// <summary>
  215. /// Gets or sets the etag.
  216. /// </summary>
  217. /// <value>The etag.</value>
  218. [IgnoreDataMember]
  219. public string ExternalEtag { get; set; }
  220. [IgnoreDataMember]
  221. public virtual bool IsHidden => false;
  222. public BaseItem GetOwner()
  223. {
  224. var ownerId = OwnerId;
  225. return ownerId.Equals(Guid.Empty) ? null : LibraryManager.GetItemById(ownerId);
  226. }
  227. /// <summary>
  228. /// Gets or sets the type of the location.
  229. /// </summary>
  230. /// <value>The type of the location.</value>
  231. [IgnoreDataMember]
  232. public virtual LocationType LocationType
  233. {
  234. get
  235. {
  236. //if (IsOffline)
  237. //{
  238. // return LocationType.Offline;
  239. //}
  240. var path = Path;
  241. if (string.IsNullOrEmpty(path))
  242. {
  243. if (SourceType == SourceType.Channel)
  244. {
  245. return LocationType.Remote;
  246. }
  247. return LocationType.Virtual;
  248. }
  249. return FileSystem.IsPathFile(path) ? LocationType.FileSystem : LocationType.Remote;
  250. }
  251. }
  252. [IgnoreDataMember]
  253. public MediaProtocol? PathProtocol
  254. {
  255. get
  256. {
  257. var path = Path;
  258. if (string.IsNullOrEmpty(path))
  259. {
  260. return null;
  261. }
  262. return MediaSourceManager.GetPathProtocol(path);
  263. }
  264. }
  265. public bool IsPathProtocol(MediaProtocol protocol)
  266. {
  267. var current = PathProtocol;
  268. return current.HasValue && current.Value == protocol;
  269. }
  270. [IgnoreDataMember]
  271. public bool IsFileProtocol => IsPathProtocol(MediaProtocol.File);
  272. [IgnoreDataMember]
  273. public bool HasPathProtocol => PathProtocol.HasValue;
  274. [IgnoreDataMember]
  275. public virtual bool SupportsLocalMetadata
  276. {
  277. get
  278. {
  279. if (SourceType == SourceType.Channel)
  280. {
  281. return false;
  282. }
  283. return IsFileProtocol;
  284. }
  285. }
  286. [IgnoreDataMember]
  287. public virtual string FileNameWithoutExtension
  288. {
  289. get
  290. {
  291. if (IsFileProtocol)
  292. {
  293. return System.IO.Path.GetFileNameWithoutExtension(Path);
  294. }
  295. return null;
  296. }
  297. }
  298. [IgnoreDataMember]
  299. public virtual bool EnableAlphaNumericSorting => true;
  300. private List<Tuple<StringBuilder, bool>> GetSortChunks(string s1)
  301. {
  302. var list = new List<Tuple<StringBuilder, bool>>();
  303. int thisMarker = 0;
  304. while (thisMarker < s1.Length)
  305. {
  306. if (thisMarker >= s1.Length)
  307. {
  308. break;
  309. }
  310. char thisCh = s1[thisMarker];
  311. var thisChunk = new StringBuilder();
  312. while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || SortHelper.InChunk(thisCh, thisChunk[0])))
  313. {
  314. thisChunk.Append(thisCh);
  315. thisMarker++;
  316. if (thisMarker < s1.Length)
  317. {
  318. thisCh = s1[thisMarker];
  319. }
  320. }
  321. var isNumeric = thisChunk.Length > 0 && char.IsDigit(thisChunk[0]);
  322. list.Add(new Tuple<StringBuilder, bool>(thisChunk, isNumeric));
  323. }
  324. return list;
  325. }
  326. /// <summary>
  327. /// This is just a helper for convenience
  328. /// </summary>
  329. /// <value>The primary image path.</value>
  330. [IgnoreDataMember]
  331. public string PrimaryImagePath => this.GetImagePath(ImageType.Primary);
  332. public bool IsMetadataFetcherEnabled(LibraryOptions libraryOptions, string name)
  333. {
  334. if (SourceType == SourceType.Channel)
  335. {
  336. // hack alert
  337. return !EnableMediaSourceDisplay;
  338. }
  339. var typeOptions = libraryOptions.GetTypeOptions(GetType().Name);
  340. if (typeOptions != null)
  341. {
  342. return typeOptions.MetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
  343. }
  344. if (!libraryOptions.EnableInternetProviders)
  345. {
  346. return false;
  347. }
  348. var itemConfig = ConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase));
  349. return itemConfig == null || !itemConfig.DisabledMetadataFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
  350. }
  351. public bool IsImageFetcherEnabled(LibraryOptions libraryOptions, string name)
  352. {
  353. if (this is Channel)
  354. {
  355. // hack alert
  356. return true;
  357. }
  358. if (SourceType == SourceType.Channel)
  359. {
  360. // hack alert
  361. return !EnableMediaSourceDisplay;
  362. }
  363. var typeOptions = libraryOptions.GetTypeOptions(GetType().Name);
  364. if (typeOptions != null)
  365. {
  366. return typeOptions.ImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
  367. }
  368. if (!libraryOptions.EnableInternetProviders)
  369. {
  370. return false;
  371. }
  372. var itemConfig = ConfigurationManager.Configuration.MetadataOptions.FirstOrDefault(i => string.Equals(i.ItemType, GetType().Name, StringComparison.OrdinalIgnoreCase));
  373. return itemConfig == null || !itemConfig.DisabledImageFetchers.Contains(name, StringComparer.OrdinalIgnoreCase);
  374. }
  375. public virtual bool CanDelete()
  376. {
  377. if (SourceType == SourceType.Channel)
  378. {
  379. return ChannelManager.CanDelete(this);
  380. }
  381. return IsFileProtocol;
  382. }
  383. public virtual bool IsAuthorizedToDelete(User user, List<Folder> allCollectionFolders)
  384. {
  385. if (user.Policy.EnableContentDeletion)
  386. {
  387. return true;
  388. }
  389. var allowed = user.Policy.EnableContentDeletionFromFolders;
  390. if (SourceType == SourceType.Channel)
  391. {
  392. return allowed.Contains(ChannelId.ToString(""), StringComparer.OrdinalIgnoreCase);
  393. }
  394. else
  395. {
  396. var collectionFolders = LibraryManager.GetCollectionFolders(this, allCollectionFolders);
  397. foreach (var folder in collectionFolders)
  398. {
  399. if (allowed.Contains(folder.Id.ToString("N"), StringComparer.OrdinalIgnoreCase))
  400. {
  401. return true;
  402. }
  403. }
  404. }
  405. return false;
  406. }
  407. public bool CanDelete(User user, List<Folder> allCollectionFolders)
  408. {
  409. return CanDelete() && IsAuthorizedToDelete(user, allCollectionFolders);
  410. }
  411. public bool CanDelete(User user)
  412. {
  413. var allCollectionFolders = LibraryManager.GetUserRootFolder().Children.OfType<Folder>().ToList();
  414. return CanDelete(user, allCollectionFolders);
  415. }
  416. public virtual bool CanDownload()
  417. {
  418. return false;
  419. }
  420. public virtual bool IsAuthorizedToDownload(User user)
  421. {
  422. return user.Policy.EnableContentDownloading;
  423. }
  424. public bool CanDownload(User user)
  425. {
  426. return CanDownload() && IsAuthorizedToDownload(user);
  427. }
  428. /// <summary>
  429. /// Gets or sets the date created.
  430. /// </summary>
  431. /// <value>The date created.</value>
  432. [IgnoreDataMember]
  433. public DateTime DateCreated { get; set; }
  434. /// <summary>
  435. /// Gets or sets the date modified.
  436. /// </summary>
  437. /// <value>The date modified.</value>
  438. [IgnoreDataMember]
  439. public DateTime DateModified { get; set; }
  440. [IgnoreDataMember]
  441. public DateTime DateLastSaved { get; set; }
  442. [IgnoreDataMember]
  443. public DateTime DateLastRefreshed { get; set; }
  444. /// <summary>
  445. /// The logger
  446. /// </summary>
  447. public static ILogger Logger { get; set; }
  448. public static ILibraryManager LibraryManager { get; set; }
  449. public static IServerConfigurationManager ConfigurationManager { get; set; }
  450. public static IProviderManager ProviderManager { get; set; }
  451. public static ILocalizationManager LocalizationManager { get; set; }
  452. public static IItemRepository ItemRepository { get; set; }
  453. public static IFileSystem FileSystem { get; set; }
  454. public static IUserDataManager UserDataManager { get; set; }
  455. public static IChannelManager ChannelManager { get; set; }
  456. public static IMediaSourceManager MediaSourceManager { get; set; }
  457. /// <summary>
  458. /// Returns a <see cref="string" /> that represents this instance.
  459. /// </summary>
  460. /// <returns>A <see cref="string" /> that represents this instance.</returns>
  461. public override string ToString()
  462. {
  463. return Name;
  464. }
  465. [IgnoreDataMember]
  466. public bool IsLocked { get; set; }
  467. /// <summary>
  468. /// Gets or sets the locked fields.
  469. /// </summary>
  470. /// <value>The locked fields.</value>
  471. [IgnoreDataMember]
  472. public MetadataFields[] LockedFields { get; set; }
  473. /// <summary>
  474. /// Gets the type of the media.
  475. /// </summary>
  476. /// <value>The type of the media.</value>
  477. [IgnoreDataMember]
  478. public virtual string MediaType => null;
  479. [IgnoreDataMember]
  480. public virtual string[] PhysicalLocations
  481. {
  482. get
  483. {
  484. if (!IsFileProtocol)
  485. {
  486. return new string[] { };
  487. }
  488. return new[] { Path };
  489. }
  490. }
  491. private string _forcedSortName;
  492. /// <summary>
  493. /// Gets or sets the name of the forced sort.
  494. /// </summary>
  495. /// <value>The name of the forced sort.</value>
  496. [IgnoreDataMember]
  497. public string ForcedSortName
  498. {
  499. get => _forcedSortName;
  500. set { _forcedSortName = value; _sortName = null; }
  501. }
  502. private string _sortName;
  503. /// <summary>
  504. /// Gets the name of the sort.
  505. /// </summary>
  506. /// <value>The name of the sort.</value>
  507. [IgnoreDataMember]
  508. public string SortName
  509. {
  510. get
  511. {
  512. if (_sortName == null)
  513. {
  514. if (!string.IsNullOrEmpty(ForcedSortName))
  515. {
  516. // Need the ToLower because that's what CreateSortName does
  517. _sortName = ModifySortChunks(ForcedSortName).ToLowerInvariant();
  518. }
  519. else
  520. {
  521. _sortName = CreateSortName();
  522. }
  523. }
  524. return _sortName;
  525. }
  526. set => _sortName = value;
  527. }
  528. public string GetInternalMetadataPath()
  529. {
  530. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  531. return GetInternalMetadataPath(basePath);
  532. }
  533. protected virtual string GetInternalMetadataPath(string basePath)
  534. {
  535. if (SourceType == SourceType.Channel)
  536. {
  537. return System.IO.Path.Combine(basePath, "channels", ChannelId.ToString("N"), Id.ToString("N"));
  538. }
  539. var idString = Id.ToString("N");
  540. basePath = System.IO.Path.Combine(basePath, "library");
  541. return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString);
  542. }
  543. /// <summary>
  544. /// Creates the name of the sort.
  545. /// </summary>
  546. /// <returns>System.String.</returns>
  547. protected virtual string CreateSortName()
  548. {
  549. if (Name == null) return null; //some items may not have name filled in properly
  550. if (!EnableAlphaNumericSorting)
  551. {
  552. return Name.TrimStart();
  553. }
  554. var sortable = Name.Trim().ToLowerInvariant();
  555. foreach (var removeChar in ConfigurationManager.Configuration.SortRemoveCharacters)
  556. {
  557. sortable = sortable.Replace(removeChar, string.Empty);
  558. }
  559. foreach (var replaceChar in ConfigurationManager.Configuration.SortReplaceCharacters)
  560. {
  561. sortable = sortable.Replace(replaceChar, " ");
  562. }
  563. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  564. {
  565. // Remove from beginning if a space follows
  566. if (sortable.StartsWith(search + " "))
  567. {
  568. sortable = sortable.Remove(0, search.Length + 1);
  569. }
  570. // Remove from middle if surrounded by spaces
  571. sortable = sortable.Replace(" " + search + " ", " ");
  572. // Remove from end if followed by a space
  573. if (sortable.EndsWith(" " + search))
  574. {
  575. sortable = sortable.Remove(sortable.Length - (search.Length + 1));
  576. }
  577. }
  578. return ModifySortChunks(sortable);
  579. }
  580. private string ModifySortChunks(string name)
  581. {
  582. var chunks = GetSortChunks(name);
  583. var builder = new StringBuilder();
  584. foreach (var chunk in chunks)
  585. {
  586. var chunkBuilder = chunk.Item1;
  587. // This chunk is numeric
  588. if (chunk.Item2)
  589. {
  590. while (chunkBuilder.Length < 10)
  591. {
  592. chunkBuilder.Insert(0, '0');
  593. }
  594. }
  595. builder.Append(chunkBuilder);
  596. }
  597. //logger.LogDebug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
  598. return builder.ToString().RemoveDiacritics();
  599. }
  600. [IgnoreDataMember]
  601. public bool EnableMediaSourceDisplay
  602. {
  603. get
  604. {
  605. if (SourceType == SourceType.Channel)
  606. {
  607. return ChannelManager.EnableMediaSourceDisplay(this);
  608. }
  609. return true;
  610. }
  611. }
  612. [IgnoreDataMember]
  613. public Guid ParentId { get; set; }
  614. /// <summary>
  615. /// Gets or sets the parent.
  616. /// </summary>
  617. /// <value>The parent.</value>
  618. [IgnoreDataMember]
  619. public Folder Parent
  620. {
  621. get => GetParent() as Folder;
  622. set
  623. {
  624. }
  625. }
  626. public void SetParent(Folder parent)
  627. {
  628. ParentId = parent == null ? Guid.Empty : parent.Id;
  629. }
  630. public BaseItem GetParent()
  631. {
  632. var parentId = ParentId;
  633. if (!parentId.Equals(Guid.Empty))
  634. {
  635. return LibraryManager.GetItemById(parentId);
  636. }
  637. return null;
  638. }
  639. public IEnumerable<BaseItem> GetParents()
  640. {
  641. var parent = GetParent();
  642. while (parent != null)
  643. {
  644. yield return parent;
  645. parent = parent.GetParent();
  646. }
  647. }
  648. /// <summary>
  649. /// Finds a parent of a given type
  650. /// </summary>
  651. /// <typeparam name="T"></typeparam>
  652. /// <returns>``0.</returns>
  653. public T FindParent<T>()
  654. where T : Folder
  655. {
  656. foreach (var parent in GetParents())
  657. {
  658. var item = parent as T;
  659. if (item != null)
  660. {
  661. return item;
  662. }
  663. }
  664. return null;
  665. }
  666. [IgnoreDataMember]
  667. public virtual Guid DisplayParentId
  668. {
  669. get
  670. {
  671. var parentId = ParentId;
  672. return parentId;
  673. }
  674. }
  675. [IgnoreDataMember]
  676. public BaseItem DisplayParent
  677. {
  678. get
  679. {
  680. var id = DisplayParentId;
  681. if (id.Equals(Guid.Empty))
  682. {
  683. return null;
  684. }
  685. return LibraryManager.GetItemById(id);
  686. }
  687. }
  688. /// <summary>
  689. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  690. /// </summary>
  691. /// <value>The premiere date.</value>
  692. [IgnoreDataMember]
  693. public DateTime? PremiereDate { get; set; }
  694. /// <summary>
  695. /// Gets or sets the end date.
  696. /// </summary>
  697. /// <value>The end date.</value>
  698. [IgnoreDataMember]
  699. public DateTime? EndDate { get; set; }
  700. /// <summary>
  701. /// Gets or sets the official rating.
  702. /// </summary>
  703. /// <value>The official rating.</value>
  704. [IgnoreDataMember]
  705. public string OfficialRating { get; set; }
  706. [IgnoreDataMember]
  707. public int InheritedParentalRatingValue { get; set; }
  708. /// <summary>
  709. /// Gets or sets the critic rating.
  710. /// </summary>
  711. /// <value>The critic rating.</value>
  712. [IgnoreDataMember]
  713. public float? CriticRating { get; set; }
  714. /// <summary>
  715. /// Gets or sets the custom rating.
  716. /// </summary>
  717. /// <value>The custom rating.</value>
  718. [IgnoreDataMember]
  719. public string CustomRating { get; set; }
  720. /// <summary>
  721. /// Gets or sets the overview.
  722. /// </summary>
  723. /// <value>The overview.</value>
  724. [IgnoreDataMember]
  725. public string Overview { get; set; }
  726. /// <summary>
  727. /// Gets or sets the studios.
  728. /// </summary>
  729. /// <value>The studios.</value>
  730. [IgnoreDataMember]
  731. public string[] Studios { get; set; }
  732. /// <summary>
  733. /// Gets or sets the genres.
  734. /// </summary>
  735. /// <value>The genres.</value>
  736. [IgnoreDataMember]
  737. public string[] Genres { get; set; }
  738. /// <summary>
  739. /// Gets or sets the tags.
  740. /// </summary>
  741. /// <value>The tags.</value>
  742. [IgnoreDataMember]
  743. public string[] Tags { get; set; }
  744. [IgnoreDataMember]
  745. public string[] ProductionLocations { get; set; }
  746. /// <summary>
  747. /// Gets or sets the home page URL.
  748. /// </summary>
  749. /// <value>The home page URL.</value>
  750. [IgnoreDataMember]
  751. public string HomePageUrl { get; set; }
  752. /// <summary>
  753. /// Gets or sets the community rating.
  754. /// </summary>
  755. /// <value>The community rating.</value>
  756. [IgnoreDataMember]
  757. public float? CommunityRating { get; set; }
  758. /// <summary>
  759. /// Gets or sets the run time ticks.
  760. /// </summary>
  761. /// <value>The run time ticks.</value>
  762. [IgnoreDataMember]
  763. public long? RunTimeTicks { get; set; }
  764. /// <summary>
  765. /// Gets or sets the production year.
  766. /// </summary>
  767. /// <value>The production year.</value>
  768. [IgnoreDataMember]
  769. public int? ProductionYear { get; set; }
  770. /// <summary>
  771. /// If the item is part of a series, this is it's number in the series.
  772. /// This could be episode number, album track number, etc.
  773. /// </summary>
  774. /// <value>The index number.</value>
  775. [IgnoreDataMember]
  776. public int? IndexNumber { get; set; }
  777. /// <summary>
  778. /// For an episode this could be the season number, or for a song this could be the disc number.
  779. /// </summary>
  780. /// <value>The parent index number.</value>
  781. [IgnoreDataMember]
  782. public int? ParentIndexNumber { get; set; }
  783. [IgnoreDataMember]
  784. public virtual bool HasLocalAlternateVersions => false;
  785. [IgnoreDataMember]
  786. public string OfficialRatingForComparison
  787. {
  788. get
  789. {
  790. var officialRating = OfficialRating;
  791. if (!string.IsNullOrEmpty(officialRating))
  792. {
  793. return officialRating;
  794. }
  795. var parent = DisplayParent;
  796. if (parent != null)
  797. {
  798. return parent.OfficialRatingForComparison;
  799. }
  800. return null;
  801. }
  802. }
  803. [IgnoreDataMember]
  804. public string CustomRatingForComparison
  805. {
  806. get
  807. {
  808. var customRating = CustomRating;
  809. if (!string.IsNullOrEmpty(customRating))
  810. {
  811. return customRating;
  812. }
  813. var parent = DisplayParent;
  814. if (parent != null)
  815. {
  816. return parent.CustomRatingForComparison;
  817. }
  818. return null;
  819. }
  820. }
  821. /// <summary>
  822. /// Gets the play access.
  823. /// </summary>
  824. /// <param name="user">The user.</param>
  825. /// <returns>PlayAccess.</returns>
  826. public PlayAccess GetPlayAccess(User user)
  827. {
  828. if (!user.Policy.EnableMediaPlayback)
  829. {
  830. return PlayAccess.None;
  831. }
  832. //if (!user.IsParentalScheduleAllowed())
  833. //{
  834. // return PlayAccess.None;
  835. //}
  836. return PlayAccess.Full;
  837. }
  838. public virtual List<MediaStream> GetMediaStreams()
  839. {
  840. return MediaSourceManager.GetMediaStreams(new MediaStreamQuery
  841. {
  842. ItemId = Id
  843. });
  844. }
  845. protected virtual bool IsActiveRecording()
  846. {
  847. return false;
  848. }
  849. public virtual List<MediaSourceInfo> GetMediaSources(bool enablePathSubstitution)
  850. {
  851. if (SourceType == SourceType.Channel)
  852. {
  853. var sources = ChannelManager.GetStaticMediaSources(this, CancellationToken.None)
  854. .ToList();
  855. if (sources.Count > 0)
  856. {
  857. return sources;
  858. }
  859. }
  860. var list = GetAllItemsForMediaSources();
  861. var result = list.Select(i => GetVersionInfo(enablePathSubstitution, i.Item1, i.Item2)).ToList();
  862. if (IsActiveRecording())
  863. {
  864. foreach (var mediaSource in result)
  865. {
  866. mediaSource.Type = MediaSourceType.Placeholder;
  867. }
  868. }
  869. return result.OrderBy(i =>
  870. {
  871. if (i.VideoType == VideoType.VideoFile)
  872. {
  873. return 0;
  874. }
  875. return 1;
  876. }).ThenBy(i => i.Video3DFormat.HasValue ? 1 : 0)
  877. .ThenByDescending(i =>
  878. {
  879. var stream = i.VideoStream;
  880. return stream == null || stream.Width == null ? 0 : stream.Width.Value;
  881. })
  882. .ToList();
  883. }
  884. protected virtual List<Tuple<BaseItem, MediaSourceType>> GetAllItemsForMediaSources()
  885. {
  886. return new List<Tuple<BaseItem, MediaSourceType>>();
  887. }
  888. private MediaSourceInfo GetVersionInfo(bool enablePathSubstitution, BaseItem item, MediaSourceType type)
  889. {
  890. if (item == null)
  891. {
  892. throw new ArgumentNullException(nameof(item));
  893. }
  894. var protocol = item.PathProtocol;
  895. var info = new MediaSourceInfo
  896. {
  897. Id = item.Id.ToString("N"),
  898. Protocol = protocol ?? MediaProtocol.File,
  899. MediaStreams = MediaSourceManager.GetMediaStreams(item.Id),
  900. Name = GetMediaSourceName(item),
  901. Path = enablePathSubstitution ? GetMappedPath(item, item.Path, protocol) : item.Path,
  902. RunTimeTicks = item.RunTimeTicks,
  903. Container = item.Container,
  904. Size = item.Size,
  905. Type = type
  906. };
  907. if (string.IsNullOrEmpty(info.Path))
  908. {
  909. info.Type = MediaSourceType.Placeholder;
  910. }
  911. if (info.Protocol == MediaProtocol.File)
  912. {
  913. info.ETag = item.DateModified.Ticks.ToString(CultureInfo.InvariantCulture).GetMD5().ToString("N");
  914. }
  915. var video = item as Video;
  916. if (video != null)
  917. {
  918. info.IsoType = video.IsoType;
  919. info.VideoType = video.VideoType;
  920. info.Video3DFormat = video.Video3DFormat;
  921. info.Timestamp = video.Timestamp;
  922. if (video.IsShortcut)
  923. {
  924. info.IsRemote = true;
  925. info.Path = video.ShortcutPath;
  926. info.Protocol = MediaSourceManager.GetPathProtocol(info.Path);
  927. }
  928. if (string.IsNullOrEmpty(info.Container))
  929. {
  930. if (video.VideoType == VideoType.VideoFile || video.VideoType == VideoType.Iso)
  931. {
  932. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  933. {
  934. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  935. }
  936. }
  937. }
  938. }
  939. if (string.IsNullOrEmpty(info.Container))
  940. {
  941. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  942. {
  943. info.Container = System.IO.Path.GetExtension(item.Path).TrimStart('.');
  944. }
  945. }
  946. if (info.SupportsDirectStream && !string.IsNullOrEmpty(info.Path))
  947. {
  948. info.SupportsDirectStream = MediaSourceManager.SupportsDirectStream(info.Path, info.Protocol);
  949. }
  950. if (video != null && video.VideoType != VideoType.VideoFile)
  951. {
  952. info.SupportsDirectStream = false;
  953. }
  954. info.Bitrate = item.TotalBitrate;
  955. info.InferTotalBitrate();
  956. return info;
  957. }
  958. private string GetMediaSourceName(BaseItem item)
  959. {
  960. var terms = new List<string>();
  961. var path = item.Path;
  962. if (item.IsFileProtocol && !string.IsNullOrEmpty(path))
  963. {
  964. if (HasLocalAlternateVersions)
  965. {
  966. var displayName = System.IO.Path.GetFileNameWithoutExtension(path)
  967. .Replace(System.IO.Path.GetFileName(ContainingFolderPath), string.Empty, StringComparison.OrdinalIgnoreCase)
  968. .TrimStart(new char[] { ' ', '-' });
  969. if (!string.IsNullOrEmpty(displayName))
  970. {
  971. terms.Add(displayName);
  972. }
  973. }
  974. if (terms.Count == 0)
  975. {
  976. var displayName = System.IO.Path.GetFileNameWithoutExtension(path);
  977. terms.Add(displayName);
  978. }
  979. }
  980. if (terms.Count == 0)
  981. {
  982. terms.Add(item.Name);
  983. }
  984. var video = item as Video;
  985. if (video != null)
  986. {
  987. if (video.Video3DFormat.HasValue)
  988. {
  989. terms.Add("3D");
  990. }
  991. if (video.VideoType == VideoType.BluRay)
  992. {
  993. terms.Add("Bluray");
  994. }
  995. else if (video.VideoType == VideoType.Dvd)
  996. {
  997. terms.Add("DVD");
  998. }
  999. else if (video.VideoType == VideoType.Iso)
  1000. {
  1001. if (video.IsoType.HasValue)
  1002. {
  1003. if (video.IsoType.Value == Model.Entities.IsoType.BluRay)
  1004. {
  1005. terms.Add("Bluray");
  1006. }
  1007. else if (video.IsoType.Value == Model.Entities.IsoType.Dvd)
  1008. {
  1009. terms.Add("DVD");
  1010. }
  1011. }
  1012. else
  1013. {
  1014. terms.Add("ISO");
  1015. }
  1016. }
  1017. }
  1018. return string.Join("/", terms.ToArray());
  1019. }
  1020. /// <summary>
  1021. /// Loads the theme songs.
  1022. /// </summary>
  1023. /// <returns>List{Audio.Audio}.</returns>
  1024. private static Audio.Audio[] LoadThemeSongs(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1025. {
  1026. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1027. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  1028. .SelectMany(i => FileSystem.GetFiles(i.FullName))
  1029. .ToList();
  1030. // Support plex/xbmc convention
  1031. files.AddRange(fileSystemChildren
  1032. .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
  1033. );
  1034. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1035. .OfType<Audio.Audio>()
  1036. .Select(audio =>
  1037. {
  1038. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1039. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  1040. if (dbItem != null)
  1041. {
  1042. audio = dbItem;
  1043. }
  1044. else
  1045. {
  1046. // item is new
  1047. audio.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeSong;
  1048. }
  1049. return audio;
  1050. // Sort them so that the list can be easily compared for changes
  1051. }).OrderBy(i => i.Path).ToArray();
  1052. }
  1053. /// <summary>
  1054. /// Loads the video backdrops.
  1055. /// </summary>
  1056. /// <returns>List{Video}.</returns>
  1057. private static Video[] LoadThemeVideos(IEnumerable<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  1058. {
  1059. var files = fileSystemChildren.Where(i => i.IsDirectory)
  1060. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  1061. .SelectMany(i => FileSystem.GetFiles(i.FullName));
  1062. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  1063. .OfType<Video>()
  1064. .Select(item =>
  1065. {
  1066. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1067. var dbItem = LibraryManager.GetItemById(item.Id) as Video;
  1068. if (dbItem != null)
  1069. {
  1070. item = dbItem;
  1071. }
  1072. else
  1073. {
  1074. // item is new
  1075. item.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeVideo;
  1076. }
  1077. return item;
  1078. // Sort them so that the list can be easily compared for changes
  1079. }).OrderBy(i => i.Path).ToArray();
  1080. }
  1081. public Task RefreshMetadata(CancellationToken cancellationToken)
  1082. {
  1083. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)), cancellationToken);
  1084. }
  1085. protected virtual void TriggerOnRefreshStart()
  1086. {
  1087. }
  1088. protected virtual void TriggerOnRefreshComplete()
  1089. {
  1090. }
  1091. /// <summary>
  1092. /// Overrides the base implementation to refresh metadata for local trailers
  1093. /// </summary>
  1094. /// <param name="options">The options.</param>
  1095. /// <param name="cancellationToken">The cancellation token.</param>
  1096. /// <returns>true if a provider reports we changed</returns>
  1097. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  1098. {
  1099. TriggerOnRefreshStart();
  1100. var requiresSave = false;
  1101. if (SupportsOwnedItems)
  1102. {
  1103. try
  1104. {
  1105. var files = IsFileProtocol ?
  1106. GetFileSystemChildren(options.DirectoryService).ToList() :
  1107. new List<FileSystemMetadata>();
  1108. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  1109. if (ownedItemsChanged)
  1110. {
  1111. requiresSave = true;
  1112. }
  1113. }
  1114. catch (Exception ex)
  1115. {
  1116. Logger.LogError(ex, "Error refreshing owned items for {path}", Path ?? Name);
  1117. }
  1118. }
  1119. try
  1120. {
  1121. var refreshOptions = requiresSave
  1122. ? new MetadataRefreshOptions(options)
  1123. {
  1124. ForceSave = true
  1125. }
  1126. : options;
  1127. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  1128. }
  1129. finally
  1130. {
  1131. TriggerOnRefreshComplete();
  1132. }
  1133. }
  1134. [IgnoreDataMember]
  1135. protected virtual bool SupportsOwnedItems => !ParentId.Equals(Guid.Empty) && IsFileProtocol;
  1136. [IgnoreDataMember]
  1137. public virtual bool SupportsPeople => false;
  1138. [IgnoreDataMember]
  1139. public virtual bool SupportsThemeMedia => false;
  1140. /// <summary>
  1141. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  1142. /// Returns true or false indicating if changes were found.
  1143. /// </summary>
  1144. /// <param name="options"></param>
  1145. /// <param name="fileSystemChildren"></param>
  1146. /// <param name="cancellationToken"></param>
  1147. /// <returns></returns>
  1148. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1149. {
  1150. var themeSongsChanged = false;
  1151. var themeVideosChanged = false;
  1152. var localTrailersChanged = false;
  1153. if (IsFileProtocol && SupportsOwnedItems)
  1154. {
  1155. if (SupportsThemeMedia)
  1156. {
  1157. if (!IsInMixedFolder)
  1158. {
  1159. themeSongsChanged = await RefreshThemeSongs(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1160. themeVideosChanged = await RefreshThemeVideos(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1161. }
  1162. }
  1163. var hasTrailers = this as IHasTrailers;
  1164. if (hasTrailers != null)
  1165. {
  1166. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  1167. }
  1168. }
  1169. return themeSongsChanged || themeVideosChanged || localTrailersChanged;
  1170. }
  1171. protected virtual FileSystemMetadata[] GetFileSystemChildren(IDirectoryService directoryService)
  1172. {
  1173. var path = ContainingFolderPath;
  1174. return directoryService.GetFileSystemEntries(path);
  1175. }
  1176. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1177. {
  1178. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService);
  1179. var newItemIds = newItems.Select(i => i.Id);
  1180. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  1181. var ownerId = item.Id;
  1182. var tasks = newItems.Select(i =>
  1183. {
  1184. var subOptions = new MetadataRefreshOptions(options);
  1185. if (i.ExtraType != 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.ToArray();
  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 => System.IO.Path.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. => GetImageInfo(imageType, imageIndex)?.Path;
  1851. /// <summary>
  1852. /// Gets the image information.
  1853. /// </summary>
  1854. /// <param name="imageType">Type of the image.</param>
  1855. /// <param name="imageIndex">Index of the image.</param>
  1856. /// <returns>ItemImageInfo.</returns>
  1857. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1858. {
  1859. if (imageType == ImageType.Chapter)
  1860. {
  1861. var chapter = ItemRepository.GetChapter(this, imageIndex);
  1862. if (chapter == null)
  1863. {
  1864. return null;
  1865. }
  1866. var path = chapter.ImagePath;
  1867. if (string.IsNullOrEmpty(path))
  1868. {
  1869. return null;
  1870. }
  1871. return new ItemImageInfo
  1872. {
  1873. Path = path,
  1874. DateModified = chapter.ImageDateModified,
  1875. Type = imageType
  1876. };
  1877. }
  1878. return GetImages(imageType)
  1879. .ElementAtOrDefault(imageIndex);
  1880. }
  1881. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1882. {
  1883. if (imageType == ImageType.Chapter)
  1884. {
  1885. throw new ArgumentException("No image info for chapter images");
  1886. }
  1887. return ImageInfos.Where(i => i.Type == imageType);
  1888. }
  1889. /// <summary>
  1890. /// Adds the images.
  1891. /// </summary>
  1892. /// <param name="imageType">Type of the image.</param>
  1893. /// <param name="images">The images.</param>
  1894. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1895. /// <exception cref="ArgumentException">Cannot call AddImages with chapter images</exception>
  1896. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1897. {
  1898. if (imageType == ImageType.Chapter)
  1899. {
  1900. throw new ArgumentException("Cannot call AddImages with chapter images");
  1901. }
  1902. var existingImages = GetImages(imageType)
  1903. .ToList();
  1904. var newImageList = new List<FileSystemMetadata>();
  1905. var imageAdded = false;
  1906. var imageUpdated = false;
  1907. foreach (var newImage in images)
  1908. {
  1909. if (newImage == null)
  1910. {
  1911. throw new ArgumentException("null image found in list");
  1912. }
  1913. var existing = existingImages
  1914. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1915. if (existing == null)
  1916. {
  1917. newImageList.Add(newImage);
  1918. imageAdded = true;
  1919. }
  1920. else
  1921. {
  1922. if (existing.IsLocalFile)
  1923. {
  1924. var newDateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1925. // If date changed then we need to reset saved image dimensions
  1926. if (existing.DateModified != newDateModified && (existing.Width > 0 || existing.Height > 0))
  1927. {
  1928. existing.Width = 0;
  1929. existing.Height = 0;
  1930. imageUpdated = true;
  1931. }
  1932. existing.DateModified = newDateModified;
  1933. }
  1934. }
  1935. }
  1936. if (imageAdded || images.Count != existingImages.Count)
  1937. {
  1938. var newImagePaths = images.Select(i => i.FullName).ToList();
  1939. var deleted = existingImages
  1940. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !File.Exists(i.Path))
  1941. .ToList();
  1942. if (deleted.Count > 0)
  1943. {
  1944. ImageInfos = ImageInfos.Except(deleted).ToArray();
  1945. }
  1946. }
  1947. if (newImageList.Count > 0)
  1948. {
  1949. ImageInfos = ImageInfos.Concat(newImageList.Select(i => GetImageInfo(i, imageType))).ToArray();
  1950. }
  1951. return imageUpdated || newImageList.Count > 0;
  1952. }
  1953. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1954. {
  1955. return new ItemImageInfo
  1956. {
  1957. Path = file.FullName,
  1958. Type = type,
  1959. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1960. };
  1961. }
  1962. /// <summary>
  1963. /// Gets the file system path to delete when the item is to be deleted
  1964. /// </summary>
  1965. /// <returns></returns>
  1966. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  1967. {
  1968. return new[] {
  1969. new FileSystemMetadata
  1970. {
  1971. FullName = Path,
  1972. IsDirectory = IsFolder
  1973. }
  1974. }.Concat(GetLocalMetadataFilesToDelete());
  1975. }
  1976. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  1977. {
  1978. if (IsFolder || !IsInMixedFolder)
  1979. {
  1980. return new List<FileSystemMetadata>();
  1981. }
  1982. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  1983. var extensions = new List<string> { ".nfo", ".xml", ".srt", ".vtt", ".sub", ".idx", ".txt", ".edl", ".bif", ".smi", ".ttml" };
  1984. extensions.AddRange(SupportedImageExtensions);
  1985. return FileSystem.GetFiles(System.IO.Path.GetDirectoryName(Path), extensions.ToArray(), false, false)
  1986. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  1987. .ToList();
  1988. }
  1989. public bool AllowsMultipleImages(ImageType type)
  1990. {
  1991. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1992. }
  1993. public void SwapImages(ImageType type, int index1, int index2)
  1994. {
  1995. if (!AllowsMultipleImages(type))
  1996. {
  1997. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1998. }
  1999. var info1 = GetImageInfo(type, index1);
  2000. var info2 = GetImageInfo(type, index2);
  2001. if (info1 == null || info2 == null)
  2002. {
  2003. // Nothing to do
  2004. return;
  2005. }
  2006. if (!info1.IsLocalFile || !info2.IsLocalFile)
  2007. {
  2008. // TODO: Not supported yet
  2009. return;
  2010. }
  2011. var path1 = info1.Path;
  2012. var path2 = info2.Path;
  2013. FileSystem.SwapFiles(path1, path2);
  2014. // Refresh these values
  2015. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  2016. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  2017. info1.Width = 0;
  2018. info1.Height = 0;
  2019. info2.Width = 0;
  2020. info2.Height = 0;
  2021. UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  2022. }
  2023. public virtual bool IsPlayed(User user)
  2024. {
  2025. var userdata = UserDataManager.GetUserData(user, this);
  2026. return userdata != null && userdata.Played;
  2027. }
  2028. public bool IsFavoriteOrLiked(User user)
  2029. {
  2030. var userdata = UserDataManager.GetUserData(user, this);
  2031. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  2032. }
  2033. public virtual bool IsUnplayed(User user)
  2034. {
  2035. if (user == null)
  2036. {
  2037. throw new ArgumentNullException(nameof(user));
  2038. }
  2039. var userdata = UserDataManager.GetUserData(user, this);
  2040. return userdata == null || !userdata.Played;
  2041. }
  2042. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  2043. {
  2044. return GetItemLookupInfo<ItemLookupInfo>();
  2045. }
  2046. protected T GetItemLookupInfo<T>()
  2047. where T : ItemLookupInfo, new()
  2048. {
  2049. return new T
  2050. {
  2051. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  2052. MetadataLanguage = GetPreferredMetadataLanguage(),
  2053. Name = GetNameForMetadataLookup(),
  2054. ProviderIds = ProviderIds,
  2055. IndexNumber = IndexNumber,
  2056. ParentIndexNumber = ParentIndexNumber,
  2057. Year = ProductionYear,
  2058. PremiereDate = PremiereDate
  2059. };
  2060. }
  2061. protected virtual string GetNameForMetadataLookup()
  2062. {
  2063. return Name;
  2064. }
  2065. /// <summary>
  2066. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  2067. /// </summary>
  2068. public virtual bool BeforeMetadataRefresh(bool replaceAllMetdata)
  2069. {
  2070. _sortName = null;
  2071. var hasChanges = false;
  2072. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  2073. {
  2074. Name = System.IO.Path.GetFileNameWithoutExtension(Path);
  2075. hasChanges = true;
  2076. }
  2077. return hasChanges;
  2078. }
  2079. protected static string GetMappedPath(BaseItem item, string path, MediaProtocol? protocol)
  2080. {
  2081. if (protocol.HasValue && protocol.Value == MediaProtocol.File)
  2082. {
  2083. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  2084. }
  2085. return path;
  2086. }
  2087. public virtual void FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, DtoOptions fields)
  2088. {
  2089. if (RunTimeTicks.HasValue)
  2090. {
  2091. double pct = RunTimeTicks.Value;
  2092. if (pct > 0)
  2093. {
  2094. pct = userData.PlaybackPositionTicks / pct;
  2095. if (pct > 0)
  2096. {
  2097. dto.PlayedPercentage = 100 * pct;
  2098. }
  2099. }
  2100. }
  2101. }
  2102. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  2103. {
  2104. var newOptions = new MetadataRefreshOptions(options);
  2105. newOptions.SearchResult = null;
  2106. var item = this;
  2107. if (copyTitleMetadata)
  2108. {
  2109. // Take some data from the main item, for querying purposes
  2110. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  2111. {
  2112. newOptions.ForceSave = true;
  2113. ownedItem.Genres = item.Genres;
  2114. }
  2115. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  2116. {
  2117. newOptions.ForceSave = true;
  2118. ownedItem.Studios = item.Studios;
  2119. }
  2120. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  2121. {
  2122. newOptions.ForceSave = true;
  2123. ownedItem.ProductionLocations = item.ProductionLocations;
  2124. }
  2125. if (item.CommunityRating != ownedItem.CommunityRating)
  2126. {
  2127. ownedItem.CommunityRating = item.CommunityRating;
  2128. newOptions.ForceSave = true;
  2129. }
  2130. if (item.CriticRating != ownedItem.CriticRating)
  2131. {
  2132. ownedItem.CriticRating = item.CriticRating;
  2133. newOptions.ForceSave = true;
  2134. }
  2135. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  2136. {
  2137. ownedItem.Overview = item.Overview;
  2138. newOptions.ForceSave = true;
  2139. }
  2140. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  2141. {
  2142. ownedItem.OfficialRating = item.OfficialRating;
  2143. newOptions.ForceSave = true;
  2144. }
  2145. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  2146. {
  2147. ownedItem.CustomRating = item.CustomRating;
  2148. newOptions.ForceSave = true;
  2149. }
  2150. }
  2151. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  2152. }
  2153. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  2154. {
  2155. var newOptions = new MetadataRefreshOptions(options);
  2156. newOptions.SearchResult = null;
  2157. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  2158. // Try to retrieve it from the db. If we don't find it, use the resolved version
  2159. var video = LibraryManager.GetItemById(id) as Video;
  2160. if (video == null)
  2161. {
  2162. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  2163. newOptions.ForceSave = true;
  2164. }
  2165. //var parentId = Id;
  2166. //if (!video.IsOwnedItem || video.ParentId != parentId)
  2167. //{
  2168. // video.IsOwnedItem = true;
  2169. // video.ParentId = parentId;
  2170. // newOptions.ForceSave = true;
  2171. //}
  2172. if (video == null)
  2173. {
  2174. return Task.FromResult(true);
  2175. }
  2176. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  2177. }
  2178. public string GetEtag(User user)
  2179. {
  2180. var list = GetEtagValues(user);
  2181. return string.Join("|", list.ToArray()).GetMD5().ToString("N");
  2182. }
  2183. protected virtual List<string> GetEtagValues(User user)
  2184. {
  2185. return new List<string>
  2186. {
  2187. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  2188. };
  2189. }
  2190. public virtual IEnumerable<Guid> GetAncestorIds()
  2191. {
  2192. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  2193. }
  2194. public BaseItem GetTopParent()
  2195. {
  2196. if (IsTopParent)
  2197. {
  2198. return this;
  2199. }
  2200. foreach (var parent in GetParents())
  2201. {
  2202. if (parent.IsTopParent)
  2203. {
  2204. return parent;
  2205. }
  2206. }
  2207. return null;
  2208. }
  2209. [IgnoreDataMember]
  2210. public virtual bool IsTopParent
  2211. {
  2212. get
  2213. {
  2214. if (this is BasePluginFolder || this is Channel)
  2215. {
  2216. return true;
  2217. }
  2218. var view = this as IHasCollectionType;
  2219. if (view != null)
  2220. {
  2221. if (string.Equals(view.CollectionType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  2222. {
  2223. return true;
  2224. }
  2225. }
  2226. if (GetParent() is AggregateFolder)
  2227. {
  2228. return true;
  2229. }
  2230. return false;
  2231. }
  2232. }
  2233. [IgnoreDataMember]
  2234. public virtual bool SupportsAncestors => true;
  2235. [IgnoreDataMember]
  2236. public virtual bool StopRefreshIfLocalMetadataFound => true;
  2237. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  2238. {
  2239. return new[] { Id };
  2240. }
  2241. public virtual List<ExternalUrl> GetRelatedUrls()
  2242. {
  2243. return new List<ExternalUrl>();
  2244. }
  2245. public virtual double? GetRefreshProgress()
  2246. {
  2247. return null;
  2248. }
  2249. public virtual ItemUpdateType OnMetadataChanged()
  2250. {
  2251. var updateType = ItemUpdateType.None;
  2252. var item = this;
  2253. var inheritedParentalRatingValue = item.GetInheritedParentalRatingValue() ?? 0;
  2254. if (inheritedParentalRatingValue != item.InheritedParentalRatingValue)
  2255. {
  2256. item.InheritedParentalRatingValue = inheritedParentalRatingValue;
  2257. updateType |= ItemUpdateType.MetadataImport;
  2258. }
  2259. return updateType;
  2260. }
  2261. /// <summary>
  2262. /// Updates the official rating based on content and returns true or false indicating if it changed.
  2263. /// </summary>
  2264. /// <returns></returns>
  2265. public bool UpdateRatingToItems(IList<BaseItem> children)
  2266. {
  2267. var currentOfficialRating = OfficialRating;
  2268. // Gather all possible ratings
  2269. var ratings = children
  2270. .Select(i => i.OfficialRating)
  2271. .Where(i => !string.IsNullOrEmpty(i))
  2272. .Distinct(StringComparer.OrdinalIgnoreCase)
  2273. .Select(i => new Tuple<string, int?>(i, LocalizationManager.GetRatingLevel(i)))
  2274. .OrderBy(i => i.Item2 ?? 1000)
  2275. .Select(i => i.Item1);
  2276. OfficialRating = ratings.FirstOrDefault() ?? currentOfficialRating;
  2277. return !string.Equals(currentOfficialRating ?? string.Empty, OfficialRating ?? string.Empty,
  2278. StringComparison.OrdinalIgnoreCase);
  2279. }
  2280. public IEnumerable<BaseItem> GetThemeSongs()
  2281. {
  2282. return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeSong)).OrderBy(i => i.SortName);
  2283. }
  2284. public IEnumerable<BaseItem> GetThemeVideos()
  2285. {
  2286. return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeVideo)).OrderBy(i => i.SortName);
  2287. }
  2288. /// <summary>
  2289. /// Gets or sets the remote trailers.
  2290. /// </summary>
  2291. /// <value>The remote trailers.</value>
  2292. public MediaUrl[] RemoteTrailers { get; set; }
  2293. public IEnumerable<BaseItem> GetExtras()
  2294. {
  2295. return ThemeVideoIds.Select(LibraryManager.GetItemById).Where(i => i.ExtraType.Equals(Model.Entities.ExtraType.ThemeVideo)).OrderBy(i => i.SortName);
  2296. }
  2297. public IEnumerable<BaseItem> GetExtras(ExtraType[] unused)
  2298. {
  2299. return GetExtras();
  2300. }
  2301. public IEnumerable<BaseItem> GetDisplayExtras()
  2302. {
  2303. return GetExtras();
  2304. }
  2305. public virtual bool IsHD => Height >= 720;
  2306. public bool IsShortcut { get; set; }
  2307. public string ShortcutPath { get; set; }
  2308. public int Width { get; set; }
  2309. public int Height { get; set; }
  2310. public Guid[] ExtraIds { get; set; }
  2311. public virtual long GetRunTimeTicksForPlayState()
  2312. {
  2313. return RunTimeTicks ?? 0;
  2314. }
  2315. // what does this do?
  2316. public static ExtraType[] DisplayExtraTypes = new[] { Model.Entities.ExtraType.ThemeSong, Model.Entities.ExtraType.ThemeVideo };
  2317. public virtual bool SupportsExternalTransfer => false;
  2318. }
  2319. }