mirror of
https://github.com/nagisa77/OpenIsle.git
synced 2026-02-06 23:21:16 +08:00
Compare commits
73 Commits
codex/add-
...
feature/we
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a722c81c5 | ||
|
|
15071471b2 | ||
|
|
98a9939738 | ||
|
|
9554030054 | ||
|
|
72e9a77373 | ||
|
|
ed7dcd9414 | ||
|
|
79fe8b5997 | ||
|
|
cfce4d7d1d | ||
|
|
b7f5d8485c | ||
|
|
d4677a5799 | ||
|
|
99644046fc | ||
|
|
22c9bd7d39 | ||
|
|
3fc6929075 | ||
|
|
4eed6889d6 | ||
|
|
959b0f6a48 | ||
|
|
91ffacc335 | ||
|
|
4969a759aa | ||
|
|
81e3a80d35 | ||
|
|
d717ce03c1 | ||
|
|
66035447a8 | ||
|
|
fa1148bc4e | ||
|
|
f60f184c84 | ||
|
|
06ffb180fe | ||
|
|
1b892828f1 | ||
|
|
1aa88ab0fe | ||
|
|
86126699d3 | ||
|
|
a6a07b9bda | ||
|
|
d8b3c68150 | ||
|
|
318b481c4b | ||
|
|
7338b891db | ||
|
|
eb18dc8e94 | ||
|
|
aec5321f89 | ||
|
|
2e658f37a4 | ||
|
|
7ccb2a44e3 | ||
|
|
0fa08e2260 | ||
|
|
38a49f7414 | ||
|
|
fb89c9fb25 | ||
|
|
e9458f5419 | ||
|
|
2d87c8f23d | ||
|
|
cb281e4030 | ||
|
|
9b85d77158 | ||
|
|
a3b28eafe4 | ||
|
|
805a8df7d3 | ||
|
|
02be045f55 | ||
|
|
ac3c7b7bec | ||
|
|
c344b5b4ae | ||
|
|
e7a1e1d159 | ||
|
|
30b56e54cf | ||
|
|
cc525c1c27 | ||
|
|
3f2829cd37 | ||
|
|
3258a42b44 | ||
|
|
a64fd71bbe | ||
|
|
1a12bec7b1 | ||
|
|
fbca19791a | ||
|
|
10b6fdd1cb | ||
|
|
7dd1f1b3d0 | ||
|
|
df92ff664c | ||
|
|
73168c1859 | ||
|
|
77856ff9af | ||
|
|
df49b21620 | ||
|
|
fbe2c66955 | ||
|
|
df7ca77652 | ||
|
|
fe84e3f2fa | ||
|
|
c307732696 | ||
|
|
35bcd2cdc2 | ||
|
|
a29bf7d860 | ||
|
|
27393c15f2 | ||
|
|
c91a787f29 | ||
|
|
6096712291 | ||
|
|
6d20addcde | ||
|
|
d8f9fd670c | ||
|
|
5ebe739917 | ||
|
|
022edc866a |
116
CONTRIBUTING.md
Normal file
116
CONTRIBUTING.md
Normal file
@@ -0,0 +1,116 @@
|
||||
#### **⚠️注意:仅想修改前端的朋友可不用部署后端服务**
|
||||
|
||||
## 如何部署
|
||||
|
||||
> Step1 先克隆仓库
|
||||
|
||||
```shell
|
||||
git clone https://github.com/nagisa77/OpenIsle.git
|
||||
cd OpenIsle
|
||||
```
|
||||
|
||||
> Step2 后端部署
|
||||
|
||||
```shell
|
||||
cd backend
|
||||
```
|
||||
|
||||
以IDEA编辑器为例,IDEA打开backend文件夹。
|
||||
|
||||
- 设置VM Option,最好运行在其他端口,非8080,这里设置8081
|
||||
|
||||
```shell
|
||||
-Dserver.port=8081
|
||||
```
|
||||
|
||||

|
||||
|
||||
- 设置jdk版本为java 17
|
||||
|
||||

|
||||
|
||||
- 本机配置MySQL服务(网上很多教程,忽略)
|
||||
- 设置环境变量.env 文件 或.properties 文件(二选一)
|
||||
|
||||
1. 环境变量文件生成
|
||||
|
||||
```shell
|
||||
cp open-isle.env.example open-isle.env
|
||||
```
|
||||
|
||||
修改环境变量,留下需要的,比如你要开发Google登录业务,就需要谷歌相关的变量,数据库是一定要的
|
||||
|
||||

|
||||
|
||||
应用环境文件, 选择刚刚的`open-isle.env`
|
||||
|
||||

|
||||
|
||||
2. 直接修改 .properities 文件
|
||||
|
||||
位置src/main/application.properties, 数据库需要修改标红处,其他按需修改
|
||||
|
||||

|
||||
|
||||
处理完环境问题直接跑起来就能通了
|
||||
|
||||

