TopicRepository.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using System.Threading.Tasks;
  4. using AutoMapper;
  5. using Dapper;
  6. using GxPress.Common.AppOptions;
  7. using GxPress.Common.Page;
  8. using GxPress.Common.Tools;
  9. using GxPress.Entity;
  10. using GxPress.Repository.Interface;
  11. using GxPress.Request.App.Topic;
  12. using GxPress.Result.App.Topic;
  13. using Microsoft.Extensions.Options;
  14. using Datory;
  15. using GxPress.Entity.Topic;
  16. using GxPress.Result;
  17. using SqlKata;
  18. using GxPress.Result.Job;
  19. using GxPress.EnumConst;
  20. using Newtonsoft.Json;
  21. namespace GxPress.Repository.Implement
  22. {
  23. public class TopicRepository : ITopicRepository
  24. {
  25. private readonly Repository<Entity.Topic.Topic> _repository;
  26. private readonly Repository<TopicAddressee> _topicAddresseeRepository;
  27. private readonly Repository<User> _userRepository;
  28. private readonly IMapper _mapper;
  29. private readonly string _connectionString;
  30. private readonly string _databaseTypeStr;
  31. private readonly Repository<GroupUser> _groupUserRepository;
  32. private readonly Repository<Entity.Visit.Visit> _visitRepository;
  33. public TopicRepository(IOptionsMonitor<DatabaseOptions> dbOptionsAccessor, IMapper mapper)
  34. {
  35. _databaseTypeStr = dbOptionsAccessor.CurrentValue.DatabaseType;
  36. _connectionString = dbOptionsAccessor.CurrentValue.ConnectionString;
  37. var databaseType = StringUtils.ToEnum<DatabaseType>(dbOptionsAccessor.CurrentValue.DatabaseType, DatabaseType.MySql);
  38. var database = new Database(databaseType, dbOptionsAccessor.CurrentValue.ConnectionString);
  39. _repository = new Repository<Entity.Topic.Topic>(database);
  40. _topicAddresseeRepository = new Repository<TopicAddressee>(database);
  41. _userRepository = new Repository<User>(database);
  42. _groupUserRepository = new Repository<GroupUser>(database);
  43. _visitRepository = new Repository<Entity.Visit.Visit>(database);
  44. _mapper = mapper;
  45. }
  46. public IDatabase Database => _repository.Database;
  47. public string TableName => _repository.TableName;
  48. public List<TableColumn> TableColumns => _repository.TableColumns;
  49. /// <summary>
  50. /// 根据userId获取话题
  51. /// </summary>
  52. /// <param name="request"></param>
  53. /// <returns></returns>
  54. public async Task<PagedList<Entity.Topic.Topic>> GetTopicByUserIdAsync(TopicPageSearchRequest request)
  55. {
  56. var query = Q.NewQuery();
  57. if (request.UserId > 0)
  58. {
  59. query.Where(nameof(Entity.Topic.Topic.UserId), request.UserId);
  60. }
  61. if (!string.IsNullOrEmpty(request.Keyword))
  62. {
  63. var like = $"%{request.Keyword}%";
  64. query.WhereLike(nameof(Entity.Topic.Topic.Title), like);
  65. }
  66. var pagedList = new PagedList<Entity.Topic.Topic>
  67. {
  68. Total = await _repository.CountAsync(query)
  69. };
  70. var list = await _repository.GetAllAsync(query.ForPage(request.Page, request.PerPage));
  71. pagedList.Items = list;
  72. return pagedList;
  73. }
  74. /// <summary>
  75. /// APP列表显示用
  76. /// </summary>
  77. /// <param name="contentJsonDataList"></param>
  78. /// <returns></returns>
  79. public List<ContentJsonData> GetListAsync(List<ContentJsonData> contentJsonDataList)
  80. {
  81. var result = new List<ContentJsonData>();
  82. if (contentJsonDataList.Count > 0)
  83. {
  84. //查询文本
  85. var txtType = contentJsonDataList.FirstOrDefault(n => n.Type == 1);
  86. if (txtType != null)
  87. result.Add(txtType);
  88. //拼接图片
  89. var imgType = contentJsonDataList.FindAll(n => n.Type == 2);
  90. if (imgType.Any())
  91. {
  92. foreach (var item in imgType)
  93. {
  94. //判断图片数量
  95. if (result.Count(n => n.Type == 2) > 8)
  96. break;
  97. result.Add(item);
  98. }
  99. }
  100. }
  101. return result;
  102. }
  103. /// <summary>
  104. /// 根据GroupId获取通知
  105. /// </summary>
  106. /// <param name="request"></param>
  107. /// <returns></returns>
  108. public async Task<PagedList<TopicListPageResult>> FindTopicByGroupIdAsync(TopicDetailListRequest request)
  109. {
  110. var topicConts = GxPress.EnumConst.AllTypeConst.Topic.GetHashCode();
  111. //用户收件人
  112. var resultData = new PagedList<TopicListPageResult>();
  113. var showKey = $@"SELECT a.*,(SELECT
  114. COUNT(1)
  115. FROM
  116. tede_analyze
  117. WHERE
  118. TypeValue ={topicConts}
  119. AND SourceId = a.Id
  120. AND AnalyzeType = 1) AS PraiseCount,
  121. (SELECT
  122. COUNT(1)
  123. FROM
  124. tede_analyze
  125. WHERE
  126. UserId = {request.UserId} AND TypeValue = {topicConts}
  127. AND SourceId = a.Id
  128. AND AnalyzeType = 1
  129. LIMIT 0 , 1) AS IsPraise,
  130. (SELECT
  131. COUNT(1)
  132. FROM
  133. tede_comment
  134. WHERE
  135. ArticleId = a.Id and pid=0
  136. AND TypeValue = 1) AS CommentCount,
  137. (SELECT
  138. COUNT(1)
  139. FROM
  140. tede_analyze
  141. WHERE
  142. UserId = {request.UserId} AND TypeValue = {topicConts}
  143. AND SourceId = a.Id
  144. AND AnalyzeType = 4) AS RetransmissionCount,
  145. (SELECT
  146. COUNT(1)
  147. FROM
  148. tede_analyze
  149. WHERE
  150. UserId = {request.UserId} AND TypeValue = {topicConts}
  151. AND SourceId = a.Id
  152. AND AnalyzeType = 4
  153. LIMIT 0 , 1) AS IsRetransmission,
  154. (SELECT
  155. COUNT(1)
  156. FROM
  157. tede_analyze
  158. WHERE
  159. UserId = {request.UserId} AND TypeValue = {topicConts}
  160. AND SourceId = a.Id
  161. AND AnalyzeType = 4
  162. LIMIT 0 , 1) AS IsCollect,
  163. (SELECT
  164. COUNT(1)
  165. FROM
  166. tede_analyze
  167. WHERE
  168. UserId = {request.UserId} AND TypeValue = {topicConts}
  169. AND SourceId = a.Id
  170. AND AnalyzeType = 4) AS CollectCount,b.Name,b.AvatarUrl,c.Name FROM";
  171. var countSql = $"SELECT count(1) FROM tede_topic a inner join tede_user b on a.UserId=b.Id inner join tede_Department c on c.Id=b.DepartmentId where a.GroupId={request.GroupId}";
  172. var sql =
  173. $"{showKey} tede_topic a inner join tede_user b on a.UserId=b.Id inner join tede_Department c on c.Id=b.DepartmentId where a.GroupId={request.GroupId}";
  174. var strValue = "";
  175. if (!string.IsNullOrEmpty(request.Key))
  176. strValue += $" and (a.Title like '%{request.Key}%' or a.TextContent like '%{request.Key}%' or b.Name like '%{request.Key}%')";
  177. sql += $"{strValue} order by a.CreatedDate DESC LIMIT @page , @pageSize";
  178. countSql += $"{strValue}";
  179. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  180. var database = new Database(databaseType, _connectionString);
  181. var connection = database.GetConnection();
  182. var result =
  183. connection
  184. .Query<TopicListPageResult, User, Department, TopicListPageResult>(sql,
  185. (topicListPageResult, user, department) =>
  186. {
  187. topicListPageResult.DepartmentName = department.Name;
  188. topicListPageResult.UserName = user.Name;
  189. topicListPageResult.AvatarUrl = StringUtils.AddDomainMin(user.AvatarUrl);
  190. return topicListPageResult;
  191. }, new { page = (request.Page - 1) * request.PerPage, pageSize = request.PerPage }, splitOn: "Name");
  192. resultData.Total = await connection.ExecuteScalarAsync<int>(countSql);
  193. var topicListPageResults = result as TopicListPageResult[] ?? result.ToArray();
  194. resultData.Items = topicListPageResults;
  195. return resultData;
  196. }
  197. /// <summary>
  198. ///最新 小组话题分页列表
  199. /// </summary>
  200. /// <param name="request"></param>
  201. /// <returns></returns>
  202. public async Task<PagedList<TopicListPageResult>> GetGroupTopicPageAsync(SqlKata.Query query, SqlKata.Query countQuery, TopicDetailListRequest request)
  203. {
  204. var result = new PagedList<TopicListPageResult>();
  205. result.Items = await _repository.GetAllAsync<TopicListPageResult>(query);
  206. foreach (var item in result.Items)
  207. {
  208. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  209. }
  210. result.Total = await _repository.CountAsync(countQuery);
  211. //回去小组草稿数量
  212. query = Q.NewQuery();
  213. query.WhereIn(nameof(Entity.Topic.Topic.GroupId), request.GroupIds);
  214. query.Where(nameof(Entity.Topic.Topic.IsDraft), true);
  215. query.Where(nameof(Entity.Topic.Topic.UserId), request.UserId);
  216. result.DraftCount = await CountAsync(query);
  217. return result;
  218. }
  219. /// <summary>
  220. /// 获取共享小组
  221. /// </summary>
  222. /// <returns></returns>
  223. public async Task<IEnumerable<int>> GetPublicGroupAsync(int userId)
  224. {
  225. string sql = $@"select Id from tede_group where (IsAdmin=0 or id in (select groupId FROM tede_group_user where userId={userId}))";
  226. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  227. var database = new Database(databaseType, _connectionString);
  228. var connection = database.GetConnection();
  229. var result = await connection.QueryAsync<int>(sql);
  230. return result;
  231. }
  232. /// <summary>
  233. /// 我加入的小组
  234. /// </summary>
  235. /// <param name="userId"></param>
  236. /// <returns></returns>
  237. public async Task<IEnumerable<int>> GetIntoGroupAsync(int userId)
  238. {
  239. string sql = $"select a.Id from tede_group a inner join tede_group_user b on a.Id=b.GroupId where b.UserId={userId}";
  240. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  241. var database = new Database(databaseType, _connectionString);
  242. var connection = database.GetConnection();
  243. return await connection.QueryAsync<int>(sql);
  244. }
  245. /// <summary>
  246. /// 根据小组ID获取话题数量
  247. /// </summary>
  248. /// <param name="groupId"></param>
  249. /// <returns></returns>
  250. public async Task<int> GetGroupTopicCountAsync(int groupId)
  251. {
  252. return await _repository.CountAsync(Q.Where(nameof(Entity.Topic.Topic.GroupId), groupId));
  253. }
  254. /// <summary>
  255. /// 根据ID获取话题
  256. /// </summary>
  257. /// <param name="id"></param>
  258. /// <returns></returns>
  259. public async Task<Entity.Topic.Topic> GetAsync(int id)
  260. {
  261. return await _repository.GetAsync(id);
  262. }
  263. public async Task<int> CountAsync(Query query)
  264. {
  265. return await _repository.CountAsync(query);
  266. }
  267. public async Task<IEnumerable<Entity.Topic.Topic>> GetAllAsync(Query query)
  268. {
  269. return await _repository.GetAllAsync(query);
  270. }
  271. public async Task<int> InsertAsync(Entity.Topic.Topic topic)
  272. {
  273. return await _repository.InsertAsync(topic);
  274. }
  275. public async Task<bool> DeleteAsync(int id)
  276. {
  277. return await _repository.DeleteAsync(id);
  278. }
  279. public async Task<bool> UpdateAsync(Entity.Topic.Topic topic)
  280. {
  281. return await _repository.UpdateAsync(topic);
  282. }
  283. /// <summary>
  284. /// 执行话题
  285. /// </summary>
  286. /// <returns></returns>
  287. public async Task<List<JobTopicResult>> ExecuteTopic()
  288. {
  289. string sql = @"select a.*,b.UserId,b.Id,c.Name,d.AvatarUrl from tede_topic a
  290. inner join tede_topic_addressee b on a.Id=b.TopicId
  291. inner join tede_user c on c.Id=b.UserId
  292. inner join tede_user d on d.Id=a.UserId
  293. where b.IsUpload=0
  294. order by a.CreatedDate desc limit 0,100";
  295. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  296. var database = new Database(databaseType, _connectionString);
  297. var connection = database.GetConnection();
  298. var result = await connection.QueryAsync<JobTopicResult, TopicAddressee, User, User, JobTopicResult>(sql, (jobTopicResult, topicAddressee, user, userDto) =>
  299. {
  300. jobTopicResult.UserId = topicAddressee.UserId;
  301. jobTopicResult.Name = user.Name;
  302. jobTopicResult.AvatarUrl = userDto.AvatarUrl;
  303. jobTopicResult.TopicAddresseeId = topicAddressee.Id;
  304. return jobTopicResult;
  305. }, splitOn: "UserId,Name,AvatarUrl");
  306. connection.Dispose();
  307. return result.ToList();
  308. }
  309. /// <summary>
  310. /// 新版 获取笔记话题列表
  311. /// </summary>
  312. /// <param name="request"></param>
  313. /// <returns></returns>
  314. public async Task<PagedList<TopicListPageResult>> GetTopicPage(TopicPageSearchRequest request, string sql, string countSql)
  315. {
  316. var result = new PagedList<TopicListPageResult>();
  317. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  318. var database = new Database(databaseType, _connectionString);
  319. var connection = database.GetConnection();
  320. result.Items = await connection.QueryAsync<TopicListPageResult>(sql);
  321. result.Total = await connection.ExecuteScalarAsync<int>(countSql);
  322. connection.Dispose();
  323. foreach (var item in result.Items)
  324. {
  325. item.FolderResult.FolderName = item.FolderName;
  326. item.FolderResult.Id = item.ParentId;
  327. item.AvatarUrl = StringUtils.AddDomainMin(item.AvatarUrl);
  328. }
  329. return result;
  330. }
  331. public async Task<PagedList<TopicListPageResult>> GetTopicByGroupAsync(TopicPageSearchRequest request)
  332. {
  333. var topicConstValue = AllTypeConst.Topic.GetHashCode();
  334. var sql = $@"SELECT
  335. a.*,
  336. (SELECT
  337. COUNT(1)
  338. FROM
  339. tede_analyze
  340. WHERE
  341. TypeValue ={topicConstValue} AND SourceId = a.Id
  342. AND AnalyzeType = 1) AS PraiseCount,
  343. (SELECT
  344. COUNT(1)
  345. FROM
  346. tede_analyze
  347. WHERE
  348. UserId = {request.UserId} AND TypeValue = {topicConstValue}
  349. AND SourceId = a.Id
  350. AND AnalyzeType = 1
  351. LIMIT 0 , 1) AS IsPraise,
  352. (SELECT
  353. COUNT(1)
  354. FROM
  355. tede_comment
  356. WHERE
  357. ArticleId = a.Id AND TypeValue = {topicConstValue}
  358. AND Pid = 0) AS CommentCount,
  359. (SELECT
  360. COUNT(1)
  361. FROM
  362. tede_analyze
  363. WHERE
  364. UserId = {request.UserId} AND TypeValue = {topicConstValue}
  365. AND SourceId = a.Id
  366. AND AnalyzeType = 4) AS RetransmissionCount,
  367. (SELECT
  368. COUNT(1)
  369. FROM
  370. tede_analyze
  371. WHERE
  372. UserId = {request.UserId} AND TypeValue = {topicConstValue}
  373. AND SourceId = a.Id
  374. AND AnalyzeType = 4
  375. LIMIT 0 , 1) AS IsRetransmission,
  376. (SELECT
  377. COUNT(1)
  378. FROM
  379. tede_analyze
  380. WHERE
  381. UserId = {request.UserId} AND TypeValue = {topicConstValue}
  382. AND SourceId = a.Id
  383. AND AnalyzeType = 3
  384. LIMIT 0 , 1) AS IsCollect,
  385. b.Id as GroupId,
  386. b.Name,
  387. c.Name,
  388. c.AvatarUrl
  389. FROM
  390. tede_topic a
  391. INNER JOIN
  392. tede_group b ON a.GroupId = b.id
  393. INNER JOIN
  394. tede_user c ON a.UserId = c.Id
  395. WHERE 1=1 ";
  396. if (request.TopicGroupIds.Count > 0)
  397. {
  398. var groupStr = "(";
  399. foreach (var item in request.TopicGroupIds)
  400. {
  401. groupStr += $"{item},";
  402. }
  403. groupStr = groupStr.Remove(groupStr.Length - 1, 1);
  404. groupStr += ")";
  405. sql += $@" and a.GroupId IN {groupStr}";
  406. }
  407. else
  408. sql += $@" and a.GroupId > 0";
  409. if (request.IsAdmin)
  410. {
  411. sql += $@" AND a.UserId={request.UserId}";
  412. }
  413. else
  414. {
  415. sql += $@" AND b.Id IN (SELECT
  416. GroupId
  417. FROM
  418. tede_group_user
  419. WHERE
  420. UserId = {request.UserId})";
  421. }
  422. if (!string.IsNullOrWhiteSpace(request.Keyword))
  423. {
  424. sql += $@" AND (c.Name LIKE '%{request.Keyword}%'
  425. OR a.Title LIKE '%{request.Keyword}%'
  426. OR a.TextContent LIKE '%{request.Keyword}%')";
  427. }
  428. if (!string.IsNullOrEmpty(request.Sort))
  429. sql += $@" ORDER BY a.ReadCount DESC";
  430. else
  431. sql += $@" ORDER BY a.CreatedDate DESC";
  432. sql += $@" LIMIT {(request.Page - 1) * request.PerPage} , {request.PerPage}";
  433. var result = new PagedList<TopicListPageResult>();
  434. var databaseType = StringUtils.ToEnum<DatabaseType>(_databaseTypeStr, DatabaseType.MySql);
  435. var database = new Database(databaseType, _connectionString);
  436. var connection = database.GetConnection();
  437. result.Items = await connection.QueryAsync<TopicListPageResult, Entity.Group, User, TopicListPageResult>(sql, (topicListPageResult, group, user) =>
  438. {
  439. topicListPageResult.AvatarUrl = user != null ? StringUtils.AddDomainMin(user.AvatarUrl) : "";
  440. topicListPageResult.GroupName = group != null ? group.Name : "";
  441. topicListPageResult.UserName = user != null ? user.Name : "";
  442. return topicListPageResult;
  443. }, splitOn: "Id,GroupId,Name");
  444. sql = $@"SELECT
  445. count(1)
  446. FROM
  447. tede_topic a
  448. INNER JOIN
  449. tede_group b ON a.GroupId = b.id
  450. INNER JOIN
  451. tede_user c ON a.UserId = c.Id
  452. WHERE 1=1 ";
  453. if (request.TopicGroupIds.Count > 0)
  454. {
  455. var groupStr = "(";
  456. foreach (var item in request.TopicGroupIds)
  457. {
  458. groupStr += $"{item},";
  459. }
  460. groupStr = groupStr.Remove(groupStr.Length - 1, 1);
  461. groupStr += ")";
  462. sql += $@" and a.GroupId IN {groupStr}";
  463. }
  464. else
  465. sql += $@" and a.GroupId > 0";
  466. if (request.IsAdmin)
  467. {
  468. sql += $@" AND a.UserId={request.UserId}";
  469. }
  470. else
  471. {
  472. sql += $@" AND b.Id IN (SELECT
  473. GroupId
  474. FROM
  475. tede_group_user
  476. WHERE
  477. UserId = {request.UserId})";
  478. }
  479. if (!string.IsNullOrWhiteSpace(request.Keyword))
  480. {
  481. sql += $@" AND (c.Name LIKE '%{request.Keyword}%'
  482. OR a.Title LIKE '%{request.Keyword}%'
  483. OR a.TextContent LIKE '%{request.Keyword}%')";
  484. }
  485. result.Total = await connection.ExecuteScalarAsync<int>(sql);
  486. return result;
  487. }
  488. /// <summary>
  489. /// 删除草稿箱
  490. /// </summary>
  491. /// <param name="userId"></param>
  492. /// <param name="groupId"></param>
  493. /// <returns></returns>
  494. public async Task<bool> ClearDraftAsync(int userId, int groupId)
  495. {
  496. var query = Q.NewQuery();
  497. query.Where(nameof(Entity.Topic.Topic.UserId), userId);
  498. query.Where(nameof(Entity.Topic.Topic.IsDraft), true);
  499. query.Where(nameof(Entity.Topic.Topic.GroupId), groupId);
  500. return await _repository.DeleteAsync(query) > 0;
  501. }
  502. public async Task<bool> UpdateTopicTextContentAsync()
  503. {
  504. var query = Q.NewQuery();
  505. query.Where(nameof(Entity.Topic.Topic.TextContent), "=", "");
  506. query.OrderByDesc(nameof(Entity.Topic.Topic.CreatedDate));
  507. query.Limit(100);
  508. var result = await _repository.GetAllAsync(query);
  509. foreach (var item in result)
  510. {
  511. if (!string.IsNullOrEmpty(item.Content))
  512. {
  513. var contentJsonData = JsonConvert.DeserializeObject<List<ContentJsonData>>(item.Content);
  514. foreach (var data in contentJsonData)
  515. {
  516. if (data.Type == AllTypeConst.Text.GetHashCode())
  517. item.TextContent += data.Text;
  518. }
  519. if (!string.IsNullOrEmpty(item.TextContent))
  520. await _repository.UpdateAsync(item);
  521. else
  522. {
  523. item.TextContent = "[]";
  524. await _repository.UpdateAsync(item);
  525. }
  526. }
  527. }
  528. return true;
  529. }
  530. }
  531. }