Compare commits

...

3 Commits

Author SHA1 Message Date
chuzhongzai
07b5b1c376 删除多余代码 2023-12-27 18:02:40 +08:00
chuzhongzai
2c0ed4be58 去除远程图片查询相关代码;去除标签;优化部分代码 2023-12-27 17:41:40 +08:00
chuzhongzai
793ae12348 去除远程图片查询相关代码 2023-12-27 17:34:00 +08:00
18 changed files with 20 additions and 580 deletions

View File

@ -126,7 +126,6 @@
<imageName>lionwebsite</imageName>
<buildArgs>
<arg>--gc=G1</arg>
<arg>-Ob</arg>
<arg>-H:+ReportExceptionStackTraces</arg>
<arg>--initialize-at-build-time=org.apache.commons.logging.LogFactory,org.apache.commons.logging.LogFactoryService</arg>
</buildArgs>

View File

@ -16,11 +16,11 @@ import com.pengrad.telegrambot.model.User;
@Configuration
@RegisterReflectionForBinding(classes = {CustomConfiguration.class, GidToKey.class, ImageKeyCache.class,
GalleryForQuery.class, Gallery.class, GalleryTask.class, HikariConfig.class,
PageNameCache.class, ShareFile.class, Tag.class, TagMark.class, User.class,
PageNameCache.class, ShareFile.class, User.class,
SendResponse.class, Message.class, com.pengrad.telegrambot.model.User.class,
Chat.class, MessageEntity.class,
AbstractMethodError.class, DeleteGalleryMessage.class, DownloadPostMessage.class, DownloadStatusMessage.class,
GalleryPageQueryMessage.class, GalleryRequestMessage.class, IdentityMessage.class, MaintainMessage.class, ResponseMessage.class})
IdentityMessage.class, MaintainMessage.class, ResponseMessage.class})
public class CustomBean {
@Bean

View File

@ -9,8 +9,6 @@ import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/GalleryManage")
@Slf4j
@ -28,11 +26,10 @@ public class GalleryManageController {
}
@PostMapping("")
public String create_task(String link, String targetResolution, String AuthCode,
@RequestParam(value = "tags", required = false) List<Integer> tags){
public String create_task(String link, String targetResolution, String AuthCode){
if(link == null || targetResolution == null)
return Response._failure("参数不全");
return galleryManageService.createTask(link, targetResolution, AuthCode, tags);
return galleryManageService.createTask(link, targetResolution, AuthCode);
}
@GetMapping("")
@ -41,36 +38,21 @@ public class GalleryManageController {
if(type == null)
return Response._failure("参数不全");
switch (type) {
case "link" -> {
return galleryManageService.selectTaskByLink(param);
}
case "gid" -> {
return galleryManageService.selectTaskByGid(Integer.parseInt(param));
}
case "all" -> {
return galleryManageService.selectAllGallery(userId);
}
case "name" -> {
return galleryManageService.selectGalleryByName(param);
}
case "undone" -> {
return galleryManageService.selectUnDoneGallery();
}
case "downloader" -> {
return galleryManageService.selectGalleryByDownloader(AuthCode);
}
default -> {
return Response._failure("参数错误");
}
}
return switch (type) {
case "link" -> galleryManageService.selectTaskByLink(param);
case "gid" -> galleryManageService.selectTaskByGid(Integer.parseInt(param));
case "all" -> galleryManageService.selectAllGallery(userId);
case "name" -> galleryManageService.selectGalleryByName(param);
case "undone" -> galleryManageService.selectUnDoneGallery();
case "downloader" -> galleryManageService.selectGalleryByDownloader(AuthCode);
default -> Response._failure("参数错误");
};
}
@DeleteMapping("")
public String deleteTask(Integer gid, String AuthCode){
if(gid == null)
return Response._failure("参数不全");
return galleryManageService.deleteGalleryByGid(gid, AuthCode);
}
@ -90,11 +72,6 @@ public class GalleryManageController {
return galleryManageService.getWeekUsedAmount();
}
// @GetMapping("/onlineImage/{page}")
// public void getOnlineImage(Integer gid, @PathVariable("page") Short page, HttpServletRequest request, HttpServletResponse response){
// galleryManageService.getOnlineImage(gid, page, request, response);
// }
@PostMapping("/cache")
public String cacheImageKeys(String url){
return galleryManageService.cacheImagesKey(url);

View File

@ -1,47 +0,0 @@
package com.lion.lionwebsite.Controller;
import com.lion.lionwebsite.Service.TagService;
import com.lion.lionwebsite.Util.Response;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/GalleryManage")
public class TagController {
TagService tagService;
public TagController(TagService tagService) {
this.tagService = tagService;
}
@PostMapping("/tag")
public String createTag(String tag){
return tagService.createTag(tag);
}
@PostMapping("/tagAndMark")
public String createTagAndMark(Integer gid, String tag){
return tagService.createTagAndMark(gid, tag);
}
@DeleteMapping("/tag")
public String deleteTag(Integer tid){
return tid == null ? Response._failure("参数错误") : tagService.deleteTag(tid);
}
@PostMapping("/mark")
public String markTag(Integer gid, Integer tid){
return tagService.markTag(gid, tid);
}
@PostMapping("/disMark")
public String disMarkTag(Integer gid, Integer tid){
return tagService.disMarkTag(gid, tid);
}
@GetMapping("/allTag")
public String allTag(){
return tagService.selectAllTag();
}
}

View File

@ -1,22 +0,0 @@
package com.lion.lionwebsite.Dao.cache;
import com.lion.lionwebsite.Domain.PageNameCache;
import org.apache.ibatis.annotations.*;
@Mapper
public interface PageNameCacheMapper {
@Insert("insert into pageName (gid, page, pageName) values (#{gid}, #{page}, #{pageName})")
void insertPageNameCache(PageNameCache pageNameCache);
@Select("select pageName from pageName where gid=#{gid} and page=#{page}")
String selectPageName(@Param("gid") int gid, @Param("page") short page);
@Delete("delete from pageName where gid=#{gid}")
void deletePageNameByGid(int gid);
// @Delete("delete from pageName where gid=#{gid} and page=#{page}")
// void deletePageName(PageNameCache pageNameCache);
}

View File

@ -1,60 +0,0 @@
package com.lion.lionwebsite.Dao.normal;
import com.lion.lionwebsite.Domain.Tag;
import com.lion.lionwebsite.Domain.TagMark;
import org.apache.ibatis.annotations.*;
import java.util.ArrayList;
@Mapper
public interface TagMapper {
@Insert("insert into tag (tag) values (#{tag})")
@Options(useGeneratedKeys = true, keyProperty = "id", keyColumn = "id")
void insertTag(Tag tag);
// @Select("select id, tag, usage from tag where id=#{id}")
// Tag selectTagById(int id);
//
// @Select("select id from tag where tag=#{tag}")
// int selectTidByTag(String tag);
@Select("select count(id) from tag where tag=#{tag}")
int selectTagExistByTag(String tag);
@Select("select count(id) from tag where id=#{id}")
int selectTagExistById(int id);
@Select("select id, tag, usage from tag")
ArrayList<Tag> selectAllTag();
@Delete("delete from tag where id=#{id}")
void deleteTagById(int id);
@Select("select count(id) from galleryTag where tid=#{tid}")
int selectTagUsage(int tid);
@Select("select count(id) from galleryTag where gid=#{gid} and tid=#{tid}")
int selectIsMark(@Param("gid") int gid, @Param("tid") int tid);
@Select("select tid from galleryTag where gid=#{gid}")
ArrayList<Integer> selectTagByGid(int gid);
@Insert("insert into galleryTag (gid, tid) values (#{gid}, #{tid})")
int markTag(@Param("gid") int gid, @Param("tid") int tid);
@Delete("delete from galleryTag where gid=#{gid} and tid=#{tid}")
int disMarkTag(@Param("gid") int gid, @Param("tid") int tid);
@Select("select gid, tid from galleryTag")
ArrayList<TagMark> selectAllMark();
@Update("update tag set usage=usage+1 where id=#{tid}")
void incrTagUsage(int tid);
@Update("update tag set usage=usage-1 where id=#{tid}")
void decrTagUsage(int tid);
@Delete("delete from galleryTag where gid=#{gid}")
void disMarkTagByGid(int gid);
}

View File

@ -1,14 +0,0 @@
package com.lion.lionwebsite.Domain;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Tag {
int id;
String tag;
int usage;
}

View File

@ -1,11 +0,0 @@
package com.lion.lionwebsite.Domain;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
public class TagMark {
int gid;
int tid;
}

View File

@ -13,13 +13,9 @@ public class AbstractMessage {
public static final byte RESPONSE_MESSAGE = 0;
public static final byte GALLERY_PAGE_QUERY_MESSAGE = 5;
public static final byte IDENTITY_MESSAGE = 6;
public static final byte MAINTAIN_MESSAGE = 7;
public static final byte GALLERY_REQUEST_MESSAGE = 101;
public byte messageType;
public int messageId;

View File

@ -1,21 +0,0 @@
package com.lion.lionwebsite.Message;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
@Data
public class GalleryPageQueryMessage extends AbstractMessage{
{
messageType = GALLERY_PAGE_QUERY_MESSAGE;
}
@JsonInclude(JsonInclude.Include.NON_NULL)
String name;
int page;
@JsonInclude(JsonInclude.Include.NON_NULL)
String pageName;
byte result;
}

View File

@ -1,25 +0,0 @@
package com.lion.lionwebsite.Message;
import lombok.Data;
@Data
//请求预览/压缩包
public class GalleryRequestMessage extends AbstractMessage{
public static final byte SOURCE = 1;
public static final byte PREVIEW = 2;
public static final byte COMPRESS_SOURCE = 3;
{
messageType = GALLERY_REQUEST_MESSAGE;
}
String galleryName;
byte type;
short page;
short port;
}

View File

@ -39,10 +39,8 @@ public class MessageCodec extends ByteToMessageCodec<AbstractMessage> {
AbstractMessage abstractMessage = switch (messageType){
case AbstractMessage.DOWNLOAD_POST_MESSAGE -> objectMapper.readValue(metadata, DownloadPostMessage.class);
case AbstractMessage.DOWNLOAD_STATUS_MESSAGE -> objectMapper.readValue(metadata, DownloadStatusMessage.class);
case AbstractMessage.GALLERY_REQUEST_MESSAGE -> objectMapper.readValue(metadata, GalleryRequestMessage.class);
case AbstractMessage.RESPONSE_MESSAGE -> objectMapper.readValue(metadata, ResponseMessage.class);
case AbstractMessage.DELETE_GALLERY_MESSAGE -> objectMapper.readValue(metadata, DeleteGalleryMessage.class);
case AbstractMessage.GALLERY_PAGE_QUERY_MESSAGE -> objectMapper.readValue(metadata, GalleryPageQueryMessage.class);
case AbstractMessage.IDENTITY_MESSAGE -> objectMapper.readValue(metadata, IdentityMessage.class);
case AbstractMessage.MAINTAIN_MESSAGE -> objectMapper.readValue(metadata, MaintainMessage.class);
default -> null;

View File

@ -1,8 +1,6 @@
package com.lion.lionwebsite.Service;
import cn.hutool.core.io.FileUtil;
import com.lion.lionwebsite.Dao.cache.ImageCacheMapper;
import com.lion.lionwebsite.Dao.cache.PageNameCacheMapper;
import com.lion.lionwebsite.Dao.normal.*;
import com.lion.lionwebsite.Domain.*;
import com.lion.lionwebsite.Exception.ResolutionNotMatchException;
@ -25,7 +23,6 @@ import java.io.*;
import java.net.URI;
import java.util.*;
import static com.lion.lionwebsite.Util.CustomUtil.fourZeroFour;
import static com.lion.lionwebsite.Util.CustomUtil.objectMapper;
import static com.lion.lionwebsite.Util.GalleryUtil.*;
@ -36,12 +33,6 @@ public class GalleryManageService {
String TargetPath = "/root/gallery/";
String cachePath = "/root/galleryCache/";
Map<Integer, String> gid2name_cache = new HashMap<>();
Map<Integer, Integer> gid2page_cache = new HashMap<>();
Map<String, String> page2pageNameCache = new HashMap<>();
GalleryMapper galleryMapper;
CollectMapper collectMapper;
@ -52,10 +43,6 @@ public class GalleryManageService {
ShareFileMapper shareFileMapper;
TagMapper tagMapper;
PageNameCacheMapper pageNameCacheMapper;
ImageCacheMapper imageCacheMapper;
RemoteService remoteService;
@ -63,14 +50,12 @@ public class GalleryManageService {
PushService pushService;
public GalleryManageService(GalleryMapper galleryMapper, CollectMapper collectMapper, CustomConfigurationMapper configurationMapper, UserMapper userMapper, ShareFileMapper shareFileMapper,
TagMapper tagMapper, PageNameCacheMapper pageNameCacheMapper, RemoteService remoteService, PushService pushService, ImageCacheMapper imageCacheMapper) {
RemoteService remoteService, PushService pushService, ImageCacheMapper imageCacheMapper) {
this.galleryMapper = galleryMapper;
this.collectMapper = collectMapper;
this.configurationMapper = configurationMapper;
this.userMapper = userMapper;
this.shareFileMapper = shareFileMapper;
this.tagMapper = tagMapper;
this.pageNameCacheMapper = pageNameCacheMapper;
this.remoteService = remoteService;
this.pushService = pushService;
this.imageCacheMapper = imageCacheMapper;
@ -83,7 +68,7 @@ public class GalleryManageService {
* @param AuthCode 授权码用于记录是谁下载的
* @return 提交结果
*/
public String createTask(String link, String targetResolution, String AuthCode, List<Integer> tidS) {
public String createTask(String link, String targetResolution, String AuthCode) {
Response response = Response.generateResponse();
User user = userMapper.selectUserByAuthCode(AuthCode);
// return Response._failure("调试中,请勿提交任务");
@ -147,10 +132,6 @@ public class GalleryManageService {
long usedAmount = Long.parseLong(configurationMapper.selectConfiguration(CustomConfiguration.WEEK_USED_AMOUNT).getValue());
usedAmount += gallery.getFileSize();
configurationMapper.updateConfiguration(CustomConfiguration.WEEK_USED_AMOUNT, String.valueOf(usedAmount));
if (tidS != null)
for (Integer tid : tidS)
if (tagMapper.selectTagExistById(tid) > 0)
tagMapper.markTag(gallery.getGid(), tid);
} else {
response.failure("提交失败,未知原因");
galleryMapper.deleteGalleryByGid(gallery.getGid());
@ -249,23 +230,6 @@ public class GalleryManageService {
}
}
HashMap<Integer, ArrayList<Integer>> tagsMap = new HashMap<>();
ArrayList<TagMark> tags = tagMapper.selectAllMark();
for (TagMark tagMark : tags) { //从数据库取出所有标记然后筛选出 gid -> tids 后面加个缓存
tagsMap.computeIfAbsent(tagMark.getGid(), k -> new ArrayList<>());
tagsMap.get(tagMark.getGid()).add(tagMark.getTid());
}
ArrayList<Integer> temp;
for (Gallery gallery : galleries) {
if ((temp = tagsMap.get(gallery.getGid())) != null) {
gallery.setTags(new ArrayList<>());
gallery.getTags().addAll(temp);
}
}
response.success(new ObjectMapper().valueToTree(galleries).toString());
return response.toJSONString();
}
@ -345,17 +309,6 @@ public class GalleryManageService {
else {
log.info("删除本子{}", gallery.getName());
galleryMapper.deleteGalleryByGid(gallery.getGid()); //删除本子记录
ArrayList<Integer> tidS = tagMapper.selectTagByGid(gallery.getGid());
for (Integer tid : tidS)
tagMapper.decrTagUsage(tid);
tagMapper.disMarkTagByGid(gallery.getGid()); //删除本子标记
gid2name_cache.remove(gallery.getGid()); //删除本子缓存
page2pageNameCache.remove(gallery.getName()); //移除页数缓存
pageNameCacheMapper.deletePageNameByGid(gid);
if (new File(TargetPath + "/" + gallery.getName()).isDirectory()) //删除本地缓存
FileUtil.del(TargetPath + "/" + gallery.getName());
}
switch (remoteService.deleteGallery(gallery)) {
case ErrorCode.IO_ERROR -> response.failure("本子:" + gallery.getName() + "删除失败IO错误");
@ -384,63 +337,6 @@ public class GalleryManageService {
return response.toJSONString();
}
/**
* 获取在线图片
* @param gid gid
* @param page 文件名
* @param request 请求对象
* @param response 响应对象
*/
public void getOnlineImage(Integer gid, Short page, HttpServletRequest request, HttpServletResponse response){
String name;
//本子名缓存
if((name = gid2name_cache.get(gid)) == null) //内存
if((name = galleryMapper.selectGalleryNameByGid(gid)) == null) { //数据库
fourZeroFour(response);
return;
}
else
gid2name_cache.put(gid, name);
//页数缓存
Integer real_page;
if((real_page = gid2page_cache.get(gid)) == null)
real_page = galleryMapper.selectGalleryByGid(gid).getPages();
//判断页数是否超出
if(real_page < page || page < 0){
fourZeroFour(response);
return;
}
//页名缓存
String pageName;
if((pageName = page2pageNameCache.get(gid + String.valueOf(page))) == null) //内存
if((pageName = pageNameCacheMapper.selectPageName(gid, page)) == null) //数据库
if ((pageName = remoteService.queryPageName(name, page)) == null) { //远程查询
fourZeroFour(response);
return;
}
//插入数据库
else
pageNameCacheMapper.insertPageNameCache(new PageNameCache(gid, page, pageName));
//插入缓存
else
page2pageNameCache.put(gid + String.valueOf(page), pageName);
//图片缓存
File file = new File(TargetPath, name + "/" + pageName);
if(!file.exists()) //硬盘
if(remoteService.cachePreview(name, page, file) != 0) { //远程
fourZeroFour(response);
return;
}
FileDownload.export(request, response, file.getAbsolutePath());
}
public String cacheImagesKey(String url) {
Response response = Response.generateResponse();
String gid = String.valueOf(GalleryUtil.parseGid(url));

View File

@ -35,12 +35,12 @@ public class LocalServiceImpl{
CustomConfigurationMapper configurationMapper;
ShareFileMapper shareFIleMapper;
ShareFileMapper shareFileMapper;
GalleryMapper galleryMapper;
public LocalServiceImpl(CustomConfigurationMapper configurationMapper, ShareFileMapper shareFileMapper, GalleryMapper galleryMapper){
this.shareFIleMapper = shareFileMapper;
this.shareFileMapper = shareFileMapper;
this.configurationMapper = configurationMapper;
this.galleryMapper = galleryMapper;
}
@ -183,7 +183,7 @@ public class LocalServiceImpl{
*/
@Scheduled(cron = "0 0 4 * * *")
public void checkShareCode(){
ShareFile[] shareFiles = shareFIleMapper.selectAllShareFile();
ShareFile[] shareFiles = shareFileMapper.selectAllShareFile();
Calendar now;
Calendar expireTime;
for(ShareFile shareFile: shareFiles){
@ -191,7 +191,7 @@ public class LocalServiceImpl{
expireTime = Calendar.getInstance();
expireTime.setTime(shareFile.getExpireTime());
if(now.after(expireTime))
shareFIleMapper.deleteShareFile(shareFile.getShareCode());
shareFileMapper.deleteShareFile(shareFile.getShareCode());
}
}

View File

@ -5,7 +5,6 @@ import com.lion.lionwebsite.Domain.Gallery;
import com.lion.lionwebsite.Domain.GalleryTask;
import com.lion.lionwebsite.Message.*;
import com.lion.lionwebsite.Util.CustomUtil;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
@ -18,14 +17,8 @@ import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.StandardOpenOption;
import java.util.HashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@ -148,97 +141,6 @@ public class RemoteService {
}
}
public byte cachePreview(String galleryName, short page, File file){
File parentFile = file.getParentFile();
if(!parentFile.isDirectory())
if(parentFile.mkdirs())
log.info("创建文件夹{}成功", parentFile.getAbsolutePath());
else
log.error("创建文件夹{}失败", parentFile.getAbsolutePath());
GalleryRequestMessage grm = new GalleryRequestMessage();
grm.setGalleryName(galleryName);
grm.setPage(page);
grm.setType(GalleryRequestMessage.PREVIEW);
grm.messageId = atomicInteger.getAndIncrement();
DefaultPromise<Object> downloadPromise = new DefaultPromise<>(eventLoopGroup);
DefaultPromise<Object> readyPromise = new DefaultPromise<>(eventLoopGroup);
downloadThread.submit(() -> {
try {
short port = CustomUtil._findIdlePort();
ServerSocketChannel ssChannel = ServerSocketChannel.open();
ssChannel.bind(new InetSocketAddress("0.0.0.0", port));
grm.setPort(port);
readyPromise.setSuccess("");
SocketChannel socketChannel = ssChannel.accept();
FileChannel fileChannel = FileChannel.open(file.toPath(), StandardOpenOption.WRITE, StandardOpenOption.CREATE);
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (socketChannel.read(byteBuffer) != -1){
byteBuffer.flip();
fileChannel.write(byteBuffer);
byteBuffer.clear();
}
fileChannel.close();
socketChannel.close();
ssChannel.close();
log.info("缓存预览图:" + galleryName + " " + file.getName());
downloadPromise.setSuccess("");
}catch (IOException e){
e.printStackTrace();
}
});
try{
readyPromise.await();
channel.writeAndFlush(grm);
DefaultPromise<AbstractMessage> promise = new DefaultPromise<>(eventLoopGroup);
promiseHashMap.put(grm.messageId, promise);
boolean result = promise.await(10, TimeUnit.SECONDS);
if(result){
ResponseMessage rsm = (ResponseMessage) promise.getNow();
if(rsm.getResult() == 0){
downloadPromise.await(10, TimeUnit.SECONDS);
return (byte) (downloadPromise.isSuccess()?0:1);
}else{
return rsm.getResult();
}
}else {
return -1;
}
}catch (InterruptedException e){
return -1;
}
}
public String queryPageName(String name, int page){
GalleryPageQueryMessage gpqm = new GalleryPageQueryMessage();
gpqm.setName(name);
gpqm.setPage(page);
gpqm.messageId = atomicInteger.getAndIncrement();
channel.writeAndFlush(gpqm);
DefaultPromise<AbstractMessage> promise = new DefaultPromise<>(eventLoopGroup);
promiseHashMap.put(gpqm.messageId, promise);
try{
boolean result = promise.await(10, TimeUnit.SECONDS);
if(result){
gpqm = (GalleryPageQueryMessage) promise.getNow();
if(gpqm.getResult() == 0)
return gpqm.getPageName();
else {
log.error("galleryPageQuery error:" + gpqm.getResult());
return null;
}
}else{
return null;
}
}catch (InterruptedException e){
return null;
}
}
public void monitorFunc(){
System.out.println("监听端口: " + (port + 1) + " 等待节点上线");
try(ServerSocket socket = new ServerSocket(port + 1)) {
@ -285,15 +187,12 @@ public class RemoteService {
else if(galleryTask.getProceeding() != 0)
gallery.setStatus("下载中");
log.info(gallery.getName() + "下载进度:" + gallery.getProceeding() + "/" + gallery.getPages());
galleryMapper.updateGallery(gallery);
}
}
else if(msg instanceof ResponseMessage rsm)
promiseHashMap.get(rsm.messageId).setSuccess(rsm);
else if(msg instanceof GalleryPageQueryMessage gpqm)
promiseHashMap.get(gpqm.messageId).setSuccess(gpqm);
}
@Override

View File

@ -1,125 +0,0 @@
package com.lion.lionwebsite.Service;
import com.lion.lionwebsite.Dao.normal.GalleryMapper;
import com.lion.lionwebsite.Dao.normal.TagMapper;
import com.lion.lionwebsite.Domain.Gallery;
import com.lion.lionwebsite.Domain.Tag;
import com.lion.lionwebsite.Util.Response;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.HashMap;
@Service
public class TagService {
TagMapper tagMapper;
GalleryMapper galleryMapper;
public TagService(TagMapper tagMapper, GalleryMapper galleryMapper) {
this.tagMapper = tagMapper;
this.galleryMapper = galleryMapper;
}
public String createTag(String tagStr){
Response response = Response.generateResponse();
//查看tag是否存在
if(tagMapper.selectTagExistByTag(tagStr) != 0){
response.failure("该tag:" + tagStr + "已存在");
}else{
Tag tag = new Tag(0, tagStr, 0);
tagMapper.insertTag(tag);
response.success("创建tag:" + tagStr + "成功");
response.set("tid", String.valueOf(tag.getId()));
}
return response.toJSONString();
}
public String selectAllTag(){
Response response = Response.generateResponse();
ArrayList<Tag> tags = tagMapper.selectAllTag();
HashMap<Integer, Tag> tagHashMap = new HashMap<>();
for (Tag tag : tags) {
tagHashMap.put(tag.getId(), tag);
}
if(tags.isEmpty())
response.failure("当前还没有标签");
else
response.success(new ObjectMapper().valueToTree(tagHashMap).toString());
return response.toJSONString();
}
public String deleteTag(int tagId){
Response response = Response.generateResponse();
if(tagMapper.selectTagUsage(tagId) == 0){
tagMapper.deleteTagById(tagId);
response.success("标签删除成功");
}else{
response.failure("标签删除失败,还有本子引用该标签(如果还显示可以删除,请刷新)");
}
return response.toJSONString();
}
public String markTag(int gid, int tid){
Response response = Response.generateResponse();
Gallery gallery = galleryMapper.selectGalleryByGid(gid);
if(gallery == null)//查看本子是否存在
response.failure("本子不存在,无法标记标签");
else if (tagMapper.selectTagExistById(tid) == 0) //查看标签是否存在
response.failure("标签不存在,无法标记标签");
else
if(tagMapper.selectIsMark(gid, tid) != 0) //查看是否已有该条记录
response.failure("当前本子已有该标签");
else {
if (tagMapper.markTag(gid, tid) == 1) {
response.success("标记本子成功");
tagMapper.incrTagUsage(tid);
}
else
response.failure("未知错误");
}
return response.toJSONString();
}
public String createTagAndMark(int gid, String tagString){
Response response = Response.generateResponse();
Gallery gallery = galleryMapper.selectGalleryByGid(gid);
//查看tag是否存在
if(tagMapper.selectTagExistByTag(tagString) != 0){
response.failure("该tag:" + tagString + "已存在,请刷新再尝试");
}else if(gallery == null) {//查看本子是否存在
response.failure("本子不存在,取消创建标签,请刷新再尝试");
}else{
Tag tag = new Tag(0, tagString, 0);
tagMapper.insertTag(tag);
if (tagMapper.markTag(gid, tag.getId()) == 1) {
response.success("创建标签并标记成功");
response.set("tid", String.valueOf(tag.getId()));
tagMapper.incrTagUsage(tag.getId());
}
}
return response.toJSONString();
}
public String disMarkTag(int gid, int tid){
Response response = Response.generateResponse();
if(tagMapper.disMarkTag(gid, tid) == 0)
response.failure("取消标记失败,可能并没有标记");
else {
response.success("取消标记成功");
tagMapper.decrTagUsage(tid);
}
return response.toJSONString();
}
}

Binary file not shown.

Binary file not shown.