ApiService.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439
  1. using MediaBrowser.Controller;
  2. using MediaBrowser.Controller.Entities;
  3. using MediaBrowser.Controller.Entities.Movies;
  4. using MediaBrowser.Controller.Entities.TV;
  5. using MediaBrowser.Model.DTO;
  6. using MediaBrowser.Model.Entities;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Linq;
  10. using System.Net;
  11. using System.Threading.Tasks;
  12. namespace MediaBrowser.Api
  13. {
  14. /// <summary>
  15. /// Contains some helpers for the api
  16. /// </summary>
  17. public static class ApiService
  18. {
  19. /// <summary>
  20. /// Gets an Item by Id, or the root item if none is supplied
  21. /// </summary>
  22. public static BaseItem GetItemById(string id)
  23. {
  24. Guid guid = string.IsNullOrEmpty(id) ? Guid.Empty : new Guid(id);
  25. return Kernel.Instance.GetItemById(guid);
  26. }
  27. /// <summary>
  28. /// Gets a User by Id
  29. /// </summary>
  30. /// <param name="logActivity">Whether or not to update the user's LastActivityDate</param>
  31. public static User GetUserById(string id, bool logActivity)
  32. {
  33. Guid guid = new Guid(id);
  34. User user = Kernel.Instance.Users.FirstOrDefault(u => u.Id == guid);
  35. if (logActivity)
  36. {
  37. LogUserActivity(user);
  38. }
  39. return user;
  40. }
  41. /// <summary>
  42. /// Gets the default User
  43. /// </summary>
  44. /// <param name="logActivity">Whether or not to update the user's LastActivityDate</param>
  45. public static User GetDefaultUser(bool logActivity)
  46. {
  47. User user = Kernel.Instance.GetDefaultUser();
  48. if (logActivity)
  49. {
  50. LogUserActivity(user);
  51. }
  52. return user;
  53. }
  54. /// <summary>
  55. /// Updates LastActivityDate for a given User
  56. /// </summary>
  57. public static void LogUserActivity(User user)
  58. {
  59. user.LastActivityDate = DateTime.UtcNow;
  60. Kernel.Instance.SaveUser(user);
  61. }
  62. /// <summary>
  63. /// Converts a BaseItem to a DTOBaseItem
  64. /// </summary>
  65. public async static Task<DTOBaseItem> GetDTOBaseItem(BaseItem item, User user,
  66. bool includeChildren = true,
  67. bool includePeople = true)
  68. {
  69. DTOBaseItem dto = new DTOBaseItem();
  70. List<Task> tasks = new List<Task>();
  71. tasks.Add(AttachStudios(dto, item));
  72. if (includeChildren)
  73. {
  74. tasks.Add(AttachChildren(dto, item, user));
  75. tasks.Add(AttachLocalTrailers(dto, item, user));
  76. }
  77. if (includePeople)
  78. {
  79. tasks.Add(AttachPeople(dto, item));
  80. }
  81. AttachBasicFields(dto, item, user);
  82. // Make sure all the tasks we kicked off have completed.
  83. if (tasks.Count > 0)
  84. {
  85. await Task.WhenAll(tasks).ConfigureAwait(false);
  86. }
  87. return dto;
  88. }
  89. /// <summary>
  90. /// Sets simple property values on a DTOBaseItem
  91. /// </summary>
  92. private static void AttachBasicFields(DTOBaseItem dto, BaseItem item, User user)
  93. {
  94. dto.AspectRatio = item.AspectRatio;
  95. dto.BackdropCount = item.BackdropImagePaths == null ? 0 : item.BackdropImagePaths.Count();
  96. dto.DateCreated = item.DateCreated;
  97. dto.DisplayMediaType = item.DisplayMediaType;
  98. if (item.Genres != null)
  99. {
  100. dto.Genres = item.Genres.ToArray();
  101. }
  102. dto.HasArt = !string.IsNullOrEmpty(item.ArtImagePath);
  103. dto.HasBanner = !string.IsNullOrEmpty(item.BannerImagePath);
  104. dto.HasLogo = !string.IsNullOrEmpty(item.LogoImagePath);
  105. dto.HasPrimaryImage = !string.IsNullOrEmpty(item.PrimaryImagePath);
  106. dto.HasThumb = !string.IsNullOrEmpty(item.ThumbnailImagePath);
  107. dto.Id = item.Id;
  108. dto.IsNew = item.IsRecentlyAdded(user);
  109. dto.IndexNumber = item.IndexNumber;
  110. dto.IsFolder = item.IsFolder;
  111. dto.Language = item.Language;
  112. dto.LocalTrailerCount = item.LocalTrailers == null ? 0 : item.LocalTrailers.Count();
  113. dto.Name = item.Name;
  114. dto.OfficialRating = item.OfficialRating;
  115. dto.Overview = item.Overview;
  116. // If there are no backdrops, indicate what parent has them in case the UI wants to allow inheritance
  117. if (dto.BackdropCount == 0)
  118. {
  119. int backdropCount;
  120. dto.ParentBackdropItemId = GetParentBackdropItemId(item, out backdropCount);
  121. dto.ParentBackdropCount = backdropCount;
  122. }
  123. if (item.Parent != null)
  124. {
  125. dto.ParentId = item.Parent.Id;
  126. }
  127. dto.ParentIndexNumber = item.ParentIndexNumber;
  128. // If there is no logo, indicate what parent has one in case the UI wants to allow inheritance
  129. if (!dto.HasLogo)
  130. {
  131. dto.ParentLogoItemId = GetParentLogoItemId(item);
  132. }
  133. dto.Path = item.Path;
  134. dto.PremiereDate = item.PremiereDate;
  135. dto.ProductionYear = item.ProductionYear;
  136. dto.ProviderIds = item.ProviderIds;
  137. dto.RunTimeTicks = item.RunTimeTicks;
  138. dto.SortName = item.SortName;
  139. if (item.Taglines != null)
  140. {
  141. dto.Taglines = item.Taglines.ToArray();
  142. }
  143. dto.TrailerUrl = item.TrailerUrl;
  144. dto.Type = item.GetType().Name;
  145. dto.UserRating = item.UserRating;
  146. dto.UserData = GetDTOUserItemData(item.GetUserData(user, false));
  147. Folder folder = item as Folder;
  148. if (folder != null)
  149. {
  150. dto.SpecialCounts = folder.GetSpecialCounts(user);
  151. dto.IsRoot = folder.IsRoot;
  152. dto.IsVirtualFolder = folder.IsVirtualFolder;
  153. }
  154. // Add AudioInfo
  155. Audio audio = item as Audio;
  156. if (audio != null)
  157. {
  158. dto.AudioInfo = new AudioInfo()
  159. {
  160. Album = audio.Album,
  161. AlbumArtist = audio.AlbumArtist,
  162. Artist = audio.Artist,
  163. BitRate = audio.BitRate,
  164. Channels = audio.Channels
  165. };
  166. }
  167. // Add VideoInfo
  168. Video video = item as Video;
  169. if (video != null)
  170. {
  171. dto.VideoInfo = new VideoInfo()
  172. {
  173. Height = video.Height,
  174. Width = video.Width,
  175. Codec = video.Codec,
  176. VideoType = video.VideoType,
  177. ScanType = video.ScanType
  178. };
  179. if (video.AudioStreams != null)
  180. {
  181. dto.VideoInfo.AudioStreams = video.AudioStreams.ToArray();
  182. }
  183. if (video.Subtitles != null)
  184. {
  185. dto.VideoInfo.Subtitles = video.Subtitles.ToArray();
  186. }
  187. }
  188. // Add SeriesInfo
  189. Series series = item as Series;
  190. if (series != null)
  191. {
  192. DayOfWeek[] airDays = series.AirDays == null ? new DayOfWeek[] { } : series.AirDays.ToArray(); ;
  193. dto.SeriesInfo = new SeriesInfo()
  194. {
  195. AirDays = airDays,
  196. AirTime = series.AirTime,
  197. Status = series.Status
  198. };
  199. }
  200. // Add MovieInfo
  201. Movie movie = item as Movie;
  202. if (movie != null)
  203. {
  204. int specialFeatureCount = movie.SpecialFeatures == null ? 0 : movie.SpecialFeatures.Count();
  205. dto.MovieInfo = new MovieInfo()
  206. {
  207. SpecialFeatureCount = specialFeatureCount
  208. };
  209. }
  210. }
  211. /// <summary>
  212. /// Attaches Studio DTO's to a DTOBaseItem
  213. /// </summary>
  214. private static async Task AttachStudios(DTOBaseItem dto, BaseItem item)
  215. {
  216. // Attach Studios by transforming them into BaseItemStudio (DTO)
  217. if (item.Studios != null)
  218. {
  219. Studio[] entities = await Task.WhenAll<Studio>(item.Studios.Select(c => Kernel.Instance.ItemController.GetStudio(c))).ConfigureAwait(false);
  220. dto.Studios = new BaseItemStudio[entities.Length];
  221. for (int i = 0; i < entities.Length; i++)
  222. {
  223. Studio entity = entities[i];
  224. BaseItemStudio baseItemStudio = new BaseItemStudio();
  225. baseItemStudio.Name = entity.Name;
  226. baseItemStudio.HasImage = !string.IsNullOrEmpty(entity.PrimaryImagePath);
  227. dto.Studios[i] = baseItemStudio;
  228. }
  229. }
  230. }
  231. /// <summary>
  232. /// Attaches child DTO's to a DTOBaseItem
  233. /// </summary>
  234. private static async Task AttachChildren(DTOBaseItem dto, BaseItem item, User user)
  235. {
  236. var folder = item as Folder;
  237. if (folder != null)
  238. {
  239. IEnumerable<BaseItem> children = folder.GetChildren(user);
  240. dto.Children = await Task.WhenAll<DTOBaseItem>(children.Select(c => GetDTOBaseItem(c, user, false, false))).ConfigureAwait(false);
  241. }
  242. }
  243. /// <summary>
  244. /// Attaches trailer DTO's to a DTOBaseItem
  245. /// </summary>
  246. private static async Task AttachLocalTrailers(DTOBaseItem dto, BaseItem item, User user)
  247. {
  248. if (item.LocalTrailers != null && item.LocalTrailers.Any())
  249. {
  250. dto.LocalTrailers = await Task.WhenAll<DTOBaseItem>(item.LocalTrailers.Select(c => GetDTOBaseItem(c, user, false, false))).ConfigureAwait(false);
  251. }
  252. }
  253. /// <summary>
  254. /// Attaches People DTO's to a DTOBaseItem
  255. /// </summary>
  256. private static async Task AttachPeople(DTOBaseItem dto, BaseItem item)
  257. {
  258. // Attach People by transforming them into BaseItemPerson (DTO)
  259. if (item.People != null)
  260. {
  261. IEnumerable<Person> entities = await Task.WhenAll<Person>(item.People.Select(c => Kernel.Instance.ItemController.GetPerson(c.Key))).ConfigureAwait(false);
  262. dto.People = item.People.Select(p =>
  263. {
  264. BaseItemPerson baseItemPerson = new BaseItemPerson();
  265. baseItemPerson.Name = p.Key;
  266. baseItemPerson.Overview = p.Value.Overview;
  267. baseItemPerson.Type = p.Value.Type;
  268. Person ibnObject = entities.First(i => i.Name.Equals(p.Key, StringComparison.OrdinalIgnoreCase));
  269. if (ibnObject != null)
  270. {
  271. baseItemPerson.HasImage = !string.IsNullOrEmpty(ibnObject.PrimaryImagePath);
  272. }
  273. return baseItemPerson;
  274. }).ToArray();
  275. }
  276. }
  277. /// <summary>
  278. /// If an item does not any backdrops, this can be used to find the first parent that does have one
  279. /// </summary>
  280. private static Guid? GetParentBackdropItemId(BaseItem item, out int backdropCount)
  281. {
  282. backdropCount = 0;
  283. var parent = item.Parent;
  284. while (parent != null)
  285. {
  286. if (parent.BackdropImagePaths != null && parent.BackdropImagePaths.Any())
  287. {
  288. backdropCount = parent.BackdropImagePaths.Count();
  289. return parent.Id;
  290. }
  291. parent = parent.Parent;
  292. }
  293. return null;
  294. }
  295. /// <summary>
  296. /// If an item does not have a logo, this can be used to find the first parent that does have one
  297. /// </summary>
  298. private static Guid? GetParentLogoItemId(BaseItem item)
  299. {
  300. var parent = item.Parent;
  301. while (parent != null)
  302. {
  303. if (!string.IsNullOrEmpty(parent.LogoImagePath))
  304. {
  305. return parent.Id;
  306. }
  307. parent = parent.Parent;
  308. }
  309. return null;
  310. }
  311. /// <summary>
  312. /// Gets an ImagesByName entity along with the number of items containing it
  313. /// </summary>
  314. public static IBNItem GetIBNItem(BaseEntity entity, int itemCount)
  315. {
  316. return new IBNItem()
  317. {
  318. Id = entity.Id,
  319. BaseItemCount = itemCount,
  320. HasImage = !string.IsNullOrEmpty(entity.PrimaryImagePath),
  321. Name = entity.Name
  322. };
  323. }
  324. /// <summary>
  325. /// Converts a User to a DTOUser
  326. /// </summary>
  327. public static DTOUser GetDTOUser(User user)
  328. {
  329. return new DTOUser()
  330. {
  331. Id = user.Id,
  332. Name = user.Name,
  333. HasImage = !string.IsNullOrEmpty(user.PrimaryImagePath),
  334. HasPassword = !string.IsNullOrEmpty(user.Password),
  335. LastActivityDate = user.LastActivityDate,
  336. LastLoginDate = user.LastLoginDate
  337. };
  338. }
  339. /// <summary>
  340. /// Converts a UserItemData to a DTOUserItemData
  341. /// </summary>
  342. public static DTOUserItemData GetDTOUserItemData(UserItemData data)
  343. {
  344. if (data == null)
  345. {
  346. return null;
  347. }
  348. return new DTOUserItemData()
  349. {
  350. IsFavorite = data.IsFavorite,
  351. Likes = data.Likes,
  352. PlaybackPositionTicks = data.PlaybackPositionTicks,
  353. PlayCount = data.PlayCount,
  354. Rating = data.Rating
  355. };
  356. }
  357. public static bool IsApiUrlMatch(string url, HttpListenerRequest request)
  358. {
  359. url = "/api/" + url;
  360. return request.Url.LocalPath.EndsWith(url, StringComparison.OrdinalIgnoreCase);
  361. }
  362. }
  363. }