BaseItem.cs 76 KB

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