BaseItem.cs 75 KB

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