BaseItem.cs 76 KB

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