BaseItem.cs 75 KB

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