OftenContactRepository.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Threading.Tasks;
  4. using System.Transactions;
  5. using AutoMapper;
  6. using GxPress.Common.AppOptions;
  7. using GxPress.Common.Exceptions;
  8. using GxPress.Common.Tools;
  9. using GxPress.Entity;
  10. using GxPress.Repository.Interface;
  11. using GxPress.Request.App.OftenContact;
  12. using GxPress.Result.App.OftenContact;
  13. using Microsoft.Extensions.Options;
  14. using Datory;
  15. using SqlKata;
  16. using Dapper;
  17. using GxPress.Result.Job;
  18. using System.Linq;
  19. namespace GxPress.Repository.Implement
  20. {
  21. public class OftenContactRepository : IOftenContactRepository
  22. {
  23. private readonly Repository<OftenContact> _repository;
  24. private readonly Repository<User> _userRepository;
  25. private readonly Repository<ChatRecord> _chatRecordRepository;
  26. private readonly Repository<GroupChat> _groupChatRepository;
  27. private readonly Repository<Entity.Middle.Middle> _middleRepository;
  28. private readonly IMapper _mapper;
  29. private readonly string _connectionString;
  30. private readonly string _databaseTypeStr;
  31. public OftenContactRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper)
  32. {
  33. _databaseTypeStr = dbOptionsAccessor.CurrentValue.DatabaseType;
  34. _connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
  35. var databaseType = StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
  36. var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
  37. _repository = new Repository<OftenContact>(database);
  38. _userRepository = new Repository<User>(database);
  39. _chatRecordRepository = new Repository<ChatRecord>(database);
  40. _groupChatRepository = new Repository<GroupChat>(database);
  41. _middleRepository = new Repository<Entity.Middle.Middle>(database);
  42. _mapper = mapper;
  43. }
  44. public IDatabase Database => _repository.Database;
  45. public string TableName => _repository.TableName;
  46. public List<TableColumn> TableColumns => _repository.TableColumns;
  47. public async Task<bool> DeleteAsync(int id)
  48. {
  49. return await _repository.DeleteAsync(id);
  50. }
  51. /// <summary>
  52. /// 添加好友关系
  53. /// </summary>
  54. /// <param name="request"></param>
  55. /// <param name="userId"></param>
  56. /// <returns></returns>
  57. public async Task<bool> InsertAsync(OftenContactInRequest request, int userId)
  58. {
  59. if (string.IsNullOrEmpty(request.ContactUserId))
  60. throw new BusinessException("缺少必要字段");
  61. if (request.ChatType == 0)
  62. throw new BusinessException("类型必须");
  63. var count = await _repository.CountAsync(Q.Where(nameof(OftenContact.UserId), userId)
  64. .Where(nameof(OftenContact.ContactUserId), request.ContactUserId));
  65. if (count > 0)
  66. {
  67. //修改好友关系
  68. await _repository.UpdateAsync(Q.Set(nameof(OftenContact.IsDelete), false)
  69. .Where(nameof(OftenContact.UserId), userId)
  70. .Where(nameof(OftenContact.ContactUserId), request.ContactUserId));
  71. if (request.ChatType == 1)
  72. await _repository.UpdateAsync(Q.Set(nameof(OftenContact.IsDelete), false)
  73. .Where(nameof(OftenContact.UserId), int.Parse(request.ContactUserId))
  74. .Where(nameof(OftenContact.ContactUserId), userId));
  75. return true;
  76. }
  77. try
  78. {
  79. using (TransactionScope transactionScope = new TransactionScope())
  80. {
  81. if (request.ChatType == 1)
  82. {
  83. var oftenContact = new OftenContact
  84. {
  85. IndividualGroupId = request.IndividualGroupId,
  86. ContactUserId = request.ContactUserId,
  87. UserId = userId,
  88. ChatType = request.ChatType,
  89. IsBlack = false,
  90. IsDelete = false
  91. };
  92. await _repository.InsertAsync(oftenContact);
  93. oftenContact = new OftenContact
  94. {
  95. IndividualGroupId = 0,
  96. ContactUserId = userId.ToString(),
  97. UserId = int.Parse(request.ContactUserId),
  98. ChatType = request.ChatType,
  99. IsBlack = false,
  100. IsDelete = false
  101. };
  102. await _repository.InsertAsync(oftenContact);
  103. }
  104. else
  105. {
  106. var oftenContact = new OftenContact
  107. {
  108. IndividualGroupId = request.IndividualGroupId,
  109. ContactUserId = request.ContactUserId,
  110. UserId = userId,
  111. ChatType = request.ChatType,
  112. IsBlack = false,
  113. IsDelete = false
  114. };
  115. await _repository.InsertAsync(oftenContact);
  116. }
  117. transactionScope.Complete();
  118. }
  119. }
  120. catch (Exception e)
  121. {
  122. Console.WriteLine(e);
  123. throw;
  124. }
  125. return true;
  126. }
  127. /// <summary>
  128. /// 修改黑名单
  129. /// </summary>
  130. /// <param name="userId"></param>
  131. /// <param name="blackUserId"></param>
  132. /// <returns></returns>
  133. public async Task<bool> SetBlackUserAsync(int userId, int blackUserId)
  134. {
  135. //获取
  136. var oftenContact = await _repository.GetAsync(Q.Where(nameof(OftenContact.UserId), userId)
  137. .Where(nameof(OftenContact.ContactUserId), blackUserId.ToString()));
  138. if (oftenContact != null)
  139. {
  140. oftenContact.IsBlack = !oftenContact.IsBlack;
  141. return await _repository.UpdateAsync(oftenContact);
  142. }
  143. return true;
  144. }
  145. public async Task<OftenContact> FindOftenContactAsync(int userId, string groupChatImId)
  146. {
  147. return await _repository.GetAsync(Q.Where(nameof(OftenContact.UserId), userId)
  148. .Where(nameof(OftenContact.ContactUserId), groupChatImId));
  149. }
  150. /// <summary>
  151. /// 移除当前文件夹关系
  152. /// </summary>
  153. /// <param name="request"></param>
  154. /// <returns></returns>
  155. public async Task<bool> RemoveOftenContactAsync(OftenContactDeRequest request)
  156. {
  157. var oftenContact = await _repository.GetAsync(request.OftenContactId);
  158. oftenContact.IndividualGroupId = 0;
  159. return await _repository.UpdateAsync(oftenContact);
  160. }
  161. /// <summary>
  162. /// 设置置顶
  163. /// </summary>
  164. /// <returns></returns>
  165. public async Task<bool> SetOftenContactIsTopAsync(OftenContactDeRequest request)
  166. {
  167. var oftenContact = await _repository.GetAsync(request.OftenContactId);
  168. if (oftenContact == null)
  169. throw new BusinessException("聊天不存在");
  170. return await _repository.UpdateAsync(Q.Set(nameof(OftenContact.IsTop), !oftenContact.IsTop)
  171. .Where(nameof(oftenContact.Id), request.OftenContactId)) > 0;
  172. }
  173. /// <summary>
  174. /// 移动到文件夹
  175. /// </summary>
  176. /// <param name="request"></param>
  177. /// <returns></returns>
  178. public async Task<bool> MoveOftenContactToIndividualGroupAsync(OftenContactUpRequest request)
  179. {
  180. return await _repository.UpdateAsync(Q
  181. .Set(nameof(OftenContact.IndividualGroupId), request.IndividualGroupId)
  182. .WhereIn(nameof(OftenContact.Id), request.OftenContactIds)) > 0;
  183. }
  184. /// <summary>
  185. /// 删除聊天界面
  186. /// </summary>
  187. /// <param name="oftenContactIds"></param>
  188. /// <returns></returns>
  189. public async Task<bool> DeleteAsync(List<int> oftenContactIds)
  190. {
  191. return await _repository.UpdateAsync(Q.Set(nameof(OftenContact.IsDelete), true)
  192. .WhereIn(nameof(OftenContact.Id), oftenContactIds)) > 0;
  193. }
  194. /// <summary>
  195. /// 获取是否置顶
  196. /// </summary>
  197. /// <param name="userId"></param>
  198. /// <param name="imId"></param>
  199. /// <returns></returns>
  200. public async Task<bool> GetIsTopAsync(int userId, string imId)
  201. {
  202. var oftenContact = await _repository.GetAsync(Q.Where(nameof(Entity.OftenContact.UserId), userId)
  203. .Where(nameof(Entity.OftenContact.ContactUserId), imId));
  204. if (oftenContact == null)
  205. return false;
  206. var midel = await _middleRepository.GetAsync(Q.Where(nameof(Entity.Middle.Middle.FolderType), 10).Where(nameof(Entity.Middle.Middle.MiddleId), oftenContact.Id));
  207. return midel.IsTop;
  208. }
  209. public async Task<int> CountAsync(Query query)
  210. {
  211. return await _repository.CountAsync(query);
  212. }
  213. public async Task<bool> UpdateAsync(Query query)
  214. {
  215. return await _repository.UpdateAsync(query) > 0;
  216. }
  217. public async Task<int> InsertAsync(OftenContact oftenContact)
  218. {
  219. return await _repository.InsertAsync(oftenContact);
  220. }
  221. /// <summary>
  222. /// 插入多个
  223. /// </summary>
  224. /// <param name="oftenContacts"></param>
  225. /// <returns></returns>
  226. public async Task<bool> InsertAsync(List<OftenContact> oftenContacts)
  227. {
  228. if (oftenContacts.Count == 0 || oftenContacts == null)
  229. return false;
  230. string sql = @"INSERT INTO `tede_often_contact`(`Guid`,`CreatedDate`,`LastModifiedDate`,`UserId`,`ContactUserId`,`IndividualGroupId`,`UpdateTime`,`ChatType`,`IsBlack`,`IsTop`,`IsDelete`)VALUES";
  231. foreach (var item in oftenContacts)
  232. {
  233. var guId = Guid.NewGuid().ToString();
  234. var nowTime = System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
  235. var isBlack = item.IsBlack ? 1 : 0;
  236. var isTop = item.IsTop ? 1 : 0;
  237. var isDelete = item.IsDelete ? 1 : 0;
  238. sql += $@"('{guId}','{nowTime}','{nowTime}',{item.UserId},'{item.ContactUserId}',{item.IndividualGroupId},'{nowTime}',{item.ChatType},{isBlack},{isTop},{isDelete}),";
  239. }
  240. sql = sql.Remove(sql.Length - 1, 1);
  241. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  242. var database = new Database(databaseType, _connectionString);
  243. var connection = database.GetConnection();
  244. return await connection.ExecuteAsync(sql) > 0;
  245. }
  246. public async Task<Entity.OftenContact> GetAsync(SqlKata.Query query)
  247. {
  248. return await _repository.GetAsync(query);
  249. }
  250. public async Task<IEnumerable<Entity.OftenContact>> GetAllAsync(SqlKata.Query query)
  251. {
  252. return await _repository.GetAllAsync(query);
  253. }
  254. /// <summary>
  255. /// 根据用户ID获取最近聊天用户
  256. /// </summary>
  257. /// <param name="userId"></param>
  258. /// <returns></returns>
  259. public async Task<IEnumerable<int>> GetAllAsync(int userId)
  260. {
  261. return await _repository.GetAllAsync<int>(Q.Select(nameof(OftenContact.ContactUserId)).Where(nameof(OftenContact.UserId), userId).Where(nameof(OftenContact.ChatType), 1));
  262. }
  263. public async Task<IEnumerable<OftenContactInfo>> GetContactInfosAsync(OftenContactSearchRequest request)
  264. {
  265. var sql =
  266. $"select a.*,b.* from tede_middle a left join tede_often_contact b on a.MiddleId=b.Id where a.FolderType=10 and a.UserId={request.UserId} and a.ParentId={request.IndividualGroupId} and a.IsDelete=0 order by a. IsTop desc,a.LastModifiedDate desc";
  267. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  268. var database = new Database(databaseType, _connectionString);
  269. var connection = database.GetConnection();
  270. var result =
  271. await connection
  272. .QueryAsync<OftenContactInfo, Entity.OftenContact, OftenContactInfo>(sql,
  273. (oftenContactInfo, oftenContact) =>
  274. {
  275. oftenContactInfo.ChatType = oftenContact == null ? 0 : oftenContact.ChatType;
  276. oftenContactInfo.ContactUserId = oftenContact == null ? "" : oftenContact.ContactUserId;
  277. return oftenContactInfo;
  278. }, splitOn: "Id,Id");
  279. return result;
  280. }
  281. public async Task<IEnumerable<OftenContactInfo>> GetContactInfoAllAsync(OftenContactSearchRequest request)
  282. {
  283. var sql =
  284. $"select a.*,b.* from tede_middle a inner join tede_often_contact b on a.MiddleId=b.Id where a.FolderType=10 and a.UserId={request.UserId} and a.IsDelete=0 order by a. IsTop desc,a.LastModifiedDate desc";
  285. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  286. var database = new Database(databaseType, _connectionString);
  287. var connection = database.GetConnection();
  288. var result =
  289. await connection
  290. .QueryAsync<OftenContactInfo, Entity.OftenContact, OftenContactInfo>(sql,
  291. (oftenContactInfo, oftenContact) =>
  292. {
  293. oftenContactInfo.ChatType = oftenContact == null ? 0 : oftenContact.ChatType;
  294. oftenContactInfo.ContactUserId = oftenContact == null ? "" : oftenContact.ContactUserId;
  295. return oftenContactInfo;
  296. }, splitOn: "Id,Id");
  297. return result;
  298. }
  299. /// <summary>
  300. /// 获取全局索引聊天群
  301. /// </summary>
  302. /// <returns></returns>
  303. public async Task<List<JobChatResult>> ElasticSearchGroupChat()
  304. {
  305. string sql = "select a.Id,a.GuId,a.MiddleId,a.UserId,a.CreatedDate,b.ContactUserId,c.AvatarUrl,c.Name from tede_middle a inner join tede_often_contact b on a.MiddleId=b.Id inner join tede_group_chat c on c.GroupChatImId=b.ContactUserId where a.FolderType=10 and b.ChatType=2 and a.IsUpload=0 order by a.CreatedDate desc limit 0,100";
  306. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  307. var database = new Database(databaseType, _connectionString);
  308. var connection = database.GetConnection();
  309. var result =
  310. await connection
  311. .QueryAsync<JobChatResult, Entity.OftenContact, Entity.GroupChat, JobChatResult>(sql,
  312. (jobChatResult, oftenContact, groupChat) =>
  313. {
  314. jobChatResult.ChatType = 2;
  315. jobChatResult.Name = groupChat != null ? groupChat.Name : "";
  316. jobChatResult.AvatarUrl = groupChat != null ? groupChat.AvatarUrl : "";
  317. jobChatResult.ImId = oftenContact != null ? oftenContact.ContactUserId : "";
  318. return jobChatResult;
  319. }, splitOn: "Id,ContactUserId,AvatarUrl");
  320. return result.ToList();
  321. }
  322. /// <summary>
  323. /// 获取全局索引聊天
  324. /// </summary>
  325. /// <returns></returns>
  326. public async Task<List<JobChatResult>> ElasticSearchChat()
  327. {
  328. string sql = "select a.Id,a.GuId,a.MiddleId,a.UserId,a.CreatedDate,b.ContactUserId,c.AvatarUrl,c.Name,c.ImId from tede_middle a inner join tede_often_contact b on a.MiddleId=b.Id inner join tede_user c on c.Id=b.ContactUserId where a.FolderType=10 and b.ChatType=1 and a.IsUpload=0 order by a.CreatedDate desc limit 0,100";
  329. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  330. var database = new Database(databaseType, _connectionString);
  331. var connection = database.GetConnection();
  332. var result =
  333. await connection
  334. .QueryAsync<JobChatResult, Entity.OftenContact, Entity.User, JobChatResult>(sql,
  335. (jobChatResult, oftenContact, user) =>
  336. {
  337. jobChatResult.ChatType = 1;
  338. jobChatResult.Name = user != null ? user.Name : "";
  339. jobChatResult.AvatarUrl = user != null ? user.AvatarUrl : "";
  340. jobChatResult.ImId = user != null ? user.ImId : "";
  341. jobChatResult.ToUserId = oftenContact != null ? Convert.ToInt32(oftenContact.ContactUserId) : 0;
  342. return jobChatResult;
  343. }, splitOn: "Id,ContactUserId,AvatarUrl");
  344. return result.ToList();
  345. }
  346. }
  347. }