BaseItem.cs 75 KB

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