This commit is contained in:
2026-04-30 18:53:50 +08:00
parent 88c2fa5d03
commit c764603dbd
20 changed files with 866 additions and 654 deletions
@@ -1,103 +1,148 @@
package com.cyynote.controller;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.cyynote.controller.BaseController;
import com.cyynote.model.NoteModel;
import com.cyynote.model.UserModel;
import com.cyynote.payload.request.LoginRequest;
import com.cyynote.payload.request.SignupRequest;
import java.sql.SQLException;
import java.util.List;
import java.util.logging.Logger;
import com.cyynote.payload.request.UpdatePasswordRequest;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Result;
import org.noear.wood.DbContext;
import org.noear.wood.DbTableQuery;
import org.noear.wood.annotation.Db;
@Mapping("/api/auth")
@Controller
public class AuthController extends BaseController {
private static final Logger log = Logger.getLogger(com.cyynote.controller.AuthController.class.getName());
@Db
DbContext db;
@Mapping("/logout")
public void logout(Context ctx) {
ctx.sessionClear();
}
@Post
@Mapping("/signin")
public Result signin(Context ctx, @Body LoginRequest loginRequest) throws SQLException {
log.info("name:" + loginRequest.getUsername());
log.info("password:" + loginRequest.getPassword());
long count = db.table("user").selectCount();
log.info("countUser:" + count);
List<UserModel> all = ((DbTableQuery)this.db.table("user")).selectList("*", UserModel.class);
log.info( all.toString());
UserModel model = (UserModel)((DbTableQuery)((DbTableQuery)this.db.table("user").whereEq("username", loginRequest.getUsername())).andEq("password", loginRequest.getPassword())).selectItem("*", UserModel.class);
if ("admin".equals(model.getUsername())) {
ctx.sessionSet("user_name", loginRequest.getUsername());
ctx.sessionSet("user_id", model.getId());
JSONObject obj = new JSONObject();
String token = ctx.sessionState().sessionToken();
obj.put("accessToken", token);
obj.put("id", Integer.valueOf(1));
obj.put("username", loginRequest.getUsername());
obj.put("email", "1");
obj.put("roles", "1");
int flag = ((DbTableQuery)this.db.table("user").set("token", token).set("logintime", DateUtil.now()).whereEq("id", model.getId())).update();
System.out.println(flag);
return Result.succeed(obj);
}
return Result.failure();
}
@Post
@Mapping("/updatePassword")
public Result updatePassword(Context ctx, @Body UpdatePasswordRequest loginRequest) throws SQLException {
log.info("name:" + loginRequest.getUsername());
log.info("old - password:" + loginRequest.getOldpassword());
log.info("new - password:" + loginRequest.getNewpassword());
long count = db.table("user").selectCount();
log.info("countUser:" + count);
List<UserModel> all = ((DbTableQuery)this.db.table("user")).selectList("*", UserModel.class);
log.info( all.toString());
UserModel model = (UserModel)((DbTableQuery)((DbTableQuery)this.db.table("user").whereEq("username", loginRequest.getUsername())).andEq("password", loginRequest.getOldpassword())).selectItem("*", UserModel.class);
if ("admin".equals(model.getUsername())) {
int flag = ((DbTableQuery)this.db.table("user").set("password", loginRequest.getNewpassword()).whereEq("id", model.getId())).update();
System.out.println(flag);
return Result.succeed(flag);
}
return Result.failure();
}
@Post
@Mapping("/signup")
public Result signup(@Body SignupRequest signUpRequest) {
log.info("signUpRequest:" + JSONObject.toJSONString(signUpRequest, new com.alibaba.fastjson2.JSONWriter.Feature[0]));
JSONObject obj = new JSONObject();
return Result.succeed(obj);
}
}
package com.cyynote.controller;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONObject;
import com.cyynote.model.UserModel;
import com.cyynote.payload.request.LoginRequest;
import com.cyynote.payload.request.SignupRequest;
import com.cyynote.payload.request.UpdatePasswordRequest;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Post;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Result;
import org.noear.wood.DbContext;
import org.noear.wood.DbTableQuery;
import org.noear.wood.annotation.Db;
@Mapping("/api/auth")
@Controller
public class AuthController extends BaseController {
private static final Logger log = Logger.getLogger(AuthController.class.getName());
@Db
DbContext db;
@Mapping("/logout")
public void logout(Context ctx) {
ctx.sessionClear();
}
@Post
@Mapping("/signin")
public Result signin(Context ctx, @Body LoginRequest loginRequest) throws SQLException {
if (loginRequest == null || loginRequest.getUsername() == null || loginRequest.getPassword() == null) {
ctx.status(400);
return Result.failure(400, "用户名和密码不能为空");
}
log.info("signin username:" + loginRequest.getUsername());
UserModel model = (UserModel) ((DbTableQuery) ((DbTableQuery) this.db.table("user")
.whereEq("username", loginRequest.getUsername()))
.andEq("password", loginRequest.getPassword()))
.selectItem("*", UserModel.class);
if (model == null) {
ctx.status(401);
return Result.failure(401, "用户名或密码错误");
}
ctx.sessionSet("user_name", model.getUsername());
ctx.sessionSet("user_id", model.getId());
String token = ctx.sessionState().sessionToken();
((DbTableQuery) this.db.table("user")
.set("token", token)
.set("logintime", DateUtil.now())
.whereEq("id", model.getId()))
.update();
JSONObject user = new JSONObject();
user.put("id", model.getId());
user.put("username", model.getUsername());
user.put("email", model.getEmail());
user.put("roles", normalizeRoles(model.getRole()));
JSONObject payload = new JSONObject();
payload.put("accessToken", token);
payload.put("tokenType", "Bearer");
payload.put("user", user);
return Result.succeed(payload);
}
@Post
@Mapping("/updatePassword")
public Result updatePassword(Context ctx, @Body UpdatePasswordRequest loginRequest) throws SQLException {
if (loginRequest == null || loginRequest.getUsername() == null || loginRequest.getOldpassword() == null || loginRequest.getNewpassword() == null) {
ctx.status(400);
return Result.failure(400, "参数不完整");
}
log.info("update password username:" + loginRequest.getUsername());
UserModel model = (UserModel) ((DbTableQuery) ((DbTableQuery) this.db.table("user")
.whereEq("username", loginRequest.getUsername()))
.andEq("password", loginRequest.getOldpassword()))
.selectItem("*", UserModel.class);
if (model == null) {
ctx.status(400);
return Result.failure(400, "用户名或旧密码错误");
}
int flag = ((DbTableQuery) this.db.table("user")
.set("password", loginRequest.getNewpassword())
.whereEq("id", model.getId()))
.update();
return Result.succeed(flag);
}
@Post
@Mapping("/signup")
public Result signup(Context ctx, @Body SignupRequest signUpRequest) throws SQLException {
log.info("signup username:" + (signUpRequest == null ? null : signUpRequest.getUsername()));
if (signUpRequest == null || signUpRequest.getUsername() == null || signUpRequest.getPassword() == null || signUpRequest.getEmail() == null) {
ctx.status(400);
return Result.failure(400, "用户名、邮箱和密码不能为空");
}
long exists = ((DbTableQuery) this.db.table("user")
.whereEq("username", signUpRequest.getUsername()))
.selectCount();
if (exists > 0) {
ctx.status(409);
return Result.failure(409, "用户名已存在");
}
UserModel user = new UserModel();
user.setUsername(signUpRequest.getUsername());
user.setEmail(signUpRequest.getEmail());
user.setPassword(signUpRequest.getPassword());
user.setRole("ROLE_USER");
this.db.table("user").setEntityIf(user, (k, v) -> Boolean.valueOf(v != null)).insert();
return Result.succeed("注册成功");
}
private List<String> normalizeRoles(String role) {
if (role == null || role.isBlank()) {
return List.of("ROLE_USER");
}
if (role.startsWith("ROLE_")) {
return List.of(role);
}
if ("admin".equalsIgnoreCase(role)) {
return List.of("ROLE_ADMIN");
}
if ("moderator".equalsIgnoreCase(role) || "mod".equalsIgnoreCase(role)) {
return List.of("ROLE_MODERATOR");
}
if (role.contains(",")) {
return Arrays.asList(role.split(","));
}
return List.of("ROLE_USER");
}
}
@@ -1,44 +1,39 @@
package com.cyynote.controller;
import io.jsonwebtoken.Claims;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.handle.Result;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import org.noear.solon.sessionstate.jwt.JwtUtils;
@Component
public class JwtInterceptor implements RouterInterceptor {
public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
boolean flag = true;
if ("/api/auth/signup".equals(ctx.path()) ||
"/api/auth/signin".equals(ctx.path()) ||
"/demo".equals(ctx.path()) ||
"/api/auth/logout".equals(ctx.path())
)
flag = false;
if (flag)
if (null != ctx.header("Authorization")) {
String token = ctx.header("Authorization");
token = token.replace("Bearer ", "");
System.out.println("token:" + token);
Claims claims = JwtUtils.parseJwt(token);
System.out.println("claims:" + claims);
if (null != claims) {
System.out.println("username:" + claims.get("user_name"));
System.out.println("exp:" + claims.get("exp"));
} else {
ctx.status(401);
ctx.render(Result.failure(401, ""));
}
} else {
ctx.status(401);
ctx.render(Result.failure(401, ""));
}
chain.doIntercept(ctx, mainHandler);
}
}
package com.cyynote.controller;
import io.jsonwebtoken.Claims;
import org.noear.solon.annotation.Component;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Handler;
import org.noear.solon.core.handle.Result;
import org.noear.solon.core.route.RouterInterceptor;
import org.noear.solon.core.route.RouterInterceptorChain;
import org.noear.solon.sessionstate.jwt.JwtUtils;
@Component
public class JwtInterceptor implements RouterInterceptor {
public void doIntercept(Context ctx, Handler mainHandler, RouterInterceptorChain chain) throws Throwable {
boolean requireAuth = !("/api/auth/signup".equals(ctx.path())
|| "/api/auth/signin".equals(ctx.path())
|| "/demo".equals(ctx.path())
|| "/api/auth/logout".equals(ctx.path())
|| "OPTIONS".equalsIgnoreCase(ctx.method()));
if (requireAuth) {
String token = ctx.header("Authorization");
if (token == null || token.isBlank()) {
ctx.status(401);
ctx.render(Result.failure(401, "未登录或登录已过期"));
return;
}
token = token.replace("Bearer ", "");
Claims claims = JwtUtils.parseJwt(token);
if (claims == null) {
ctx.status(401);
ctx.render(Result.failure(401, "未登录或登录已过期"));
return;
}
}
chain.doIntercept(ctx, mainHandler);
}
}
@@ -1,207 +1,219 @@
package com.cyynote.controller;
import cn.hutool.*;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.JSONObject;
import com.cyynote.controller.BaseController;
import com.cyynote.dso.NoteSqlAnnotation;
import com.cyynote.model.HistoryModel;
import com.cyynote.model.NoteModel;
import com.cyynote.payload.request.NoteRequest;
import com.cyynote.util.TreeBuild;
import com.cyynote.util.TreeNode;
import io.jsonwebtoken.Claims;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Path;
import org.noear.solon.annotation.Post;
import org.noear.solon.annotation.Put;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Result;
import org.noear.solon.sessionstate.jwt.JwtUtils;
import org.noear.solon.web.cors.annotation.CrossOrigin;
import org.noear.wood.DbContext;
import org.noear.wood.DbTableQuery;
import org.noear.wood.annotation.Db;
@Mapping("/api/note")
@Controller
public class NoteController extends BaseController {
private static final Logger log = Logger.getLogger(com.cyynote.controller.NoteController.class.getName());
@Db
NoteSqlAnnotation mapper;
@Db
DbContext db;
private static final String QUERY_F = "id,pid,title,createtime,updatetime,viewtime,flag";
@Get
@Mapping("get1")
public String test_post_get(Context context, @Path String appname) {
return context.path();
}
@Post
@Mapping("post")
public String test_post(Context context) {
return context.param("name");
}
@Put
@Mapping("put")
public String test_put(Context context, String name) {
return context.param("name");
}
@Get
@Mapping("/all")
public Result noteAccess(Context ctx) throws Exception {
List<NoteModel> all = ((DbTableQuery)this.db.table("note").whereEq("flag", Integer.valueOf(1))).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
List<TreeNode> treeNodeList = new ArrayList<>();
for (NoteModel n : all) {
TreeNode treeNode = new TreeNode(n.getId().intValue(), n.getPid().intValue(), n.getTitle(), String.valueOf(n.getId()), String.valueOf(n.getId()));
treeNodeList.add(treeNode);
}
TreeBuild bb = new TreeBuild(treeNodeList);
List<TreeNode> collect = bb.buildTree();
return Result.succeed(JSONArray.parseArray(JSONArray.toJSONString(collect)));
}
@Get
@Mapping("/home")
public Result noteHome(Context ctx, @Path int type, @Path String search) throws Exception {
System.out.println(type);
System.out.println(search);
List<NoteModel> all = new ArrayList<>();
if (type == 0) {
all = ((DbTableQuery)((DbTableQuery)this.db.table("note").whereLk("context", "%" + search + "%")).andLk("title", "%" + search + "%")).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
} else if (type == 1) {
all = ((DbTableQuery)((DbTableQuery)((DbTableQuery)this.db.table("note").whereEq("flag", Integer.valueOf(1))).orderByDesc("updatetime")).limit(20)).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
} else if (type == 2) {
all = ((DbTableQuery)((DbTableQuery)((DbTableQuery)this.db.table("note").whereEq("flag", Integer.valueOf(1))).orderByDesc("createtime")).limit(20)).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
} else if (type == 3) {
all = ((DbTableQuery)((DbTableQuery)((DbTableQuery)this.db.table("note").whereEq("flag", Integer.valueOf(1))).orderByDesc("viewtime")).limit(20)).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
} else if (type == 4) {
all = ((DbTableQuery)((DbTableQuery)((DbTableQuery)this.db.table("note").whereEq("flag", Integer.valueOf(0))).orderByDesc("updatetime")).limit(10000)).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
}
return Result.succeed(JSONArray.parseArray(JSONArray.toJSONString(all)));
}
@Get
@Mapping("/get")
public Result getNote(Context ctx, @Path int id) throws Exception {
NoteModel model = (NoteModel)((DbTableQuery)this.db.table("note").whereEq("id", Integer.valueOf(id))).selectItem("*", NoteModel.class);
String time = DateUtil.now();
System.out.println(time);
int flag = ((DbTableQuery)this.db.table("note").set("viewtime", time).whereEq("id", Integer.valueOf(id))).update();
System.out.println(flag);
log.info(JSONObject.toJSONString(model, new com.alibaba.fastjson2.JSONWriter.Feature[0]));
return Result.succeed(model);
}
@Get
@Mapping("/add")
public Result addNote(Context ctx, @Path int pid) throws Exception {
String userid = getUserInfoId(ctx);
if (null == userid)
return Result.failure(401);
NoteModel note = new NoteModel();
note.setPid(Integer.valueOf(pid));
note.setTitle("未命名Note");
note.setFlag(Integer.valueOf(1));
note.setCreatetime(DateUtil.now());
note.setContext("{\"root\":{\"children\":[{\"children\":[{\"detail\":0,\"format\":0,\"mode\":\"normal\",\"style\":\"\",\"text\":\"未命名Note\",\"type\":\"text\",\"version\":1}],\"direction\":\"ltr\",\"format\":\"\",\"indent\":0,\"type\":\"paragraph\",\"version\":1}],\"direction\":\"ltr\",\"format\":\"\",\"indent\":0,\"type\":\"root\",\"version\":1}}");
// note.setContext("{\"root\": {\"type\": \"root\", \"format\": \"\", \"indent\": 0, \"version\": 1, \"children\": [{\"type\": \"paragraph\", \"format\": \"\", \"indent\": 0, \"version\": 1, \"children\": [], \"direction\": null}], \"direction\": null}}");
this.db.table("note").setEntityIf(note, (k, v) -> Boolean.valueOf((v != null))).insert();
return Result.succeed("ok");
}
@Post
@Mapping("/update")
public Result updateNote(@Body NoteRequest noteRequest) throws SQLException {
NoteModel note = (NoteModel)((DbTableQuery)this.db.table("note").whereEq("id", noteRequest.getId())).selectItem("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
note.setTitle(noteRequest.getTitle());
note.setUpdatetime(DateUtil.now());
String cc = noteRequest.getContext();
JSONObject ar = JSONObject.parseObject(cc);
note.setContext(ar.toJSONString());
int flag = ((DbTableQuery)this.db.table("note").set("title", noteRequest.getTitle()).set("updatetime", DateUtil.now()).set("context", ar.toJSONString()).whereEq("id", noteRequest.getId())).update();
log.info("updateNote+ flag");
HistoryModel history = new HistoryModel();
history.setNid(Integer.valueOf(noteRequest.getId().intValue()));
history.setTitle(noteRequest.getTitle());
history.setFlag(Integer.valueOf(1));
history.setCreatetime(DateUtil.now());
history.setContext(ar.toJSONString());
long his = this.db.table("history").setEntityIf(history, (k, v) -> Boolean.valueOf((v != null))).insert();
log.info("history+ his");
return Result.succeed("ok");
}
@Post
@Mapping("/delete")
public Result deleteNote(@Body NoteRequest noteRequest) throws SQLException {
int flag = ((DbTableQuery)this.db.table("note").set("title", noteRequest.getTitle()).set("flag", Integer.valueOf(0)).whereEq("id", noteRequest.getId())).update();
System.out.println(flag);
return Result.succeed("ok");
}
@Get
@Mapping("/deleteBack")
public Result deleteBack(@Path int id) throws Exception {
int flag = ((DbTableQuery)this.db.table("note").set("flag", Integer.valueOf(1)).whereEq("id", Integer.valueOf(id))).update();
System.out.println(flag);
return Result.succeed("ok");
}
@Get
@Mapping("/historyQueryOrDelete")
public Result historyQueryOrDelete(@Path int flag) throws Exception {
log.info("history+ flag" + flag);
if(flag==0){
long count = db.table("history").selectCount();
log.info("count:" + count);
return Result.succeed(count);
}else if(flag==1){
int flagdb = db.table("history").whereEq("flag",1).delete();
log.info("flagdb:" + flagdb);
return Result.succeed(0);
}
return null;
}
private String getUserInfoId(Context ctx) {
String userId = "";
if (null != ctx.header("Authorization")) {
String token = ctx.header("Authorization");
token = token.replace("Bearer ", "");
System.out.println("token:" + token);
Claims claims = JwtUtils.parseJwt(token);
System.out.println("claims:" + claims);
if (null != claims) {
System.out.println("username:" + claims.get("user_name"));
System.out.println("userid:" + claims.get("user_id"));
System.out.println("exp:" + claims.get("exp"));
userId = claims.get("user_id").toString();
return userId;
}
return null;
}
return null;
}
}
package com.cyynote.controller;
import cn.hutool.*;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cyynote.dso.NoteSqlAnnotation;
import com.cyynote.model.HistoryModel;
import com.cyynote.model.NoteModel;
import com.cyynote.payload.request.NoteRequest;
import com.cyynote.util.TreeBuild;
import com.cyynote.util.TreeNode;
import io.jsonwebtoken.Claims;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import org.noear.solon.annotation.Body;
import org.noear.solon.annotation.Controller;
import org.noear.solon.annotation.Get;
import org.noear.solon.annotation.Mapping;
import org.noear.solon.annotation.Path;
import org.noear.solon.annotation.Post;
import org.noear.solon.annotation.Put;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.Result;
import org.noear.solon.sessionstate.jwt.JwtUtils;
import org.noear.wood.DbContext;
import org.noear.wood.DbTableQuery;
import org.noear.wood.annotation.Db;
@Mapping("/api/note")
@Controller
public class NoteController extends BaseController {
private static final Logger log = Logger.getLogger(com.cyynote.controller.NoteController.class.getName());
@Db
NoteSqlAnnotation mapper;
@Db
DbContext db;
private static final String QUERY_F = "id,pid,title,createtime,updatetime,viewtime,flag";
@Get
@Mapping("get1")
public String test_post_get(Context context, @Path String appname) {
return context.path();
}
@Post
@Mapping("post")
public String test_post(Context context) {
return context.param("name");
}
@Put
@Mapping("put")
public String test_put(Context context, String name) {
return context.param("name");
}
@Get
@Mapping("/all")
public Result noteAccess(Context ctx) throws Exception {
List<NoteModel> all = ((DbTableQuery)this.db.table("note").whereEq("flag", Integer.valueOf(1))).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
List<TreeNode> treeNodeList = new ArrayList<>();
for (NoteModel n : all) {
TreeNode treeNode = new TreeNode(n.getId().intValue(), n.getPid().intValue(), n.getTitle(), String.valueOf(n.getId()), String.valueOf(n.getId()));
treeNodeList.add(treeNode);
}
TreeBuild bb = new TreeBuild(treeNodeList);
List<TreeNode> collect = bb.buildTree();
return Result.succeed(JSONArray.parseArray(JSONArray.toJSONString(collect)));
}
@Get
@Mapping("/home")
public Result noteHome(Context ctx, @Path int type, @Path String search) throws Exception {
List<NoteModel> all = new ArrayList<>();
if (type == 0) {
all = ((DbTableQuery)((DbTableQuery)this.db.table("note").whereLk("context", "%" + search + "%")).andLk("title", "%" + search + "%")).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
} else if (type == 1) {
all = ((DbTableQuery)((DbTableQuery)((DbTableQuery)this.db.table("note").whereEq("flag", Integer.valueOf(1))).orderByDesc("updatetime")).limit(20)).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
} else if (type == 2) {
all = ((DbTableQuery)((DbTableQuery)((DbTableQuery)this.db.table("note").whereEq("flag", Integer.valueOf(1))).orderByDesc("createtime")).limit(20)).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
} else if (type == 3) {
all = ((DbTableQuery)((DbTableQuery)((DbTableQuery)this.db.table("note").whereEq("flag", Integer.valueOf(1))).orderByDesc("viewtime")).limit(20)).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
} else if (type == 4) {
all = ((DbTableQuery)((DbTableQuery)((DbTableQuery)this.db.table("note").whereEq("flag", Integer.valueOf(0))).orderByDesc("updatetime")).limit(10000)).selectList("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
}
return Result.succeed(JSONArray.parseArray(JSONArray.toJSONString(all)));
}
@Get
@Mapping("/get")
public Result getNote(Context ctx, @Path int id) throws Exception {
NoteModel model = (NoteModel)((DbTableQuery)this.db.table("note").whereEq("id", Integer.valueOf(id))).selectItem("*", NoteModel.class);
if (model == null) {
ctx.status(404);
return Result.failure(404, "笔记不存在");
}
String time = DateUtil.now();
((DbTableQuery)this.db.table("note").set("viewtime", time).whereEq("id", Integer.valueOf(id))).update();
model.setViewtime(time);
log.info(JSONObject.toJSONString(model, new com.alibaba.fastjson2.JSONWriter.Feature[0]));
return Result.succeed(model);
}
@Get
@Mapping("/add")
public Result addNote(Context ctx, @Path int pid) throws Exception {
String userid = getUserInfoId(ctx);
if (null == userid)
return Result.failure(401);
NoteModel note = new NoteModel();
note.setPid(Integer.valueOf(pid));
note.setTitle("未命名Note");
note.setFlag(Integer.valueOf(1));
note.setCreatetime(DateUtil.now());
note.setUpdatetime(note.getCreatetime());
note.setViewtime(note.getCreatetime());
note.setContext("{\"root\":{\"children\":[{\"children\":[{\"detail\":0,\"format\":0,\"mode\":\"normal\",\"style\":\"\",\"text\":\"未命名Note\",\"type\":\"text\",\"version\":1}],\"direction\":\"ltr\",\"format\":\"\",\"indent\":0,\"type\":\"paragraph\",\"version\":1}],\"direction\":\"ltr\",\"format\":\"\",\"indent\":0,\"type\":\"root\",\"version\":1}}");
// note.setContext("{\"root\": {\"type\": \"root\", \"format\": \"\", \"indent\": 0, \"version\": 1, \"children\": [{\"type\": \"paragraph\", \"format\": \"\", \"indent\": 0, \"version\": 1, \"children\": [], \"direction\": null}], \"direction\": null}}");
this.db.table("note").setEntityIf(note, (k, v) -> Boolean.valueOf((v != null))).insert();
return Result.succeed("ok");
}
@Post
@Mapping("/update")
public Result updateNote(Context ctx, @Body NoteRequest noteRequest) throws SQLException {
if (noteRequest == null || noteRequest.getId() == null || noteRequest.getTitle() == null || noteRequest.getContext() == null) {
ctx.status(400);
return Result.failure(400, "参数不完整");
}
NoteModel note = (NoteModel)((DbTableQuery)this.db.table("note").whereEq("id", noteRequest.getId())).selectItem("id,pid,title,createtime,updatetime,viewtime,flag", NoteModel.class);
if (note == null) {
ctx.status(404);
return Result.failure(404, "笔记不存在");
}
note.setTitle(noteRequest.getTitle());
note.setUpdatetime(DateUtil.now());
String cc = noteRequest.getContext();
JSONObject ar = JSONObject.parseObject(cc);
note.setContext(ar.toJSONString());
int flag = ((DbTableQuery)this.db.table("note").set("title", noteRequest.getTitle()).set("updatetime", DateUtil.now()).set("context", ar.toJSONString()).whereEq("id", noteRequest.getId())).update();
log.info("updateNote+ flag");
HistoryModel history = new HistoryModel();
history.setNid(Integer.valueOf(noteRequest.getId().intValue()));
history.setTitle(noteRequest.getTitle());
history.setFlag(Integer.valueOf(1));
history.setCreatetime(DateUtil.now());
history.setContext(ar.toJSONString());
long his = this.db.table("history").setEntityIf(history, (k, v) -> Boolean.valueOf((v != null))).insert();
log.info("history+ his");
return Result.succeed("ok");
}
@Post
@Mapping("/delete")
public Result deleteNote(Context ctx, @Body NoteRequest noteRequest) throws SQLException {
if (noteRequest == null || noteRequest.getId() == null) {
ctx.status(400);
return Result.failure(400, "笔记ID不能为空");
}
int flag = ((DbTableQuery)this.db.table("note").set("flag", Integer.valueOf(0)).set("updatetime", DateUtil.now()).whereEq("id", noteRequest.getId())).update();
if (flag == 0) {
ctx.status(404);
return Result.failure(404, "笔记不存在");
}
return Result.succeed("ok");
}
@Get
@Mapping("/deleteBack")
public Result deleteBack(Context ctx, @Path int id) throws Exception {
int flag = ((DbTableQuery)this.db.table("note").set("flag", Integer.valueOf(1)).set("updatetime", DateUtil.now()).whereEq("id", Integer.valueOf(id))).update();
if (flag == 0) {
ctx.status(404);
return Result.failure(404, "笔记不存在");
}
return Result.succeed("ok");
}
@Get
@Mapping("/historyQueryOrDelete")
public Result historyQueryOrDelete(@Path int flag) throws Exception {
log.info("history+ flag" + flag);
if(flag==0){
long count = db.table("history").selectCount();
log.info("count:" + count);
return Result.succeed(count);
}else if(flag==1){
int flagdb = db.table("history").whereEq("flag",1).delete();
log.info("flagdb:" + flagdb);
return Result.succeed(0);
}
return Result.failure(400, "不支持的操作类型");
}
private String getUserInfoId(Context ctx) {
String userId = "";
if (null != ctx.header("Authorization")) {
String token = ctx.header("Authorization");
token = token.replace("Bearer ", "");
Claims claims = JwtUtils.parseJwt(token);
if (null != claims) {
userId = claims.get("user_id").toString();
return userId;
}
return null;
}
return null;
}
}