using HuanMeng.MiaoYu.Code.Cache.Special; using HuanMeng.MiaoYu.Model.Dto.Music; using HuanMeng.MiaoYu.Model.Dto.Shop; using HuanMeng.MiaoYu.Model.EnumModel.Product; using Newtonsoft.Json; using StackExchange.Redis; using System.Net.Http.Headers; namespace HuanMeng.MiaoYu.Code.Music { /// /// ai音乐逻辑类 /// public class MusicBLL : MiaoYuBase { public MusicBLL(IServiceProvider serviceProvider) : base(serviceProvider) { } /// /// /// /// /// public async Task> GetAppConfig(string? version) { var images = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList(this); MusicConfigDto musicConfigDto = new MusicConfigDto() { IsCheck = false, MallBanner = images.GetImageUrl(9002), MyPageMallEntrance = images.GetImageUrl(9001) }; return new BaseResponse(ResonseCode.Success, "", musicConfigDto) { }; } /// /// 获取音乐分类 /// /// public Task>> GetMusicGenresList() { //图片 var genresList = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList(this, it => it.IsEnabled); var list = Mapper.Map>(genresList); var obj = Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.IsPublic).GroupBy(it => it.GenreId).Select(it => new { GenreId = it.Key, Count = it.Count() }).ToList(); if (obj != null) { list = list.Where(it => obj.Any(item => item.GenreId == it.Id)).ToList(); } list.Insert(0, new MusicGenresDto() { Id = 0, GenreName = "推荐" }); return Task.FromResult(new BaseResponse>(ResonseCode.Success, "", list)); } /// /// 获取用户信息 /// /// public async Task> GetUserInfo() { var user = await Dao.daoDbMiaoYu.context.T_User.FirstOrDefaultAsync(it => it.Id == _UserId); if (user == null) { throw new Exception("用户不存在"); } //获取用户余额 UserInfoBLL userInfoBLL = new UserInfoBLL(Dao, _UserId); var Currency = userInfoBLL[UserCurrencyType.音乐点数]?.CurrencyMoney; string sqlString = $@"select isnull(sum(PlayCount),0) PlayCount,isnull(sum(LikeCount),0) LikeCount,isnull(sum(DownloadCount),0) DownloadCount from M_Songs where AuthorId={_UserId}"; var info = Dao.daoDbMiaoYu.context.Database.SqlQueryRaw(sqlString).FirstOrDefault(); var songVipInfo = IsMusicVipInfo(); List characters = new List(); return new BaseResponse(ResonseCode.Success, "请求成功", new MusicUserDto { NickName = user.NickName, UserId = user.Id, UserIconUrl = string.IsNullOrEmpty(user?.UserIconUrl) ? "https://cos.shhuanmeng.com/default.png" : user?.UserIconUrl, Vip = songVipInfo.isVip ? 1 : 0, VipExpirationAt = songVipInfo.expirationAt, DownloadCount = info.DownloadCount, LikeCount = info.LikeCount, PlayCount = info.PlayCount, MusicPoints = (int)Currency }); } /// /// 分类下详情列表,每次只显示50个 /// /// /// public async Task>> GetMusicGenresInfo(int genresId) { List list = new List(); if (genresId == 0) { list = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.IsPublic) .OrderByDescending(it => it.CreationTimestamp).Take(50) .ToListAsync(); } else { list = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.GenreId == genresId && it.IsPublic) .OrderByDescending(it => it.CreationTimestamp).Take(50) .ToListAsync(); } var data = Mapper.Map>(list); if (_UserId > 0) { var fList = await Dao.daoDbMiaoYu.context.M_Favorites.Where(it => it.UserId == _UserId).Select(it => it.SongId).ToListAsync(); var lList = await Dao.daoDbMiaoYu.context.M_Likes.Where(it => it.UserId == _UserId).Select(it => it.SongId).ToListAsync(); if (fList == null) { fList = new List(); } if (lList == null) { lList = new List(); } data.ForEach(it => { if (fList.Contains(it.Id)) { it.IsFavorites = true; } if (lList.Contains(it.Id)) { it.IsLikes = true; } }); } return new BaseResponse>(ResonseCode.Success, "", data); } /// /// 创作页面音乐标签 /// /// public async Task>> GetUserMusicGenresList() { List musicUserGenresDtos = new List(); //图片 var genresList = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList(this, it => it.IsEnabled)?.Select(it => new MusicUserGenresDto() { GenreName = it.GenreName, GenreType = 0, OrderId = it.OrderId }).ToList(); musicUserGenresDtos.AddRange(genresList ?? new List()); var _userList = await Dao.daoDbMiaoYu.context.M_UserGenres.Where(it => it.UserId == _UserId).ToListAsync(); var userGenresList = _userList?.Select(it => new MusicUserGenresDto() { GenreName = it.GenreName, GenreType = 1, OrderId = it.Id }).ToList(); musicUserGenresDtos.AddRange(userGenresList ?? new List()); musicUserGenresDtos = musicUserGenresDtos.OrderBy(it => it.GenreType).ThenBy(it => it.OrderId).ToList(); return new BaseResponse>(ResonseCode.Success, "", musicUserGenresDtos); } /// /// 创建我的音乐风格 /// /// public async Task> CreateUserMusicGenres(string genresName) { if (_UserId == 0) { throw new Exception("请先登录"); } var genresCount = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList(this, it => it.IsEnabled)?.Where(it => it.GenreName == genresName).Count(); if (genresCount > 0) { throw new Exception("音乐风格名称重复"); } var c = Dao.daoDbMiaoYu.context.M_UserGenres.Where(it => it.UserId == _UserId && it.GenreName == genresName).Count(); if (c > 0) { throw new Exception("音乐风格名称重复"); } M_UserGenres m_UserGenres = new M_UserGenres() { CreateAt = DateTime.Now, GenreName = genresName, UserId = _UserId, }; Dao.daoDbMiaoYu.context.Add(m_UserGenres); await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "创建成功", true); } /// /// 我的音乐列表 /// /// public async Task>> GetMyMusicList() { var list = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.AuthorId == _UserId && it.State >= 0).ToListAsync(); var data = Mapper.Map>(list); return new BaseResponse>(ResonseCode.Success, "", data); } private bool IsMusicVip() { var songVip = Dao.daoDbMiaoYu.context.M_SongVIP.FirstOrDefault(it => it.UserId == _UserId && it.ExpirationAt > DateTime.Now); return songVip != null; } private (bool isVip, DateTime? expirationAt) IsMusicVipInfo() { var songVip = Dao.daoDbMiaoYu.context.M_SongVIP.FirstOrDefault(it => it.UserId == _UserId && it.ExpirationAt > DateTime.Now); return (songVip != null, songVip != null ? songVip?.ExpirationAt : null); } /// /// 创建音乐 /// /// /// /// public async Task> CreateMusic(MusicCreateRequest musicCreateRequest) { if (_UserId == 0) { throw new Exception("请先登录"); } bool isSongVip = IsMusicVip(); UserInfoBLL userInfoBLL = new UserInfoBLL(Dao, _UserId); if (!isSongVip) { if (!userInfoBLL.IsCheckingSufficient(UserCurrencyType.音乐点数, 10)) { throw new Exception("音乐点数不足"); } } bool isGenresId = false; var genresId = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList(this, it => it.IsEnabled)?.FirstOrDefault(it => it.GenreName == musicCreateRequest.GenreName)?.Id; if (genresId == null || genresId <= 0) { isGenresId = true; genresId = Dao.daoDbMiaoYu.context.M_UserGenres.Where(it => it.UserId == _UserId && it.GenreName == musicCreateRequest.GenreName).FirstOrDefault()?.Id; } Dictionary keyValuePairs = new Dictionary(); keyValuePairs.Add("gpt_description_prompt", $"歌曲风格:{musicCreateRequest.GenreName}"); keyValuePairs.Add("make_instrumental", false); keyValuePairs.Add("mv", "chirp-v3-5"); keyValuePairs.Add("prompt", musicCreateRequest.Prompt); var requestBody = JsonConvert.SerializeObject(keyValuePairs); var httpClient = HttpClientFactory.CreateClient(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); httpClient.DefaultRequestHeaders.Add("authorization", "Bearer hk-ylg6c31000042000fef54b80aec96b39e83b36f6e551440b"); var content = new StringContent(requestBody, Encoding.UTF8, "application/json"); var url = "https://api.openai-hk.com/sunoapi/generate/description-mode"; var response = await httpClient.PostAsync(url, content); if (response == null || !response.IsSuccessStatusCode) { throw new Exception("创建音乐失败"); } var responseContent = await response.Content.ReadAsStringAsync(); if (string.IsNullOrEmpty(responseContent)) { throw new Exception("创建音乐失败!"); } var obj = JsonConvert.DeserializeObject(responseContent); var id = obj?["id"]?.ToString() ?? ""; var musicId1 = obj?.SelectToken("clips[0].id")?.ToString(); var musicId2 = obj?.SelectToken("clips[1].id")?.ToString(); M_SongInfo m_SongInfo = new M_SongInfo() { CompleteAt = DateTime.Now, CreateAt = DateTime.Now, GetUrl = url, RequestInfo = requestBody, ResonseInfo = responseContent, Status = "正在生成", UpdateAt = DateTime.Now, UserId = _UserId }; Dao.daoDbMiaoYu.context.Add(m_SongInfo); Dao.daoDbMiaoYu.context.SaveChanges(); if (string.IsNullOrEmpty(musicId1) && string.IsNullOrEmpty(musicId2)) { throw new Exception("创建音乐失败!!!"); } if (!string.IsNullOrEmpty(musicId1)) { var song1 = GetSong(musicCreateRequest.GenreName, musicCreateRequest.Name, musicId1, m_SongInfo.Id, genresId); song1.AuthorName = userInfoBLL.UserName; song1.IsUserGenre = isGenresId; Dao.daoDbMiaoYu.context.Add(song1); } if (!string.IsNullOrEmpty(musicId2)) { var song2 = GetSong(musicCreateRequest.GenreName, musicCreateRequest.Name, musicId2, m_SongInfo.Id, genresId); song2.AuthorName = userInfoBLL.UserName; song2.IsUserGenre = isGenresId; Dao.daoDbMiaoYu.context.Add(song2); } //扣除货币 if (!isSongVip) { userInfoBLL[UserCurrencyType.音乐点数].ConsumeMoneyNoWork(-10, Dao); } else { var log = new T_User_Currency_Log() { Consume = 0, ConsumeType = 0, CreateTime = DateTime.Now, CurrencyType = (int)UserCurrencyType.音乐点数, UpdateTime = DateTime.Now, UserId = _UserId, Remarks = "会员生成音乐", Title = "音乐生成", OrderId = "", IsHide = false }; Dao.daoDbMiaoYu.context.T_User_Currency_Log.Add(log); } Dao.daoDbMiaoYu.context.SaveChanges(); return new BaseResponse(ResonseCode.Success, "音乐正在生成", m_SongInfo.Id) { }; } /// /// 删除音乐 /// /// /// public async Task> DelMusic(int id) { var s = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.Id == id && it.AuthorId == _UserId).FirstOrDefaultAsync(); if (s == null) { return new BaseResponse(ResonseCode.Success, "未找到音乐", false); } s.State = -2; s.IsPublic = false; await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "删除成功", false); } /// /// 获取音乐生成进度 /// /// /// public async Task> GetMusicSchedule(int id) { var s = await Dao.daoDbMiaoYu.context.M_SongInfo.Where(it => it.Id == id).FirstOrDefaultAsync(); if (s?.Status == "已完成") { return new BaseResponse(ResonseCode.Success, "", true); } return new BaseResponse(ResonseCode.Success, "", false); } /// /// 歌曲审核 /// /// /// public async Task> MusicSongsReview(int id) { var songs = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.Id == id).FirstOrDefaultAsync(); if (songs == null) { throw new Exception("歌曲不存在"); } if (songs.State == 0) { throw new Exception("请等待歌曲生成成功"); } if (songs.State == -3) { throw new Exception("歌曲审核失败"); } if (songs.State == 3 && songs.IsPublic) { throw new Exception("歌曲已经在公开状态中"); } if (songs.State == 3 && !songs.IsPublic) { songs.IsPublic = true; await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "歌曲已公开", true); } //songs.State = 2; songs.State = 3; songs.IsPublic = true; await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "歌曲已提交审核", true); } /// /// 取消审核 /// /// /// /// public async Task> MusicCancelSongsReview(int id) { var songs = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.Id == id).FirstOrDefaultAsync(); if (songs == null) { throw new Exception("歌曲不存在"); } if (songs.State == 0) { throw new Exception("请等待歌曲生成成功"); } if (songs.State == 2) { songs.State = 1; } if (songs.State == 3) { songs.IsPublic = false; } await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "歌曲已取消公开", true); } /// /// 点赞和取消点赞 /// /// /// /// public async Task> MusicSongLike(int id) { var songs = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.Id == id).FirstOrDefaultAsync(); if (songs == null) { throw new Exception("歌曲不存在"); } if (songs.State <= 0) { throw new Exception("请等待歌曲生成成功"); } var likes = await Dao.daoDbMiaoYu.context.M_Likes.FirstOrDefaultAsync(it => it.SongId == songs.Id && it.UserId == _UserId); if (likes == null) { likes = new M_Likes() { LikedAt = DateTime.Now, SongId = songs.Id, UserId = _UserId }; Dao.daoDbMiaoYu.context.Add(likes); songs.LikeCount++; await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "点赞成功", true) { }; } else { Dao.daoDbMiaoYu.context.M_Likes.Remove(likes); songs.LikeCount--; if (songs.LikeCount <= 0) { songs.LikeCount = 0; } await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "取消点赞成功", true) { }; } } /// /// 收藏和取消收藏 /// /// /// /// public async Task> MusicSongFavorites(int id) { var songs = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.Id == id).FirstOrDefaultAsync(); if (songs == null) { throw new Exception("歌曲不存在"); } if (songs.State <= 0) { throw new Exception("请等待歌曲生成成功"); } var likes = await Dao.daoDbMiaoYu.context.M_Favorites.FirstOrDefaultAsync(it => it.SongId == songs.Id && it.UserId == _UserId); if (likes == null) { likes = new M_Favorites() { FavoritedAt = DateTime.Now, SongId = songs.Id, UserId = _UserId, }; Dao.daoDbMiaoYu.context.Add(likes); songs.FavoritesCount++; await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "收藏成功", true) { }; } else { Dao.daoDbMiaoYu.context.M_Favorites.Remove(likes); songs.FavoritesCount--; if (songs.FavoritesCount <= 0) { songs.FavoritesCount = 0; } await Dao.daoDbMiaoYu.context.SaveChangesAsync(); return new BaseResponse(ResonseCode.Success, "取消收藏成功", true) { }; } } /// /// 获取我的收藏 /// /// /// /// public async Task>> GetMusicSongFavorites() { var favorites = await Dao.daoDbMiaoYu.context.M_Favorites.Where(it => it.UserId == _UserId).Select(it => it.SongId).ToListAsync(); if (favorites == null || favorites.Count == 0) { return new BaseResponse>(ResonseCode.Success, "", new List()); } var list = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => favorites.Contains(it.Id)).ToListAsync(); if (list == null || list.Count == 0) { return new BaseResponse>(ResonseCode.Success, "", new List()); } var data = Mapper.Map>(list); return new BaseResponse>(ResonseCode.Success, "", data); } /// /// 获取我的收藏 /// /// /// /// public async Task>> GetMusicSongLikes() { var likes = await Dao.daoDbMiaoYu.context.M_Likes.Where(it => it.UserId == _UserId).Select(it => it.SongId).ToListAsync(); if (likes == null || likes.Count == 0) { return new BaseResponse>(ResonseCode.Success, "", new List()); } var list = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => likes.Contains(it.Id)).ToListAsync(); if (list == null || list.Count == 0) { return new BaseResponse>(ResonseCode.Success, "", new List()); } var data = Mapper.Map>(list); return new BaseResponse>(ResonseCode.Success, "", data); } /// /// /// /// /// /// /// /// /// private M_Songs GetSong(string genreName, string name, string musicId1, int songInfoId, int? genresId) { M_Songs m_Songs = new M_Songs() { AuthorId = _UserId, CoverImage = "https://cos.shhuanmeng.com/yinyue/fengmian.png", CreationTimestamp = DateTime.Now, DownloadCount = 0, LikeCount = 0, PlayCount = 0, Duration = TimeOnly.MinValue, Genre = genreName, GenreId = genresId, ImageLargeUrl = "https://cos.shhuanmeng.com/yinyue/fengmian.png", IsPublic = false, Lyrics = "", MusicAddress = "", SongInfoId = songInfoId, SpecialId = musicId1, State = 0, Title = name, FavoritesCount = 0, }; return m_Songs; } /// /// 商城 /// /// public async Task> GetShopInfoList() { MShopInfoDto myAccountInfoDto = new MShopInfoDto(); UserInfoBLL user = new UserInfoBLL(Dao, _UserId); Dictionary orderDictionary = new Dictionary(); if (_UserId > 0) { orderDictionary = Dao.daoDbMiaoYu.context.T_Order .Where(it => it.UserId == _UserId) .GroupBy(it => it.ProductId) .ToDictionary(it => it.Key, it => it.Count()); } ProductEntityCache productEntityCache = new ProductEntityCache(this); var list = productEntityCache.GetMallItemDto(ProductType.音乐点数商城, orderDictionary); myAccountInfoDto.ProductList = list; var list1 = productEntityCache.GetMallItemDto(ProductType.音乐VIP商城, orderDictionary); myAccountInfoDto.VipList = list1; return new BaseResponse(ResonseCode.Success, "", myAccountInfoDto); } } }