|
||||
|
||||
> Step3 前端部署
|
||||
|
||||
前端可以依赖本机部署的后端,也可以直接调用线上的后端接口
|
||||
|
||||
```shell
|
||||
cd ../frontend_nuxt/
|
||||
```
|
||||
|
||||
copy环境.env文件
|
||||
|
||||
```shell
|
||||
cp .env.staging.example .env
|
||||
```
|
||||
|
||||
1. 依赖本机部署的后端:打开本文件夹,修改.env 修改为瞄准本机后端端口
|
||||
|
||||
```yaml
|
||||
; 本地部署后端
|
||||
NUXT_PUBLIC_API_BASE_URL=https://127.0.0.1:8081
|
||||
; 预发环境后端
|
||||
; NUXT_PUBLIC_API_BASE_URL=https://staging.open-isle.com
|
||||
; 生产环境后端
|
||||
; NUXT_PUBLIC_API_BASE_URL=https://www.open-isle.com
|
||||
```
|
||||
|
||||
2. 依赖预发环境后台环境
|
||||
|
||||
**(⚠️强烈推荐只部署前端的朋友使用该环境)**
|
||||
|
||||
```yaml
|
||||
; 本地部署后端
|
||||
; NUXT_PUBLIC_API_BASE_URL=https://127.0.0.1:8081
|
||||
; 预发环境后端
|
||||
NUXT_PUBLIC_API_BASE_URL=https://staging.open-isle.com
|
||||
; 生产环境后端
|
||||
; NUXT_PUBLIC_API_BASE_URL=https://www.open-isle.com
|
||||
```
|
||||
|
||||
4. 依赖线上后台环境
|
||||
|
||||
```yaml
|
||||
; 本地部署后端
|
||||
; NUXT_PUBLIC_API_BASE_URL=https://127.0.0.1:8081
|
||||
; 预发环境后端
|
||||
; NUXT_PUBLIC_API_BASE_URL=https://staging.open-isle.com
|
||||
; 生产环境后端
|
||||
NUXT_PUBLIC_API_BASE_URL=https://www.open-isle.com
|
||||
```
|
||||
|
||||
```shell
|
||||
# 安装依赖
|
||||
npm install --verbose
|
||||
|
||||
# 运行前端服务
|
||||
npm run dev
|
||||
```
|
||||
|
||||
如此一来,浏览器访问 http://127.0.0.1:3000 即可访问前端页面
|
||||
37
README.md
37
README.md
@@ -1,45 +1,18 @@
|
||||
<p align="center">
|
||||
<img alt="OpenIsle" src="https://openisle-1307107697.cos.ap-guangzhou.myqcloud.com/assert/image.png" width="200">
|
||||
<br><br>
|
||||
<br>
|
||||
高效的开源社区前后端端平台
|
||||
<br><br>
|
||||
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-blue.svg?style=flat-square"></a>
|
||||
<br><br><br>
|
||||
<img alt="Image" src="https://openisle-1307107697.cos.accelerate.myqcloud.com/dynamic_assert/22752cfac5a04a9c90c41995b9f55fed.png" width="1200">
|
||||
</p>
|
||||
|
||||
## 💡 简介
|
||||
|
||||
OpenIsle 是一个使用 Spring Boot 和 Vue 3 构建的全栈开源社区平台,提供用户注册、登录、贴文发布、评论交互等完整功能,可用于项目社区或直接打造自主社区站点。
|
||||
|
||||
## 🚧 开发
|
||||
## 🚧 开发 & 部署
|
||||
|
||||
### 后端
|
||||
|
||||
1. 确保安装 JDK 17 及 Maven
|
||||
2. 信息配置修改 `src/main/resources/application.properties`,或通过环境变量设置数据库等参数
|
||||
3. 执行 `mvn clean package` 生成包,之后使用 `java -jar target/openisle-0.0.1-SNAPSHOT.jar`启动,或在开发时直接使用 `mvn spring-boot:run`
|
||||
|
||||
### 前端
|
||||
|
||||
1. 进入前端目录
|
||||
```bash
|
||||
cd frontend_nuxt
|
||||
```
|
||||
2. 安装依赖
|
||||
```bash
|
||||
npm install
|
||||
```
|
||||
3. 启动开发服务
|
||||
```bash
|
||||
npm run dev
|
||||
```
|
||||
|
||||
生产版本使用如下命令编译:
|
||||
|
||||
```bash
|
||||
npm run build
|
||||
```
|
||||
|
||||
会在 `.output` 目录生成文件,配合线上网站方式部署
|
||||
详细见 [Contributing](https://github.com/nagisa77/OpenIsle?tab=contributing-ov-file)
|
||||
|
||||
## ✨ 项目特点
|
||||
|
||||
|
||||
@@ -47,13 +47,14 @@ public class AuthController {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "Invalid captcha"));
|
||||
}
|
||||
if (req.getInviteToken() != null && !req.getInviteToken().isEmpty()) {
|
||||
if (!inviteService.validate(req.getInviteToken())) {
|
||||
InviteService.InviteValidateResult result = inviteService.validate(req.getInviteToken());
|
||||
if (!result.isValidate()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "邀请码使用次数过多"));
|
||||
}
|
||||
try {
|
||||
User user = userService.registerWithInvite(
|
||||
req.getUsername(), req.getEmail(), req.getPassword());
|
||||
inviteService.consume(req.getInviteToken());
|
||||
inviteService.consume(req.getInviteToken(), user.getUsername());
|
||||
emailService.sendEmail(user.getEmail(), "在网站填写验证码以验证", "您的验证码是 " + user.getVerificationCode());
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"token", jwtService.generateToken(user.getUsername()),
|
||||
@@ -144,7 +145,8 @@ public class AuthController {
|
||||
@PostMapping("/google")
|
||||
public ResponseEntity<?> loginWithGoogle(@RequestBody GoogleLoginRequest req) {
|
||||
boolean viaInvite = req.getInviteToken() != null && !req.getInviteToken().isEmpty();
|
||||
if (viaInvite && !inviteService.validate(req.getInviteToken())) {
|
||||
InviteService.InviteValidateResult inviteValidateResult = inviteService.validate(req.getInviteToken());
|
||||
if (viaInvite && !inviteValidateResult.isValidate()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "Invalid invite token"));
|
||||
}
|
||||
Optional<AuthResult> resultOpt = googleAuthService.authenticate(
|
||||
@@ -154,7 +156,7 @@ public class AuthController {
|
||||
if (resultOpt.isPresent()) {
|
||||
AuthResult result = resultOpt.get();
|
||||
if (viaInvite && result.isNewUser()) {
|
||||
inviteService.consume(req.getInviteToken());
|
||||
inviteService.consume(req.getInviteToken(), inviteValidateResult.getInviteToken().getInviter().getUsername());
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"token", jwtService.generateToken(result.getUser().getUsername()),
|
||||
"reason_code", "INVITE_APPROVED"
|
||||
@@ -218,7 +220,8 @@ public class AuthController {
|
||||
@PostMapping("/github")
|
||||
public ResponseEntity<?> loginWithGithub(@RequestBody GithubLoginRequest req) {
|
||||
boolean viaInvite = req.getInviteToken() != null && !req.getInviteToken().isEmpty();
|
||||
if (viaInvite && !inviteService.validate(req.getInviteToken())) {
|
||||
InviteService.InviteValidateResult inviteValidateResult = inviteService.validate(req.getInviteToken());
|
||||
if (viaInvite && !inviteValidateResult.isValidate()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "Invalid invite token"));
|
||||
}
|
||||
Optional<AuthResult> resultOpt = githubAuthService.authenticate(
|
||||
@@ -229,7 +232,7 @@ public class AuthController {
|
||||
if (resultOpt.isPresent()) {
|
||||
AuthResult result = resultOpt.get();
|
||||
if (viaInvite && result.isNewUser()) {
|
||||
inviteService.consume(req.getInviteToken());
|
||||
inviteService.consume(req.getInviteToken(), inviteValidateResult.getInviteToken().getInviter().getUsername());
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"token", jwtService.generateToken(result.getUser().getUsername()),
|
||||
"reason_code", "INVITE_APPROVED"
|
||||
@@ -265,7 +268,8 @@ public class AuthController {
|
||||
@PostMapping("/discord")
|
||||
public ResponseEntity<?> loginWithDiscord(@RequestBody DiscordLoginRequest req) {
|
||||
boolean viaInvite = req.getInviteToken() != null && !req.getInviteToken().isEmpty();
|
||||
if (viaInvite && !inviteService.validate(req.getInviteToken())) {
|
||||
InviteService.InviteValidateResult inviteValidateResult = inviteService.validate(req.getInviteToken());
|
||||
if (viaInvite && !inviteValidateResult.isValidate()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "Invalid invite token"));
|
||||
}
|
||||
Optional<AuthResult> resultOpt = discordAuthService.authenticate(
|
||||
@@ -276,7 +280,7 @@ public class AuthController {
|
||||
if (resultOpt.isPresent()) {
|
||||
AuthResult result = resultOpt.get();
|
||||
if (viaInvite && result.isNewUser()) {
|
||||
inviteService.consume(req.getInviteToken());
|
||||
inviteService.consume(req.getInviteToken(), inviteValidateResult.getInviteToken().getInviter().getUsername());
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"token", jwtService.generateToken(result.getUser().getUsername()),
|
||||
"reason_code", "INVITE_APPROVED"
|
||||
@@ -311,7 +315,8 @@ public class AuthController {
|
||||
@PostMapping("/twitter")
|
||||
public ResponseEntity<?> loginWithTwitter(@RequestBody TwitterLoginRequest req) {
|
||||
boolean viaInvite = req.getInviteToken() != null && !req.getInviteToken().isEmpty();
|
||||
if (viaInvite && !inviteService.validate(req.getInviteToken())) {
|
||||
InviteService.InviteValidateResult inviteValidateResult = inviteService.validate(req.getInviteToken());
|
||||
if (viaInvite && !inviteValidateResult.isValidate()) {
|
||||
return ResponseEntity.badRequest().body(Map.of("error", "Invalid invite token"));
|
||||
}
|
||||
Optional<AuthResult> resultOpt = twitterAuthService.authenticate(
|
||||
@@ -323,7 +328,7 @@ public class AuthController {
|
||||
if (resultOpt.isPresent()) {
|
||||
AuthResult result = resultOpt.get();
|
||||
if (viaInvite && result.isNewUser()) {
|
||||
inviteService.consume(req.getInviteToken());
|
||||
inviteService.consume(req.getInviteToken(), inviteValidateResult.getInviteToken().getInviter().getUsername());
|
||||
return ResponseEntity.ok(Map.of(
|
||||
"token", jwtService.generateToken(result.getUser().getUsername()),
|
||||
"reason_code", "INVITE_APPROVED"
|
||||
|
||||
@@ -47,7 +47,7 @@ public class CommentController {
|
||||
Comment comment = commentService.addComment(auth.getName(), postId, req.getContent());
|
||||
CommentDto dto = commentMapper.toDto(comment);
|
||||
dto.setReward(levelService.awardForComment(auth.getName()));
|
||||
dto.setPointReward(pointService.awardForComment(auth.getName(),postId));
|
||||
dto.setPointReward(pointService.awardForComment(auth.getName(), postId, comment.getId()));
|
||||
log.debug("createComment succeeded for comment {}", comment.getId());
|
||||
return ResponseEntity.ok(dto);
|
||||
}
|
||||
|
||||
@@ -23,9 +23,19 @@ public class NotificationController {
|
||||
private final NotificationMapper notificationMapper;
|
||||
|
||||
@GetMapping
|
||||
public List<NotificationDto> list(@RequestParam(value = "read", required = false) Boolean read,
|
||||
public List<NotificationDto> list(@RequestParam(value = "page", defaultValue = "0") int page,
|
||||
@RequestParam(value = "size", defaultValue = "30") int size,
|
||||
Authentication auth) {
|
||||
return notificationService.listNotifications(auth.getName(), read).stream()
|
||||
return notificationService.listNotifications(auth.getName(), null, page, size).stream()
|
||||
.map(notificationMapper::toDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@GetMapping("/unread")
|
||||
public List<NotificationDto> listUnread(@RequestParam(value = "page", defaultValue = "0") int page,
|
||||
@RequestParam(value = "size", defaultValue = "30") int size,
|
||||
Authentication auth) {
|
||||
return notificationService.listNotifications(auth.getName(), false, page, size).stream()
|
||||
.map(notificationMapper::toDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.openisle.controller;
|
||||
|
||||
import com.openisle.dto.PointHistoryDto;
|
||||
import com.openisle.mapper.PointHistoryMapper;
|
||||
import com.openisle.service.PointService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@RestController
|
||||
@RequestMapping("/api/point-histories")
|
||||
@RequiredArgsConstructor
|
||||
public class PointHistoryController {
|
||||
private final PointService pointService;
|
||||
private final PointHistoryMapper pointHistoryMapper;
|
||||
|
||||
@GetMapping
|
||||
public List<PointHistoryDto> list(Authentication auth) {
|
||||
return pointService.listHistory(auth.getName()).stream()
|
||||
.map(pointHistoryMapper::toDto)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
}
|
||||
@@ -45,7 +45,7 @@ public class PostController {
|
||||
draftService.deleteDraft(auth.getName());
|
||||
PostDetailDto dto = postMapper.toDetailDto(post, auth.getName());
|
||||
dto.setReward(levelService.awardForPost(auth.getName()));
|
||||
dto.setPointReward(pointService.awardForPost(auth.getName()));
|
||||
dto.setPointReward(pointService.awardForPost(auth.getName(), post.getId()));
|
||||
return ResponseEntity.ok(dto);
|
||||
}
|
||||
|
||||
@@ -62,6 +62,16 @@ public class PostController {
|
||||
postService.deletePost(id, auth.getName());
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/close")
|
||||
public PostSummaryDto close(@PathVariable Long id, Authentication auth) {
|
||||
return postMapper.toSummaryDto(postService.closePost(id, auth.getName()));
|
||||
}
|
||||
|
||||
@PostMapping("/{id}/reopen")
|
||||
public PostSummaryDto reopen(@PathVariable Long id, Authentication auth) {
|
||||
return postMapper.toSummaryDto(postService.reopenPost(id, auth.getName()));
|
||||
}
|
||||
|
||||
@GetMapping("/{id}")
|
||||
public ResponseEntity<PostDetailDto> getPost(@PathVariable Long id, Authentication auth) {
|
||||
String viewer = auth != null ? auth.getName() : null;
|
||||
|
||||
23
backend/src/main/java/com/openisle/dto/PointHistoryDto.java
Normal file
23
backend/src/main/java/com/openisle/dto/PointHistoryDto.java
Normal file
@@ -0,0 +1,23 @@
|
||||
package com.openisle.dto;
|
||||
|
||||
import com.openisle.model.PointHistoryType;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Getter
|
||||
@Setter
|
||||
public class PointHistoryDto {
|
||||
private Long id;
|
||||
private PointHistoryType type;
|
||||
private int amount;
|
||||
private int balance;
|
||||
private Long postId;
|
||||
private String postTitle;
|
||||
private Long commentId;
|
||||
private String commentContent;
|
||||
private Long fromUserId;
|
||||
private String fromUserName;
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -32,5 +32,6 @@ public class PostSummaryDto {
|
||||
private PostType type;
|
||||
private LotteryDto lottery;
|
||||
private boolean rssExcluded;
|
||||
private boolean closed;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.openisle.mapper;
|
||||
|
||||
import com.openisle.dto.PointHistoryDto;
|
||||
import com.openisle.model.PointHistory;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class PointHistoryMapper {
|
||||
public PointHistoryDto toDto(PointHistory history) {
|
||||
PointHistoryDto dto = new PointHistoryDto();
|
||||
dto.setId(history.getId());
|
||||
dto.setType(history.getType());
|
||||
dto.setAmount(history.getAmount());
|
||||
dto.setBalance(history.getBalance());
|
||||
dto.setCreatedAt(history.getCreatedAt());
|
||||
if (history.getPost() != null) {
|
||||
dto.setPostId(history.getPost().getId());
|
||||
dto.setPostTitle(history.getPost().getTitle());
|
||||
}
|
||||
if (history.getComment() != null) {
|
||||
dto.setCommentId(history.getComment().getId());
|
||||
dto.setCommentContent(history.getComment().getContent());
|
||||
if (history.getComment().getPost() != null && dto.getPostId() == null) {
|
||||
dto.setPostId(history.getComment().getPost().getId());
|
||||
dto.setPostTitle(history.getComment().getPost().getTitle());
|
||||
}
|
||||
}
|
||||
if (history.getFromUser() != null) {
|
||||
dto.setFromUserId(history.getFromUser().getId());
|
||||
dto.setFromUserName(history.getFromUser().getUsername());
|
||||
}
|
||||
return dto;
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,7 @@ public class PostMapper {
|
||||
dto.setStatus(post.getStatus());
|
||||
dto.setPinnedAt(post.getPinnedAt());
|
||||
dto.setRssExcluded(post.getRssExcluded() == null || post.getRssExcluded());
|
||||
dto.setClosed(post.isClosed());
|
||||
|
||||
List<ReactionDto> reactions = reactionService.getReactionsForPost(post.getId())
|
||||
.stream()
|
||||
|
||||
@@ -14,6 +14,8 @@ public enum NotificationType {
|
||||
POST_REVIEW_REQUEST,
|
||||
/** Your post under review was approved or rejected */
|
||||
POST_REVIEWED,
|
||||
/** An administrator deleted your post */
|
||||
POST_DELETED,
|
||||
/** A subscribed post received a new comment */
|
||||
POST_UPDATED,
|
||||
/** Someone subscribed to your post */
|
||||
|
||||
49
backend/src/main/java/com/openisle/model/PointHistory.java
Normal file
49
backend/src/main/java/com/openisle/model/PointHistory.java
Normal file
@@ -0,0 +1,49 @@
|
||||
package com.openisle.model;
|
||||
|
||||
import jakarta.persistence.*;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** Point change history for a user. */
|
||||
@Entity
|
||||
@Getter
|
||||
@Setter
|
||||
@NoArgsConstructor
|
||||
@Table(name = "point_histories")
|
||||
public class PointHistory {
|
||||
@Id
|
||||
@GeneratedValue(strategy = GenerationType.IDENTITY)
|
||||
private Long id;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "user_id")
|
||||
private User user;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false)
|
||||
private PointHistoryType type;
|
||||
|
||||
@Column(nullable = false)
|
||||
private int amount;
|
||||
|
||||
@Column(nullable = false)
|
||||
private int balance;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "post_id")
|
||||
private Post post;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "comment_id")
|
||||
private Comment comment;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY)
|
||||
@JoinColumn(name = "from_user_id")
|
||||
private User fromUser;
|
||||
|
||||
@Column(name = "created_at", nullable = false)
|
||||
private LocalDateTime createdAt;
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package com.openisle.model;
|
||||
|
||||
public enum PointHistoryType {
|
||||
POST,
|
||||
COMMENT,
|
||||
POST_LIKED,
|
||||
COMMENT_LIKED,
|
||||
INVITE,
|
||||
SYSTEM_ONLINE
|
||||
}
|
||||
@@ -64,6 +64,9 @@ public class Post {
|
||||
@Column(nullable = false)
|
||||
private PostType type = PostType.NORMAL;
|
||||
|
||||
@Column(nullable = false)
|
||||
private boolean closed = false;
|
||||
|
||||
@Column
|
||||
private LocalDateTime pinnedAt;
|
||||
|
||||
|
||||
@@ -6,6 +6,8 @@ import com.openisle.model.Post;
|
||||
import com.openisle.model.Comment;
|
||||
import com.openisle.model.NotificationType;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@@ -13,7 +15,12 @@ import java.util.List;
|
||||
public interface NotificationRepository extends JpaRepository<Notification, Long> {
|
||||
List<Notification> findByUserOrderByCreatedAtDesc(User user);
|
||||
List<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read);
|
||||
Page<Notification> findByUserOrderByCreatedAtDesc(User user, Pageable pageable);
|
||||
Page<Notification> findByUserAndReadOrderByCreatedAtDesc(User user, boolean read, Pageable pageable);
|
||||
Page<Notification> findByUserAndTypeNotInOrderByCreatedAtDesc(User user, java.util.Collection<NotificationType> types, Pageable pageable);
|
||||
Page<Notification> findByUserAndReadAndTypeNotInOrderByCreatedAtDesc(User user, boolean read, java.util.Collection<NotificationType> types, Pageable pageable);
|
||||
long countByUserAndRead(User user, boolean read);
|
||||
long countByUserAndReadAndTypeNotIn(User user, boolean read, java.util.Collection<NotificationType> types);
|
||||
List<Notification> findByPost(Post post);
|
||||
List<Notification> findByComment(Comment comment);
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
package com.openisle.repository;
|
||||
|
||||
import com.openisle.model.PointHistory;
|
||||
import com.openisle.model.User;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface PointHistoryRepository extends JpaRepository<PointHistory, Long> {
|
||||
List<PointHistory> findByUserOrderByIdDesc(User user);
|
||||
long countByUser(User user);
|
||||
}
|
||||
@@ -52,6 +52,9 @@ public class CommentService {
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||
Post post = postRepository.findById(postId)
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("Post not found"));
|
||||
if (post.isClosed()) {
|
||||
throw new IllegalStateException("Post closed");
|
||||
}
|
||||
Comment comment = new Comment();
|
||||
comment.setAuthor(author);
|
||||
comment.setPost(post);
|
||||
@@ -94,6 +97,9 @@ public class CommentService {
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||
Comment parent = commentRepository.findById(parentId)
|
||||
.orElseThrow(() -> new IllegalArgumentException("Comment not found"));
|
||||
if (parent.getPost().isClosed()) {
|
||||
throw new IllegalStateException("Post closed");
|
||||
}
|
||||
Comment comment = new Comment();
|
||||
comment.setAuthor(author);
|
||||
comment.setPost(parent.getPost());
|
||||
|
||||
@@ -5,6 +5,7 @@ import com.openisle.model.User;
|
||||
import com.openisle.repository.InviteTokenRepository;
|
||||
import com.openisle.repository.UserRepository;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.time.LocalDate;
|
||||
@@ -18,6 +19,12 @@ public class InviteService {
|
||||
private final JwtService jwtService;
|
||||
private final PointService pointService;
|
||||
|
||||
@Value
|
||||
public class InviteValidateResult {
|
||||
InviteToken inviteToken;
|
||||
boolean validate;
|
||||
}
|
||||
|
||||
public String generate(String username) {
|
||||
User inviter = userRepository.findByUsername(username).orElseThrow();
|
||||
LocalDate today = LocalDate.now();
|
||||
@@ -35,20 +42,23 @@ public class InviteService {
|
||||
return token;
|
||||
}
|
||||
|
||||
public boolean validate(String token) {
|
||||
public InviteValidateResult validate(String token) {
|
||||
if (token == null || token.isEmpty()) {
|
||||
return new InviteValidateResult(null, false);
|
||||
}
|
||||
try {
|
||||
jwtService.validateAndGetSubjectForInvite(token);
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
return new InviteValidateResult(null, false);
|
||||
}
|
||||
InviteToken invite = inviteTokenRepository.findById(token).orElse(null);
|
||||
return invite != null && invite.getUsageCount() < 3;
|
||||
return new InviteValidateResult(invite, invite != null && invite.getUsageCount() < 3);
|
||||
}
|
||||
|
||||
public void consume(String token) {
|
||||
public void consume(String token, String newUserName) {
|
||||
InviteToken invite = inviteTokenRepository.findById(token).orElseThrow();
|
||||
invite.setUsageCount(invite.getUsageCount() + 1);
|
||||
inviteTokenRepository.save(invite);
|
||||
pointService.awardForInvite(invite.getInviter().getUsername());
|
||||
pointService.awardForInvite(invite.getInviter().getUsername(), newUserName);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -23,7 +23,6 @@ import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.ArrayList;
|
||||
import java.util.concurrent.Executor;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/** Service for creating and retrieving notifications. */
|
||||
@Service
|
||||
@@ -180,17 +179,26 @@ public class NotificationService {
|
||||
userRepository.save(user);
|
||||
}
|
||||
|
||||
public List<Notification> listNotifications(String username, Boolean read) {
|
||||
public List<Notification> listNotifications(String username, Boolean read, int page, int size) {
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
|
||||
List<Notification> list;
|
||||
org.springframework.data.domain.Pageable pageable = org.springframework.data.domain.PageRequest.of(page, size);
|
||||
org.springframework.data.domain.Page<Notification> result;
|
||||
if (read == null) {
|
||||
list = notificationRepository.findByUserOrderByCreatedAtDesc(user);
|
||||
if (disabled.isEmpty()) {
|
||||
result = notificationRepository.findByUserOrderByCreatedAtDesc(user, pageable);
|
||||
} else {
|
||||
result = notificationRepository.findByUserAndTypeNotInOrderByCreatedAtDesc(user, disabled, pageable);
|
||||
}
|
||||
} else {
|
||||
list = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read);
|
||||
if (disabled.isEmpty()) {
|
||||
result = notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, read, pageable);
|
||||
} else {
|
||||
result = notificationRepository.findByUserAndReadAndTypeNotInOrderByCreatedAtDesc(user, read, disabled, pageable);
|
||||
}
|
||||
}
|
||||
return list.stream().filter(n -> !disabled.contains(n.getType())).collect(Collectors.toList());
|
||||
return result.getContent();
|
||||
}
|
||||
|
||||
public void markRead(String username, List<Long> ids) {
|
||||
@@ -209,8 +217,10 @@ public class NotificationService {
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||
Set<NotificationType> disabled = user.getDisabledNotificationTypes();
|
||||
return notificationRepository.findByUserAndReadOrderByCreatedAtDesc(user, false).stream()
|
||||
.filter(n -> !disabled.contains(n.getType())).count();
|
||||
if (disabled.isEmpty()) {
|
||||
return notificationRepository.countByUserAndRead(user, false);
|
||||
}
|
||||
return notificationRepository.countByUserAndReadAndTypeNotIn(user, false, disabled);
|
||||
}
|
||||
|
||||
public void notifyMentions(String content, User fromUser, Post post, Comment comment) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
package com.openisle.service;
|
||||
|
||||
import com.openisle.model.PointLog;
|
||||
import com.openisle.model.User;
|
||||
import com.openisle.model.*;
|
||||
import com.openisle.repository.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -16,19 +15,22 @@ public class PointService {
|
||||
private final PointLogRepository pointLogRepository;
|
||||
private final PostRepository postRepository;
|
||||
private final CommentRepository commentRepository;
|
||||
private final PointHistoryRepository pointHistoryRepository;
|
||||
|
||||
public int awardForPost(String userName) {
|
||||
public int awardForPost(String userName, Long postId) {
|
||||
User user = userRepository.findByUsername(userName).orElseThrow();
|
||||
PointLog log = getTodayLog(user);
|
||||
if (log.getPostCount() > 1) return 0;
|
||||
log.setPostCount(log.getPostCount() + 1);
|
||||
pointLogRepository.save(log);
|
||||
return addPoint(user, 30);
|
||||
Post post = postRepository.findById(postId).orElseThrow();
|
||||
return addPoint(user, 30, PointHistoryType.POST, post, null, null);
|
||||
}
|
||||
|
||||
public int awardForInvite(String userName) {
|
||||
public int awardForInvite(String userName, String inviteeName) {
|
||||
User user = userRepository.findByUsername(userName).orElseThrow();
|
||||
return addPoint(user, 500);
|
||||
User invitee = userRepository.findByUsername(inviteeName).orElseThrow();
|
||||
return addPoint(user, 500, PointHistoryType.INVITE, null, null, invitee);
|
||||
}
|
||||
|
||||
private PointLog getTodayLog(User user) {
|
||||
@@ -45,20 +47,41 @@ public class PointService {
|
||||
});
|
||||
}
|
||||
|
||||
private int addPoint(User user, int amount) {
|
||||
private int addPoint(User user, int amount, PointHistoryType type,
|
||||
Post post, Comment comment, User fromUser) {
|
||||
if (pointHistoryRepository.countByUser(user) == 0) {
|
||||
recordHistory(user, PointHistoryType.SYSTEM_ONLINE, 0, null, null, null);
|
||||
}
|
||||
user.setPoint(user.getPoint() + amount);
|
||||
userRepository.save(user);
|
||||
recordHistory(user, type, amount, post, comment, fromUser);
|
||||
return amount;
|
||||
}
|
||||
|
||||
private void recordHistory(User user, PointHistoryType type, int amount,
|
||||
Post post, Comment comment, User fromUser) {
|
||||
PointHistory history = new PointHistory();
|
||||
history.setUser(user);
|
||||
history.setType(type);
|
||||
history.setAmount(amount);
|
||||
history.setBalance(user.getPoint());
|
||||
history.setPost(post);
|
||||
history.setComment(comment);
|
||||
history.setFromUser(fromUser);
|
||||
history.setCreatedAt(java.time.LocalDateTime.now());
|
||||
pointHistoryRepository.save(history);
|
||||
}
|
||||
|
||||
// 同时为评论者和发帖人增加积分,返回值为评论者增加的积分数
|
||||
// 注意需要考虑发帖和回复是同一人的场景
|
||||
public int awardForComment(String commenterName, Long postId) {
|
||||
public int awardForComment(String commenterName, Long postId, Long commentId) {
|
||||
// 标记评论者是否已达到积分奖励上限
|
||||
boolean isTheRewardCapped = false;
|
||||
|
||||
// 根据帖子id找到发帖人
|
||||
User poster = postRepository.findById(postId).orElseThrow().getAuthor();
|
||||
Post post = postRepository.findById(postId).orElseThrow();
|
||||
User poster = post.getAuthor();
|
||||
Comment comment = commentRepository.findById(commentId).orElseThrow();
|
||||
|
||||
// 获取评论者的加分日志
|
||||
User commenter = userRepository.findByUsername(commenterName).orElseThrow();
|
||||
@@ -74,15 +97,15 @@ public class PointService {
|
||||
} else {
|
||||
log.setCommentCount(log.getCommentCount() + 1);
|
||||
pointLogRepository.save(log);
|
||||
return addPoint(commenter, 10);
|
||||
return addPoint(commenter, 10, PointHistoryType.COMMENT, post, comment, null);
|
||||
}
|
||||
} else {
|
||||
addPoint(poster, 10);
|
||||
addPoint(poster, 10, PointHistoryType.COMMENT, post, comment, commenter);
|
||||
// 如果发帖人与评论者不是同一个,则根据是否达到积分上限来判断评论者加分情况
|
||||
if (isTheRewardCapped) {
|
||||
return 0;
|
||||
} else {
|
||||
return addPoint(commenter, 10);
|
||||
return addPoint(commenter, 10, PointHistoryType.COMMENT, post, comment, null);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -101,7 +124,8 @@ public class PointService {
|
||||
}
|
||||
|
||||
// 如果不是同一个,则为发帖人加分
|
||||
return addPoint(poster, 10);
|
||||
Post post = postRepository.findById(postId).orElseThrow();
|
||||
return addPoint(poster, 10, PointHistoryType.POST_LIKED, post, null, reactioner);
|
||||
}
|
||||
|
||||
// 考虑点赞者和评论者是同一个的情况
|
||||
@@ -118,7 +142,17 @@ public class PointService {
|
||||
}
|
||||
|
||||
// 如果不是同一个,则为发帖人加分
|
||||
return addPoint(commenter, 10);
|
||||
Comment comment = commentRepository.findById(commentId).orElseThrow();
|
||||
Post post = comment.getPost();
|
||||
return addPoint(commenter, 10, PointHistoryType.COMMENT_LIKED, post, comment, reactioner);
|
||||
}
|
||||
|
||||
public java.util.List<PointHistory> listHistory(String userName) {
|
||||
User user = userRepository.findByUsername(userName).orElseThrow();
|
||||
if (pointHistoryRepository.countByUser(user) == 0) {
|
||||
recordHistory(user, PointHistoryType.SYSTEM_ONLINE, 0, null, null, null);
|
||||
}
|
||||
return pointHistoryRepository.findByUserOrderByIdDesc(user);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -512,6 +512,30 @@ public class PostService {
|
||||
return postRepository.save(post);
|
||||
}
|
||||
|
||||
public Post closePost(Long id, String username) {
|
||||
Post post = postRepository.findById(id)
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("Post not found"));
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||
if (!user.getId().equals(post.getAuthor().getId()) && user.getRole() != Role.ADMIN) {
|
||||
throw new IllegalArgumentException("Unauthorized");
|
||||
}
|
||||
post.setClosed(true);
|
||||
return postRepository.save(post);
|
||||
}
|
||||
|
||||
public Post reopenPost(Long id, String username) {
|
||||
Post post = postRepository.findById(id)
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("Post not found"));
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||
if (!user.getId().equals(post.getAuthor().getId()) && user.getRole() != Role.ADMIN) {
|
||||
throw new IllegalArgumentException("Unauthorized");
|
||||
}
|
||||
post.setClosed(false);
|
||||
return postRepository.save(post);
|
||||
}
|
||||
|
||||
@org.springframework.transaction.annotation.Transactional
|
||||
public Post updatePost(Long id,
|
||||
String username,
|
||||
@@ -555,7 +579,9 @@ public class PostService {
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("Post not found"));
|
||||
User user = userRepository.findByUsername(username)
|
||||
.orElseThrow(() -> new com.openisle.exception.NotFoundException("User not found"));
|
||||
if (!user.getId().equals(post.getAuthor().getId()) && user.getRole() != Role.ADMIN) {
|
||||
User author = post.getAuthor();
|
||||
boolean adminDeleting = !user.getId().equals(author.getId()) && user.getRole() == Role.ADMIN;
|
||||
if (!user.getId().equals(author.getId()) && user.getRole() != Role.ADMIN) {
|
||||
throw new IllegalArgumentException("Unauthorized");
|
||||
}
|
||||
for (Comment c : commentRepository.findByPostAndParentIsNullOrderByCreatedAtAsc(post)) {
|
||||
@@ -572,7 +598,12 @@ public class PostService {
|
||||
future.cancel(false);
|
||||
}
|
||||
}
|
||||
String title = post.getTitle();
|
||||
postRepository.delete(post);
|
||||
if (adminDeleting) {
|
||||
notificationService.createNotification(author, NotificationType.POST_DELETED,
|
||||
null, null, null, user, null, title);
|
||||
}
|
||||
}
|
||||
|
||||
public java.util.List<Post> getPostsByIds(java.util.List<Long> ids) {
|
||||
|
||||
@@ -45,7 +45,7 @@ class NotificationControllerTest {
|
||||
p.setId(2L);
|
||||
n.setPost(p);
|
||||
n.setCreatedAt(LocalDateTime.now());
|
||||
when(notificationService.listNotifications("alice", null))
|
||||
when(notificationService.listNotifications("alice", null, 0, 30))
|
||||
.thenReturn(List.of(n));
|
||||
|
||||
NotificationDto dto = new NotificationDto();
|
||||
@@ -62,6 +62,24 @@ class NotificationControllerTest {
|
||||
.andExpect(jsonPath("$[0].post.id").value(2));
|
||||
}
|
||||
|
||||
@Test
|
||||
void listUnreadNotifications() throws Exception {
|
||||
Notification n = new Notification();
|
||||
n.setId(5L);
|
||||
n.setType(NotificationType.POST_VIEWED);
|
||||
when(notificationService.listNotifications("alice", false, 0, 30))
|
||||
.thenReturn(List.of(n));
|
||||
|
||||
NotificationDto dto = new NotificationDto();
|
||||
dto.setId(5L);
|
||||
when(notificationMapper.toDto(n)).thenReturn(dto);
|
||||
|
||||
mockMvc.perform(get("/api/notifications/unread")
|
||||
.principal(new UsernamePasswordAuthenticationToken("alice","p")))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$[0].id").value(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void markReadEndpoint() throws Exception {
|
||||
mockMvc.perform(post("/api/notifications/read")
|
||||
|
||||
@@ -11,6 +11,9 @@ import org.mockito.Mockito;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
import java.util.HashSet;
|
||||
import org.springframework.data.domain.PageImpl;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
@@ -62,15 +65,17 @@ class NotificationServiceTest {
|
||||
User user = new User();
|
||||
user.setId(2L);
|
||||
user.setUsername("bob");
|
||||
user.setDisabledNotificationTypes(new HashSet<>());
|
||||
when(uRepo.findByUsername("bob")).thenReturn(Optional.of(user));
|
||||
|
||||
Notification n = new Notification();
|
||||
when(nRepo.findByUserOrderByCreatedAtDesc(user)).thenReturn(List.of(n));
|
||||
when(nRepo.findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class)))
|
||||
.thenReturn(new PageImpl<>(List.of(n)));
|
||||
|
||||
List<Notification> list = service.listNotifications("bob", null);
|
||||
List<Notification> list = service.listNotifications("bob", null, 0, 10);
|
||||
|
||||
assertEquals(1, list.size());
|
||||
verify(nRepo).findByUserOrderByCreatedAtDesc(user);
|
||||
verify(nRepo).findByUserOrderByCreatedAtDesc(eq(user), any(Pageable.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -87,6 +92,7 @@ class NotificationServiceTest {
|
||||
User user = new User();
|
||||
user.setId(3L);
|
||||
user.setUsername("carl");
|
||||
user.setDisabledNotificationTypes(new HashSet<>());
|
||||
when(uRepo.findByUsername("carl")).thenReturn(Optional.of(user));
|
||||
when(nRepo.countByUserAndRead(user, false)).thenReturn(5L);
|
||||
|
||||
@@ -96,6 +102,56 @@ class NotificationServiceTest {
|
||||
verify(nRepo).countByUserAndRead(user, false);
|
||||
}
|
||||
|
||||
@Test
|
||||
void listNotificationsFiltersDisabledTypes() {
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
UserRepository uRepo = mock(UserRepository.class);
|
||||
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||
EmailSender email = mock(EmailSender.class);
|
||||
PushNotificationService push = mock(PushNotificationService.class);
|
||||
Executor executor = Runnable::run;
|
||||
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||
|
||||
User user = new User();
|
||||
user.setId(4L);
|
||||
user.setUsername("dana");
|
||||
when(uRepo.findByUsername("dana")).thenReturn(Optional.of(user));
|
||||
|
||||
Notification n = new Notification();
|
||||
when(nRepo.findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class)))
|
||||
.thenReturn(new PageImpl<>(List.of(n)));
|
||||
|
||||
List<Notification> list = service.listNotifications("dana", null, 0, 10);
|
||||
|
||||
assertEquals(1, list.size());
|
||||
verify(nRepo).findByUserAndTypeNotInOrderByCreatedAtDesc(eq(user), eq(user.getDisabledNotificationTypes()), any(Pageable.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void countUnreadFiltersDisabledTypes() {
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
UserRepository uRepo = mock(UserRepository.class);
|
||||
ReactionRepository rRepo = mock(ReactionRepository.class);
|
||||
EmailSender email = mock(EmailSender.class);
|
||||
PushNotificationService push = mock(PushNotificationService.class);
|
||||
Executor executor = Runnable::run;
|
||||
NotificationService service = new NotificationService(nRepo, uRepo, email, push, rRepo, executor);
|
||||
org.springframework.test.util.ReflectionTestUtils.setField(service, "websiteUrl", "https://ex.com");
|
||||
|
||||
User user = new User();
|
||||
user.setId(5L);
|
||||
user.setUsername("erin");
|
||||
when(uRepo.findByUsername("erin")).thenReturn(Optional.of(user));
|
||||
when(nRepo.countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes())))
|
||||
.thenReturn(2L);
|
||||
|
||||
long count = service.countUnread("erin");
|
||||
|
||||
assertEquals(2L, count);
|
||||
verify(nRepo).countByUserAndReadAndTypeNotIn(eq(user), eq(false), eq(user.getDisabledNotificationTypes()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createRegisterRequestNotificationsDeletesOldOnes() {
|
||||
NotificationRepository nRepo = mock(NotificationRepository.class);
|
||||
|
||||
@@ -61,6 +61,58 @@ class PostServiceTest {
|
||||
verify(postRepo).delete(post);
|
||||
}
|
||||
|
||||
@Test
|
||||
void deletePostByAdminNotifiesAuthor() {
|
||||
PostRepository postRepo = mock(PostRepository.class);
|
||||
UserRepository userRepo = mock(UserRepository.class);
|
||||
CategoryRepository catRepo = mock(CategoryRepository.class);
|
||||
TagRepository tagRepo = mock(TagRepository.class);
|
||||
LotteryPostRepository lotteryRepo = mock(LotteryPostRepository.class);
|
||||
NotificationService notifService = mock(NotificationService.class);
|
||||
SubscriptionService subService = mock(SubscriptionService.class);
|
||||
CommentService commentService = mock(CommentService.class);
|
||||
CommentRepository commentRepo = mock(CommentRepository.class);
|
||||
ReactionRepository reactionRepo = mock(ReactionRepository.class);
|
||||
PostSubscriptionRepository subRepo = mock(PostSubscriptionRepository.class);
|
||||
NotificationRepository notificationRepo = mock(NotificationRepository.class);
|
||||
PostReadService postReadService = mock(PostReadService.class);
|
||||
ImageUploader imageUploader = mock(ImageUploader.class);
|
||||
TaskScheduler taskScheduler = mock(TaskScheduler.class);
|
||||
EmailSender emailSender = mock(EmailSender.class);
|
||||
ApplicationContext context = mock(ApplicationContext.class);
|
||||
|
||||
PostService service = new PostService(postRepo, userRepo, catRepo, tagRepo, lotteryRepo,
|
||||
notifService, subService, commentService, commentRepo,
|
||||
reactionRepo, subRepo, notificationRepo, postReadService,
|
||||
imageUploader, taskScheduler, emailSender, context, PublishMode.DIRECT);
|
||||
when(context.getBean(PostService.class)).thenReturn(service);
|
||||
|
||||
Post post = new Post();
|
||||
post.setId(1L);
|
||||
post.setTitle("T");
|
||||
post.setContent("");
|
||||
User author = new User();
|
||||
author.setId(2L);
|
||||
author.setRole(Role.USER);
|
||||
post.setAuthor(author);
|
||||
|
||||
User admin = new User();
|
||||
admin.setId(1L);
|
||||
admin.setRole(Role.ADMIN);
|
||||
|
||||
when(postRepo.findById(1L)).thenReturn(Optional.of(post));
|
||||
when(userRepo.findByUsername("admin")).thenReturn(Optional.of(admin));
|
||||
when(commentRepo.findByPostAndParentIsNullOrderByCreatedAtAsc(post)).thenReturn(List.of());
|
||||
when(reactionRepo.findByPost(post)).thenReturn(List.of());
|
||||
when(subRepo.findByPost(post)).thenReturn(List.of());
|
||||
when(notificationRepo.findByPost(post)).thenReturn(List.of());
|
||||
|
||||
service.deletePost(1L, "admin");
|
||||
|
||||
verify(notifService).createNotification(eq(author), eq(NotificationType.POST_DELETED), isNull(),
|
||||
isNull(), isNull(), eq(admin), isNull(), eq("T"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createPostRespectsRateLimit() {
|
||||
PostRepository postRepo = mock(PostRepository.class);
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<GlobalPopups />
|
||||
<ConfirmDialog />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -28,6 +29,7 @@
|
||||
import HeaderComponent from '~/components/HeaderComponent.vue'
|
||||
import MenuComponent from '~/components/MenuComponent.vue'
|
||||
import GlobalPopups from '~/components/GlobalPopups.vue'
|
||||
import ConfirmDialog from '~/components/ConfirmDialog.vue'
|
||||
import { useIsMobile } from '~/utils/screen'
|
||||
|
||||
const isMobile = useIsMobile()
|
||||
|
||||
@@ -90,7 +90,8 @@ body {
|
||||
}
|
||||
|
||||
.vditor-toolbar--pin {
|
||||
top: var(--header-height) !important;
|
||||
top: calc(var(--header-height) + 1px) !important;
|
||||
z-index: 2000;
|
||||
}
|
||||
|
||||
.vditor-panel {
|
||||
@@ -183,7 +184,7 @@ body {
|
||||
font-family: 'Maple Mono', monospace;
|
||||
font-size: 13px;
|
||||
border-radius: 4px;
|
||||
white-space: no-wrap;
|
||||
white-space: break-spaces;
|
||||
background-color: var(--code-highlight-background-color);
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
65
frontend_nuxt/components/BaseSwitch.vue
Normal file
65
frontend_nuxt/components/BaseSwitch.vue
Normal file
@@ -0,0 +1,65 @@
|
||||
<template>
|
||||
<label class="switch">
|
||||
<input
|
||||
type="checkbox"
|
||||
:checked="modelValue"
|
||||
@change="$emit('update:modelValue', $event.target.checked)"
|
||||
/>
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
defineProps({
|
||||
modelValue: { type: Boolean, default: false },
|
||||
})
|
||||
|
||||
defineEmits(['update:modelValue'])
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.switch {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: 40px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.switch input {
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.slider {
|
||||
position: absolute;
|
||||
cursor: pointer;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: #ccc;
|
||||
transition: 0.2s;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
.slider:before {
|
||||
position: absolute;
|
||||
content: '';
|
||||
height: 16px;
|
||||
width: 16px;
|
||||
left: 2px;
|
||||
bottom: 2px;
|
||||
background-color: white;
|
||||
transition: 0.2s;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
input:checked + .slider {
|
||||
background-color: var(--primary-color);
|
||||
}
|
||||
|
||||
input:checked + .slider:before {
|
||||
transform: translateX(20px);
|
||||
}
|
||||
</style>
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
getEditorTheme as getEditorThemeUtil,
|
||||
getPreviewTheme as getPreviewThemeUtil,
|
||||
} from '~/utils/vditor'
|
||||
import '~/assets/global.css'
|
||||
import LoginOverlay from '~/components/LoginOverlay.vue'
|
||||
|
||||
export default {
|
||||
|
||||
@@ -57,7 +57,7 @@
|
||||
v-if="showEditor"
|
||||
@submit="submitReply"
|
||||
:loading="isWaitingForReply"
|
||||
:disabled="!loggedIn"
|
||||
:disabled="!loggedIn || postClosed"
|
||||
:show-login-overlay="!loggedIn"
|
||||
:parent-user-name="comment.userName"
|
||||
/>
|
||||
@@ -76,6 +76,7 @@
|
||||
:level="level + 1"
|
||||
:default-show-replies="item.openReplies"
|
||||
:post-author-id="postAuthorId"
|
||||
:post-closed="postClosed"
|
||||
/>
|
||||
</template>
|
||||
</BaseTimeline>
|
||||
@@ -122,6 +123,10 @@ const props = defineProps({
|
||||
type: [Number, String],
|
||||
required: true,
|
||||
},
|
||||
postClosed: {
|
||||
type: Boolean,
|
||||
default: false,
|
||||
},
|
||||
})
|
||||
|
||||
const emit = defineEmits(['deleted'])
|
||||
@@ -148,6 +153,7 @@ const toggleReplies = () => {
|
||||
}
|
||||
|
||||
const toggleEditor = () => {
|
||||
if (props.postClosed) return
|
||||
showEditor.value = !showEditor.value
|
||||
if (showEditor.value) {
|
||||
setTimeout(() => {
|
||||
@@ -213,6 +219,10 @@ const deleteComment = async () => {
|
||||
}
|
||||
const submitReply = async (parentUserName, text, clear) => {
|
||||
if (!text.trim()) return
|
||||
if (props.postClosed) {
|
||||
toast.error('帖子已关闭')
|
||||
return
|
||||
}
|
||||
isWaitingForReply.value = true
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
|
||||
71
frontend_nuxt/components/ConfirmDialog.vue
Normal file
71
frontend_nuxt/components/ConfirmDialog.vue
Normal file
@@ -0,0 +1,71 @@
|
||||
<template>
|
||||
<BasePopup :visible="visible" @close="onCancel">
|
||||
<div class="confirm-dialog" role="dialog" aria-modal="true">
|
||||
<h3 class="confirm-title">{{ title }}</h3>
|
||||
<p class="confirm-message">{{ message }}</p>
|
||||
<div class="confirm-actions">
|
||||
<div class="cancel-button" @click="onCancel">取消</div>
|
||||
<div class="confirm-button" @click="onConfirm">确认</div>
|
||||
</div>
|
||||
</div>
|
||||
</BasePopup>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import BasePopup from '~/components/BasePopup.vue'
|
||||
import { useConfirm } from '~/composables/useConfirm'
|
||||
|
||||
const { visible, title, message, onConfirm, onCancel } = useConfirm()
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.confirm-dialog {
|
||||
padding: 20px;
|
||||
text-align: center;
|
||||
}
|
||||
.confirm-title {
|
||||
margin-top: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
}
|
||||
.confirm-message {
|
||||
margin: 16px 0 20px;
|
||||
line-height: 1.6;
|
||||
color: var(--text-secondary, #666);
|
||||
}
|
||||
.confirm-actions {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
gap: 12px;
|
||||
}
|
||||
.confirm-button,
|
||||
.cancel-button {
|
||||
min-width: 88px;
|
||||
height: 36px;
|
||||
padding: 0 14px;
|
||||
border-radius: 8px;
|
||||
cursor: pointer;
|
||||
border: 1px solid transparent;
|
||||
}
|
||||
.confirm-button {
|
||||
background: var(--primary-color);
|
||||
color: #fff;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.confirm-button:hover {
|
||||
background: var(--primary-color-hover);
|
||||
}
|
||||
.cancel-button {
|
||||
background: transparent;
|
||||
color: var(--primary-color);
|
||||
border-color: currentColor;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
.cancel-button:hover {
|
||||
opacity: 0.85;
|
||||
}
|
||||
</style>
|
||||
@@ -50,7 +50,7 @@ onMounted(async () => {
|
||||
})
|
||||
|
||||
const checkMilkTeaActivity = async () => {
|
||||
if (!process.client) return
|
||||
if (!import.meta.client) return
|
||||
if (localStorage.getItem('milkTeaActivityPopupShown')) return
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/activities`)
|
||||
@@ -68,7 +68,7 @@ const checkMilkTeaActivity = async () => {
|
||||
}
|
||||
|
||||
const checkInviteCodeActivity = async () => {
|
||||
if (!process.client) return
|
||||
if (!import.meta.client) return
|
||||
if (localStorage.getItem('inviteCodeActivityPopupShown')) return
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/activities`)
|
||||
@@ -86,32 +86,30 @@ const checkInviteCodeActivity = async () => {
|
||||
}
|
||||
|
||||
const closeInviteCodePopup = () => {
|
||||
if (!process.client) return
|
||||
if (!import.meta.client) return
|
||||
localStorage.setItem('inviteCodeActivityPopupShown', 'true')
|
||||
showInviteCodePopup.value = false
|
||||
}
|
||||
|
||||
const closeMilkTeaPopup = () => {
|
||||
if (!process.client) return
|
||||
if (!import.meta.client) return
|
||||
localStorage.setItem('milkTeaActivityPopupShown', 'true')
|
||||
showMilkTeaPopup.value = false
|
||||
checkNotificationSetting()
|
||||
}
|
||||
|
||||
const checkNotificationSetting = async () => {
|
||||
if (!process.client) return
|
||||
if (!import.meta.client) return
|
||||
if (!authState.loggedIn) return
|
||||
if (localStorage.getItem('notificationSettingPopupShown')) return
|
||||
showNotificationPopup.value = true
|
||||
}
|
||||
const closeNotificationPopup = () => {
|
||||
if (!process.client) return
|
||||
if (!import.meta.client) return
|
||||
localStorage.setItem('notificationSettingPopupShown', 'true')
|
||||
showNotificationPopup.value = false
|
||||
checkNewMedals()
|
||||
}
|
||||
const checkNewMedals = async () => {
|
||||
if (!process.client) return
|
||||
if (!import.meta.client) return
|
||||
if (!authState.loggedIn || !authState.userId) return
|
||||
try {
|
||||
const res = await fetch(`${API_BASE_URL}/api/medals?userId=${authState.userId}`)
|
||||
@@ -129,7 +127,7 @@ const checkNewMedals = async () => {
|
||||
}
|
||||
}
|
||||
const closeMedalPopup = () => {
|
||||
if (!process.client) return
|
||||
if (!import.meta.client) return
|
||||
const seen = new Set(JSON.parse(localStorage.getItem('seenMedals') || '[]'))
|
||||
newMedals.value.forEach((m) => seen.add(m.type))
|
||||
localStorage.setItem('seenMedals', JSON.stringify([...seen]))
|
||||
|
||||
102
frontend_nuxt/components/InfiniteLoadMore.vue
Normal file
102
frontend_nuxt/components/InfiniteLoadMore.vue
Normal file
@@ -0,0 +1,102 @@
|
||||
<template>
|
||||
<!-- 当 done 后整个容器自动隐藏,不再占位 -->
|
||||
<div v-show="!done" class="infinite-loadmore">
|
||||
<div v-show="isLoading" class="loading-container bottom-loading" aria-live="polite">
|
||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||
</div>
|
||||
<!-- 永久存在的底部触发器(由组件内部持有与观察) -->
|
||||
<div ref="sentinel" class="load-more-trigger" aria-hidden="true"></div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, onBeforeUnmount, watch, nextTick } from 'vue'
|
||||
|
||||
const props = defineProps({
|
||||
/** 父组件提供:执行“加载下一页”的函数
|
||||
* 返回:
|
||||
* - boolean:true 表示“已经没有更多数据(done)”
|
||||
* - { done: boolean }:同上
|
||||
*/
|
||||
onLoad: { type: Function, required: true },
|
||||
/** pause=true 时暂停观察(例如首屏/筛选加载过程) */
|
||||
pause: { type: Boolean, default: false },
|
||||
/** 预取范围,默认 200px */
|
||||
rootMargin: { type: String, default: '200px 0px' },
|
||||
/** 触发阈值 */
|
||||
threshold: { type: Number, default: 0 },
|
||||
})
|
||||
|
||||
const isLoading = ref(false)
|
||||
const done = ref(false)
|
||||
const sentinel = ref(null)
|
||||
let io = null
|
||||
|
||||
const stopObserver = () => {
|
||||
if (io) {
|
||||
io.disconnect()
|
||||
io = null
|
||||
}
|
||||
}
|
||||
|
||||
const startObserver = () => {
|
||||
if (!import.meta.client || props.pause || done.value) return
|
||||
stopObserver()
|
||||
io = new IntersectionObserver(
|
||||
async (entries) => {
|
||||
const e = entries[0]
|
||||
if (!e?.isIntersecting || isLoading.value || done.value) return
|
||||
isLoading.value = true
|
||||
try {
|
||||
const res = await props.onLoad()
|
||||
const finished = typeof res === 'boolean' ? res : !!(res && res.done)
|
||||
if (finished) {
|
||||
done.value = true
|
||||
stopObserver()
|
||||
}
|
||||
} finally {
|
||||
isLoading.value = false
|
||||
}
|
||||
},
|
||||
{ root: null, rootMargin: props.rootMargin, threshold: props.threshold },
|
||||
)
|
||||
if (sentinel.value) io.observe(sentinel.value)
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
nextTick(startObserver)
|
||||
})
|
||||
onBeforeUnmount(stopObserver)
|
||||
|
||||
watch(
|
||||
() => props.pause,
|
||||
(p) => {
|
||||
if (p) stopObserver()
|
||||
else nextTick(startObserver)
|
||||
},
|
||||
)
|
||||
|
||||
/** 父组件可选择性调用,用于外部强制重置(一般直接用 :key 重建更简单) */
|
||||
const reset = () => {
|
||||
done.value = false
|
||||
nextTick(startObserver)
|
||||
}
|
||||
defineExpose({ reset })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.infinite-loadmore {
|
||||
}
|
||||
|
||||
.loading-container {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 100px; /* 与原样式匹配 */
|
||||
}
|
||||
|
||||
.load-more-trigger {
|
||||
width: 100%;
|
||||
height: 1px;
|
||||
}
|
||||
</style>
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
getEditorTheme as getEditorThemeUtil,
|
||||
getPreviewTheme as getPreviewThemeUtil,
|
||||
} from '~/utils/vditor'
|
||||
import '~/assets/global.css'
|
||||
|
||||
export default {
|
||||
name: 'PostEditor',
|
||||
|
||||
@@ -51,6 +51,10 @@ import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { toast } from '~/main'
|
||||
import { authState, getToken } from '~/utils/auth'
|
||||
import { reactionEmojiMap } from '~/utils/reactions'
|
||||
import { useReactionTypes } from '~/composables/useReactionTypes'
|
||||
|
||||
const { reactionTypes, initialize } = useReactionTypes()
|
||||
|
||||
const config = useRuntimeConfig()
|
||||
const API_BASE_URL = config.public.apiBaseUrl
|
||||
const emit = defineEmits(['update:modelValue'])
|
||||
@@ -66,30 +70,6 @@ watch(
|
||||
)
|
||||
|
||||
const reactions = ref(props.modelValue)
|
||||
const reactionTypes = ref([])
|
||||
|
||||
let cachedTypes = null
|
||||
const fetchTypes = async () => {
|
||||
if (cachedTypes) return cachedTypes
|
||||
try {
|
||||
const token = getToken()
|
||||
const res = await fetch(`${API_BASE_URL}/api/reaction-types`, {
|
||||
headers: { Authorization: token ? `Bearer ${token}` : '' },
|
||||
})
|
||||
if (res.ok) {
|
||||
cachedTypes = await res.json()
|
||||
} else {
|
||||
cachedTypes = []
|
||||
}
|
||||
} catch {
|
||||
cachedTypes = []
|
||||
}
|
||||
return cachedTypes
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
reactionTypes.value = await fetchTypes()
|
||||
})
|
||||
|
||||
const counts = computed(() => {
|
||||
const c = {}
|
||||
@@ -200,6 +180,10 @@ const toggleReaction = async (type) => {
|
||||
toast.error('操作失败')
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await initialize()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style>
|
||||
@@ -253,7 +237,7 @@ const toggleReaction = async (type) => {
|
||||
|
||||
.make-reaction-item {
|
||||
cursor: pointer;
|
||||
padding: 10px;
|
||||
padding: 4px;
|
||||
opacity: 0.5;
|
||||
border-radius: 8px;
|
||||
font-size: 20px;
|
||||
|
||||
@@ -63,7 +63,7 @@ const isImageIcon = (icon) => {
|
||||
}
|
||||
|
||||
const buildTagsUrl = (kw = '') => {
|
||||
const base = API_BASE_URL || (process.client ? window.location.origin : '')
|
||||
const base = API_BASE_URL || (import.meta.client ? window.location.origin : '')
|
||||
const url = new URL('/api/tags', base)
|
||||
|
||||
if (kw) url.searchParams.set('keyword', kw)
|
||||
|
||||
52
frontend_nuxt/composables/useConfirm.ts
Normal file
52
frontend_nuxt/composables/useConfirm.ts
Normal file
@@ -0,0 +1,52 @@
|
||||
// composables/useConfirm.ts
|
||||
import { ref } from 'vue'
|
||||
|
||||
// 全局单例(SPA 下即可;Nuxt/SSR 下见文末“SSR 提醒”)
|
||||
const visible = ref(false)
|
||||
const title = ref('')
|
||||
const message = ref('')
|
||||
|
||||
let resolver: ((ok: boolean) => void) | null = null
|
||||
|
||||
function reset() {
|
||||
visible.value = false
|
||||
title.value = ''
|
||||
message.value = ''
|
||||
resolver = null
|
||||
}
|
||||
|
||||
export function useConfirm() {
|
||||
/**
|
||||
* 打开确认框,返回 Promise<boolean>
|
||||
* - 确认 => resolve(true)
|
||||
* - 取消/关闭 => resolve(false)
|
||||
* 若并发调用,以最后一次为准(更简单直观)
|
||||
*/
|
||||
const confirm = (t: string, m: string) => {
|
||||
title.value = t
|
||||
message.value = m
|
||||
visible.value = true
|
||||
return new Promise<boolean>((resolve) => {
|
||||
resolver = resolve
|
||||
})
|
||||
}
|
||||
|
||||
const onConfirm = () => {
|
||||
resolver?.(true)
|
||||
reset()
|
||||
}
|
||||
|
||||
const onCancel = () => {
|
||||
resolver?.(false)
|
||||
reset()
|
||||
}
|
||||
|
||||
return {
|
||||
visible,
|
||||
title,
|
||||
message,
|
||||
confirm,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
}
|
||||
}
|
||||
52
frontend_nuxt/composables/useReactionTypes.js
Normal file
52
frontend_nuxt/composables/useReactionTypes.js
Normal file
@@ -0,0 +1,52 @@
|
||||
import { ref } from 'vue'
|
||||
|
||||
const reactionTypes = ref([])
|
||||
let isLoading = false
|
||||
let isInitialized = false
|
||||
|
||||
export function useReactionTypes() {
|
||||
const config = useRuntimeConfig()
|
||||
const API_BASE_URL = config.public.apiBaseUrl
|
||||
|
||||
const fetchReactionTypes = async () => {
|
||||
if (isInitialized || isLoading) {
|
||||
reactionTypes.value = [...(window.reactionTypes || [])]
|
||||
return reactionTypes.value
|
||||
}
|
||||
|
||||
isLoading = true
|
||||
try {
|
||||
const token = getToken()
|
||||
const res = await fetch(`${API_BASE_URL}/api/reaction-types`, {
|
||||
headers: { Authorization: token ? `Bearer ${token}` : '' },
|
||||
})
|
||||
if (res.ok) {
|
||||
reactionTypes.value = await res.json()
|
||||
window.reactionTypes = [...reactionTypes.value]
|
||||
isInitialized = true
|
||||
} else {
|
||||
reactionTypes.value = []
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch reaction types:', error)
|
||||
reactionTypes.value = []
|
||||
} finally {
|
||||
isLoading = false
|
||||
}
|
||||
return reactionTypes.value
|
||||
}
|
||||
|
||||
const initialize = async () => {
|
||||
if (!isInitialized) {
|
||||
await fetchReactionTypes()
|
||||
}
|
||||
return reactionTypes.value
|
||||
}
|
||||
|
||||
return {
|
||||
reactionTypes: readonly(reactionTypes),
|
||||
fetchReactionTypes,
|
||||
initialize,
|
||||
isInitialized: readonly(isInitialized)
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
// 导出一个便捷的 toast 对象
|
||||
export const toast = {
|
||||
success: async (message) => {
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
try {
|
||||
const { useToast } = await import('vue-toastification')
|
||||
const toastInstance = useToast()
|
||||
@@ -12,7 +12,7 @@ export const toast = {
|
||||
}
|
||||
},
|
||||
error: async (message) => {
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
try {
|
||||
const { useToast } = await import('vue-toastification')
|
||||
const toastInstance = useToast()
|
||||
@@ -23,7 +23,7 @@ export const toast = {
|
||||
}
|
||||
},
|
||||
warning: async (message) => {
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
try {
|
||||
const { useToast } = await import('vue-toastification')
|
||||
const toastInstance = useToast()
|
||||
@@ -34,7 +34,7 @@ export const toast = {
|
||||
}
|
||||
},
|
||||
info: async (message) => {
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
try {
|
||||
const { useToast } = await import('vue-toastification')
|
||||
const toastInstance = useToast()
|
||||
@@ -48,7 +48,7 @@ export const toast = {
|
||||
|
||||
// 导出 useToast composable
|
||||
export const useToast = () => {
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
return new Promise(async (resolve) => {
|
||||
try {
|
||||
const { useToast: useVueToast } = await import('vue-toastification')
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
<template>
|
||||
<div class="site-stats-page">
|
||||
<div v-if="isLoading" class="loading-message">
|
||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||
</div>
|
||||
<ClientOnly>
|
||||
<VChart
|
||||
v-if="dauOption"
|
||||
@@ -51,8 +54,10 @@ const dauOption = ref(null)
|
||||
const newUserOption = ref(null)
|
||||
const postOption = ref(null)
|
||||
const commentOption = ref(null)
|
||||
const isLoading = ref(false)
|
||||
|
||||
async function loadData() {
|
||||
isLoading.value = true
|
||||
const token = getToken()
|
||||
const headers = { Authorization: `Bearer ${token}` }
|
||||
|
||||
@@ -93,6 +98,7 @@ async function loadData() {
|
||||
const data = await commentRes.json()
|
||||
commentOption.value = toOption('每日回贴量', data)
|
||||
}
|
||||
isLoading.value = false
|
||||
}
|
||||
|
||||
onMounted(loadData)
|
||||
@@ -105,4 +111,11 @@ onMounted(loadData)
|
||||
background-color: var(--background-color);
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.loading-message {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
align-items: center;
|
||||
height: 400px;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -102,25 +102,33 @@
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<div v-else-if="selectedTopic === '热门'" class="placeholder-container">
|
||||
热门帖子功能开发中,敬请期待。
|
||||
</div>
|
||||
<div v-else class="placeholder-container">分类浏览功能开发中,敬请期待。</div>
|
||||
<div v-if="isLoadingMore && articles.length > 0" class="loading-container bottom-loading">
|
||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||
</div>
|
||||
|
||||
<!-- ✅ 通用“底部加载更多”组件(自管 loading/observer/并发) -->
|
||||
<InfiniteLoadMore
|
||||
v-if="articles.length > 0"
|
||||
:key="ioKey"
|
||||
:on-load="fetchNextPage"
|
||||
:pause="pendingFirst"
|
||||
root-margin="200px 0px"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref, watch } from 'vue'
|
||||
import { computed, onMounted, onBeforeUnmount, nextTick, ref, watch } from 'vue'
|
||||
import ArticleCategory from '~/components/ArticleCategory.vue'
|
||||
import ArticleTags from '~/components/ArticleTags.vue'
|
||||
import CategorySelect from '~/components/CategorySelect.vue'
|
||||
import SearchDropdown from '~/components/SearchDropdown.vue'
|
||||
import TagSelect from '~/components/TagSelect.vue'
|
||||
import InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
|
||||
import { getToken } from '~/utils/auth'
|
||||
import { useScrollLoadMore } from '~/utils/loadMore'
|
||||
import { stripMarkdown } from '~/utils/markdown'
|
||||
import { useIsMobile } from '~/utils/screen'
|
||||
import TimeManager from '~/utils/time'
|
||||
@@ -144,8 +152,6 @@ const route = useRoute()
|
||||
const tagOptions = ref([])
|
||||
const categoryOptions = ref([])
|
||||
|
||||
const isLoadingMore = ref(false)
|
||||
|
||||
const topics = ref(['最新回复', '最新', '排行榜' /*, '热门', '类别'*/])
|
||||
const selectedTopicCookie = useCookie('homeTab')
|
||||
const selectedTopic = ref(
|
||||
@@ -162,7 +168,6 @@ const articles = ref([])
|
||||
const page = ref(0)
|
||||
const pageSize = 10
|
||||
const isMobile = useIsMobile()
|
||||
const allLoaded = ref(false)
|
||||
|
||||
/** URL 参数 -> 本地筛选值 **/
|
||||
const selectedCategorySet = (category) => {
|
||||
@@ -286,80 +291,54 @@ const {
|
||||
},
|
||||
)
|
||||
|
||||
/** 首屏/筛选变更:重置分页并灌入 firstPage **/
|
||||
/** 首屏/筛选变更:重置分页并灌入 firstPage(InfiniteLoadMore 会凭 key 重建状态) **/
|
||||
watch(
|
||||
firstPage,
|
||||
(data) => {
|
||||
page.value = 0
|
||||
articles.value = [...(data || [])]
|
||||
allLoaded.value = (data?.length || 0) < pageSize
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
/** —— 滚动加载更多 —— **/
|
||||
let inflight = null
|
||||
/** —— 提供给 InfiniteLoadMore 的加载函数 —— **/
|
||||
const fetchNextPage = async () => {
|
||||
if (allLoaded.value || pendingFirst.value || inflight) return
|
||||
// 若首屏仍在 pending,由组件 pause 控制,这里兜底返回“未完成”
|
||||
if (pendingFirst.value) return false
|
||||
|
||||
const nextPage = page.value + 1
|
||||
isLoadingMore.value = true
|
||||
inflight = $fetch(buildUrl({ pageNo: nextPage }), { headers: tokenHeader.value })
|
||||
.then((res) => {
|
||||
const data = Array.isArray(res) ? res : []
|
||||
const mapped = data.map((p) => ({
|
||||
id: p.id,
|
||||
title: p.title,
|
||||
description: p.content,
|
||||
category: p.category,
|
||||
tags: p.tags || [],
|
||||
members: (p.participants || []).map((m) => ({ id: m.id, avatar: m.avatar })),
|
||||
comments: p.commentCount,
|
||||
views: p.views,
|
||||
time: TimeManager.format(
|
||||
selectedTopic.value === '最新回复' ? p.lastReplyAt || p.createdAt : p.createdAt,
|
||||
),
|
||||
pinned: Boolean(p.pinned ?? p.pinnedAt ?? p.pinned_at),
|
||||
type: p.type,
|
||||
}))
|
||||
articles.value.push(...mapped)
|
||||
if (data.length < pageSize) {
|
||||
allLoaded.value = true
|
||||
} else {
|
||||
page.value = nextPage
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
inflight = null
|
||||
isLoadingMore.value = false
|
||||
})
|
||||
const res = await $fetch(buildUrl({ pageNo: nextPage }), { headers: tokenHeader.value })
|
||||
const data = Array.isArray(res) ? res : []
|
||||
const mapped = data.map((p) => ({
|
||||
id: p.id,
|
||||
title: p.title,
|
||||
description: p.content,
|
||||
category: p.category,
|
||||
tags: p.tags || [],
|
||||
members: (p.participants || []).map((m) => ({ id: m.id, avatar: m.avatar })),
|
||||
comments: p.commentCount,
|
||||
views: p.views,
|
||||
time: TimeManager.format(
|
||||
selectedTopic.value === '最新回复' ? p.lastReplyAt || p.createdAt : p.createdAt,
|
||||
),
|
||||
pinned: Boolean(p.pinned ?? p.pinnedAt ?? p.pinned_at),
|
||||
type: p.type,
|
||||
}))
|
||||
articles.value.push(...mapped)
|
||||
|
||||
const done = data.length < pageSize
|
||||
if (!done) page.value = nextPage
|
||||
return done // ✅ 返回给组件,决定是否停止观察
|
||||
}
|
||||
|
||||
/** 绑定滚动加载(避免挂载瞬间触发) **/
|
||||
let initialReady = false
|
||||
const loadMoreGuarded = async () => {
|
||||
if (!initialReady) return
|
||||
await fetchNextPage()
|
||||
}
|
||||
useScrollLoadMore(loadMoreGuarded)
|
||||
watch(
|
||||
articles,
|
||||
() => {
|
||||
if (!initialReady && articles.value.length) initialReady = true
|
||||
},
|
||||
{ immediate: true },
|
||||
)
|
||||
|
||||
/** 切换分类/标签/Tab:useAsyncData 已 watch,这里只需确保 options 加载 **/
|
||||
/** 选项首屏加载与状态持久 **/
|
||||
watch([selectedCategory, selectedTags], () => {
|
||||
loadOptions()
|
||||
})
|
||||
watch(selectedTopic, (val) => {
|
||||
// 仅当需要额外选项时加载
|
||||
loadOptions()
|
||||
selectedTopicCookie.value = val
|
||||
if (process.client) {
|
||||
localStorage.setItem('homeTab', val)
|
||||
}
|
||||
if (import.meta.client) localStorage.setItem('homeTab', val)
|
||||
})
|
||||
|
||||
/** 选项首屏加载:服务端执行一次;客户端兜底 **/
|
||||
@@ -368,9 +347,14 @@ if (import.meta.server) {
|
||||
}
|
||||
onMounted(() => {
|
||||
if (categoryOptions.value.length === 0 && tagOptions.value.length === 0) loadOptions()
|
||||
|
||||
window.addEventListener('refresh-home', refreshFirst)
|
||||
})
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('refresh-home', refreshFirst)
|
||||
})
|
||||
|
||||
/** 供 InfiniteLoadMore 重建用的 key:筛选/Tab 改变即重建内部状态 */
|
||||
const ioKey = computed(() => asyncKey.value.join('::'))
|
||||
|
||||
/** 其他工具函数 **/
|
||||
const sanitizeDescription = (text) => stripMarkdown(text)
|
||||
@@ -407,6 +391,7 @@ const sanitizeDescription = (text) => stripMarkdown(text)
|
||||
height: 200px;
|
||||
}
|
||||
|
||||
/* 这里的 bottom-loading 可保留给首屏 loading 使用;InfiniteLoadMore 自带同名样式也兼容 */
|
||||
.bottom-loading {
|
||||
height: 100px;
|
||||
}
|
||||
@@ -550,6 +535,7 @@ const sanitizeDescription = (text) => stripMarkdown(text)
|
||||
}
|
||||
|
||||
.article-item-description {
|
||||
max-width: 100%;
|
||||
margin-top: 10px;
|
||||
font-size: 14px;
|
||||
color: gray;
|
||||
|
||||
@@ -33,15 +33,13 @@
|
||||
<div v-if="selectedTab === 'control'">
|
||||
<div class="message-control-container">
|
||||
<div class="message-control-title">通知设置</div>
|
||||
<div class="message-control-push-item-container">
|
||||
<div
|
||||
v-for="pref in notificationPrefs"
|
||||
:key="pref.type"
|
||||
class="message-control-push-item"
|
||||
:class="{ select: pref.enabled }"
|
||||
@click="togglePref(pref)"
|
||||
>
|
||||
{{ formatType(pref.type) }}
|
||||
<div class="message-control-item-container">
|
||||
<div v-for="pref in notificationPrefs" :key="pref.type" class="message-control-item">
|
||||
<div class="message-control-item-label">{{ formatType(pref.type) }}</div>
|
||||
<BaseSwitch
|
||||
:model-value="pref.enabled"
|
||||
@update:modelValue="(val) => togglePref(pref, val)"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -53,13 +51,13 @@
|
||||
</div>
|
||||
|
||||
<BasePlaceholder
|
||||
v-else-if="filteredNotifications.length === 0"
|
||||
v-else-if="notifications.length === 0"
|
||||
text="暂时没有消息 :)"
|
||||
icon="fas fa-inbox"
|
||||
/>
|
||||
|
||||
<div class="timeline-container" v-if="filteredNotifications.length > 0">
|
||||
<BaseTimeline :items="filteredNotifications">
|
||||
<div class="timeline-container" v-if="notifications.length > 0">
|
||||
<BaseTimeline :items="notifications">
|
||||
<template #item="{ item }">
|
||||
<div class="notif-content" :class="{ read: item.read }">
|
||||
<span v-if="!item.read" class="unread-dot"></span>
|
||||
@@ -495,6 +493,24 @@
|
||||
已被管理员拒绝
|
||||
</NotificationContainer>
|
||||
</template>
|
||||
<template v-else-if="item.type === 'POST_DELETED'">
|
||||
<NotificationContainer :item="item" :markRead="markRead">
|
||||
管理员
|
||||
<template v-if="item.fromUser">
|
||||
<NuxtLink
|
||||
class="notif-content-text"
|
||||
@click="markRead(item.id)"
|
||||
:to="`/users/${item.fromUser.id}`"
|
||||
>
|
||||
{{ item.fromUser.username }}
|
||||
</NuxtLink>
|
||||
</template>
|
||||
删除了您的帖子
|
||||
<span class="notif-content-text">
|
||||
{{ stripMarkdownLength(item.content, 100) }}
|
||||
</span>
|
||||
</NotificationContainer>
|
||||
</template>
|
||||
<template v-else>
|
||||
<NotificationContainer :item="item" :markRead="markRead">
|
||||
{{ formatType(item.type) }}
|
||||
@@ -505,16 +521,18 @@
|
||||
</div>
|
||||
</template>
|
||||
</BaseTimeline>
|
||||
<InfiniteLoadMore :key="selectedTab" :on-load="loadMore" :pause="isLoadingMessage" />
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { ref, watch, onActivated } from 'vue'
|
||||
import BasePlaceholder from '~/components/BasePlaceholder.vue'
|
||||
import BaseTimeline from '~/components/BaseTimeline.vue'
|
||||
import NotificationContainer from '~/components/NotificationContainer.vue'
|
||||
import InfiniteLoadMore from '~/components/InfiniteLoadMore.vue'
|
||||
import { toast } from '~/main'
|
||||
import { authState, getToken } from '~/utils/auth'
|
||||
import { stripMarkdownLength } from '~/utils/markdown'
|
||||
@@ -522,11 +540,15 @@ import {
|
||||
fetchNotifications,
|
||||
fetchUnreadCount,
|
||||
isLoadingMessage,
|
||||
markRead,
|
||||
markNotificationRead,
|
||||
notifications,
|
||||
markAllRead,
|
||||
hasMore,
|
||||
fetchNotificationPreferences,
|
||||
updateNotificationPreference,
|
||||
} from '~/utils/notification'
|
||||
import TimeManager from '~/utils/time'
|
||||
import BaseSwitch from '~/components/BaseSwitch.vue'
|
||||
|
||||
const config = useRuntimeConfig()
|
||||
const API_BASE_URL = config.public.apiBaseUrl
|
||||
@@ -535,25 +557,53 @@ const selectedTab = ref(
|
||||
['all', 'unread', 'control'].includes(route.query.tab) ? route.query.tab : 'unread',
|
||||
)
|
||||
const notificationPrefs = ref([])
|
||||
const filteredNotifications = computed(() =>
|
||||
selectedTab.value === 'all' ? notifications.value : notifications.value.filter((n) => !n.read),
|
||||
)
|
||||
const page = ref(0)
|
||||
const pageSize = 30
|
||||
|
||||
const loadMore = async () => {
|
||||
if (!hasMore.value) return true
|
||||
page.value++
|
||||
await fetchNotifications({
|
||||
page: page.value,
|
||||
size: pageSize,
|
||||
unread: selectedTab.value === 'unread',
|
||||
append: true,
|
||||
})
|
||||
return !hasMore.value
|
||||
}
|
||||
|
||||
watch(selectedTab, async (tab) => {
|
||||
page.value = 0
|
||||
await fetchNotifications({ page: 0, size: pageSize, unread: tab === 'unread' })
|
||||
})
|
||||
|
||||
const fetchPrefs = async () => {
|
||||
notificationPrefs.value = await fetchNotificationPreferences()
|
||||
}
|
||||
|
||||
const togglePref = async (pref) => {
|
||||
const ok = await updateNotificationPreference(pref.type, !pref.enabled)
|
||||
const togglePref = async (pref, value) => {
|
||||
const ok = await updateNotificationPreference(pref.type, value)
|
||||
if (ok) {
|
||||
pref.enabled = !pref.enabled
|
||||
await fetchNotifications()
|
||||
pref.enabled = value
|
||||
await fetchNotifications({
|
||||
page: page.value,
|
||||
size: pageSize,
|
||||
unread: selectedTab.value === 'unread',
|
||||
})
|
||||
await fetchUnreadCount()
|
||||
} else {
|
||||
toast.error('操作失败')
|
||||
}
|
||||
}
|
||||
|
||||
const markRead = async (id) => {
|
||||
markNotificationRead(id)
|
||||
if (selectedTab.value === 'unread') {
|
||||
const index = notifications.value.findIndex((n) => n.id === id)
|
||||
if (index !== -1) notifications.value.splice(index, 1)
|
||||
}
|
||||
}
|
||||
|
||||
const approve = async (id, nid) => {
|
||||
const token = getToken()
|
||||
if (!token) return
|
||||
@@ -622,13 +672,16 @@ const formatType = (t) => {
|
||||
return '抽奖中奖了'
|
||||
case 'LOTTERY_DRAW':
|
||||
return '抽奖已开奖'
|
||||
case 'POST_DELETED':
|
||||
return '帖子被删除'
|
||||
default:
|
||||
return t
|
||||
}
|
||||
}
|
||||
|
||||
onActivated(() => {
|
||||
fetchNotifications()
|
||||
onActivated(async () => {
|
||||
page.value = 0
|
||||
await fetchNotifications({ page: 0, size: pageSize, unread: selectedTab.value === 'unread' })
|
||||
fetchPrefs()
|
||||
})
|
||||
</script>
|
||||
@@ -644,8 +697,6 @@ onActivated(() => {
|
||||
.message-page {
|
||||
background-color: var(--background-color);
|
||||
overflow-x: hidden;
|
||||
height: calc(100vh - var(--header-height));
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.message-page-header {
|
||||
@@ -794,26 +845,21 @@ onActivated(() => {
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.message-control-push-item-container {
|
||||
.message-control-item-container {
|
||||
display: flex;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.message-control-push-item {
|
||||
font-size: 14px;
|
||||
margin-bottom: 5px;
|
||||
padding: 8px 16px;
|
||||
border: 1px solid var(--normal-border-color);
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: all 0.3s ease;
|
||||
.message-control-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
max-width: 200px;
|
||||
}
|
||||
|
||||
.message-control-push-item.select {
|
||||
background-color: var(--primary-color);
|
||||
color: white;
|
||||
.message-control-item-label {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
|
||||
@@ -1,62 +1,171 @@
|
||||
<template>
|
||||
<div class="point-mall-page">
|
||||
<section class="rules">
|
||||
<div class="section-title">🎉 积分规则</div>
|
||||
<div class="section-content">
|
||||
<div class="section-item" v-for="(rule, idx) in pointRules" :key="idx">{{ rule }}</div>
|
||||
<div class="point-tabs">
|
||||
<div
|
||||
:class="['point-tab-item', { selected: selectedTab === 'mall' }]"
|
||||
@click="selectedTab = 'mall'"
|
||||
>
|
||||
积分兑换
|
||||
</div>
|
||||
<div
|
||||
:class="['point-tab-item', { selected: selectedTab === 'history' }]"
|
||||
@click="selectedTab = 'history'"
|
||||
>
|
||||
积分历史
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="loading-points-container" v-if="isLoading">
|
||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||
</div>
|
||||
|
||||
<div class="point-info">
|
||||
<p v-if="authState.loggedIn && point !== null">
|
||||
<span><i class="fas fa-coins coin-icon"></i></span>我的积分:<span class="point-value">{{
|
||||
point
|
||||
}}</span>
|
||||
</p>
|
||||
</div>
|
||||
<template v-if="selectedTab === 'mall'">
|
||||
<div class="point-mall-page-content">
|
||||
<section class="rules">
|
||||
<div class="section-title">🎉 积分规则</div>
|
||||
<div class="section-content">
|
||||
<div class="section-item" v-for="(rule, idx) in pointRules" :key="idx">{{ rule }}</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="goods">
|
||||
<div class="goods-item" v-for="(good, idx) in goods" :key="idx">
|
||||
<img class="goods-item-image" :src="good.image" alt="good.name" />
|
||||
<div class="goods-item-name">{{ good.name }}</div>
|
||||
<div class="goods-item-cost">
|
||||
<i class="fas fa-coins"></i>
|
||||
{{ good.cost }} 积分
|
||||
<div class="loading-points-container" v-if="isLoading">
|
||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||
</div>
|
||||
<div
|
||||
class="goods-item-button"
|
||||
:class="{ disabled: !authState.loggedIn || point === null || point < good.cost }"
|
||||
@click="openRedeem(good)"
|
||||
>
|
||||
兑换
|
||||
|
||||
<div class="point-info">
|
||||
<p v-if="authState.loggedIn && point !== null">
|
||||
<span><i class="fas fa-coins coin-icon"></i></span>我的积分:<span
|
||||
class="point-value"
|
||||
>{{ point }}</span
|
||||
>
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<section class="goods">
|
||||
<div class="goods-item" v-for="(good, idx) in goods" :key="idx">
|
||||
<img class="goods-item-image" :src="good.image" alt="good.name" />
|
||||
<div class="goods-item-name">{{ good.name }}</div>
|
||||
<div class="goods-item-cost">
|
||||
<i class="fas fa-coins"></i>
|
||||
{{ good.cost }} 积分
|
||||
</div>
|
||||
<div
|
||||
class="goods-item-button"
|
||||
:class="{ disabled: !authState.loggedIn || point === null || point < good.cost }"
|
||||
@click="openRedeem(good)"
|
||||
>
|
||||
兑换
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
<RedeemPopup
|
||||
:visible="dialogVisible"
|
||||
v-model="contact"
|
||||
:loading="loading"
|
||||
@close="closeRedeem"
|
||||
@submit="submitRedeem"
|
||||
/>
|
||||
</div>
|
||||
</section>
|
||||
<RedeemPopup
|
||||
:visible="dialogVisible"
|
||||
v-model="contact"
|
||||
:loading="loading"
|
||||
@close="closeRedeem"
|
||||
@submit="submitRedeem"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<template v-else>
|
||||
<div class="loading-points-container" v-if="historyLoading">
|
||||
<l-hatch size="28" stroke="4" speed="3.5" color="var(--primary-color)"></l-hatch>
|
||||
</div>
|
||||
<BasePlaceholder v-else-if="histories.length === 0" text="暂无积分记录" icon="fas fa-inbox" />
|
||||
<div class="timeline-container" v-else>
|
||||
<BaseTimeline :items="histories">
|
||||
<template #item="{ item }">
|
||||
<div class="history-content">
|
||||
<template v-if="item.type === 'POST'">
|
||||
发送帖子
|
||||
<NuxtLink :to="`/posts/${item.postId}`" class="timeline-link">{{
|
||||
item.postTitle
|
||||
}}</NuxtLink>
|
||||
,获得{{ item.amount }}积分
|
||||
</template>
|
||||
<template v-else-if="item.type === 'COMMENT'">
|
||||
在文章
|
||||
<NuxtLink :to="`/posts/${item.postId}`" class="timeline-link">{{
|
||||
item.postTitle
|
||||
}}</NuxtLink>
|
||||
中
|
||||
<template v-if="!item.fromUserId">
|
||||
发送评论
|
||||
<NuxtLink
|
||||
:to="`/posts/${item.postId}#comment-${item.commentId}`"
|
||||
class="timeline-link"
|
||||
>{{ stripMarkdownLength(item.commentContent, 100) }}</NuxtLink
|
||||
>
|
||||
,获得{{ item.amount }}积分
|
||||
</template>
|
||||
<template v-else>
|
||||
被评论
|
||||
<NuxtLink
|
||||
:to="`/posts/${item.postId}#comment-${item.commentId}`"
|
||||
class="timeline-link"
|
||||
>{{ stripMarkdownLength(item.commentContent, 100) }}</NuxtLink
|
||||
>
|
||||
,获得{{ item.amount }}积分
|
||||
</template>
|
||||
</template>
|
||||
<template v-else-if="item.type === 'POST_LIKED' && item.fromUserId">
|
||||
帖子
|
||||
<NuxtLink :to="`/posts/${item.postId}`" class="timeline-link">{{
|
||||
item.postTitle
|
||||
}}</NuxtLink>
|
||||
被
|
||||
<NuxtLink :to="`/users/${item.fromUserId}`" class="timeline-link">{{
|
||||
item.fromUserName
|
||||
}}</NuxtLink>
|
||||
按赞,获得{{ item.amount }}积分
|
||||
</template>
|
||||
<template v-else-if="item.type === 'COMMENT_LIKED' && item.fromUserId">
|
||||
评论
|
||||
<NuxtLink
|
||||
:to="`/posts/${item.postId}#comment-${item.commentId}`"
|
||||
class="timeline-link"
|
||||
>{{ stripMarkdownLength(item.commentContent, 100) }}</NuxtLink
|
||||
>
|
||||
被
|
||||
<NuxtLink :to="`/users/${item.fromUserId}`" class="timeline-link">{{
|
||||
item.fromUserName
|
||||
}}</NuxtLink>
|
||||
按赞,获得{{ item.amount }}积分
|
||||
</template>
|
||||
<template v-else-if="item.type === 'INVITE' && item.fromUserId">
|
||||
邀请了好友
|
||||
<NuxtLink :to="`/users/${item.fromUserId}`" class="timeline-link">{{
|
||||
item.fromUserName
|
||||
}}</NuxtLink>
|
||||
加入社区 🎉,获得 {{ item.amount }} 积分
|
||||
</template>
|
||||
<template v-else-if="item.type === 'SYSTEM_ONLINE'"> 积分历史系统上线 </template>
|
||||
<i class="fas fa-coins"></i> 你目前的积分是 {{ item.balance }}
|
||||
</div>
|
||||
<div class="history-time">{{ TimeManager.format(item.createdAt) }}</div>
|
||||
</template>
|
||||
</BaseTimeline>
|
||||
</div>
|
||||
</template>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { onMounted, ref } from 'vue'
|
||||
import { onMounted, ref, watch } from 'vue'
|
||||
import { authState, fetchCurrentUser, getToken } from '~/utils/auth'
|
||||
import { toast } from '~/main'
|
||||
import RedeemPopup from '~/components/RedeemPopup.vue'
|
||||
import BaseTimeline from '~/components/BaseTimeline.vue'
|
||||
import BasePlaceholder from '~/components/BasePlaceholder.vue'
|
||||
import { stripMarkdownLength } from '~/utils/markdown'
|
||||
import TimeManager from '~/utils/time'
|
||||
|
||||
const config = useRuntimeConfig()
|
||||
const API_BASE_URL = config.public.apiBaseUrl
|
||||
|
||||
const selectedTab = ref('mall')
|
||||
const point = ref(null)
|
||||
const isLoading = ref(false)
|
||||
const histories = ref([])
|
||||
const historyLoading = ref(false)
|
||||
const historyLoaded = ref(false)
|
||||
|
||||
const pointRules = [
|
||||
'发帖:每天前两次,每次 30 积分',
|
||||
@@ -72,6 +181,15 @@ const contact = ref('')
|
||||
const loading = ref(false)
|
||||
const selectedGood = ref(null)
|
||||
|
||||
const iconMap = {
|
||||
POST: 'fas fa-file-alt',
|
||||
COMMENT: 'fas fa-comment',
|
||||
POST_LIKED: 'fas fa-thumbs-up',
|
||||
COMMENT_LIKED: 'fas fa-thumbs-up',
|
||||
INVITE: 'fas fa-user-plus',
|
||||
SYSTEM_ONLINE: 'fas fa-clock',
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
isLoading.value = true
|
||||
if (authState.loggedIn) {
|
||||
@@ -82,6 +200,12 @@ onMounted(async () => {
|
||||
isLoading.value = false
|
||||
})
|
||||
|
||||
watch(selectedTab, (val) => {
|
||||
if (val === 'history' && !historyLoaded.value) {
|
||||
loadHistory()
|
||||
}
|
||||
})
|
||||
|
||||
const loadGoods = async () => {
|
||||
const res = await fetch(`${API_BASE_URL}/api/point-goods`)
|
||||
if (res.ok) {
|
||||
@@ -89,6 +213,26 @@ const loadGoods = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const loadHistory = async () => {
|
||||
if (!authState.loggedIn) {
|
||||
historyLoaded.value = true
|
||||
return
|
||||
}
|
||||
historyLoading.value = true
|
||||
const token = getToken()
|
||||
const res = await fetch(`${API_BASE_URL}/api/point-histories`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
if (res.ok) {
|
||||
histories.value = (await res.json()).map((item) => ({
|
||||
...item,
|
||||
icon: iconMap[item.type],
|
||||
}))
|
||||
}
|
||||
historyLoading.value = false
|
||||
historyLoaded.value = true
|
||||
}
|
||||
|
||||
const openRedeem = (good) => {
|
||||
if (!authState.loggedIn || point.value === null || point.value < good.cost) {
|
||||
toast.error('积分不足')
|
||||
@@ -129,12 +273,44 @@ const submitRedeem = async () => {
|
||||
|
||||
<style scoped>
|
||||
.point-mall-page {
|
||||
padding: 0 20px;
|
||||
max-width: var(--page-max-width);
|
||||
background-color: var(--background-color);
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.point-mall-page-content {
|
||||
padding: 0 20px;
|
||||
}
|
||||
|
||||
.point-tabs {
|
||||
display: flex;
|
||||
border-bottom: 1px solid var(--normal-border-color);
|
||||
}
|
||||
|
||||
.point-tab-item {
|
||||
padding: 10px 15px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.point-tab-item.selected {
|
||||
border-bottom: 2px solid var(--primary-color);
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.timeline-container {
|
||||
padding: 10px 20px;
|
||||
}
|
||||
|
||||
.timeline-link {
|
||||
color: var(--primary-color);
|
||||
text-decoration: none;
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
.timeline-link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.loading-points-container {
|
||||
margin-top: 100px;
|
||||
display: flex;
|
||||
@@ -215,6 +391,17 @@ const submitRedeem = async () => {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.history-content {
|
||||
font-size: 14px;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.history-time {
|
||||
font-size: 12px;
|
||||
color: var(--text-color);
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.section-title {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
|
||||
@@ -15,8 +15,9 @@
|
||||
<div class="article-title-container-right">
|
||||
<div v-if="status === 'PENDING'" class="article-pending-button">审核中</div>
|
||||
<div v-if="status === 'REJECTED'" class="article-block-button">已拒绝</div>
|
||||
<div v-if="closed" class="article-closed-button">已关闭</div>
|
||||
<div
|
||||
v-if="loggedIn && !isAuthor && !subscribed"
|
||||
v-if="!closed && loggedIn && !isAuthor && !subscribed"
|
||||
class="article-subscribe-button"
|
||||
@click="subscribePost"
|
||||
>
|
||||
@@ -26,7 +27,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div
|
||||
v-if="loggedIn && !isAuthor && subscribed"
|
||||
v-if="!closed && loggedIn && !isAuthor && subscribed"
|
||||
class="article-unsubscribe-button"
|
||||
@click="unsubscribePost"
|
||||
>
|
||||
@@ -167,11 +168,13 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="closed" class="post-close-container">该帖子已关闭,内容仅供阅读,无法进行互动</div>
|
||||
|
||||
<ClientOnly>
|
||||
<CommentEditor
|
||||
@submit="postComment"
|
||||
:loading="isWaitingPostingComment"
|
||||
:disabled="!loggedIn"
|
||||
:disabled="!loggedIn || closed"
|
||||
:show-login-overlay="!loggedIn"
|
||||
:parent-user-name="author.username"
|
||||
/>
|
||||
@@ -196,6 +199,7 @@
|
||||
:level="0"
|
||||
:default-show-replies="item.openReplies"
|
||||
:post-author-id="author.id"
|
||||
:post-closed="closed"
|
||||
@deleted="onCommentDeleted"
|
||||
/>
|
||||
</template>
|
||||
@@ -232,7 +236,16 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, onMounted, onBeforeUnmount, nextTick, watch, watchEffect } from 'vue'
|
||||
import {
|
||||
ref,
|
||||
computed,
|
||||
onMounted,
|
||||
onBeforeUnmount,
|
||||
nextTick,
|
||||
watch,
|
||||
watchEffect,
|
||||
onActivated,
|
||||
} from 'vue'
|
||||
import VueEasyLightbox from 'vue-easy-lightbox'
|
||||
import { useRoute } from 'vue-router'
|
||||
import CommentItem from '~/components/CommentItem.vue'
|
||||
@@ -251,6 +264,8 @@ import { useRouter } from 'vue-router'
|
||||
import { useIsMobile } from '~/utils/screen'
|
||||
import Dropdown from '~/components/Dropdown.vue'
|
||||
import { ClientOnly } from '#components'
|
||||
import { useConfirm } from '~/composables/useConfirm'
|
||||
const { confirm } = useConfirm()
|
||||
|
||||
const config = useRuntimeConfig()
|
||||
const API_BASE_URL = config.public.apiBaseUrl
|
||||
@@ -267,6 +282,7 @@ const tags = ref([])
|
||||
const postReactions = ref([])
|
||||
const comments = ref([])
|
||||
const status = ref('PUBLISHED')
|
||||
const closed = ref(false)
|
||||
const pinnedAt = ref(null)
|
||||
const rssExcluded = ref(false)
|
||||
const isWaitingPostingComment = ref(false)
|
||||
@@ -279,7 +295,7 @@ const commentSort = ref('NEWEST')
|
||||
const isFetchingComments = ref(false)
|
||||
const isMobile = useIsMobile()
|
||||
|
||||
const headerHeight = process.client
|
||||
const headerHeight = import.meta.client
|
||||
? parseFloat(getComputedStyle(document.documentElement).getPropertyValue('--header-height')) || 0
|
||||
: 0
|
||||
|
||||
@@ -293,7 +309,7 @@ useHead(() => ({
|
||||
],
|
||||
}))
|
||||
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
onBeforeUnmount(() => {
|
||||
window.removeEventListener('scroll', updateCurrentIndex)
|
||||
if (countdownTimer) clearInterval(countdownTimer)
|
||||
@@ -339,7 +355,7 @@ const updateCountdown = () => {
|
||||
countdown.value = `${h}:${m}:${s}`
|
||||
}
|
||||
const startCountdown = () => {
|
||||
if (!process.client) return
|
||||
if (!import.meta.client) return
|
||||
if (countdownTimer) clearInterval(countdownTimer)
|
||||
updateCountdown()
|
||||
countdownTimer = setInterval(updateCountdown, 1000)
|
||||
@@ -349,7 +365,12 @@ const articleMenuItems = computed(() => {
|
||||
const items = []
|
||||
if (isAuthor.value || isAdmin.value) {
|
||||
items.push({ text: '编辑文章', onClick: () => editPost() })
|
||||
items.push({ text: '删除文章', color: 'red', onClick: () => deletePost() })
|
||||
items.push({ text: '删除文章', color: 'red', onClick: deletePost })
|
||||
if (closed.value) {
|
||||
items.push({ text: '重新打开帖子', onClick: () => reopenPost() })
|
||||
} else {
|
||||
items.push({ text: '关闭帖子', onClick: () => closePost() })
|
||||
}
|
||||
}
|
||||
if (isAdmin.value) {
|
||||
if (pinnedAt.value) {
|
||||
@@ -485,6 +506,7 @@ watchEffect(() => {
|
||||
postReactions.value = data.reactions || []
|
||||
subscribed.value = !!data.subscribed
|
||||
status.value = data.status
|
||||
closed.value = data.closed
|
||||
pinnedAt.value = data.pinnedAt
|
||||
rssExcluded.value = data.rssExcluded
|
||||
postTime.value = TimeManager.format(data.createdAt)
|
||||
@@ -493,7 +515,7 @@ watchEffect(() => {
|
||||
})
|
||||
|
||||
// 404 客户端跳转
|
||||
// if (postError.value?.statusCode === 404 && process.client) {
|
||||
// if (postError.value?.statusCode === 404 && import.meta.client) {
|
||||
// router.replace('/404')
|
||||
// }
|
||||
|
||||
@@ -544,6 +566,10 @@ const onSliderInput = (e) => {
|
||||
|
||||
const postComment = async (parentUserName, text, clear) => {
|
||||
if (!text.trim()) return
|
||||
if (closed.value) {
|
||||
toast.error('帖子已关闭')
|
||||
return
|
||||
}
|
||||
console.debug('Posting comment', { postId, text })
|
||||
isWaitingPostingComment.value = true
|
||||
const token = getToken()
|
||||
@@ -682,24 +708,62 @@ const includeRss = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const closePost = async () => {
|
||||
const token = getToken()
|
||||
if (!token) return
|
||||
const res = await fetch(`${API_BASE_URL}/api/posts/${postId}/close`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
if (res.ok) {
|
||||
closed.value = true
|
||||
toast.success('已关闭')
|
||||
await refreshPost()
|
||||
} else {
|
||||
toast.error('操作失败')
|
||||
}
|
||||
}
|
||||
|
||||
const reopenPost = async () => {
|
||||
const token = getToken()
|
||||
if (!token) return
|
||||
const res = await fetch(`${API_BASE_URL}/api/posts/${postId}/reopen`, {
|
||||
method: 'POST',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
if (res.ok) {
|
||||
closed.value = false
|
||||
toast.success('已重新打开')
|
||||
await refreshPost()
|
||||
} else {
|
||||
toast.error('操作失败')
|
||||
}
|
||||
}
|
||||
|
||||
const editPost = () => {
|
||||
navigateTo(`/posts/${postId}/edit`, { replace: true })
|
||||
}
|
||||
|
||||
const deletePost = async () => {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
toast.error('请先登录')
|
||||
return
|
||||
}
|
||||
const res = await fetch(`${API_BASE_URL}/api/posts/${postId}`, {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
if (res.ok) {
|
||||
toast.success('已删除')
|
||||
navigateTo('/', { replace: true })
|
||||
} else {
|
||||
try {
|
||||
const ok = await confirm('删除帖子', '此操作不可恢复,确认要删除吗?')
|
||||
if (!ok) return
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
toast.error('请先登录')
|
||||
return
|
||||
}
|
||||
const res = await fetch(`${API_BASE_URL}/api/posts/${postId}`, {
|
||||
method: 'DELETE',
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
if (res.ok) {
|
||||
toast.success('已删除')
|
||||
navigateTo('/', { replace: true })
|
||||
} else {
|
||||
toast.error('操作失败')
|
||||
}
|
||||
} catch (e) {
|
||||
toast.error('操作失败')
|
||||
}
|
||||
}
|
||||
@@ -812,7 +876,8 @@ const gotoProfile = () => {
|
||||
navigateTo(`/users/${author.value.id}`, { replace: true })
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const initPage = async () => {
|
||||
scrollTo(0, 0)
|
||||
await fetchComments()
|
||||
const hash = location.hash
|
||||
const id = hash.startsWith('#comment-') ? hash.substring('#comment-'.length) : null
|
||||
@@ -820,6 +885,14 @@ onMounted(async () => {
|
||||
updateCurrentIndex()
|
||||
window.addEventListener('scroll', updateCurrentIndex)
|
||||
jumpToHashComment()
|
||||
}
|
||||
|
||||
onActivated(async () => {
|
||||
await initPage()
|
||||
})
|
||||
|
||||
onMounted(async () => {
|
||||
await initPage()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -845,6 +918,10 @@ onMounted(async () => {
|
||||
width: calc(85% - 40px);
|
||||
}
|
||||
|
||||
.info-content-text p code {
|
||||
padding: 2px 4px;
|
||||
}
|
||||
|
||||
.post-page-scroller-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -868,6 +945,18 @@ onMounted(async () => {
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.post-close-container {
|
||||
padding: 40px;
|
||||
margin-top: 15px;
|
||||
text-align: center;
|
||||
font-size: 12px;
|
||||
color: var(--text-color);
|
||||
background-color: var(--background-color);
|
||||
border: 1px dashed var(--normal-border-color);
|
||||
border-radius: 10px;
|
||||
opacity: 0.5;
|
||||
}
|
||||
|
||||
.scroller {
|
||||
margin-top: 20px;
|
||||
margin-left: 20px;
|
||||
@@ -982,6 +1071,7 @@ onMounted(async () => {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.article-closed-button,
|
||||
.article-subscribe-button-text,
|
||||
.article-unsubscribe-button-text {
|
||||
white-space: nowrap;
|
||||
@@ -1024,6 +1114,15 @@ onMounted(async () => {
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.article-closed-button {
|
||||
background-color: var(--background-color);
|
||||
color: gray;
|
||||
border: 1px solid gray;
|
||||
padding: 5px 10px;
|
||||
border-radius: 8px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.article-title {
|
||||
font-size: 30px;
|
||||
font-weight: bold;
|
||||
|
||||
@@ -38,10 +38,7 @@
|
||||
</div>
|
||||
<div class="form-row switch-row">
|
||||
<div class="setting-title">毛玻璃效果</div>
|
||||
<label class="switch">
|
||||
<input type="checkbox" v-model="frosted" />
|
||||
<span class="slider"></span>
|
||||
</label>
|
||||
<BaseSwitch v-model="frosted" />
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="role === 'ADMIN'" class="admin-section">
|
||||
@@ -76,6 +73,7 @@ import { ref, onMounted, watch } from 'vue'
|
||||
import AvatarCropper from '~/components/AvatarCropper.vue'
|
||||
import BaseInput from '~/components/BaseInput.vue'
|
||||
import Dropdown from '~/components/Dropdown.vue'
|
||||
import BaseSwitch from '~/components/BaseSwitch.vue'
|
||||
import { toast } from '~/main'
|
||||
import { fetchCurrentUser, getToken, setToken } from '~/utils/auth'
|
||||
import { frostedState, setFrosted } from '~/utils/frosted'
|
||||
@@ -318,51 +316,6 @@ const save = async () => {
|
||||
max-width: 200px;
|
||||
}
|
||||
|
||||
.switch {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: 40px;
|
||||
height: 20px;
|
||||
}
|
||||
|
||||
.switch input {
|
||||
opacity: 0;
|
||||
width: 0;
|
||||
height: 0;
|
||||
}
|
||||
|
||||
.slider {
|
||||
position: absolute;
|
||||
cursor: pointer;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background-color: #ccc;
|
||||
transition: 0.2s;
|
||||
border-radius: 20px;
|
||||
}
|
||||
|
||||
.slider:before {
|
||||
position: absolute;
|
||||
content: '';
|
||||
height: 16px;
|
||||
width: 16px;
|
||||
left: 2px;
|
||||
bottom: 2px;
|
||||
background-color: white;
|
||||
transition: 0.2s;
|
||||
border-radius: 50%;
|
||||
}
|
||||
|
||||
input:checked + .slider {
|
||||
background-color: var(--primary-color);
|
||||
}
|
||||
|
||||
input:checked + .slider:before {
|
||||
transform: translateX(20px);
|
||||
}
|
||||
|
||||
.profile-section {
|
||||
margin-bottom: 30px;
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
class="signup-page-button-primary"
|
||||
@click="sendVerification"
|
||||
>
|
||||
<div class="signup-page-button-text">验证邮箱</div>
|
||||
<div class="signup-page-button-text">验证并注册</div>
|
||||
</div>
|
||||
<div v-else class="signup-page-button-primary disabled">
|
||||
<div class="signup-page-button-text">
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { clearToken } from '~/utils/auth'
|
||||
|
||||
export default defineNuxtPlugin(() => {
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
const originalFetch = window.fetch
|
||||
window.fetch = async (input, init) => {
|
||||
const response = await originalFetch(input, init)
|
||||
|
||||
@@ -4,7 +4,7 @@ import '~/assets/toast.css'
|
||||
|
||||
export default defineNuxtPlugin(async (nuxtApp) => {
|
||||
// 确保只在客户端环境中注册插件
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
try {
|
||||
// 使用动态导入来避免 CommonJS 模块问题
|
||||
const { default: Toast, POSITION } = await import('vue-toastification')
|
||||
|
||||
1
frontend_nuxt/public/tencent2707107139169774686.txt
Normal file
1
frontend_nuxt/public/tencent2707107139169774686.txt
Normal file
@@ -0,0 +1 @@
|
||||
1839503219847005265
|
||||
@@ -12,7 +12,7 @@ export const authState = reactive({
|
||||
role: null,
|
||||
})
|
||||
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
authState.loggedIn =
|
||||
localStorage.getItem(TOKEN_KEY) !== null && localStorage.getItem(TOKEN_KEY) !== ''
|
||||
authState.userId = localStorage.getItem(USER_ID_KEY)
|
||||
@@ -21,18 +21,18 @@ if (process.client) {
|
||||
}
|
||||
|
||||
export function getToken() {
|
||||
return process.client ? localStorage.getItem(TOKEN_KEY) : null
|
||||
return import.meta.client ? localStorage.getItem(TOKEN_KEY) : null
|
||||
}
|
||||
|
||||
export function setToken(token) {
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
localStorage.setItem(TOKEN_KEY, token)
|
||||
authState.loggedIn = true
|
||||
}
|
||||
}
|
||||
|
||||
export function clearToken() {
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
localStorage.removeItem(TOKEN_KEY)
|
||||
clearUserInfo()
|
||||
authState.loggedIn = false
|
||||
@@ -40,7 +40,7 @@ export function clearToken() {
|
||||
}
|
||||
|
||||
export function setUserInfo({ id, username }) {
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
authState.userId = id
|
||||
authState.username = username
|
||||
if (arguments[0] && arguments[0].role) {
|
||||
@@ -53,7 +53,7 @@ export function setUserInfo({ id, username }) {
|
||||
}
|
||||
|
||||
export function clearUserInfo() {
|
||||
if (process.client) {
|
||||
if (import.meta.client) {
|
||||
localStorage.removeItem(USER_ID_KEY)
|
||||
localStorage.removeItem(USERNAME_KEY)
|
||||
localStorage.removeItem(ROLE_KEY)
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
import { ref, onMounted, onUnmounted, onActivated, nextTick } from 'vue'
|
||||
|
||||
export function useScrollLoadMore(loadMore, offset = 50) {
|
||||
const savedScrollTop = ref(0)
|
||||
|
||||
const handleScroll = () => {
|
||||
if (!process.client) return
|
||||
const scrollTop = window.scrollY || document.documentElement.scrollTop
|
||||
const scrollHeight = document.documentElement.scrollHeight
|
||||
const windowHeight = window.innerHeight
|
||||
savedScrollTop.value = scrollTop
|
||||
if (scrollHeight - (scrollTop + windowHeight) <= offset) {
|
||||
loadMore()
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
if (process.client) {
|
||||
window.addEventListener('scroll', handleScroll, { passive: true })
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (process.client) {
|
||||
window.removeEventListener('scroll', handleScroll)
|
||||
}
|
||||
})
|
||||
|
||||
onActivated(() => {
|
||||
if (process.client) {
|
||||
nextTick(() => {
|
||||
window.scrollTo({ top: savedScrollTop.value })
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
return { savedScrollTop }
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import hljs from 'highlight.js'
|
||||
import hljs from 'highlight.js/lib/common'
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
const theme =
|
||||
document.documentElement.dataset.theme ||
|
||||
|
||||
@@ -26,6 +26,7 @@ const iconMap = {
|
||||
LOTTERY_WIN: 'fas fa-trophy',
|
||||
LOTTERY_DRAW: 'fas fa-bullhorn',
|
||||
MENTION: 'fas fa-at',
|
||||
POST_DELETED: 'fas fa-trash',
|
||||
}
|
||||
|
||||
export async function fetchUnreadCount() {
|
||||
@@ -118,179 +119,178 @@ export async function updateNotificationPreference(type, enabled) {
|
||||
function createFetchNotifications() {
|
||||
const notifications = ref([])
|
||||
const isLoadingMessage = ref(false)
|
||||
const fetchNotifications = async () => {
|
||||
const hasMore = ref(true)
|
||||
|
||||
const fetchNotifications = async ({
|
||||
page = 0,
|
||||
size = 30,
|
||||
unread = false,
|
||||
append = false,
|
||||
} = {}) => {
|
||||
const config = useRuntimeConfig()
|
||||
const API_BASE_URL = config.public.apiBaseUrl
|
||||
if (isLoadingMessage && notifications && markRead) {
|
||||
try {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
toast.error('请先登录')
|
||||
return
|
||||
}
|
||||
isLoadingMessage.value = true
|
||||
notifications.value = []
|
||||
const res = await fetch(`${API_BASE_URL}/api/notifications`, {
|
||||
try {
|
||||
const token = getToken()
|
||||
if (!token) {
|
||||
toast.error('请先登录')
|
||||
return
|
||||
}
|
||||
if (!append) notifications.value = []
|
||||
isLoadingMessage.value = true
|
||||
const res = await fetch(
|
||||
`${API_BASE_URL}/api/notifications${unread ? '/unread' : ''}?page=${page}&size=${size}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
isLoadingMessage.value = false
|
||||
if (!res.ok) {
|
||||
toast.error('获取通知失败')
|
||||
return
|
||||
}
|
||||
const data = await res.json()
|
||||
|
||||
for (const n of data) {
|
||||
if (n.type === 'COMMENT_REPLY') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
src: n.comment.author.avatar,
|
||||
iconClick: () => {
|
||||
markRead(n.id)
|
||||
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'REACTION') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
emoji: reactionEmojiMap[n.reactionType],
|
||||
iconClick: () => {
|
||||
if (n.fromUser) {
|
||||
markRead(n.id)
|
||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'POST_VIEWED') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
src: n.fromUser ? n.fromUser.avatar : null,
|
||||
icon: n.fromUser ? undefined : iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.fromUser) {
|
||||
markRead(n.id)
|
||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'LOTTERY_WIN') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.post) {
|
||||
markRead(n.id)
|
||||
router.push(`/posts/${n.post.id}`)
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'LOTTERY_DRAW') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.post) {
|
||||
markRead(n.id)
|
||||
router.push(`/posts/${n.post.id}`)
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'POST_UPDATED') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
src: n.comment.author.avatar,
|
||||
iconClick: () => {
|
||||
markRead(n.id)
|
||||
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'USER_ACTIVITY') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
src: n.comment.author.avatar,
|
||||
iconClick: () => {
|
||||
markRead(n.id)
|
||||
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'MENTION') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.fromUser) {
|
||||
markRead(n.id)
|
||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.fromUser) {
|
||||
markRead(n.id)
|
||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'FOLLOWED_POST') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.post) {
|
||||
markRead(n.id)
|
||||
navigateTo(`/posts/${n.post.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'POST_SUBSCRIBED' || n.type === 'POST_UNSUBSCRIBED') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.post) {
|
||||
markRead(n.id)
|
||||
navigateTo(`/posts/${n.post.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'POST_REVIEW_REQUEST') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
src: n.fromUser ? n.fromUser.avatar : null,
|
||||
icon: n.fromUser ? undefined : iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.post) {
|
||||
markRead(n.id)
|
||||
navigateTo(`/posts/${n.post.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'REGISTER_REQUEST') {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {},
|
||||
})
|
||||
} else {
|
||||
notifications.value.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
})
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
},
|
||||
)
|
||||
isLoadingMessage.value = false
|
||||
if (!res.ok) {
|
||||
toast.error('获取通知失败')
|
||||
return
|
||||
}
|
||||
const data = await res.json()
|
||||
const arr = []
|
||||
|
||||
for (const n of data) {
|
||||
if (n.type === 'COMMENT_REPLY') {
|
||||
arr.push({
|
||||
...n,
|
||||
src: n.comment.author.avatar,
|
||||
iconClick: () => {
|
||||
markNotificationRead(n.id)
|
||||
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'REACTION') {
|
||||
arr.push({
|
||||
...n,
|
||||
emoji: reactionEmojiMap[n.reactionType],
|
||||
iconClick: () => {
|
||||
if (n.fromUser) {
|
||||
markNotificationRead(n.id)
|
||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'POST_VIEWED') {
|
||||
arr.push({
|
||||
...n,
|
||||
src: n.fromUser ? n.fromUser.avatar : null,
|
||||
icon: n.fromUser ? undefined : iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.fromUser) {
|
||||
markNotificationRead(n.id)
|
||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'POST_DELETED') {
|
||||
arr.push({
|
||||
...n,
|
||||
src: n.fromUser ? n.fromUser.avatar : null,
|
||||
icon: n.fromUser ? undefined : iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.fromUser) {
|
||||
markNotificationRead(n.id)
|
||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'LOTTERY_WIN' || n.type === 'LOTTERY_DRAW') {
|
||||
arr.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.post) {
|
||||
markNotificationRead(n.id)
|
||||
navigateTo(`/posts/${n.post.id}`)
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'POST_UPDATED' || n.type === 'USER_ACTIVITY') {
|
||||
arr.push({
|
||||
...n,
|
||||
src: n.comment.author.avatar,
|
||||
iconClick: () => {
|
||||
markNotificationRead(n.id)
|
||||
navigateTo(`/users/${n.comment.author.id}`, { replace: true })
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'MENTION') {
|
||||
arr.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.fromUser) {
|
||||
markNotificationRead(n.id)
|
||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'USER_FOLLOWED' || n.type === 'USER_UNFOLLOWED') {
|
||||
arr.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.fromUser) {
|
||||
markNotificationRead(n.id)
|
||||
navigateTo(`/users/${n.fromUser.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (
|
||||
n.type === 'FOLLOWED_POST' ||
|
||||
n.type === 'POST_SUBSCRIBED' ||
|
||||
n.type === 'POST_UNSUBSCRIBED'
|
||||
) {
|
||||
arr.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.post) {
|
||||
markNotificationRead(n.id)
|
||||
navigateTo(`/posts/${n.post.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'POST_REVIEW_REQUEST') {
|
||||
arr.push({
|
||||
...n,
|
||||
src: n.fromUser ? n.fromUser.avatar : null,
|
||||
icon: n.fromUser ? undefined : iconMap[n.type],
|
||||
iconClick: () => {
|
||||
if (n.post) {
|
||||
markNotificationRead(n.id)
|
||||
navigateTo(`/posts/${n.post.id}`, { replace: true })
|
||||
}
|
||||
},
|
||||
})
|
||||
} else if (n.type === 'REGISTER_REQUEST') {
|
||||
arr.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
iconClick: () => {},
|
||||
})
|
||||
} else {
|
||||
arr.push({
|
||||
...n,
|
||||
icon: iconMap[n.type],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
if (append) notifications.value.push(...arr)
|
||||
else notifications.value = arr
|
||||
hasMore.value = data.length === size
|
||||
} catch (e) {
|
||||
console.error(e)
|
||||
isLoadingMessage.value = false
|
||||
}
|
||||
}
|
||||
|
||||
const markRead = async (id) => {
|
||||
const markNotificationRead = async (id) => {
|
||||
if (!id) return
|
||||
const n = notifications.value.find((n) => n.id === id)
|
||||
if (!n || n.read) return
|
||||
@@ -332,13 +332,19 @@ function createFetchNotifications() {
|
||||
}
|
||||
return {
|
||||
fetchNotifications,
|
||||
markRead,
|
||||
markNotificationRead,
|
||||
notifications,
|
||||
isLoadingMessage,
|
||||
markRead,
|
||||
markAllRead,
|
||||
hasMore,
|
||||
}
|
||||
}
|
||||
|
||||
export const { fetchNotifications, markRead, notifications, isLoadingMessage, markAllRead } =
|
||||
createFetchNotifications()
|
||||
export const {
|
||||
fetchNotifications,
|
||||
markNotificationRead,
|
||||
notifications,
|
||||
isLoadingMessage,
|
||||
markAllRead,
|
||||
hasMore,
|
||||
} = createFetchNotifications()
|
||||
|
||||
@@ -2,7 +2,6 @@ import Vditor from 'vditor'
|
||||
import { getToken, authState } from './auth'
|
||||
import { searchUsers, fetchFollowings, fetchAdmins } from './user'
|
||||
import { tiebaEmoji } from './tiebaEmoji'
|
||||
import '~/assets/global.css'
|
||||
|
||||
export function getEditorTheme() {
|
||||
return document.documentElement.dataset.theme === 'dark' ? 'dark' : 'classic'
|
||||
|
||||
Reference in New Issue
Block a user