using GDZZ.Core; using Furion.DependencyInjection; using Furion.DynamicApiController; using Mapster; using Microsoft.AspNetCore.Mvc; using System.Linq; using System.Threading.Tasks; using GDZZ.Application.Entity; using System.Collections.Generic; using K4os.Hash.xxHash; using GDZZ.Core.Entity; using Furion; using GDZZ.Application.Help; using Furion.LinqBuilder; using System; using static K4os.Compression.LZ4.Engine.Pubternal; using Microsoft.AspNetCore.SignalR; using GDZZ.Application.Service.LiveHistoryContacts.Dto; using Microsoft.AspNetCore.Http; using SqlSugar; using System.IO; using Yitter.IdGenerator; using Microsoft.Extensions.Options; using ICacheService = GDZZ.Application.Help.ICacheService; namespace GDZZ.Application { /// /// 聊天服务 /// [ApiDescriptionSettings("Application", Name = "LiveHistoryContacts", Order = 1)] public class LiveHistoryContactsService : ILiveHistoryContactsService, IDynamicApiController, ITransient { private readonly SqlSugarRepository _rep; //聊天历史任务列表仓储 private readonly SqlSugarRepository liveMessageRep; //消息仓储 private readonly SqlSugarRepository liveUserFriend; //好友表仓储 private readonly SqlSugarRepository _sysUserRep; // 用户表仓储 private readonly SqlSugarRepository _sysOnlineUerRep; // 在线用户表仓储 private readonly ICacheService cacheService; private readonly IHubContext _chatHubContext; private readonly UploadFileOptions _options; public LiveHistoryContactsService(SqlSugarRepository rep, ICacheService cacheService, IOptions options, SqlSugarRepository _sysUserRep, SqlSugarRepository sysOnlineUerRep, SqlSugarRepository liveUserFriend, IHubContext chatHubContext, SqlSugarRepository liveMessageRep) { _rep = rep; _options = options.Value; this.cacheService = cacheService; this._chatHubContext= chatHubContext; this._sysOnlineUerRep = sysOnlineUerRep; this.liveUserFriend = liveUserFriend; this.liveMessageRep = liveMessageRep; this._sysUserRep = _sysUserRep; } #region 聊天列表 /// /// 新增联系人 /// /// [HttpPost("/Mini/LiveHistoryContacts/AddLive")] public async Task AddLive(AddLiveHistoryContactsInput input) { var entity = input.Adapt(); await _rep.InsertAsync(entity); await this.cacheService.DelLiveHistoryService(UserManager.UserId); } /// /// 修改消息条数 /// /// [HttpPut("/Mini/LiveHistoryContacts/UPLive")] public async Task UPLive(UpdateLiveHistoryContactsInput input) { var entity = input.Adapt(); await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync(); await this.cacheService.DelLiveHistoryService(UserManager.UserId); } /// /// 删除联系人 /// /// [HttpDelete("/Mini/LiveHistoryContacts/DelLive")] public async Task DelLive(long ID) { var entity = await this.liveUserFriend.SingleAsync(x => x.Id == ID); await _rep.DeleteAsync(entity); await this.cacheService.DelLiveHistoryService(UserManager.UserId); } /// /// 获取联系人 /// /// /// [HttpGet("/Mini/LiveHistoryContacts/list")] public async Task> List() { var history = await this.cacheService.GetLiveHistoryService(UserManager.UserId); if (!history.IsNullOrEmpty()) return history; List historyLists = new List(); //获取好友列表 var friends = await this.liveUserFriend.Where(x => x.CreatedUserId == UserManager.UserId).ToListAsync(); foreach (var item in friends) { //获取用户信息 var sysUser = await this._sysUserRep.SingleAsync(x => x.Id == item.FriendID); if (sysUser == null) continue; var liveHis = new LiveHistoryLists() { Avatar = sysUser.Avatar, DisplayName = sysUser.NickName, Id = item.FriendID, Index = sysUser.Name.Substring(0, 1), LastSendTime = (DateTime.Now.ToUniversalTime().Ticks - 621355968000000000) / 10000000, Unread = await this.cacheService.GetUnreadAsync(UserManager.UserId) }; //查询聊天记录 //rm -rf mk dir ls install cd home //ru-rf var live = await this.liveMessageRep.Where(x => x.CreatedUserId == UserManager.UserId && x.OtherUserID == item.FriendID || (x.CreatedUserId == item.FriendID && x.OtherUserID == UserManager.UserId)).OrderByDescending(x =>x.CreatedTime).FirstAsync(); if (live != null) { liveHis.LastSendTime = (live.SendTime.ToUniversalTime().Ticks - 621355968000000000) / 10000; liveHis.LastSendTimeData = live.SendTime; liveHis.LastContent = live.Content; liveHis.Type = live.Type; } historyLists.Add(liveHis); } await this.cacheService.SetLiveHistoryService(UserManager.UserId, historyLists); return historyLists; } #endregion #region 聊天详情 /// /// 获取聊天详情 /// /// [HttpGet("/Mini/LiveHistoryContacts/GetMessageLists")] public async Task> GetMessageLists(long OtherUserID) { var res = await this.liveMessageRep.Where(x => x.CreatedUserId == UserManager.UserId && x.OtherUserID == OtherUserID).ToListAsync(); return res.Adapt>(); } /// /// 增加聊天详情 /// /// /// [HttpPost("/Mini/LiveHistoryContacts/addMessage")] public async Task AddMessage(AddLiveMessageInput input) { var entity = input.Adapt(); var live = this.liveMessageRep.InsertReturnEntity(entity); var user = await _sysOnlineUerRep.Where(m => m.UserId == entity.OtherUserID).OrderByDescending(x=>x.LastTime).FirstAsync(); if (user != null) { var livemes = new LiveMessageInput() { id = live.Id.ToString(), type = live.Type, content = live.Content, sendTime = new DateTimeOffset((DateTime)live.CreatedTime).ToUnixTimeSeconds(), status = "succeed", toContactId = entity.OtherUserID, fromUser = new Fromuser() { avatar = this._sysUserRep.FirstOrDefaultAsync(x => x.Id == UserManager.UserId).Result.Avatar, displayName = UserManager.Name, id = UserManager.UserId } }; await this.cacheService.SetUnreadAsync(UserManager.UserId); await this.cacheService.SetUnreadAsync(entity.OtherUserID); var livejson = livemes.ToJsonString(); await _chatHubContext.Clients.Client(user.ConnectionId).SendMessage(livejson, "SendMessage"); } } /// /// 上传文件 /// /// /// [HttpPost("/Mini/LiveHistoryContacts/upload")] public async Task UploadFileDefault(IFormFile file) { // 可以读取系统配置来决定将文件存储到什么地方 return await UploadFile(file, _options.Default.path, FileLocation.LOCAL); } /// /// 上传文件 /// /// /// /// private static async Task UploadFile(IFormFile file, string pathType, FileLocation fileLocation) { var fileSizeKb = (long)(file.Length / 1024.0); // 文件大小KB var originalFilename = file.FileName; // 文件原始名称 var fileSuffix = Path.GetExtension(file.FileName).ToLower(); // 文件后缀 // 先存库获取Id var id = YitIdHelper.NextId(); var newFile = new SysFile { Id = id, FileLocation = (int)FileLocation.LOCAL, FileBucket = FileLocation.LOCAL.ToString(), FileObjectName = $"{YitIdHelper.NextId()}{fileSuffix}", FileOriginName = originalFilename, FileSuffix = fileSuffix.TrimStart('.'), FileSizeKb = fileSizeKb.ToString(), FilePath = pathType }; newFile = await App.GetService().Insertable(newFile).ExecuteReturnEntityAsync(); var finalName = newFile.FileObjectName; // 生成文件的最终名称 if (fileLocation == FileLocation.LOCAL) // 本地存储 { var filePath = Path.Combine(App.WebHostEnvironment.WebRootPath, pathType); if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath); using (var stream = File.Create(Path.Combine(filePath, finalName))) { await file.CopyToAsync(stream); } } else if (fileLocation == FileLocation.ALIYUN) // 阿里云OSS { var filePath = pathType + finalName; OSSClientUtil.DeletefileCode(filePath); var stream = file.OpenReadStream(); OSSClientUtil.PushMedia(stream, filePath); } newFile.FileObjectName = finalName; return new LiveFileOutput() { Id = finalName, FileUrl= "/"+pathType + "/"+ finalName }; // 返回文件唯一标识 } #endregion } }