HuanMengProject/src/0-core/HuanMeng.MiaoYu.Code/Music/MusicBLL.cs
2024-09-29 20:22:15 +08:00

600 lines
24 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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
{
/// <summary>
/// ai音乐逻辑类
/// </summary>
public class MusicBLL : MiaoYuBase
{
public MusicBLL(IServiceProvider serviceProvider) : base(serviceProvider)
{
}
/// <summary>
///
/// </summary>
/// <param name="version"></param>
/// <returns></returns>
public async Task<BaseResponse<MusicConfigDto>> GetAppConfig(string? version)
{
var images = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList<T_Image_Config>(this);
MusicConfigDto musicConfigDto = new MusicConfigDto()
{
IsCheck = true,
MallBanner = images.GetImageUrl(9002),
MyPageMallEntrance = images.GetImageUrl(9001)
};
return new BaseResponse<MusicConfigDto>(ResonseCode.Success, "", musicConfigDto) { };
}
/// <summary>
/// 获取音乐分类
/// </summary>
/// <returns></returns>
public Task<BaseResponse<List<MusicGenresDto>>> GetMusicGenresList()
{
//图片
var genresList = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList<M_MusicGenres>(this, it => it.IsEnabled);
var list = Mapper.Map<List<MusicGenresDto>>(genresList);
list.Insert(0, new MusicGenresDto()
{
Id = 0,
GenreName = "推荐"
});
return Task.FromResult(new BaseResponse<List<MusicGenresDto>>(ResonseCode.Success, "", list));
}
/// <summary>
/// 获取用户信息
/// </summary>
/// <returns></returns>
public async Task<BaseResponse<MusicUserDto>> 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<MusicSongsInfo>(sqlString).FirstOrDefault();
List<CreateCharacterInfo> characters = new List<CreateCharacterInfo>();
return new BaseResponse<MusicUserDto>(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
});
}
/// <summary>
/// 分类下详情列表每次只显示50个
/// </summary>
/// <param name="genresId"></param>
/// <returns></returns>
public async Task<BaseResponse<List<MusicSongInfoDto>>> GetMusicGenresInfo(int genresId)
{
List<M_Songs> list = new List<M_Songs>();
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<MusicSongInfoDto>>(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<int>();
}
if (lList == null)
{
lList = new List<int>();
}
data.ForEach(it =>
{
if (fList.Contains(it.Id))
{
it.IsFavorites = true;
}
if (lList.Contains(it.Id))
{
it.IsLikes = true;
}
});
}
return new BaseResponse<List<MusicSongInfoDto>>(ResonseCode.Success, "", data);
}
/// <summary>
/// 创作页面音乐标签
/// </summary>
/// <returns></returns>
public async Task<BaseResponse<List<MusicUserGenresDto>>> GetUserMusicGenresList()
{
List<MusicUserGenresDto> musicUserGenresDtos = new List<MusicUserGenresDto>();
//图片
var genresList = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList<M_MusicGenres>(this, it => it.IsEnabled)?.Select(it => new MusicUserGenresDto() { GenreName = it.GenreName, GenreType = 0, OrderId = it.OrderId }).ToList();
musicUserGenresDtos.AddRange(genresList ?? new List<MusicUserGenresDto>());
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<MusicUserGenresDto>());
musicUserGenresDtos = musicUserGenresDtos.OrderBy(it => it.GenreType).ThenBy(it => it.OrderId).ToList();
return new BaseResponse<List<MusicUserGenresDto>>(ResonseCode.Success, "", musicUserGenresDtos);
}
/// <summary>
/// 创建我的音乐风格
/// </summary>
/// <returns></returns>
public async Task<BaseResponse<bool>> CreateUserMusicGenres(string genresName)
{
if (_UserId == 0)
{
throw new Exception("请先登录");
}
var genresCount = MiaoYuCacheExtend.GetMiaoYuDataEntityCacheList<M_MusicGenres>(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<bool>(ResonseCode.Success, "创建成功", true);
}
/// <summary>
/// 我的音乐列表
/// </summary>
/// <returns></returns>
public async Task<BaseResponse<List<MusicSongInfoDto>>> GetMyMusicList()
{
var list = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => it.AuthorId == _UserId && it.State >= 0).ToListAsync();
var data = Mapper.Map<List<MusicSongInfoDto>>(list);
return new BaseResponse<List<MusicSongInfoDto>>(ResonseCode.Success, "", data);
}
/// <summary>
/// 创建音乐
/// </summary>
/// <param name="musicCreateRequest"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<BaseResponse<int>> 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<M_MusicGenres>(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<string, object> keyValuePairs = new Dictionary<string, object>();
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<JObject>(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<int>(ResonseCode.Success, "音乐正在生成", m_SongInfo.Id) { };
}
/// <summary>
/// 删除音乐
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<BaseResponse<bool>> 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<bool>(ResonseCode.Success, "未找到音乐", false);
}
s.State = -2;
s.IsPublic = false;
await Dao.daoDbMiaoYu.context.SaveChangesAsync();
return new BaseResponse<bool>(ResonseCode.Success, "删除成功", false);
}
/// <summary>
/// 获取音乐生成进度
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<BaseResponse<bool>> GetMusicSchedule(int id)
{
var s = await Dao.daoDbMiaoYu.context.M_SongInfo.Where(it => it.Id == id).FirstOrDefaultAsync();
if (s?.Status == "已完成")
{
return new BaseResponse<bool>(ResonseCode.Success, "", true);
}
return new BaseResponse<bool>(ResonseCode.Success, "", false);
}
/// <summary>
/// 歌曲审核
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public async Task<BaseResponse<bool>> 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<bool>(ResonseCode.Success, "歌曲已公开", true);
}
songs.State = 2;
await Dao.daoDbMiaoYu.context.SaveChangesAsync();
return new BaseResponse<bool>(ResonseCode.Success, "歌曲已提交审核", true);
}
/// <summary>
/// 取消审核
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<BaseResponse<bool>> 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<bool>(ResonseCode.Success, "歌曲已取消公开", true);
}
/// <summary>
/// 点赞和取消点赞
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<BaseResponse<bool>> 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<bool>(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<bool>(ResonseCode.Success, "取消点赞成功", true) { };
}
}
/// <summary>
/// 收藏和取消收藏
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<BaseResponse<bool>> 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<bool>(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<bool>(ResonseCode.Success, "取消收藏成功", true) { };
}
}
/// <summary>
/// 获取我的收藏
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<BaseResponse<List<MusicSongInfoDto>>> 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<List<MusicSongInfoDto>>(ResonseCode.Success, "", new List<MusicSongInfoDto>());
}
var list = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => favorites.Contains(it.Id)).ToListAsync();
if (list == null || list.Count == 0)
{
return new BaseResponse<List<MusicSongInfoDto>>(ResonseCode.Success, "", new List<MusicSongInfoDto>());
}
var data = Mapper.Map<List<MusicSongInfoDto>>(list);
return new BaseResponse<List<MusicSongInfoDto>>(ResonseCode.Success, "", data);
}
/// <summary>
/// 获取我的收藏
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
/// <exception cref="Exception"></exception>
public async Task<BaseResponse<List<MusicSongInfoDto>>> 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<List<MusicSongInfoDto>>(ResonseCode.Success, "", new List<MusicSongInfoDto>());
}
var list = await Dao.daoDbMiaoYu.context.M_Songs.Where(it => likes.Contains(it.Id)).ToListAsync();
if (list == null || list.Count == 0)
{
return new BaseResponse<List<MusicSongInfoDto>>(ResonseCode.Success, "", new List<MusicSongInfoDto>());
}
var data = Mapper.Map<List<MusicSongInfoDto>>(list);
return new BaseResponse<List<MusicSongInfoDto>>(ResonseCode.Success, "", data);
}
/// <summary>
///
/// </summary>
/// <param name="genreName"></param>
/// <param name="name"></param>
/// <param name="musicId1"></param>
/// <param name="songInfoId"></param>
/// <param name="genresId"></param>
/// <returns></returns>
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;
}
/// <summary>
/// 商城
/// </summary>
/// <returns></returns>
public async Task<BaseResponse<MShopInfoDto>> GetShopInfoList()
{
MShopInfoDto myAccountInfoDto = new MShopInfoDto();
UserInfoBLL user = new UserInfoBLL(Dao, _UserId);
Dictionary<string, int> orderDictionary = new Dictionary<string, int>();
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<MShopInfoDto>(ResonseCode.Success, "", myAccountInfoDto);
}
}
}