BaseItem.cs 71 KB

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