OftenContactRepository.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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<List<OftenContactInfo>> GetContactInfosAsync(OftenContactSearchRequest request)
  264. {
  265. var chatConst = GxPress.EnumConst.AllTypeConst.Wechat.GetHashCode();
  266. var sql =
  267. $@"SELECT
  268. a.Id,
  269. a.AttributeValue,
  270. a.FolderName,
  271. a.FolderType,
  272. b.CreatedDate,
  273. b.LastModifiedDate,
  274. b.UserId,
  275. b.ContactUserId,
  276. b.IndividualGroupId,
  277. b.UpdateTime,
  278. b.ChatType,
  279. b.IsBlack,
  280. a.IsTop,
  281. a.IsDelete
  282. FROM
  283. tede_middle a
  284. LEFT JOIN
  285. tede_often_contact b ON a.MiddleId = b.Id
  286. WHERE
  287. a.FolderType = {chatConst} AND a.UserId = {request.UserId}
  288. AND a.ParentId = {request.IndividualGroupId}
  289. AND a.IsDelete = 0
  290. ORDER BY a.IsTop DESC , a.LastModifiedDate DESC";
  291. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  292. var database = new Database(databaseType, _connectionString);
  293. var connection = database.GetConnection();
  294. var result =
  295. await connection
  296. .QueryAsync<OftenContactInfo>(sql);
  297. return result.ToList();
  298. }
  299. public async Task<IEnumerable<OftenContactInfo>> GetContactInfoAllAsync(OftenContactSearchRequest request)
  300. {
  301. var sql =
  302. $"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";
  303. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  304. var database = new Database(databaseType, _connectionString);
  305. var connection = database.GetConnection();
  306. var result =
  307. await connection
  308. .QueryAsync<OftenContactInfo, Entity.OftenContact, OftenContactInfo>(sql,
  309. (oftenContactInfo, oftenContact) =>
  310. {
  311. oftenContactInfo.ChatType = oftenContact == null ? 0 : oftenContact.ChatType;
  312. oftenContactInfo.ContactUserId = oftenContact == null ? "" : oftenContact.ContactUserId;
  313. return oftenContactInfo;
  314. }, splitOn: "Id,Id");
  315. return result;
  316. }
  317. /// <summary>
  318. /// 获取全局索引聊天群
  319. /// </summary>
  320. /// <returns></returns>
  321. public async Task<List<JobChatResult>> ElasticSearchGroupChat()
  322. {
  323. 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";
  324. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  325. var database = new Database(databaseType, _connectionString);
  326. var connection = database.GetConnection();
  327. var result =
  328. await connection
  329. .QueryAsync<JobChatResult, Entity.OftenContact, Entity.GroupChat, JobChatResult>(sql,
  330. (jobChatResult, oftenContact, groupChat) =>
  331. {
  332. jobChatResult.ChatType = 2;
  333. jobChatResult.Name = groupChat != null ? groupChat.Name : "";
  334. jobChatResult.AvatarUrl = groupChat != null ? groupChat.AvatarUrl : "";
  335. jobChatResult.ImId = oftenContact != null ? oftenContact.ContactUserId : "";
  336. return jobChatResult;
  337. }, splitOn: "Id,ContactUserId,AvatarUrl");
  338. return result.ToList();
  339. }
  340. /// <summary>
  341. /// 获取全局索引聊天
  342. /// </summary>
  343. /// <returns></returns>
  344. public async Task<List<JobChatResult>> ElasticSearchChat()
  345. {
  346. 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";
  347. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  348. var database = new Database(databaseType, _connectionString);
  349. var connection = database.GetConnection();
  350. var result =
  351. await connection
  352. .QueryAsync<JobChatResult, Entity.OftenContact, Entity.User, JobChatResult>(sql,
  353. (jobChatResult, oftenContact, user) =>
  354. {
  355. jobChatResult.ChatType = 1;
  356. jobChatResult.Name = user != null ? user.Name : "";
  357. jobChatResult.AvatarUrl = user != null ? user.AvatarUrl : "";
  358. jobChatResult.ImId = user != null ? user.ImId : "";
  359. jobChatResult.ToUserId = oftenContact != null ? Convert.ToInt32(oftenContact.ContactUserId) : 0;
  360. return jobChatResult;
  361. }, splitOn: "Id,ContactUserId,AvatarUrl");
  362. return result.ToList();
  363. }
  364. }
  365. }