using HuanMeng.MiaoYu.Code.Cache.Contract;
using HuanMeng.MiaoYu.Model.DbSqlServer.Db_MiaoYu;
using HuanMeng.MiaoYu.Model.Dto.Music;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json;
using HuanMeng.MiaoYu.Code.Chat.Contract;
using Org.BouncyCastle.Utilities;
using HuanMeng.MiaoYu.Code.Users;
using Org.BouncyCastle.Crypto;
using HuanMeng.MiaoYu.Model.Dto;
using HuanMeng.MiaoYu.Code.DataAccess;
using HuanMeng.MiaoYu.Code.Cache.Special;
using HuanMeng.MiaoYu.Model.Dto.Shop;
using HuanMeng.MiaoYu.Model.EnumModel.Product;
namespace HuanMeng.MiaoYu.Code.Music
{
///
/// ai音乐逻辑类
///
public class MusicBLL : MiaoYuBase
{
public MusicBLL(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
///
/// 获取音乐分类
///
///
public Task>> GetMusicGenresList()
{
//图片
var genresList = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList(this, it => it.IsEnabled);
var list = Mapper.Map>(genresList);
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();
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 = 0,
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);
}
///
/// 创建音乐
///
///
///
///
public async Task> CreateMusic(MusicCreateRequest musicCreateRequest)
{
if (_UserId == 0)
{
throw new Exception("请先登录");
}
UserInfoBLL userInfoBLL = new UserInfoBLL(Dao, _UserId);
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);
}
//扣除货币
userInfoBLL[UserCurrencyType.音乐点数].ConsumeMoneyNoWork(-10, Dao);
Dao.daoDbMiaoYu.context.SaveChanges();
return new BaseResponse(ResonseCode.Success, "音乐正在生成", m_SongInfo.Id) { };
}
///
/// 获取音乐生成进度
///
///
///
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;
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) { };
}
}
///
///
///
///
///
///
///
///
///
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);
}
}
}