BaseItem.cs 75 KB

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