BaseItem.cs 75 KB

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