BaseItem.cs 80 KB

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