2
0

BaseItem.cs 71 KB

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