BaseItem.cs 75 KB

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