2
0

BaseItem.cs 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420
  1. using MediaBrowser.Common.Extensions;
  2. using MediaBrowser.Controller.Channels;
  3. using MediaBrowser.Controller.Collections;
  4. using MediaBrowser.Controller.Configuration;
  5. using MediaBrowser.Controller.Drawing;
  6. using MediaBrowser.Controller.Library;
  7. using MediaBrowser.Controller.LiveTv;
  8. using MediaBrowser.Controller.Persistence;
  9. using MediaBrowser.Controller.Providers;
  10. using MediaBrowser.Model.Configuration;
  11. using MediaBrowser.Model.Dto;
  12. using MediaBrowser.Model.Entities;
  13. using MediaBrowser.Model.Library;
  14. using MediaBrowser.Model.Logging;
  15. using MediaBrowser.Model.Users;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Globalization;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Text;
  22. using System.Threading;
  23. using System.Threading.Tasks;
  24. using MediaBrowser.Common.IO;
  25. using MediaBrowser.Controller.Extensions;
  26. using MediaBrowser.Controller.IO;
  27. using MediaBrowser.Controller.Sorting;
  28. using MediaBrowser.Model.Extensions;
  29. using MediaBrowser.Model.Globalization;
  30. using MediaBrowser.Model.IO;
  31. using MediaBrowser.Model.LiveTv;
  32. using MediaBrowser.Model.Providers;
  33. using MediaBrowser.Model.Querying;
  34. using MediaBrowser.Model.Serialization;
  35. namespace MediaBrowser.Controller.Entities
  36. {
  37. /// <summary>
  38. /// Class BaseItem
  39. /// </summary>
  40. public abstract class BaseItem : IHasProviderIds, IHasImages, IHasUserData, IHasMetadata, IHasLookupInfo<ItemLookupInfo>
  41. {
  42. protected BaseItem()
  43. {
  44. ThemeSongIds = new List<Guid>();
  45. ThemeVideoIds = new List<Guid>();
  46. Keywords = new List<string>();
  47. Tags = new List<string>();
  48. Genres = new List<string>();
  49. Studios = new List<string>();
  50. ProviderIds = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
  51. LockedFields = new List<MetadataFields>();
  52. ImageInfos = new List<ItemImageInfo>();
  53. InheritedTags = new List<string>();
  54. ProductionLocations = new List<string>();
  55. SourceType = SourceType.Library;
  56. }
  57. public static readonly char[] SlugReplaceChars = { '?', '/', '&' };
  58. public static char SlugChar = '-';
  59. /// <summary>
  60. /// The supported image extensions
  61. /// </summary>
  62. public static readonly string[] SupportedImageExtensions = { ".png", ".jpg", ".jpeg", ".tbn", ".gif" };
  63. public static readonly List<string> SupportedImageExtensionsList = SupportedImageExtensions.ToList();
  64. /// <summary>
  65. /// The trailer folder name
  66. /// </summary>
  67. public static string TrailerFolderName = "trailers";
  68. public static string ThemeSongsFolderName = "theme-music";
  69. public static string ThemeSongFilename = "theme";
  70. public static string ThemeVideosFolderName = "backdrops";
  71. public List<Guid> ThemeSongIds { get; set; }
  72. public List<Guid> ThemeVideoIds { get; set; }
  73. [IgnoreDataMember]
  74. public string PreferredMetadataCountryCode { get; set; }
  75. [IgnoreDataMember]
  76. public string PreferredMetadataLanguage { get; set; }
  77. public long? Size { get; set; }
  78. public string Container { get; set; }
  79. [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. _name = value;
  166. // lazy load this again
  167. _sortName = null;
  168. }
  169. }
  170. [IgnoreDataMember]
  171. public string SlugName
  172. {
  173. get
  174. {
  175. var name = Name;
  176. if (string.IsNullOrWhiteSpace(name))
  177. {
  178. return string.Empty;
  179. }
  180. return SlugReplaceChars.Aggregate(name, (current, c) => current.Replace(c, SlugChar));
  181. }
  182. }
  183. [IgnoreDataMember]
  184. public bool IsUnaired
  185. {
  186. get { return PremiereDate.HasValue && PremiereDate.Value.ToLocalTime().Date >= DateTime.Now.Date; }
  187. }
  188. public int? TotalBitrate { get; set; }
  189. public ExtraType? ExtraType { get; set; }
  190. [IgnoreDataMember]
  191. public bool IsThemeMedia
  192. {
  193. get
  194. {
  195. return ExtraType.HasValue && (ExtraType.Value == Model.Entities.ExtraType.ThemeSong || ExtraType.Value == Model.Entities.ExtraType.ThemeVideo);
  196. }
  197. }
  198. [IgnoreDataMember]
  199. public string OriginalTitle { get; set; }
  200. /// <summary>
  201. /// Gets or sets the id.
  202. /// </summary>
  203. /// <value>The id.</value>
  204. [IgnoreDataMember]
  205. public Guid Id { get; set; }
  206. /// <summary>
  207. /// Gets or sets a value indicating whether this instance is hd.
  208. /// </summary>
  209. /// <value><c>true</c> if this instance is hd; otherwise, <c>false</c>.</value>
  210. [IgnoreDataMember]
  211. public bool? IsHD { get; set; }
  212. /// <summary>
  213. /// Gets or sets the audio.
  214. /// </summary>
  215. /// <value>The audio.</value>
  216. [IgnoreDataMember]
  217. public ProgramAudio? Audio { get; set; }
  218. /// <summary>
  219. /// Return the id that should be used to key display prefs for this item.
  220. /// Default is based on the type for everything except actual generic folders.
  221. /// </summary>
  222. /// <value>The display prefs id.</value>
  223. [IgnoreDataMember]
  224. public virtual Guid DisplayPreferencesId
  225. {
  226. get
  227. {
  228. var thisType = GetType();
  229. return thisType == typeof(Folder) ? Id : thisType.FullName.GetMD5();
  230. }
  231. }
  232. /// <summary>
  233. /// Gets or sets the path.
  234. /// </summary>
  235. /// <value>The path.</value>
  236. [IgnoreDataMember]
  237. public virtual string Path { get; set; }
  238. [IgnoreDataMember]
  239. public virtual SourceType SourceType { get; set; }
  240. /// <summary>
  241. /// Returns the folder containing the item.
  242. /// If the item is a folder, it returns the folder itself
  243. /// </summary>
  244. [IgnoreDataMember]
  245. public virtual string ContainingFolderPath
  246. {
  247. get
  248. {
  249. if (IsFolder)
  250. {
  251. return Path;
  252. }
  253. return FileSystem.GetDirectoryName(Path);
  254. }
  255. }
  256. /// <summary>
  257. /// Gets or sets the name of the service.
  258. /// </summary>
  259. /// <value>The name of the service.</value>
  260. [IgnoreDataMember]
  261. public string ServiceName { get; set; }
  262. /// <summary>
  263. /// If this content came from an external service, the id of the content on that service
  264. /// </summary>
  265. [IgnoreDataMember]
  266. public string ExternalId { get; set; }
  267. [IgnoreDataMember]
  268. public string ExternalSeriesId { get; set; }
  269. /// <summary>
  270. /// Gets or sets the etag.
  271. /// </summary>
  272. /// <value>The etag.</value>
  273. [IgnoreDataMember]
  274. public string ExternalEtag { get; set; }
  275. [IgnoreDataMember]
  276. public virtual bool IsHidden
  277. {
  278. get
  279. {
  280. return false;
  281. }
  282. }
  283. [IgnoreDataMember]
  284. public virtual bool IsOwnedItem
  285. {
  286. get
  287. {
  288. // Local trailer, special feature, theme video, etc.
  289. // An item that belongs to another item but is not part of the Parent-Child tree
  290. return !IsFolder && ParentId == Guid.Empty && LocationType == LocationType.FileSystem;
  291. }
  292. }
  293. /// <summary>
  294. /// Gets or sets the type of the location.
  295. /// </summary>
  296. /// <value>The type of the location.</value>
  297. [IgnoreDataMember]
  298. public virtual LocationType LocationType
  299. {
  300. get
  301. {
  302. //if (IsOffline)
  303. //{
  304. // return LocationType.Offline;
  305. //}
  306. if (string.IsNullOrWhiteSpace(Path))
  307. {
  308. if (SourceType == SourceType.Channel)
  309. {
  310. return LocationType.Remote;
  311. }
  312. return LocationType.Virtual;
  313. }
  314. return FileSystem.IsPathFile(Path) ? LocationType.FileSystem : LocationType.Remote;
  315. }
  316. }
  317. [IgnoreDataMember]
  318. public virtual bool SupportsLocalMetadata
  319. {
  320. get
  321. {
  322. if (SourceType == SourceType.Channel)
  323. {
  324. return false;
  325. }
  326. var locationType = LocationType;
  327. return locationType != LocationType.Remote && locationType != LocationType.Virtual;
  328. }
  329. }
  330. [IgnoreDataMember]
  331. public virtual string FileNameWithoutExtension
  332. {
  333. get
  334. {
  335. if (LocationType == LocationType.FileSystem)
  336. {
  337. return System.IO.Path.GetFileNameWithoutExtension(Path);
  338. }
  339. return null;
  340. }
  341. }
  342. [IgnoreDataMember]
  343. public virtual bool EnableAlphaNumericSorting
  344. {
  345. get
  346. {
  347. return true;
  348. }
  349. }
  350. private List<Tuple<StringBuilder, bool>> GetSortChunks(string s1)
  351. {
  352. var list = new List<Tuple<StringBuilder, bool>>();
  353. int thisMarker = 0, thisNumericChunk = 0;
  354. while (thisMarker < s1.Length)
  355. {
  356. if (thisMarker >= s1.Length)
  357. {
  358. break;
  359. }
  360. char thisCh = s1[thisMarker];
  361. StringBuilder thisChunk = new StringBuilder();
  362. while ((thisMarker < s1.Length) && (thisChunk.Length == 0 || SortHelper.InChunk(thisCh, thisChunk[0])))
  363. {
  364. thisChunk.Append(thisCh);
  365. thisMarker++;
  366. if (thisMarker < s1.Length)
  367. {
  368. thisCh = s1[thisMarker];
  369. }
  370. }
  371. var isNumeric = thisChunk.Length > 0 && char.IsDigit(thisChunk[0]);
  372. list.Add(new Tuple<StringBuilder, bool>(thisChunk, isNumeric));
  373. }
  374. return list;
  375. }
  376. /// <summary>
  377. /// This is just a helper for convenience
  378. /// </summary>
  379. /// <value>The primary image path.</value>
  380. [IgnoreDataMember]
  381. public string PrimaryImagePath
  382. {
  383. get { return this.GetImagePath(ImageType.Primary); }
  384. }
  385. public virtual bool IsInternetMetadataEnabled()
  386. {
  387. return LibraryManager.GetLibraryOptions(this).EnableInternetProviders;
  388. }
  389. public virtual bool CanDelete()
  390. {
  391. if (SourceType == SourceType.Channel)
  392. {
  393. return false;
  394. }
  395. var locationType = LocationType;
  396. return locationType != LocationType.Remote &&
  397. locationType != LocationType.Virtual;
  398. }
  399. public virtual bool IsAuthorizedToDelete(User user)
  400. {
  401. return user.Policy.EnableContentDeletion;
  402. }
  403. public bool CanDelete(User user)
  404. {
  405. return CanDelete() && IsAuthorizedToDelete(user);
  406. }
  407. public virtual bool CanDownload()
  408. {
  409. return false;
  410. }
  411. public virtual bool IsAuthorizedToDownload(User user)
  412. {
  413. return user.Policy.EnableContentDownloading;
  414. }
  415. public bool CanDownload(User user)
  416. {
  417. return CanDownload() && IsAuthorizedToDownload(user);
  418. }
  419. /// <summary>
  420. /// Gets or sets the date created.
  421. /// </summary>
  422. /// <value>The date created.</value>
  423. [IgnoreDataMember]
  424. public DateTime DateCreated { get; set; }
  425. /// <summary>
  426. /// Gets or sets the date modified.
  427. /// </summary>
  428. /// <value>The date modified.</value>
  429. [IgnoreDataMember]
  430. public DateTime DateModified { get; set; }
  431. [IgnoreDataMember]
  432. public DateTime DateLastSaved { get; set; }
  433. [IgnoreDataMember]
  434. public DateTime DateLastRefreshed { get; set; }
  435. [IgnoreDataMember]
  436. public virtual bool EnableRefreshOnDateModifiedChange
  437. {
  438. get { return false; }
  439. }
  440. /// <summary>
  441. /// The logger
  442. /// </summary>
  443. public static ILogger Logger { get; set; }
  444. public static ILibraryManager LibraryManager { get; set; }
  445. public static IServerConfigurationManager ConfigurationManager { get; set; }
  446. public static IProviderManager ProviderManager { get; set; }
  447. public static ILocalizationManager LocalizationManager { get; set; }
  448. public static IItemRepository ItemRepository { get; set; }
  449. public static IFileSystem FileSystem { get; set; }
  450. public static IUserDataManager UserDataManager { get; set; }
  451. public static ILiveTvManager LiveTvManager { get; set; }
  452. public static IChannelManager ChannelManager { get; set; }
  453. public static ICollectionManager CollectionManager { get; set; }
  454. public static IImageProcessor ImageProcessor { get; set; }
  455. public static IMediaSourceManager MediaSourceManager { get; set; }
  456. /// <summary>
  457. /// Returns a <see cref="System.String" /> that represents this instance.
  458. /// </summary>
  459. /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
  460. public override string ToString()
  461. {
  462. return Name;
  463. }
  464. [IgnoreDataMember]
  465. public bool IsLocked { get; set; }
  466. /// <summary>
  467. /// Gets or sets the locked fields.
  468. /// </summary>
  469. /// <value>The locked fields.</value>
  470. [IgnoreDataMember]
  471. public List<MetadataFields> LockedFields { get; set; }
  472. /// <summary>
  473. /// Gets the type of the media.
  474. /// </summary>
  475. /// <value>The type of the media.</value>
  476. [IgnoreDataMember]
  477. public virtual string MediaType
  478. {
  479. get
  480. {
  481. return null;
  482. }
  483. }
  484. [IgnoreDataMember]
  485. public virtual IEnumerable<string> PhysicalLocations
  486. {
  487. get
  488. {
  489. var locationType = LocationType;
  490. if (locationType == LocationType.Remote || locationType == LocationType.Virtual)
  491. {
  492. return new string[] { };
  493. }
  494. return new[] { Path };
  495. }
  496. }
  497. private string _forcedSortName;
  498. /// <summary>
  499. /// Gets or sets the name of the forced sort.
  500. /// </summary>
  501. /// <value>The name of the forced sort.</value>
  502. [IgnoreDataMember]
  503. public string ForcedSortName
  504. {
  505. get { return _forcedSortName; }
  506. set { _forcedSortName = value; _sortName = null; }
  507. }
  508. private string _sortName;
  509. /// <summary>
  510. /// Gets the name of the sort.
  511. /// </summary>
  512. /// <value>The name of the sort.</value>
  513. [IgnoreDataMember]
  514. public string SortName
  515. {
  516. get
  517. {
  518. if (_sortName == null)
  519. {
  520. if (!string.IsNullOrWhiteSpace(ForcedSortName))
  521. {
  522. // Need the ToLower because that's what CreateSortName does
  523. _sortName = ModifySortChunks(ForcedSortName).ToLower();
  524. }
  525. else
  526. {
  527. _sortName = CreateSortName();
  528. }
  529. }
  530. return _sortName;
  531. }
  532. set
  533. {
  534. _sortName = value;
  535. }
  536. }
  537. public string GetInternalMetadataPath()
  538. {
  539. var basePath = ConfigurationManager.ApplicationPaths.InternalMetadataPath;
  540. return GetInternalMetadataPath(basePath);
  541. }
  542. protected virtual string GetInternalMetadataPath(string basePath)
  543. {
  544. if (SourceType == SourceType.Channel)
  545. {
  546. return System.IO.Path.Combine(basePath, "channels", ChannelId, Id.ToString("N"));
  547. }
  548. var idString = Id.ToString("N");
  549. basePath = System.IO.Path.Combine(basePath, "library");
  550. return System.IO.Path.Combine(basePath, idString.Substring(0, 2), idString);
  551. }
  552. /// <summary>
  553. /// Creates the name of the sort.
  554. /// </summary>
  555. /// <returns>System.String.</returns>
  556. protected virtual string CreateSortName()
  557. {
  558. if (Name == null) return null; //some items may not have name filled in properly
  559. if (!EnableAlphaNumericSorting)
  560. {
  561. return Name.TrimStart();
  562. }
  563. var sortable = Name.Trim().ToLower();
  564. sortable = ConfigurationManager.Configuration.SortRemoveCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), string.Empty));
  565. sortable = ConfigurationManager.Configuration.SortReplaceCharacters.Aggregate(sortable, (current, search) => current.Replace(search.ToLower(), " "));
  566. foreach (var search in ConfigurationManager.Configuration.SortRemoveWords)
  567. {
  568. var searchLower = search.ToLower();
  569. // Remove from beginning if a space follows
  570. if (sortable.StartsWith(searchLower + " "))
  571. {
  572. sortable = sortable.Remove(0, searchLower.Length + 1);
  573. }
  574. // Remove from middle if surrounded by spaces
  575. sortable = sortable.Replace(" " + searchLower + " ", " ");
  576. // Remove from end if followed by a space
  577. if (sortable.EndsWith(" " + searchLower))
  578. {
  579. sortable = sortable.Remove(sortable.Length - (searchLower.Length + 1));
  580. }
  581. }
  582. return ModifySortChunks(sortable);
  583. }
  584. private string ModifySortChunks(string name)
  585. {
  586. var chunks = GetSortChunks(name);
  587. var builder = new StringBuilder();
  588. foreach (var chunk in chunks)
  589. {
  590. var chunkBuilder = chunk.Item1;
  591. // This chunk is numeric
  592. if (chunk.Item2)
  593. {
  594. while (chunkBuilder.Length < 10)
  595. {
  596. chunkBuilder.Insert(0, '0');
  597. }
  598. }
  599. builder.Append(chunkBuilder);
  600. }
  601. //Logger.Debug("ModifySortChunks Start: {0} End: {1}", name, builder.ToString());
  602. return builder.ToString().RemoveDiacritics();
  603. }
  604. [IgnoreDataMember]
  605. public Guid ParentId { get; set; }
  606. /// <summary>
  607. /// Gets or sets the parent.
  608. /// </summary>
  609. /// <value>The parent.</value>
  610. [IgnoreDataMember]
  611. public Folder Parent
  612. {
  613. get { return GetParent() as Folder; }
  614. set
  615. {
  616. }
  617. }
  618. public void SetParent(Folder parent)
  619. {
  620. ParentId = parent == null ? Guid.Empty : parent.Id;
  621. }
  622. [IgnoreDataMember]
  623. public IEnumerable<Folder> Parents
  624. {
  625. get { return GetParents().OfType<Folder>(); }
  626. }
  627. public BaseItem GetParent()
  628. {
  629. if (ParentId != Guid.Empty)
  630. {
  631. return LibraryManager.GetItemById(ParentId);
  632. }
  633. return null;
  634. }
  635. public IEnumerable<BaseItem> GetParents()
  636. {
  637. var parent = GetParent();
  638. while (parent != null)
  639. {
  640. yield return parent;
  641. parent = parent.GetParent();
  642. }
  643. }
  644. /// <summary>
  645. /// Finds a parent of a given type
  646. /// </summary>
  647. /// <typeparam name="T"></typeparam>
  648. /// <returns>``0.</returns>
  649. public T FindParent<T>()
  650. where T : Folder
  651. {
  652. return GetParents().OfType<T>().FirstOrDefault();
  653. }
  654. [IgnoreDataMember]
  655. public virtual Guid? DisplayParentId
  656. {
  657. get
  658. {
  659. if (ParentId == Guid.Empty)
  660. {
  661. return null;
  662. }
  663. return ParentId;
  664. }
  665. }
  666. [IgnoreDataMember]
  667. public BaseItem DisplayParent
  668. {
  669. get
  670. {
  671. var id = DisplayParentId;
  672. if (!id.HasValue || id.Value == Guid.Empty)
  673. {
  674. return null;
  675. }
  676. return LibraryManager.GetItemById(id.Value);
  677. }
  678. }
  679. /// <summary>
  680. /// When the item first debuted. For movies this could be premiere date, episodes would be first aired
  681. /// </summary>
  682. /// <value>The premiere date.</value>
  683. [IgnoreDataMember]
  684. public DateTime? PremiereDate { get; set; }
  685. /// <summary>
  686. /// Gets or sets the end date.
  687. /// </summary>
  688. /// <value>The end date.</value>
  689. [IgnoreDataMember]
  690. public DateTime? EndDate { get; set; }
  691. /// <summary>
  692. /// Gets or sets the display type of the media.
  693. /// </summary>
  694. /// <value>The display type of the media.</value>
  695. [IgnoreDataMember]
  696. public string DisplayMediaType { get; set; }
  697. /// <summary>
  698. /// Gets or sets the official rating.
  699. /// </summary>
  700. /// <value>The official rating.</value>
  701. [IgnoreDataMember]
  702. public string OfficialRating { get; set; }
  703. [IgnoreDataMember]
  704. public int InheritedParentalRatingValue { get; set; }
  705. [IgnoreDataMember]
  706. public List<string> InheritedTags { get; set; }
  707. /// <summary>
  708. /// Gets or sets the critic rating.
  709. /// </summary>
  710. /// <value>The critic rating.</value>
  711. [IgnoreDataMember]
  712. public float? CriticRating { get; set; }
  713. /// <summary>
  714. /// Gets or sets the custom rating.
  715. /// </summary>
  716. /// <value>The custom rating.</value>
  717. [IgnoreDataMember]
  718. public string CustomRating { get; set; }
  719. /// <summary>
  720. /// Gets or sets the overview.
  721. /// </summary>
  722. /// <value>The overview.</value>
  723. [IgnoreDataMember]
  724. public string Overview { get; set; }
  725. /// <summary>
  726. /// Gets or sets the studios.
  727. /// </summary>
  728. /// <value>The studios.</value>
  729. [IgnoreDataMember]
  730. public List<string> Studios { get; set; }
  731. /// <summary>
  732. /// Gets or sets the genres.
  733. /// </summary>
  734. /// <value>The genres.</value>
  735. [IgnoreDataMember]
  736. public List<string> Genres { get; set; }
  737. /// <summary>
  738. /// Gets or sets the tags.
  739. /// </summary>
  740. /// <value>The tags.</value>
  741. [IgnoreDataMember]
  742. public List<string> Tags { get; set; }
  743. public List<string> Keywords { get; set; }
  744. public List<string> ProductionLocations { get; set; }
  745. /// <summary>
  746. /// Gets or sets the home page URL.
  747. /// </summary>
  748. /// <value>The home page URL.</value>
  749. [IgnoreDataMember]
  750. public string HomePageUrl { get; set; }
  751. /// <summary>
  752. /// Gets or sets the community rating.
  753. /// </summary>
  754. /// <value>The community rating.</value>
  755. [IgnoreDataMember]
  756. public float? CommunityRating { get; set; }
  757. /// <summary>
  758. /// Gets or sets the community rating vote count.
  759. /// </summary>
  760. /// <value>The community rating vote count.</value>
  761. [IgnoreDataMember]
  762. public int? VoteCount { get; set; }
  763. /// <summary>
  764. /// Gets or sets the run time ticks.
  765. /// </summary>
  766. /// <value>The run time ticks.</value>
  767. [IgnoreDataMember]
  768. public long? RunTimeTicks { get; set; }
  769. /// <summary>
  770. /// Gets or sets the production year.
  771. /// </summary>
  772. /// <value>The production year.</value>
  773. [IgnoreDataMember]
  774. public int? ProductionYear { get; set; }
  775. /// <summary>
  776. /// If the item is part of a series, this is it's number in the series.
  777. /// This could be episode number, album track number, etc.
  778. /// </summary>
  779. /// <value>The index number.</value>
  780. [IgnoreDataMember]
  781. public int? IndexNumber { get; set; }
  782. /// <summary>
  783. /// For an episode this could be the season number, or for a song this could be the disc number.
  784. /// </summary>
  785. /// <value>The parent index number.</value>
  786. [IgnoreDataMember]
  787. public int? ParentIndexNumber { get; set; }
  788. [IgnoreDataMember]
  789. public string OfficialRatingForComparison
  790. {
  791. get
  792. {
  793. if (!string.IsNullOrWhiteSpace(OfficialRating))
  794. {
  795. return OfficialRating;
  796. }
  797. var parent = DisplayParent;
  798. if (parent != null)
  799. {
  800. return parent.OfficialRatingForComparison;
  801. }
  802. return null;
  803. }
  804. }
  805. [IgnoreDataMember]
  806. public string CustomRatingForComparison
  807. {
  808. get
  809. {
  810. if (!string.IsNullOrWhiteSpace(CustomRating))
  811. {
  812. return CustomRating;
  813. }
  814. var parent = DisplayParent;
  815. if (parent != null)
  816. {
  817. return parent.CustomRatingForComparison;
  818. }
  819. return null;
  820. }
  821. }
  822. /// <summary>
  823. /// Gets the play access.
  824. /// </summary>
  825. /// <param name="user">The user.</param>
  826. /// <returns>PlayAccess.</returns>
  827. public PlayAccess GetPlayAccess(User user)
  828. {
  829. if (!user.Policy.EnableMediaPlayback)
  830. {
  831. return PlayAccess.None;
  832. }
  833. //if (!user.IsParentalScheduleAllowed())
  834. //{
  835. // return PlayAccess.None;
  836. //}
  837. return PlayAccess.Full;
  838. }
  839. /// <summary>
  840. /// Loads the theme songs.
  841. /// </summary>
  842. /// <returns>List{Audio.Audio}.</returns>
  843. private static IEnumerable<Audio.Audio> LoadThemeSongs(List<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  844. {
  845. var files = fileSystemChildren.Where(i => i.IsDirectory)
  846. .Where(i => string.Equals(i.Name, ThemeSongsFolderName, StringComparison.OrdinalIgnoreCase))
  847. .SelectMany(i => directoryService.GetFiles(i.FullName))
  848. .ToList();
  849. // Support plex/xbmc convention
  850. files.AddRange(fileSystemChildren
  851. .Where(i => !i.IsDirectory && string.Equals(FileSystem.GetFileNameWithoutExtension(i), ThemeSongFilename, StringComparison.OrdinalIgnoreCase))
  852. );
  853. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  854. .OfType<Audio.Audio>()
  855. .Select(audio =>
  856. {
  857. // Try to retrieve it from the db. If we don't find it, use the resolved version
  858. var dbItem = LibraryManager.GetItemById(audio.Id) as Audio.Audio;
  859. if (dbItem != null)
  860. {
  861. audio = dbItem;
  862. }
  863. audio.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeSong;
  864. return audio;
  865. // Sort them so that the list can be easily compared for changes
  866. }).OrderBy(i => i.Path).ToList();
  867. }
  868. /// <summary>
  869. /// Loads the video backdrops.
  870. /// </summary>
  871. /// <returns>List{Video}.</returns>
  872. private static IEnumerable<Video> LoadThemeVideos(IEnumerable<FileSystemMetadata> fileSystemChildren, IDirectoryService directoryService)
  873. {
  874. var files = fileSystemChildren.Where(i => i.IsDirectory)
  875. .Where(i => string.Equals(i.Name, ThemeVideosFolderName, StringComparison.OrdinalIgnoreCase))
  876. .SelectMany(i => directoryService.GetFiles(i.FullName));
  877. return LibraryManager.ResolvePaths(files, directoryService, null, new LibraryOptions())
  878. .OfType<Video>()
  879. .Select(item =>
  880. {
  881. // Try to retrieve it from the db. If we don't find it, use the resolved version
  882. var dbItem = LibraryManager.GetItemById(item.Id) as Video;
  883. if (dbItem != null)
  884. {
  885. item = dbItem;
  886. }
  887. item.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeVideo;
  888. return item;
  889. // Sort them so that the list can be easily compared for changes
  890. }).OrderBy(i => i.Path).ToList();
  891. }
  892. public Task RefreshMetadata(CancellationToken cancellationToken)
  893. {
  894. return RefreshMetadata(new MetadataRefreshOptions(new DirectoryService(Logger, FileSystem)), cancellationToken);
  895. }
  896. /// <summary>
  897. /// Overrides the base implementation to refresh metadata for local trailers
  898. /// </summary>
  899. /// <param name="options">The options.</param>
  900. /// <param name="cancellationToken">The cancellation token.</param>
  901. /// <returns>true if a provider reports we changed</returns>
  902. public async Task<ItemUpdateType> RefreshMetadata(MetadataRefreshOptions options, CancellationToken cancellationToken)
  903. {
  904. var locationType = LocationType;
  905. var requiresSave = false;
  906. if (SupportsOwnedItems)
  907. {
  908. try
  909. {
  910. var files = locationType != LocationType.Remote && locationType != LocationType.Virtual ?
  911. GetFileSystemChildren(options.DirectoryService).ToList() :
  912. new List<FileSystemMetadata>();
  913. var ownedItemsChanged = await RefreshedOwnedItems(options, files, cancellationToken).ConfigureAwait(false);
  914. if (ownedItemsChanged)
  915. {
  916. requiresSave = true;
  917. }
  918. }
  919. catch (Exception ex)
  920. {
  921. Logger.ErrorException("Error refreshing owned items for {0}", ex, Path ?? Name);
  922. }
  923. }
  924. var refreshOptions = requiresSave
  925. ? new MetadataRefreshOptions(options)
  926. {
  927. ForceSave = true
  928. }
  929. : options;
  930. return await ProviderManager.RefreshSingleItem(this, refreshOptions, cancellationToken).ConfigureAwait(false);
  931. }
  932. [IgnoreDataMember]
  933. protected virtual bool SupportsOwnedItems
  934. {
  935. get { return IsFolder || GetParent() != null; }
  936. }
  937. [IgnoreDataMember]
  938. public virtual bool SupportsPeople
  939. {
  940. get { return true; }
  941. }
  942. [IgnoreDataMember]
  943. public virtual bool SupportsThemeMedia
  944. {
  945. get { return false; }
  946. }
  947. /// <summary>
  948. /// Refreshes owned items such as trailers, theme videos, special features, etc.
  949. /// Returns true or false indicating if changes were found.
  950. /// </summary>
  951. /// <param name="options"></param>
  952. /// <param name="fileSystemChildren"></param>
  953. /// <param name="cancellationToken"></param>
  954. /// <returns></returns>
  955. protected virtual async Task<bool> RefreshedOwnedItems(MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  956. {
  957. var themeSongsChanged = false;
  958. var themeVideosChanged = false;
  959. var localTrailersChanged = false;
  960. if (LocationType == LocationType.FileSystem && GetParent() != null)
  961. {
  962. if (SupportsThemeMedia)
  963. {
  964. if (!DetectIsInMixedFolder())
  965. {
  966. themeSongsChanged = await RefreshThemeSongs(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  967. themeVideosChanged = await RefreshThemeVideos(this, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  968. }
  969. }
  970. var hasTrailers = this as IHasTrailers;
  971. if (hasTrailers != null)
  972. {
  973. localTrailersChanged = await RefreshLocalTrailers(hasTrailers, options, fileSystemChildren, cancellationToken).ConfigureAwait(false);
  974. }
  975. }
  976. return themeSongsChanged || themeVideosChanged || localTrailersChanged;
  977. }
  978. protected virtual IEnumerable<FileSystemMetadata> GetFileSystemChildren(IDirectoryService directoryService)
  979. {
  980. var path = ContainingFolderPath;
  981. return directoryService.GetFileSystemEntries(path);
  982. }
  983. private async Task<bool> RefreshLocalTrailers(IHasTrailers item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  984. {
  985. var newItems = LibraryManager.FindTrailers(this, fileSystemChildren, options.DirectoryService).ToList();
  986. var newItemIds = newItems.Select(i => i.Id).ToList();
  987. var itemsChanged = !item.LocalTrailerIds.SequenceEqual(newItemIds);
  988. var tasks = newItems.Select(i => RefreshMetadataForOwnedItem(i, true, options, cancellationToken));
  989. await Task.WhenAll(tasks).ConfigureAwait(false);
  990. item.LocalTrailerIds = newItemIds;
  991. return itemsChanged;
  992. }
  993. private async Task<bool> RefreshThemeVideos(BaseItem item, MetadataRefreshOptions options, IEnumerable<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  994. {
  995. var newThemeVideos = LoadThemeVideos(fileSystemChildren, options.DirectoryService).ToList();
  996. var newThemeVideoIds = newThemeVideos.Select(i => i.Id).ToList();
  997. var themeVideosChanged = !item.ThemeVideoIds.SequenceEqual(newThemeVideoIds);
  998. var tasks = newThemeVideos.Select(i =>
  999. {
  1000. var subOptions = new MetadataRefreshOptions(options);
  1001. if (!i.IsThemeMedia)
  1002. {
  1003. i.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeVideo;
  1004. subOptions.ForceSave = true;
  1005. }
  1006. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1007. });
  1008. await Task.WhenAll(tasks).ConfigureAwait(false);
  1009. item.ThemeVideoIds = newThemeVideoIds;
  1010. return themeVideosChanged;
  1011. }
  1012. /// <summary>
  1013. /// Refreshes the theme songs.
  1014. /// </summary>
  1015. private async Task<bool> RefreshThemeSongs(BaseItem item, MetadataRefreshOptions options, List<FileSystemMetadata> fileSystemChildren, CancellationToken cancellationToken)
  1016. {
  1017. var newThemeSongs = LoadThemeSongs(fileSystemChildren, options.DirectoryService).ToList();
  1018. var newThemeSongIds = newThemeSongs.Select(i => i.Id).ToList();
  1019. var themeSongsChanged = !item.ThemeSongIds.SequenceEqual(newThemeSongIds);
  1020. var tasks = newThemeSongs.Select(i =>
  1021. {
  1022. var subOptions = new MetadataRefreshOptions(options);
  1023. if (!i.IsThemeMedia)
  1024. {
  1025. i.ExtraType = MediaBrowser.Model.Entities.ExtraType.ThemeSong;
  1026. subOptions.ForceSave = true;
  1027. }
  1028. return RefreshMetadataForOwnedItem(i, true, subOptions, cancellationToken);
  1029. });
  1030. await Task.WhenAll(tasks).ConfigureAwait(false);
  1031. item.ThemeSongIds = newThemeSongIds;
  1032. return themeSongsChanged;
  1033. }
  1034. /// <summary>
  1035. /// Gets or sets the provider ids.
  1036. /// </summary>
  1037. /// <value>The provider ids.</value>
  1038. public Dictionary<string, string> ProviderIds { get; set; }
  1039. [IgnoreDataMember]
  1040. public virtual Folder LatestItemsIndexContainer
  1041. {
  1042. get { return null; }
  1043. }
  1044. public virtual double? GetDefaultPrimaryImageAspectRatio()
  1045. {
  1046. return null;
  1047. }
  1048. public virtual string CreatePresentationUniqueKey()
  1049. {
  1050. return Id.ToString("N");
  1051. }
  1052. [IgnoreDataMember]
  1053. public string PresentationUniqueKey { get; set; }
  1054. public string GetPresentationUniqueKey()
  1055. {
  1056. return PresentationUniqueKey ?? CreatePresentationUniqueKey();
  1057. }
  1058. public virtual bool RequiresRefresh()
  1059. {
  1060. return false;
  1061. }
  1062. public virtual List<string> GetUserDataKeys()
  1063. {
  1064. var list = new List<string>();
  1065. if (SourceType == SourceType.Channel)
  1066. {
  1067. if (!string.IsNullOrWhiteSpace(ExternalId))
  1068. {
  1069. list.Add(ExternalId);
  1070. }
  1071. }
  1072. list.Add(Id.ToString());
  1073. return list;
  1074. }
  1075. internal virtual bool IsValidFromResolver(BaseItem newItem)
  1076. {
  1077. var current = this;
  1078. if (!SupportsIsInMixedFolderDetection)
  1079. {
  1080. if (current.IsInMixedFolder != newItem.IsInMixedFolder)
  1081. {
  1082. return false;
  1083. }
  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.IsNullOrEmpty(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 Task ChangedExternally()
  1508. {
  1509. ProviderManager.QueueRefresh(Id, new MetadataRefreshOptions(FileSystem), RefreshPriority.High);
  1510. return Task.FromResult(true);
  1511. }
  1512. /// <summary>
  1513. /// Gets an image
  1514. /// </summary>
  1515. /// <param name="type">The type.</param>
  1516. /// <param name="imageIndex">Index of the image.</param>
  1517. /// <returns><c>true</c> if the specified type has image; otherwise, <c>false</c>.</returns>
  1518. /// <exception cref="System.ArgumentException">Backdrops should be accessed using Item.Backdrops</exception>
  1519. public bool HasImage(ImageType type, int imageIndex)
  1520. {
  1521. return GetImageInfo(type, imageIndex) != null;
  1522. }
  1523. public void SetImage(ItemImageInfo image, int index)
  1524. {
  1525. if (image.Type == ImageType.Chapter)
  1526. {
  1527. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1528. }
  1529. var existingImage = GetImageInfo(image.Type, index);
  1530. if (existingImage != null)
  1531. {
  1532. ImageInfos.Remove(existingImage);
  1533. }
  1534. ImageInfos.Add(image);
  1535. }
  1536. public void SetImagePath(ImageType type, int index, FileSystemMetadata file)
  1537. {
  1538. if (type == ImageType.Chapter)
  1539. {
  1540. throw new ArgumentException("Cannot set chapter images using SetImagePath");
  1541. }
  1542. var image = GetImageInfo(type, index);
  1543. if (image == null)
  1544. {
  1545. ImageInfos.Add(GetImageInfo(file, type));
  1546. }
  1547. else
  1548. {
  1549. var imageInfo = GetImageInfo(file, type);
  1550. image.Path = file.FullName;
  1551. image.DateModified = imageInfo.DateModified;
  1552. image.IsPlaceholder = false;
  1553. }
  1554. }
  1555. /// <summary>
  1556. /// Deletes the image.
  1557. /// </summary>
  1558. /// <param name="type">The type.</param>
  1559. /// <param name="index">The index.</param>
  1560. /// <returns>Task.</returns>
  1561. public Task DeleteImage(ImageType type, int index)
  1562. {
  1563. var info = GetImageInfo(type, index);
  1564. if (info == null)
  1565. {
  1566. // Nothing to do
  1567. return Task.FromResult(true);
  1568. }
  1569. // Remove it from the item
  1570. RemoveImage(info);
  1571. if (info.IsLocalFile)
  1572. {
  1573. FileSystem.DeleteFile(info.Path);
  1574. }
  1575. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1576. }
  1577. public void RemoveImage(ItemImageInfo image)
  1578. {
  1579. ImageInfos.Remove(image);
  1580. }
  1581. public virtual Task UpdateToRepository(ItemUpdateType updateReason, CancellationToken cancellationToken)
  1582. {
  1583. return LibraryManager.UpdateItem(this, updateReason, cancellationToken);
  1584. }
  1585. /// <summary>
  1586. /// Validates that images within the item are still on the file system
  1587. /// </summary>
  1588. public bool ValidateImages(IDirectoryService directoryService)
  1589. {
  1590. var allFiles = ImageInfos
  1591. .Where(i => i.IsLocalFile)
  1592. .Select(i => FileSystem.GetDirectoryName(i.Path))
  1593. .Distinct(StringComparer.OrdinalIgnoreCase)
  1594. .SelectMany(directoryService.GetFilePaths)
  1595. .ToList();
  1596. var deletedImages = ImageInfos
  1597. .Where(image => image.IsLocalFile && !allFiles.Contains(image.Path, StringComparer.OrdinalIgnoreCase))
  1598. .ToList();
  1599. if (deletedImages.Count > 0)
  1600. {
  1601. ImageInfos = ImageInfos.Except(deletedImages).ToList();
  1602. }
  1603. return deletedImages.Count > 0;
  1604. }
  1605. /// <summary>
  1606. /// Gets the image path.
  1607. /// </summary>
  1608. /// <param name="imageType">Type of the image.</param>
  1609. /// <param name="imageIndex">Index of the image.</param>
  1610. /// <returns>System.String.</returns>
  1611. /// <exception cref="System.InvalidOperationException">
  1612. /// </exception>
  1613. /// <exception cref="System.ArgumentNullException">item</exception>
  1614. public string GetImagePath(ImageType imageType, int imageIndex)
  1615. {
  1616. var info = GetImageInfo(imageType, imageIndex);
  1617. return info == null ? null : info.Path;
  1618. }
  1619. /// <summary>
  1620. /// Gets the image information.
  1621. /// </summary>
  1622. /// <param name="imageType">Type of the image.</param>
  1623. /// <param name="imageIndex">Index of the image.</param>
  1624. /// <returns>ItemImageInfo.</returns>
  1625. public ItemImageInfo GetImageInfo(ImageType imageType, int imageIndex)
  1626. {
  1627. if (imageType == ImageType.Chapter)
  1628. {
  1629. var chapter = ItemRepository.GetChapter(Id, imageIndex);
  1630. if (chapter == null)
  1631. {
  1632. return null;
  1633. }
  1634. var path = chapter.ImagePath;
  1635. if (string.IsNullOrWhiteSpace(path))
  1636. {
  1637. return null;
  1638. }
  1639. return new ItemImageInfo
  1640. {
  1641. Path = path,
  1642. DateModified = chapter.ImageDateModified,
  1643. Type = imageType
  1644. };
  1645. }
  1646. return GetImages(imageType)
  1647. .ElementAtOrDefault(imageIndex);
  1648. }
  1649. public IEnumerable<ItemImageInfo> GetImages(ImageType imageType)
  1650. {
  1651. if (imageType == ImageType.Chapter)
  1652. {
  1653. throw new ArgumentException("No image info for chapter images");
  1654. }
  1655. return ImageInfos.Where(i => i.Type == imageType);
  1656. }
  1657. /// <summary>
  1658. /// Adds the images.
  1659. /// </summary>
  1660. /// <param name="imageType">Type of the image.</param>
  1661. /// <param name="images">The images.</param>
  1662. /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
  1663. /// <exception cref="System.ArgumentException">Cannot call AddImages with chapter images</exception>
  1664. public bool AddImages(ImageType imageType, List<FileSystemMetadata> images)
  1665. {
  1666. if (imageType == ImageType.Chapter)
  1667. {
  1668. throw new ArgumentException("Cannot call AddImages with chapter images");
  1669. }
  1670. var existingImages = GetImages(imageType)
  1671. .ToList();
  1672. var newImageList = new List<FileSystemMetadata>();
  1673. var imageAdded = false;
  1674. foreach (var newImage in images)
  1675. {
  1676. if (newImage == null)
  1677. {
  1678. throw new ArgumentException("null image found in list");
  1679. }
  1680. var existing = existingImages
  1681. .FirstOrDefault(i => string.Equals(i.Path, newImage.FullName, StringComparison.OrdinalIgnoreCase));
  1682. if (existing == null)
  1683. {
  1684. newImageList.Add(newImage);
  1685. imageAdded = true;
  1686. }
  1687. else
  1688. {
  1689. if (existing.IsLocalFile)
  1690. {
  1691. existing.DateModified = FileSystem.GetLastWriteTimeUtc(newImage);
  1692. }
  1693. }
  1694. }
  1695. if (imageAdded || images.Count != existingImages.Count)
  1696. {
  1697. var newImagePaths = images.Select(i => i.FullName).ToList();
  1698. var deleted = existingImages
  1699. .Where(i => i.IsLocalFile && !newImagePaths.Contains(i.Path, StringComparer.OrdinalIgnoreCase) && !FileSystem.FileExists(i.Path))
  1700. .ToList();
  1701. ImageInfos = ImageInfos.Except(deleted).ToList();
  1702. }
  1703. ImageInfos.AddRange(newImageList.Select(i => GetImageInfo(i, imageType)));
  1704. return newImageList.Count > 0;
  1705. }
  1706. private ItemImageInfo GetImageInfo(FileSystemMetadata file, ImageType type)
  1707. {
  1708. return new ItemImageInfo
  1709. {
  1710. Path = file.FullName,
  1711. Type = type,
  1712. DateModified = FileSystem.GetLastWriteTimeUtc(file)
  1713. };
  1714. }
  1715. /// <summary>
  1716. /// Gets the file system path to delete when the item is to be deleted
  1717. /// </summary>
  1718. /// <returns></returns>
  1719. public virtual IEnumerable<FileSystemMetadata> GetDeletePaths()
  1720. {
  1721. return new[] {
  1722. new FileSystemMetadata
  1723. {
  1724. FullName = Path,
  1725. IsDirectory = IsFolder
  1726. }
  1727. }.Concat(GetLocalMetadataFilesToDelete());
  1728. }
  1729. protected List<FileSystemMetadata> GetLocalMetadataFilesToDelete()
  1730. {
  1731. if (IsFolder || !IsInMixedFolder)
  1732. {
  1733. return new List<FileSystemMetadata>();
  1734. }
  1735. var filename = System.IO.Path.GetFileNameWithoutExtension(Path);
  1736. var extensions = new[] { ".nfo", ".xml", ".srt" }.ToList();
  1737. extensions.AddRange(SupportedImageExtensionsList);
  1738. return FileSystem.GetFiles(FileSystem.GetDirectoryName(Path), extensions.ToArray(), false, false)
  1739. .Where(i => System.IO.Path.GetFileNameWithoutExtension(i.FullName).StartsWith(filename, StringComparison.OrdinalIgnoreCase))
  1740. .ToList();
  1741. }
  1742. public bool AllowsMultipleImages(ImageType type)
  1743. {
  1744. return type == ImageType.Backdrop || type == ImageType.Screenshot || type == ImageType.Chapter;
  1745. }
  1746. public Task SwapImages(ImageType type, int index1, int index2)
  1747. {
  1748. if (!AllowsMultipleImages(type))
  1749. {
  1750. throw new ArgumentException("The change index operation is only applicable to backdrops and screenshots");
  1751. }
  1752. var info1 = GetImageInfo(type, index1);
  1753. var info2 = GetImageInfo(type, index2);
  1754. if (info1 == null || info2 == null)
  1755. {
  1756. // Nothing to do
  1757. return Task.FromResult(true);
  1758. }
  1759. if (!info1.IsLocalFile || !info2.IsLocalFile)
  1760. {
  1761. // TODO: Not supported yet
  1762. return Task.FromResult(true);
  1763. }
  1764. var path1 = info1.Path;
  1765. var path2 = info2.Path;
  1766. FileSystem.SwapFiles(path1, path2);
  1767. // Refresh these values
  1768. info1.DateModified = FileSystem.GetLastWriteTimeUtc(info1.Path);
  1769. info2.DateModified = FileSystem.GetLastWriteTimeUtc(info2.Path);
  1770. return UpdateToRepository(ItemUpdateType.ImageUpdate, CancellationToken.None);
  1771. }
  1772. public virtual bool IsPlayed(User user)
  1773. {
  1774. var userdata = UserDataManager.GetUserData(user, this);
  1775. return userdata != null && userdata.Played;
  1776. }
  1777. public bool IsFavoriteOrLiked(User user)
  1778. {
  1779. var userdata = UserDataManager.GetUserData(user, this);
  1780. return userdata != null && (userdata.IsFavorite || (userdata.Likes ?? false));
  1781. }
  1782. public virtual bool IsUnplayed(User user)
  1783. {
  1784. if (user == null)
  1785. {
  1786. throw new ArgumentNullException("user");
  1787. }
  1788. var userdata = UserDataManager.GetUserData(user, this);
  1789. return userdata == null || !userdata.Played;
  1790. }
  1791. ItemLookupInfo IHasLookupInfo<ItemLookupInfo>.GetLookupInfo()
  1792. {
  1793. return GetItemLookupInfo<ItemLookupInfo>();
  1794. }
  1795. protected T GetItemLookupInfo<T>()
  1796. where T : ItemLookupInfo, new()
  1797. {
  1798. return new T
  1799. {
  1800. MetadataCountryCode = GetPreferredMetadataCountryCode(),
  1801. MetadataLanguage = GetPreferredMetadataLanguage(),
  1802. Name = GetNameForMetadataLookup(),
  1803. ProviderIds = ProviderIds,
  1804. IndexNumber = IndexNumber,
  1805. ParentIndexNumber = ParentIndexNumber,
  1806. Year = ProductionYear,
  1807. PremiereDate = PremiereDate
  1808. };
  1809. }
  1810. protected virtual string GetNameForMetadataLookup()
  1811. {
  1812. return Name;
  1813. }
  1814. /// <summary>
  1815. /// This is called before any metadata refresh and returns true or false indicating if changes were made
  1816. /// </summary>
  1817. public virtual bool BeforeMetadataRefresh()
  1818. {
  1819. _sortName = null;
  1820. var hasChanges = false;
  1821. if (string.IsNullOrEmpty(Name) && !string.IsNullOrEmpty(Path))
  1822. {
  1823. Name = FileSystem.GetFileNameWithoutExtension(Path);
  1824. hasChanges = true;
  1825. }
  1826. return hasChanges;
  1827. }
  1828. protected static string GetMappedPath(BaseItem item, string path, LocationType locationType)
  1829. {
  1830. if (locationType == LocationType.FileSystem || locationType == LocationType.Offline)
  1831. {
  1832. return LibraryManager.GetPathAfterNetworkSubstitution(path, item);
  1833. }
  1834. return path;
  1835. }
  1836. public virtual Task FillUserDataDtoValues(UserItemDataDto dto, UserItemData userData, BaseItemDto itemDto, User user, List<ItemFields> itemFields)
  1837. {
  1838. if (RunTimeTicks.HasValue)
  1839. {
  1840. double pct = RunTimeTicks.Value;
  1841. if (pct > 0)
  1842. {
  1843. pct = userData.PlaybackPositionTicks / pct;
  1844. if (pct > 0)
  1845. {
  1846. dto.PlayedPercentage = 100 * pct;
  1847. }
  1848. }
  1849. }
  1850. return Task.FromResult(true);
  1851. }
  1852. protected Task RefreshMetadataForOwnedItem(BaseItem ownedItem, bool copyTitleMetadata, MetadataRefreshOptions options, CancellationToken cancellationToken)
  1853. {
  1854. var newOptions = new MetadataRefreshOptions(options);
  1855. newOptions.SearchResult = null;
  1856. var item = this;
  1857. if (copyTitleMetadata)
  1858. {
  1859. // Take some data from the main item, for querying purposes
  1860. if (!item.Genres.SequenceEqual(ownedItem.Genres, StringComparer.Ordinal))
  1861. {
  1862. newOptions.ForceSave = true;
  1863. ownedItem.Genres = item.Genres.ToList();
  1864. }
  1865. if (!item.Studios.SequenceEqual(ownedItem.Studios, StringComparer.Ordinal))
  1866. {
  1867. newOptions.ForceSave = true;
  1868. ownedItem.Studios = item.Studios.ToList();
  1869. }
  1870. if (!item.ProductionLocations.SequenceEqual(ownedItem.ProductionLocations, StringComparer.Ordinal))
  1871. {
  1872. newOptions.ForceSave = true;
  1873. ownedItem.ProductionLocations = item.ProductionLocations.ToList();
  1874. }
  1875. if (!item.Keywords.SequenceEqual(ownedItem.Keywords, StringComparer.Ordinal))
  1876. {
  1877. newOptions.ForceSave = true;
  1878. ownedItem.Keywords = item.Keywords.ToList();
  1879. }
  1880. if (item.CommunityRating != ownedItem.CommunityRating)
  1881. {
  1882. ownedItem.CommunityRating = item.CommunityRating;
  1883. newOptions.ForceSave = true;
  1884. }
  1885. if (item.CriticRating != ownedItem.CriticRating)
  1886. {
  1887. ownedItem.CriticRating = item.CriticRating;
  1888. newOptions.ForceSave = true;
  1889. }
  1890. if (!string.Equals(item.Overview, ownedItem.Overview, StringComparison.Ordinal))
  1891. {
  1892. ownedItem.Overview = item.Overview;
  1893. newOptions.ForceSave = true;
  1894. }
  1895. if (!string.Equals(item.OfficialRating, ownedItem.OfficialRating, StringComparison.Ordinal))
  1896. {
  1897. ownedItem.OfficialRating = item.OfficialRating;
  1898. newOptions.ForceSave = true;
  1899. }
  1900. if (!string.Equals(item.CustomRating, ownedItem.CustomRating, StringComparison.Ordinal))
  1901. {
  1902. ownedItem.CustomRating = item.CustomRating;
  1903. newOptions.ForceSave = true;
  1904. }
  1905. }
  1906. return ownedItem.RefreshMetadata(newOptions, cancellationToken);
  1907. }
  1908. protected Task RefreshMetadataForOwnedVideo(MetadataRefreshOptions options, bool copyTitleMetadata, string path, CancellationToken cancellationToken)
  1909. {
  1910. var newOptions = new MetadataRefreshOptions(options);
  1911. newOptions.SearchResult = null;
  1912. var id = LibraryManager.GetNewItemId(path, typeof(Video));
  1913. // Try to retrieve it from the db. If we don't find it, use the resolved version
  1914. var video = LibraryManager.GetItemById(id) as Video;
  1915. if (video == null)
  1916. {
  1917. video = LibraryManager.ResolvePath(FileSystem.GetFileSystemInfo(path)) as Video;
  1918. newOptions.ForceSave = true;
  1919. }
  1920. if (video == null)
  1921. {
  1922. return Task.FromResult(true);
  1923. }
  1924. return RefreshMetadataForOwnedItem(video, copyTitleMetadata, newOptions, cancellationToken);
  1925. }
  1926. public string GetEtag(User user)
  1927. {
  1928. return string.Join("|", GetEtagValues(user).ToArray()).GetMD5().ToString("N");
  1929. }
  1930. protected virtual List<string> GetEtagValues(User user)
  1931. {
  1932. return new List<string>
  1933. {
  1934. DateLastSaved.Ticks.ToString(CultureInfo.InvariantCulture)
  1935. };
  1936. }
  1937. public virtual IEnumerable<Guid> GetAncestorIds()
  1938. {
  1939. return GetParents().Select(i => i.Id).Concat(LibraryManager.GetCollectionFolders(this).Select(i => i.Id));
  1940. }
  1941. public BaseItem GetTopParent()
  1942. {
  1943. if (IsTopParent)
  1944. {
  1945. return this;
  1946. }
  1947. return GetParents().FirstOrDefault(i => i.IsTopParent);
  1948. }
  1949. [IgnoreDataMember]
  1950. public virtual bool IsTopParent
  1951. {
  1952. get
  1953. {
  1954. if (this is BasePluginFolder || this is Channel)
  1955. {
  1956. return true;
  1957. }
  1958. var view = this as UserView;
  1959. if (view != null)
  1960. {
  1961. if (string.Equals(view.ViewType, CollectionType.LiveTv, StringComparison.OrdinalIgnoreCase))
  1962. {
  1963. return true;
  1964. }
  1965. if (string.Equals(view.ViewType, CollectionType.Channels, StringComparison.OrdinalIgnoreCase))
  1966. {
  1967. return true;
  1968. }
  1969. }
  1970. if (GetParent() is AggregateFolder)
  1971. {
  1972. return true;
  1973. }
  1974. return false;
  1975. }
  1976. }
  1977. [IgnoreDataMember]
  1978. public virtual bool SupportsAncestors
  1979. {
  1980. get
  1981. {
  1982. return true;
  1983. }
  1984. }
  1985. [IgnoreDataMember]
  1986. public virtual bool StopRefreshIfLocalMetadataFound
  1987. {
  1988. get
  1989. {
  1990. return true;
  1991. }
  1992. }
  1993. public virtual IEnumerable<Guid> GetIdsForAncestorQuery()
  1994. {
  1995. return new[] { Id };
  1996. }
  1997. public virtual Task Delete(DeleteOptions options)
  1998. {
  1999. return LibraryManager.DeleteItem(this, options);
  2000. }
  2001. public virtual Task OnFileDeleted()
  2002. {
  2003. // Remove from database
  2004. return Delete(new DeleteOptions
  2005. {
  2006. DeleteFileLocation = false
  2007. });
  2008. }
  2009. public virtual List<ExternalUrl> GetRelatedUrls()
  2010. {
  2011. return new List<ExternalUrl>();
  2012. }
  2013. }
  2014. }