BaseItem.cs 75 KB

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