Compare commits

..

No commits in common. "07b5b1c3761f794097831937a11383a8a0770244" and "97c1e91f440b465e5170b60a8dd159168ff6e6d9" have entirely different histories.

18 changed files with 580 additions and 20 deletions

View File

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

View File

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

View File

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

View File

@ -0,0 +1,47 @@
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

@ -0,0 +1,22 @@
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

@ -0,0 +1,60 @@
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

@ -0,0 +1,14 @@
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

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

View File

@ -13,9 +13,13 @@ public class AbstractMessage {
public static final byte RESPONSE_MESSAGE = 0; 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 IDENTITY_MESSAGE = 6;
public static final byte MAINTAIN_MESSAGE = 7; public static final byte MAINTAIN_MESSAGE = 7;
public static final byte GALLERY_REQUEST_MESSAGE = 101;
public byte messageType; public byte messageType;
public int messageId; public int messageId;

View File

@ -0,0 +1,21 @@
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

@ -0,0 +1,25 @@
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,8 +39,10 @@ public class MessageCodec extends ByteToMessageCodec<AbstractMessage> {
AbstractMessage abstractMessage = switch (messageType){ AbstractMessage abstractMessage = switch (messageType){
case AbstractMessage.DOWNLOAD_POST_MESSAGE -> objectMapper.readValue(metadata, DownloadPostMessage.class); case AbstractMessage.DOWNLOAD_POST_MESSAGE -> objectMapper.readValue(metadata, DownloadPostMessage.class);
case AbstractMessage.DOWNLOAD_STATUS_MESSAGE -> objectMapper.readValue(metadata, DownloadStatusMessage.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.RESPONSE_MESSAGE -> objectMapper.readValue(metadata, ResponseMessage.class);
case AbstractMessage.DELETE_GALLERY_MESSAGE -> objectMapper.readValue(metadata, DeleteGalleryMessage.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.IDENTITY_MESSAGE -> objectMapper.readValue(metadata, IdentityMessage.class);
case AbstractMessage.MAINTAIN_MESSAGE -> objectMapper.readValue(metadata, MaintainMessage.class); case AbstractMessage.MAINTAIN_MESSAGE -> objectMapper.readValue(metadata, MaintainMessage.class);
default -> null; default -> null;

View File

@ -1,6 +1,8 @@
package com.lion.lionwebsite.Service; package com.lion.lionwebsite.Service;
import cn.hutool.core.io.FileUtil;
import com.lion.lionwebsite.Dao.cache.ImageCacheMapper; import com.lion.lionwebsite.Dao.cache.ImageCacheMapper;
import com.lion.lionwebsite.Dao.cache.PageNameCacheMapper;
import com.lion.lionwebsite.Dao.normal.*; import com.lion.lionwebsite.Dao.normal.*;
import com.lion.lionwebsite.Domain.*; import com.lion.lionwebsite.Domain.*;
import com.lion.lionwebsite.Exception.ResolutionNotMatchException; import com.lion.lionwebsite.Exception.ResolutionNotMatchException;
@ -23,6 +25,7 @@ import java.io.*;
import java.net.URI; import java.net.URI;
import java.util.*; 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.CustomUtil.objectMapper;
import static com.lion.lionwebsite.Util.GalleryUtil.*; import static com.lion.lionwebsite.Util.GalleryUtil.*;
@ -33,6 +36,12 @@ public class GalleryManageService {
String TargetPath = "/root/gallery/"; String TargetPath = "/root/gallery/";
String cachePath = "/root/galleryCache/"; 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; GalleryMapper galleryMapper;
CollectMapper collectMapper; CollectMapper collectMapper;
@ -43,6 +52,10 @@ public class GalleryManageService {
ShareFileMapper shareFileMapper; ShareFileMapper shareFileMapper;
TagMapper tagMapper;
PageNameCacheMapper pageNameCacheMapper;
ImageCacheMapper imageCacheMapper; ImageCacheMapper imageCacheMapper;
RemoteService remoteService; RemoteService remoteService;
@ -50,12 +63,14 @@ public class GalleryManageService {
PushService pushService; PushService pushService;
public GalleryManageService(GalleryMapper galleryMapper, CollectMapper collectMapper, CustomConfigurationMapper configurationMapper, UserMapper userMapper, ShareFileMapper shareFileMapper, public GalleryManageService(GalleryMapper galleryMapper, CollectMapper collectMapper, CustomConfigurationMapper configurationMapper, UserMapper userMapper, ShareFileMapper shareFileMapper,
RemoteService remoteService, PushService pushService, ImageCacheMapper imageCacheMapper) { TagMapper tagMapper, PageNameCacheMapper pageNameCacheMapper, RemoteService remoteService, PushService pushService, ImageCacheMapper imageCacheMapper) {
this.galleryMapper = galleryMapper; this.galleryMapper = galleryMapper;
this.collectMapper = collectMapper; this.collectMapper = collectMapper;
this.configurationMapper = configurationMapper; this.configurationMapper = configurationMapper;
this.userMapper = userMapper; this.userMapper = userMapper;
this.shareFileMapper = shareFileMapper; this.shareFileMapper = shareFileMapper;
this.tagMapper = tagMapper;
this.pageNameCacheMapper = pageNameCacheMapper;
this.remoteService = remoteService; this.remoteService = remoteService;
this.pushService = pushService; this.pushService = pushService;
this.imageCacheMapper = imageCacheMapper; this.imageCacheMapper = imageCacheMapper;
@ -68,7 +83,7 @@ public class GalleryManageService {
* @param AuthCode 授权码用于记录是谁下载的 * @param AuthCode 授权码用于记录是谁下载的
* @return 提交结果 * @return 提交结果
*/ */
public String createTask(String link, String targetResolution, String AuthCode) { public String createTask(String link, String targetResolution, String AuthCode, List<Integer> tidS) {
Response response = Response.generateResponse(); Response response = Response.generateResponse();
User user = userMapper.selectUserByAuthCode(AuthCode); User user = userMapper.selectUserByAuthCode(AuthCode);
// return Response._failure("调试中,请勿提交任务"); // return Response._failure("调试中,请勿提交任务");
@ -132,6 +147,10 @@ public class GalleryManageService {
long usedAmount = Long.parseLong(configurationMapper.selectConfiguration(CustomConfiguration.WEEK_USED_AMOUNT).getValue()); long usedAmount = Long.parseLong(configurationMapper.selectConfiguration(CustomConfiguration.WEEK_USED_AMOUNT).getValue());
usedAmount += gallery.getFileSize(); usedAmount += gallery.getFileSize();
configurationMapper.updateConfiguration(CustomConfiguration.WEEK_USED_AMOUNT, String.valueOf(usedAmount)); 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 { } else {
response.failure("提交失败,未知原因"); response.failure("提交失败,未知原因");
galleryMapper.deleteGalleryByGid(gallery.getGid()); galleryMapper.deleteGalleryByGid(gallery.getGid());
@ -230,6 +249,23 @@ 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()); response.success(new ObjectMapper().valueToTree(galleries).toString());
return response.toJSONString(); return response.toJSONString();
} }
@ -309,6 +345,17 @@ public class GalleryManageService {
else { else {
log.info("删除本子{}", gallery.getName()); log.info("删除本子{}", gallery.getName());
galleryMapper.deleteGalleryByGid(gallery.getGid()); //删除本子记录 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)) { switch (remoteService.deleteGallery(gallery)) {
case ErrorCode.IO_ERROR -> response.failure("本子:" + gallery.getName() + "删除失败IO错误"); case ErrorCode.IO_ERROR -> response.failure("本子:" + gallery.getName() + "删除失败IO错误");
@ -337,6 +384,63 @@ public class GalleryManageService {
return response.toJSONString(); 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) { public String cacheImagesKey(String url) {
Response response = Response.generateResponse(); Response response = Response.generateResponse();
String gid = String.valueOf(GalleryUtil.parseGid(url)); String gid = String.valueOf(GalleryUtil.parseGid(url));

View File

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

View File

@ -5,6 +5,7 @@ import com.lion.lionwebsite.Domain.Gallery;
import com.lion.lionwebsite.Domain.GalleryTask; import com.lion.lionwebsite.Domain.GalleryTask;
import com.lion.lionwebsite.Message.*; import com.lion.lionwebsite.Message.*;
import com.lion.lionwebsite.Util.CustomUtil;
import io.netty.bootstrap.Bootstrap; import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*; import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.nio.NioEventLoopGroup;
@ -17,8 +18,14 @@ import lombok.Data;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.net.*; 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.HashMap;
import java.util.concurrent.ExecutorService; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; import java.util.concurrent.Executors;
@ -141,6 +148,97 @@ 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(){ public void monitorFunc(){
System.out.println("监听端口: " + (port + 1) + " 等待节点上线"); System.out.println("监听端口: " + (port + 1) + " 等待节点上线");
try(ServerSocket socket = new ServerSocket(port + 1)) { try(ServerSocket socket = new ServerSocket(port + 1)) {
@ -187,12 +285,15 @@ public class RemoteService {
else if(galleryTask.getProceeding() != 0) else if(galleryTask.getProceeding() != 0)
gallery.setStatus("下载中"); gallery.setStatus("下载中");
log.info(gallery.getName() + "下载进度:" + gallery.getProceeding() + "/" + gallery.getPages()); log.info(gallery.getName() + "下载进度:" + gallery.getProceeding() + "/" + gallery.getPages());
galleryMapper.updateGallery(gallery); galleryMapper.updateGallery(gallery);
} }
} }
else if(msg instanceof ResponseMessage rsm) else if(msg instanceof ResponseMessage rsm)
promiseHashMap.get(rsm.messageId).setSuccess(rsm); promiseHashMap.get(rsm.messageId).setSuccess(rsm);
else if(msg instanceof GalleryPageQueryMessage gpqm)
promiseHashMap.get(gpqm.messageId).setSuccess(gpqm);
} }
@Override @Override

View File

@ -0,0 +1,125 @@
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.