BaseItem.cs 75 KB

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