BaseItem.cs 76 KB

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