BaseItem.cs 71 KB

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