BaseItem.cs 75 KB

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