Jelajahi Sumber

fix 上传图片到cos

zwhui 2 tahun lalu
induk
melakukan
67c401c850

+ 5 - 0
midjourney/pom.xml

@@ -183,6 +183,11 @@
             <artifactId>thumbnailator</artifactId>
             <version>0.4.8</version>
         </dependency>
+        <dependency>
+            <groupId>com.qcloud</groupId>
+            <artifactId>cos_api</artifactId>
+            <version>5.6.34</version>
+        </dependency>
     </dependencies>
 
 

+ 31 - 32
midjourney/src/main/java/com/yhlxj/service/midjourney/impl/MidJourneyAccountServiceImpl.java

@@ -308,41 +308,38 @@ public class MidJourneyAccountServiceImpl extends ServiceImpl<MidjourneyAccountM
 
         String key = RedisService.key.MIDJOURNEY_ACCOUNT.getName();
         content.forEach((accountInfo)->{
-            if (StringUtils.isNotBlank(accountInfo.getRemark()) && StringUtils.isNumeric(accountInfo.getRemark())) {
-                MidjourneyAccount midjourneyAccount = getById(Long.parseLong(accountInfo.getRemark()));
-                if (midjourneyAccount == null) {
-                    midjourneyAccount = new MidjourneyAccount();
-                    midjourneyAccount.setId(Long.parseLong(accountInfo.getRemark()));
-                    midjourneyAccount.setGuildId(Long.parseLong(accountInfo.getGuildId()));
-                    midjourneyAccount.setChannelId(Long.parseLong(accountInfo.getChannelId()));
-                    midjourneyAccount.setUserToken(accountInfo.getUserToken());
-                    midjourneyAccount.setStatus(accountInfo.isEnable());
-                }
-                midjourneyAccount.setInstanceId(Long.parseLong(accountInfo.getId()));
-                if (midjourneyAccount.getStatus() != accountInfo.isEnable()) {
-                    midjourneyAccount.setStatus(accountInfo.isEnable());
-                    Long instanceId = midjourneyAccount.getInstanceId();
-                    if(accountInfo.isEnable()){
-                        Map<Object, Object> accountsUsage = redisService.hmget(key);
-                        if (MapUtil.isNotEmpty(accountsUsage)) {
-                            redisService.hset(key,midjourneyAccount.getInstanceId().toString(),accountsUsage.values().toArray()[0]);
-                        }
-                        //重置setting
-                        TASK_EXECUTOR.execute(() -> {
-                            if (!"default".equals(accountInfo.getVersion()) || !accountInfo.isRaw()) {
-                                resetAccount(instanceId);
-                            }
-                        });
-                    }else {
-                        redisService.hdel(key, instanceId.toString());
+            MidjourneyAccount midjourneyAccount = getOne(Wrappers.lambdaQuery(MidjourneyAccount.class).eq(MidjourneyAccount::getInstanceId, Long.parseLong(accountInfo.getId())).last("limit 1"));
+            if (midjourneyAccount == null) {
+                midjourneyAccount = new MidjourneyAccount();
+                midjourneyAccount.setGuildId(Long.parseLong(accountInfo.getGuildId()));
+                midjourneyAccount.setChannelId(Long.parseLong(accountInfo.getChannelId()));
+                midjourneyAccount.setUserToken(accountInfo.getUserToken());
+                midjourneyAccount.setStatus(accountInfo.isEnable());
+            }
+            midjourneyAccount.setInstanceId(Long.parseLong(accountInfo.getId()));
+            if (midjourneyAccount.getId() == null || midjourneyAccount.getStatus() != accountInfo.isEnable()) {
+                midjourneyAccount.setStatus(accountInfo.isEnable());
+                Long instanceId = midjourneyAccount.getInstanceId();
+                if(accountInfo.isEnable()){
+                    Map<Object, Object> accountsUsage = redisService.hmget(key);
+                    if (MapUtil.isNotEmpty(accountsUsage)) {
+                        redisService.hset(key,midjourneyAccount.getInstanceId().toString(),accountsUsage.values().toArray()[0]);
                     }
-
-                }
-                if (!accountInfo.isEnable() && midjourneyAccount.getId() == null) {
-                    return;
+                    //重置setting
+                    TASK_EXECUTOR.execute(() -> {
+                        if (!"default".equals(accountInfo.getVersion()) || !accountInfo.isRaw()) {
+                            resetAccount(instanceId);
+                        }
+                    });
+                }else {
+                    redisService.hdel(key, instanceId.toString());
                 }
-                saveOrUpdate(midjourneyAccount);
+
+            }
+            if (!accountInfo.isEnable() && midjourneyAccount.getId() == null) {
+                return;
             }
+            saveOrUpdate(midjourneyAccount);
         });
 
         //移除本地不存在的账号
@@ -362,5 +359,7 @@ public class MidJourneyAccountServiceImpl extends ServiceImpl<MidjourneyAccountM
         log.info("versionResult:{}", versionResult.body());
         HttpResponse resetSettingResult = HttpRequest.post("http://172.19.0.17:8080/mj/account/" + id + "/action?customId=MJ::Settings::ResetSettings&botType=MID_JOURNEY").header("mj-api-secret", "5a9a3e9b-5a5e-4b6b-9a5a-9a5a5a5a5a5a").execute();
         log.info("resetSettingResult:{}", resetSettingResult.body());
+        HttpResponse relaxModeResult = HttpRequest.post("http://172.19.0.17:8080/mj/account/" + id + "/action?customId=MJ::Settings::RelaxMode&botType=MID_JOURNEY").header("mj-api-secret", "5a9a3e9b-5a5e-4b6b-9a5a-9a5a5a5a5a5a").execute();
+        log.info("relaxModeResult:{}", relaxModeResult.body());
     }
 }

+ 33 - 9
midjourney/src/main/java/com/yhlxj/service/midjourney/impl/MidjourneyServiceImpl.java

@@ -35,6 +35,7 @@ import com.yhlxj.service.common.EnvCommonService;
 import com.yhlxj.service.midjourney.MidjourneyAccountService;
 import com.yhlxj.service.midjourney.MidjourneyService;
 import com.yhlxj.service.midjourney.MidjourneyUserSettingsService;
+import com.yhlxj.util.COSUtil;
 import com.yhlxj.web.wss.WssSession;
 import lombok.Data;
 import lombok.RequiredArgsConstructor;
@@ -51,6 +52,7 @@ import javax.imageio.stream.ImageInputStream;
 import java.awt.image.BufferedImage;
 import java.io.File;
 import java.io.IOException;
+import java.io.InputStream;
 import java.net.MalformedURLException;
 import java.net.URL;
 import java.nio.charset.Charset;
@@ -193,6 +195,9 @@ public class MidjourneyServiceImpl implements MidjourneyService {
     }
 
     public MidjourneyUserConversation saveConversation(Long userId,Integer mode,SubmitResult result, String action,String prompt, String botType, Long apiChannelId) throws Exception {
+        if (result.getCode() == 23) {
+            return null;
+        }
         Long taskId = Long.parseLong(result.getResult());
         Map<String, Object> properties = result.getProperties();
         MidjourneyUserConversation conversation = null;
@@ -393,6 +398,7 @@ public class MidjourneyServiceImpl implements MidjourneyService {
      * 恢复次数
      */
     public void recoverUserLimit(Long id,Integer mode,Long num){
+        log.info("恢复次数 id:{},mode:{},num:{}",id,mode,num);
         if (mode == 1){
             redisService.incr(RedisService.key.MIDJOURNEY_FAST_LIMIT.getName() + id, 1L);
             midjourneyUserMapper.incrFastNum(id, 1);
@@ -544,6 +550,9 @@ public class MidjourneyServiceImpl implements MidjourneyService {
         }
         SubmitResult submitResult = submit2MjProxy(url, token, mode, action, param);
         int code = submitResult.getCode();
+        if (StringUtils.isNotBlank(accountWithMinUsage) && mode == 2) {
+            submitResult.setInstanceId(Long.valueOf(accountWithMinUsage));
+        }
         if (code == 23){
             recoverUserLimit(user.getId(), mode,1L);
             return submitResult;
@@ -551,9 +560,6 @@ public class MidjourneyServiceImpl implements MidjourneyService {
         if (code != 1 && code != 21 && code != 22) {
             submitResult = checkResult(user, mode, action, instanceId, param, code, accountWithMinUsage, submitResult);
         }
-        if (StringUtils.isNotBlank(accountWithMinUsage) && mode == 2) {
-            submitResult.setInstanceId(Long.valueOf(accountWithMinUsage));
-        }
         return submitResult;
     }
 
@@ -834,7 +840,11 @@ public class MidjourneyServiceImpl implements MidjourneyService {
                 conversationMapper.updateById(conversation);
                 TASK_EXECUTOR.execute(() -> {
                     try {
-                        uploadPicToLocal(conversation,"conversation"+dbConversation.getId());
+                        String imageUrl = conversation.getImageUrl();
+                        if (StringUtil.isNotBlank(imageUrl) && "SUCCESS".equals(conversation.getStatus())) {
+                            conversation.setImageUrl(uploadPic(imageUrl, "conversation"+dbConversation.getId()));
+                            conversationMapper.updateById(conversation);
+                        }
                     } catch (IOException e) {
                         log.error("上传图片失败",e);
                     }
@@ -874,18 +884,21 @@ public class MidjourneyServiceImpl implements MidjourneyService {
 
 
     private static String uploadPic(String url, String prefix) throws IOException {
+        url = url.replace("cdn.mj.liuliangbang.vip", "cdn.discordapp.com");
         byte[] body = HttpUtil.downloadBytes(url);
         Path tempFile = Files.createTempFile(prefix, ".png");
         File file = tempFile.toFile();
         try (FileImageOutputStream imageOutput = new FileImageOutputStream(file)) {
             imageOutput.write(body, 0, body.length);
         }
-        Map<String, Object> paramMap = new HashMap<>();
-        paramMap.put("file", file);
-        String json = HttpUtil.post("https://files.liuliangbang.vip/pic/ups", paramMap);
-        log.info("上传图片结果:url:{},json:{}",url, json);
+        InputStream inputStream = FileUtil.getInputStream(file);
+        String contentType = Files.probeContentType(tempFile);
+        String originalFilename = file.getName();
+        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
+        String result = COSUtil.upLoad(inputStream, ext, contentType);
+        log.info("上传图片结果:url:{},json:{}",url, result);
         FileUtil.del(file);
-        return new JSONObject(json).getJSONObject("value").getJSONArray("saved").getJSONObject(0).getJSONObject("info").getStr("cdnUrl");
+        return result;
     }
 
     private void uploadPicToLocal(MidjourneyUserConversation conversation, String prefix) throws IOException {
@@ -1286,6 +1299,17 @@ public class MidjourneyServiceImpl implements MidjourneyService {
         url = new URL(url.getProtocol(), "cdn.mj.liuliangbang.vip", url.getPort(), url.getFile());
         conversation.setImageUrl(url.toString());
         conversationMapper.insert(conversation);
+        TASK_EXECUTOR.execute(() -> {
+            try {
+                String imageUrl = conversation.getImageUrl();
+                if (StringUtil.isNotBlank(imageUrl)) {
+                    conversation.setImageUrl(uploadPic(imageUrl, "conversation"+conversation.getId()));
+                    conversationMapper.updateById(conversation);
+                }
+            } catch (IOException e) {
+                log.error("上传图片失败",e);
+            }
+        });
         return conversation;
     }
 

+ 62 - 0
midjourney/src/main/java/com/yhlxj/util/COSUtil.java

@@ -0,0 +1,62 @@
+package com.yhlxj.util;
+
+import com.qcloud.cos.COSClient;
+import com.qcloud.cos.ClientConfig;
+import com.qcloud.cos.auth.BasicCOSCredentials;
+import com.qcloud.cos.auth.COSCredentials;
+import com.qcloud.cos.model.ObjectMetadata;
+import com.qcloud.cos.region.Region;
+
+import java.io.InputStream;
+import java.time.LocalDateTime;
+import java.time.ZoneOffset;
+import java.time.format.DateTimeFormatter;
+
+/**
+ * @author zwhui
+ * @date 2024/7/18 14:29
+ */
+public class COSUtil {
+    /**
+     * 腾讯云COS
+     */
+    public static String SECRET_ID = "AKIDUzYL8rV9kEaoy0tcQH3kR9obeqDlw6ZK"; //这个参数需要你替换为自己的
+    public static String SECRET_KEY = "258AQj1DPcvTkEtXIOZrKtcSfvhiibUN"; //这个参数需要你替换为自己的
+    public static String BUCKET_NAME = "mj-1310013563"; //这个参数需要你替换为自己的
+    public static String REGION = "ap-hongkong"; //这个参数需要你替换为自己的
+
+    public static String prePath="conversation/"; //这个参数需要你替换为自己的
+
+    /**
+     * 获取客户端对象
+     * @return
+     */
+    public static COSClient getInstance(){
+        COSCredentials cred = new BasicCOSCredentials(SECRET_ID, SECRET_KEY);
+        Region region = new Region(REGION);
+        ClientConfig clientConfig = new ClientConfig(region);
+        return new COSClient(cred, clientConfig);
+    }
+
+    /**
+     * 图片上传
+     * @param in
+     * @param ext
+     * @param contentType
+     * @return
+     */
+    public static String upLoad(InputStream in, String ext, String contentType){
+        ObjectMetadata objectMetadata = new ObjectMetadata();
+        String key = prePath+getTimeStamp()+ext;
+        objectMetadata.setContentType(contentType);
+        getInstance().putObject(BUCKET_NAME, key, in, objectMetadata);
+        return "https://cdn.mj.galaxydvd.com/"+key;
+    }
+
+    // 获得时间戳
+    public static String getTimeStamp(){
+        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
+        return LocalDateTime.now(ZoneOffset.of("+8")).format(formatter);
+    }
+
+}