BaseItem.cs 74 KB

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