移植原始版本
This commit is contained in:
44
src/main/java/com/yutou/nas/utils/ApplicationInit.java
Normal file
44
src/main/java/com/yutou/nas/utils/ApplicationInit.java
Normal file
@@ -0,0 +1,44 @@
|
||||
package com.yutou.nas.utils;
|
||||
|
||||
import com.yutou.nas.other.QQSetu;
|
||||
import org.springframework.boot.ApplicationArguments;
|
||||
import org.springframework.boot.ApplicationRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Timer;
|
||||
import java.util.TimerTask;
|
||||
|
||||
/**
|
||||
* 服务启动后执行
|
||||
*/
|
||||
@Component
|
||||
public class ApplicationInit implements ApplicationRunner {
|
||||
@Resource
|
||||
MusicToolsServiceImpl musicTools;
|
||||
@Override
|
||||
public void run(ApplicationArguments args) throws Exception {
|
||||
AudioTools.init();
|
||||
new Timer().schedule(new TimerTask() {
|
||||
@Override
|
||||
public void run() {
|
||||
String time = new SimpleDateFormat("HH:mm").format(new Date());
|
||||
switch (time){
|
||||
case "00:00":
|
||||
musicTools.scanMusic();
|
||||
break;
|
||||
case "08:00":
|
||||
case "20:00":
|
||||
QQBotManager.getInstance().reportToDayBangumi();
|
||||
break;
|
||||
case "23:59":
|
||||
QQSetu.printTodaySetu();
|
||||
break;
|
||||
|
||||
}
|
||||
}
|
||||
},0,35 * 1000);
|
||||
}
|
||||
}
|
||||
66
src/main/java/com/yutou/nas/utils/AudioTools.java
Normal file
66
src/main/java/com/yutou/nas/utils/AudioTools.java
Normal file
@@ -0,0 +1,66 @@
|
||||
package com.yutou.nas.utils;
|
||||
|
||||
import com.iflytek.cloud.speech.*;
|
||||
|
||||
public class AudioTools {
|
||||
private static boolean init = false;
|
||||
|
||||
synchronized static void init() {
|
||||
if (init) {
|
||||
return;
|
||||
}
|
||||
SpeechUtility.createUtility(SpeechConstant.APPID + "=601f7f7d");
|
||||
SpeechUtility.getUtility().setParameter(SpeechConstant.VOLUME,"100");
|
||||
SpeechUtility.getUtility().setParameter(SpeechConstant.LIB_NAME_64,"/media/yutou/4t/public/servier/tools/");
|
||||
SpeechUtility.getUtility().setParameter(SpeechConstant.LIB_NAME_32,"/media/yutou/4t/public/servier/tools/");
|
||||
init = true;
|
||||
System.out.println("讯飞语音已初始化");
|
||||
}
|
||||
|
||||
public static void playText(String text) {
|
||||
SpeechSynthesizer mss = SpeechSynthesizer.createSynthesizer();
|
||||
mss.startSpeaking(text, new SynthesizerListener() {
|
||||
@Override
|
||||
public void onBufferProgress(int progress, int beginPos, int endPos,
|
||||
String info) {
|
||||
if (progress == 100) {
|
||||
mss.destroy();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSpeakBegin() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSpeakProgress(int i, int i1, int i2) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSpeakPaused() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onSpeakResumed() {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onCompleted(SpeechError speechError) {
|
||||
System.out.println(speechError.getErrorDesc() + " code " + speechError.getErrorCode());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onEvent(int i, int i1, int i2, int i3, Object o, Object o1) {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
init();
|
||||
playText("小爱同学,开灯");
|
||||
}
|
||||
}
|
||||
86
src/main/java/com/yutou/nas/utils/ConfigTools.java
Normal file
86
src/main/java/com/yutou/nas/utils/ConfigTools.java
Normal file
@@ -0,0 +1,86 @@
|
||||
package com.yutou.nas.utils;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
|
||||
import java.io.*;
|
||||
|
||||
/**
|
||||
* 配置和参数
|
||||
*/
|
||||
public class ConfigTools {
|
||||
public static final String CONFIG="config.json";
|
||||
public static final String DATA="data.json";
|
||||
public static final String SQLITE="sqlite.json";
|
||||
static {
|
||||
try {
|
||||
File file=new File(CONFIG);
|
||||
if(!file.exists()){
|
||||
file.createNewFile();
|
||||
}
|
||||
file=new File(DATA);
|
||||
if(!file.exists()){
|
||||
file.createNewFile();
|
||||
}
|
||||
file=null;
|
||||
}catch (Exception e){
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
public static Object load(String type,String key){
|
||||
File file=new File(type);
|
||||
//System.out.println(type+"配置文件地址:"+file.getAbsolutePath());
|
||||
String src=readFile(file);
|
||||
if(src!=null){
|
||||
try {
|
||||
JSONObject json=JSONObject.parseObject(src);
|
||||
if(json==null){
|
||||
json=new JSONObject();
|
||||
saveFile(file,json.toJSONString());
|
||||
}
|
||||
return json.getOrDefault(key, "");
|
||||
}catch (Exception e){
|
||||
return "";
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
public static boolean save(String type,String key,Object data){
|
||||
File file=new File(type);
|
||||
String src=readFile(file);
|
||||
if(src==null){
|
||||
src="{}";
|
||||
}
|
||||
JSONObject json=JSONObject.parseObject(src);
|
||||
json.put(key,data);
|
||||
saveFile(file,json.toJSONString());
|
||||
return false;
|
||||
}
|
||||
public static boolean saveFile(File file,String data){
|
||||
try {
|
||||
FileWriter writer=new FileWriter(file);
|
||||
writer.write(data);
|
||||
writer.flush();
|
||||
writer.close();
|
||||
return true;
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
public static String readFile(File file){
|
||||
try {
|
||||
BufferedReader reader=new BufferedReader(new FileReader(file));
|
||||
String tmp;
|
||||
StringBuilder str= new StringBuilder();
|
||||
while ((tmp=reader.readLine())!=null){
|
||||
str.append(tmp);
|
||||
}
|
||||
reader.close();
|
||||
return str.toString();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
27
src/main/java/com/yutou/nas/utils/CorsConfig.java
Normal file
27
src/main/java/com/yutou/nas/utils/CorsConfig.java
Normal file
@@ -0,0 +1,27 @@
|
||||
package com.yutou.nas.utils;
|
||||
|
||||
import org.springframework.boot.web.servlet.FilterRegistrationBean;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
import org.springframework.web.filter.CorsFilter;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
@Configuration
|
||||
public class CorsConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
// 设置允许跨域请求的域名
|
||||
.allowedOriginPatterns("*")
|
||||
// 是否允许证书(cookies)
|
||||
.allowCredentials(true)
|
||||
// 设置允许的方法
|
||||
.allowedMethods("*")
|
||||
// 跨域允许时间
|
||||
.maxAge(3600);
|
||||
}
|
||||
}
|
||||
132
src/main/java/com/yutou/nas/utils/HttpTools.java
Normal file
132
src/main/java/com/yutou/nas/utils/HttpTools.java
Normal file
@@ -0,0 +1,132 @@
|
||||
package com.yutou.nas.utils;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.yutou.nas.utils.Interfaces.NetworkInterface;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Set;
|
||||
|
||||
public class HttpTools {
|
||||
public static String get(String url) {
|
||||
try {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
connection.setRequestProperty("User-Agent", getKuKuUA());
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
StringBuilder str = new StringBuilder();
|
||||
String tmp;
|
||||
while ((tmp = reader.readLine()) != null) {
|
||||
str.append(tmp);
|
||||
}
|
||||
reader.close();
|
||||
connection.disconnect();
|
||||
return str.toString();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static void post(final String url, final byte[] body, final NetworkInterface networkInterface) {
|
||||
|
||||
new Thread(new Runnable() {
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
String tmp;
|
||||
StringBuilder str = new StringBuilder();
|
||||
try {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
connection.setRequestMethod("POST");
|
||||
connection.setDoOutput(true);
|
||||
connection.setDoInput(true);
|
||||
connection.setConnectTimeout(5 * 1000);
|
||||
connection.setReadTimeout(10 * 1000);
|
||||
//connection.addRequestProperty("Connection", "keep-alive");
|
||||
//connection.addRequestProperty("User-Agent", getExtUa());
|
||||
//connection.addRequestProperty("content-type", "application/json");
|
||||
connection.addRequestProperty("charset", "UTF-8");
|
||||
OutputStream outputStream = connection.getOutputStream();
|
||||
|
||||
outputStream.write(body);
|
||||
outputStream.flush();
|
||||
outputStream.close();
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
|
||||
while ((tmp = reader.readLine()) != null) {
|
||||
str.append(tmp);
|
||||
}
|
||||
final String finalStr = str.toString();
|
||||
|
||||
// Log.i(TAG + "[" + url + "?" + toGetSplice(body) + "]", "body:" + str + " (" + connection.getResponseCode() + ")");
|
||||
if (networkInterface != null) {
|
||||
try {
|
||||
networkInterface.httpGetData(str.toString(), connection.getResponseCode());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
connection.disconnect();
|
||||
reader.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}).start();
|
||||
}
|
||||
|
||||
private static String getExtUa() {
|
||||
return "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36";
|
||||
}
|
||||
|
||||
private static String getKuKuUA() {
|
||||
return "/KUKU_APP(Android/#/cn.kuku.sdk/ttsdk17228/29401/A-2.9.4.01.KUSDK/868139039134314/fcddf839c8c135fa/F4:60:E2:AB:25:1A/460019406520644/+8618569400341/#/9/Redmi 6 Pro/xiaomi/1736/76fda4d6-cd6b-485f-987b-8d347b007f24/#/KUKU/Native/92972ea9651fbd2e)";
|
||||
}
|
||||
|
||||
public String toUrlParams(JSONObject json) {
|
||||
StringBuilder string = new StringBuilder();
|
||||
Set<String> keys = json.keySet();
|
||||
for (String key : keys) {
|
||||
try {
|
||||
string.append("&").append(key).append("=").append(URLEncoder.encode(json.getString(key), "UTF-8"));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
try {
|
||||
string.append("&").append(URLEncoder.encode(key, "UTF-8")).append("=");
|
||||
// string += "&" + key + "=";
|
||||
} catch (Exception e1) {
|
||||
string.append("&").append(key).append("=");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
string = new StringBuilder(string.substring(1, string.length()).replaceAll(" ", ""));
|
||||
return string.toString();
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
JSONObject json = new JSONObject();
|
||||
json.put("pid", "102");
|
||||
json.put("gid", "100584");
|
||||
json.put("gameKey", "0gha58u1c9FjZkeAsEmYIzTvp");
|
||||
json.put("access_token", "659c-S1gV0DwMXdYjPDlSrSLNYOvA8qUoCSvmdFEHvZugKgNX4Z2BCwF18A7W2gRdG7WiWfKsbZgF6YssZHhaozksI9RBn2QQFTXzmAHtbMd4ginEEtwdKmPCM4JbJGg1ollqoNE0PcGENpa4F3e7EdSOa_JFyE6XyUQN1iurJU3F8MZfLlTIcTR9USYoHX15vsAkCht_0mrapZblkeY1_8HFrmK8rlenbZLxccy7PrMz5eZ9uPPDJL5OYiEahyrtLENB8SVmlGofJfQw8wUjN8_XVZSfLMujdwz24");
|
||||
String url = "http://192.168.1.156:9020/Faxing/reg?" +
|
||||
"&tpyeCode=dimai" +
|
||||
"®ParamJson=" + json.toJSONString();
|
||||
/* ExecutorService service= Executors.newCachedThreadPool();
|
||||
for (int i = 0; i < 3000; i++) {
|
||||
service.submit(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
get(url);
|
||||
}
|
||||
});
|
||||
}*/
|
||||
System.out.println(url);
|
||||
//String str=get(url);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package com.yutou.nas.utils.Interfaces;
|
||||
|
||||
|
||||
import com.yutou.nas.mybatis.model.MusicData;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface IMusicToolsService {
|
||||
void init();
|
||||
|
||||
void scanMusic();
|
||||
|
||||
List<MusicData> getPath(String path, boolean isDir);
|
||||
|
||||
MusicData getMusicData(String md5);
|
||||
|
||||
List<MusicData> findOfTitle(String title);
|
||||
|
||||
List<MusicData> findOfArtist(String by);
|
||||
|
||||
List<MusicData> getMusicList();
|
||||
|
||||
int getLength();
|
||||
|
||||
boolean isScan();
|
||||
|
||||
String getMusicPath();
|
||||
|
||||
byte[] readImage(String path) throws Exception;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.yutou.nas.utils.Interfaces;
|
||||
|
||||
public interface NetworkInterface {
|
||||
/**
|
||||
* 请求成功
|
||||
* @param data 请求参数
|
||||
* @param state http状态
|
||||
*/
|
||||
void httpGetData(Object data, int state);
|
||||
|
||||
/**
|
||||
* 请求异常
|
||||
* @param e 异常
|
||||
*/
|
||||
void httpError(Exception e);
|
||||
}
|
||||
545
src/main/java/com/yutou/nas/utils/MusicToolsServiceImpl.java
Normal file
545
src/main/java/com/yutou/nas/utils/MusicToolsServiceImpl.java
Normal file
@@ -0,0 +1,545 @@
|
||||
package com.yutou.nas.utils;
|
||||
|
||||
import com.yutou.nas.Datas.AppData;
|
||||
import com.yutou.nas.mybatis.dao.MusicDataDao;
|
||||
import com.yutou.nas.mybatis.model.MusicData;
|
||||
import com.yutou.nas.mybatis.model.MusicDataExample;
|
||||
import com.yutou.nas.utils.Interfaces.IMusicToolsService;
|
||||
|
||||
import ealvatag.audio.AudioFile;
|
||||
import ealvatag.audio.AudioFileIO;
|
||||
import ealvatag.audio.AudioHeader;
|
||||
import ealvatag.tag.FieldKey;
|
||||
import ealvatag.tag.NullTag;
|
||||
import ealvatag.tag.Tag;
|
||||
import ealvatag.tag.images.NullArtwork;
|
||||
import net.bramp.ffmpeg.FFprobe;
|
||||
import net.bramp.ffmpeg.probe.FFmpegFormat;
|
||||
import net.bramp.ffmpeg.probe.FFmpegProbeResult;
|
||||
import net.bramp.ffmpeg.probe.FFmpegStream;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.util.StringUtils;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
|
||||
@Service("MusicToolsService")
|
||||
public class MusicToolsServiceImpl implements IMusicToolsService {
|
||||
public static final int FIND_TITLE = 1;
|
||||
public static final int FIND_ARTIST = 2;
|
||||
|
||||
private String musicPath = "/media/yutou/4t/public/音乐";
|
||||
private boolean isScan = false;
|
||||
|
||||
@Resource
|
||||
MusicDataDao musicDataDao;
|
||||
|
||||
@Override
|
||||
public void init() {
|
||||
musicPath = (String) ConfigTools.load(ConfigTools.CONFIG, "musicDir");
|
||||
scanMusic();
|
||||
}
|
||||
|
||||
@Override
|
||||
public void scanMusic() {
|
||||
if (isScan) {
|
||||
return;
|
||||
}
|
||||
if (ConfigTools.load(ConfigTools.CONFIG, "musicScan").equals("false")) {
|
||||
return;
|
||||
}
|
||||
musicPath = (String) ConfigTools.load(ConfigTools.CONFIG, "musicDir");
|
||||
musicDataDao.truncate();
|
||||
System.out.println("执行扫描:" + musicPath);
|
||||
new Thread(() -> {
|
||||
long startTime = System.currentTimeMillis();
|
||||
QQBotManager.getInstance().sendMessage("开始扫描音乐夹");
|
||||
isScan = true;
|
||||
scan(new File(musicPath));
|
||||
isScan = false;
|
||||
System.out.println("扫描完成");
|
||||
QQBotManager.getInstance().sendMessage("音乐扫描完成,共" + getLength() + "首歌,耗时:"
|
||||
+ (System.currentTimeMillis() - startTime));
|
||||
}).start();
|
||||
}
|
||||
|
||||
|
||||
private void scan(File path) {
|
||||
if (path.isFile()) {
|
||||
add(path);
|
||||
} else if (path.isDirectory()) {
|
||||
for (File file : Objects.requireNonNull(path.listFiles())) {
|
||||
if (file.isDirectory()) {
|
||||
scan(file);
|
||||
} else {
|
||||
add(file);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void getPathOrDir(String path, List<MusicData> list) {
|
||||
File files = new File(path);
|
||||
for (File file : files.listFiles()) {
|
||||
if (file.isFile()) {
|
||||
list.add(getMetadata(file));
|
||||
} else {
|
||||
getPathOrDir(file.getAbsolutePath(), list);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取指定目录下的音乐
|
||||
*
|
||||
* @param path 指定目录
|
||||
* @param isDir 是否扫描目录下的所有文件,false则仅为当前目录
|
||||
* @return 音乐列表
|
||||
*/
|
||||
@Override
|
||||
public List<MusicData> getPath(String path, boolean isDir) {
|
||||
List<MusicData> list = new ArrayList<>();
|
||||
List<MusicData> main = new ArrayList<>();
|
||||
MusicDataExample example = new MusicDataExample();
|
||||
String replacement = ConfigTools.load(ConfigTools.CONFIG, "os").equals("windows") ? "\\\\" : "/";
|
||||
String tmpPath = path;
|
||||
if (isDir) {
|
||||
example.createCriteria().andFileLike(tmpPath.replace(File.separator, replacement) + "%");
|
||||
main = musicDataDao.selectByExample(example);
|
||||
}
|
||||
tmpPath = tmpPath.replace(File.separator, replacement)
|
||||
.replace("[", "\\[")
|
||||
.replace("(", "\\(")
|
||||
.replace(")", "\\)")
|
||||
.replace("]", "\\]");
|
||||
main.addAll(musicDataDao.selectByRegexp(tmpPath + replacement + "([^" + replacement + "]+)$"));
|
||||
|
||||
if (!path.equals(AppData.defaultMusicPath) && !path.equals("root")) {
|
||||
MusicData t2 = new MusicData();
|
||||
t2.setTitle("返回");
|
||||
if (main.isEmpty()) {
|
||||
t2.setFile("root");
|
||||
} else {
|
||||
MusicData tmp = main.get(0);
|
||||
t2.setFile(new File(tmp.getLastdir()).getAbsolutePath());
|
||||
}
|
||||
System.out.println("查询地址:" + path + " 设置返回地址:" + t2.getFile());
|
||||
t2.setIsdir(1);
|
||||
list.add(t2);
|
||||
}
|
||||
getDirList(path, list);
|
||||
list.addAll(main);
|
||||
return list;
|
||||
}
|
||||
|
||||
public List<String> getAllAlbum() {
|
||||
return musicDataDao.selectAllAlbum();
|
||||
}
|
||||
|
||||
public List<String> getAllArtist() {
|
||||
return musicDataDao.selectAllArtist();
|
||||
}
|
||||
|
||||
public List<MusicData> selectAlbum(String album) {
|
||||
return musicDataDao.selectAlbum(album);
|
||||
}
|
||||
|
||||
public List<MusicData> selectArtist(String artist) {
|
||||
return musicDataDao.selectArtist(artist);
|
||||
}
|
||||
|
||||
private void getDirList(String path, List<MusicData> list) {
|
||||
File file = new File(path);
|
||||
System.out.println("扫描文件:"+path);
|
||||
if(file.isDirectory()) {
|
||||
for (File listFile : file.listFiles()) {
|
||||
if (listFile.isDirectory()) {
|
||||
MusicData data = new MusicData();
|
||||
data.setTitle(listFile.getName());
|
||||
data.setIsdir(1);
|
||||
data.setFile(listFile.getAbsolutePath());
|
||||
list.add(data);
|
||||
}
|
||||
}
|
||||
}else{
|
||||
MusicData data = new MusicData();
|
||||
data.setTitle(file.getName());
|
||||
data.setIsdir(0);
|
||||
data.setFile(file.getAbsolutePath());
|
||||
list.add(data);
|
||||
}
|
||||
}
|
||||
|
||||
private void add(File file) {
|
||||
MusicData data = getMetadata(file);
|
||||
if (data != null) {
|
||||
try {
|
||||
musicDataDao.insert(data);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
QQBotManager.getInstance().sendMessage("音乐文件添加失败:" + data.toString());
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public MusicData getMusicData(String path) {
|
||||
MusicDataExample example = new MusicDataExample();
|
||||
example.createCriteria().andFileEqualTo(path);
|
||||
List<MusicData> list = musicDataDao.selectByExample(example);
|
||||
if (list != null && list.size() > 0) {
|
||||
return list.get(0);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public MusicData getMetadata(File file) {
|
||||
try {
|
||||
if (file.getName().endsWith(".lrc")
|
||||
|| file.getName().endsWith(".jpg")
|
||||
|| file.getName().endsWith(".ini")
|
||||
|| file.getName().endsWith(".png")
|
||||
|| file.getName().endsWith(".torrent")
|
||||
|| file.getName().endsWith(".log")
|
||||
|| file.getName().endsWith(".mkv")
|
||||
|| file.getName().endsWith(".dff")
|
||||
|| file.getName().endsWith(".cue")
|
||||
|| file.getName().endsWith(".m3u")
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
AudioFile audioFile = AudioFileIO.read(file);
|
||||
Tag tag = audioFile.getTag().or(NullTag.INSTANCE);
|
||||
MusicData data = new MusicData();
|
||||
try {
|
||||
data.setAlbum(tag.getFirst(FieldKey.ALBUM));
|
||||
} catch (Exception e) {
|
||||
}
|
||||
try {
|
||||
data.setArtist(tag.getFirst(FieldKey.ARTIST));
|
||||
} catch (Exception e) {
|
||||
}
|
||||
try {
|
||||
data.setArtistSort(tag.getFirst(FieldKey.ARTIST_SORT));
|
||||
} catch (Exception e) {
|
||||
}
|
||||
try {
|
||||
data.setComment(tag.getFirst(FieldKey.COMMENT));
|
||||
} catch (Exception e) {
|
||||
}
|
||||
try {
|
||||
data.setComposer(tag.getFirst(FieldKey.COMPOSER));
|
||||
} catch (Exception e) {
|
||||
}
|
||||
try {
|
||||
data.setDiscNo(tag.getFirst(FieldKey.DISC_NO));
|
||||
} catch (Exception e) {
|
||||
}
|
||||
try {
|
||||
if (StringUtils.isEmpty(tag.getFirst(FieldKey.TITLE))) {
|
||||
data.setTitle(file.getName());
|
||||
} else {
|
||||
data.setTitle(tag.getFirst(FieldKey.TITLE));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
data.setTitle(file.getName());
|
||||
}
|
||||
try {
|
||||
data.setTrack(tag.getFirst(FieldKey.TRACK));
|
||||
} catch (Exception e) {
|
||||
}
|
||||
try {
|
||||
data.setYear(tag.getFirst(FieldKey.YEAR));
|
||||
} catch (Exception e) {
|
||||
}
|
||||
data.setFile(file.getAbsolutePath());
|
||||
data.setIsdir(file.isDirectory() ? 1 : 0);
|
||||
data.setLastdir(file.getParentFile().getParent());
|
||||
|
||||
AudioHeader header = audioFile.getAudioHeader();
|
||||
data.setBitrate(header.getBitRate());
|
||||
data.setSamplerate(header.getSampleRate());
|
||||
data.setNoofsamples(header.getNoOfSamples());
|
||||
data.setChannelcount(header.getChannelCount());
|
||||
data.setEncodingtype(header.getEncodingType());
|
||||
data.setDurationasdouble(header.getDurationAsDouble());
|
||||
data.setLossless(header.isLossless() ? 1 : 0);
|
||||
data.setVariablebitrate(header.isVariableBitRate() ? 1 : 0);
|
||||
try {
|
||||
data.setMd5(header.getClass().getMethod("getMd5").invoke(header).toString());
|
||||
} catch (Exception ignored) {
|
||||
data.setMd5(Tools.getFileMD5(file));
|
||||
}
|
||||
return data;
|
||||
} catch (IOException e) {
|
||||
return getMetadata_jthink(file);
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public MusicData getMetadata_jthink(File file) {
|
||||
try {
|
||||
org.jaudiotagger.audio.AudioFile audioFile = org.jaudiotagger.audio.AudioFileIO.read(file);
|
||||
org.jaudiotagger.tag.Tag tag = audioFile.getTag();
|
||||
MusicData data = new MusicData();
|
||||
try {
|
||||
data.setAlbum(tag.getFirst(org.jaudiotagger.tag.FieldKey.ALBUM));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
data.setArtist(tag.getFirst(org.jaudiotagger.tag.FieldKey.ARTIST));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
data.setArtistSort(tag.getFirst(org.jaudiotagger.tag.FieldKey.ARTIST_SORT));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
data.setComment(tag.getFirst(org.jaudiotagger.tag.FieldKey.COMMENT));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
data.setComposer(tag.getFirst(org.jaudiotagger.tag.FieldKey.COMPOSER));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
data.setDiscNo(tag.getFirst(org.jaudiotagger.tag.FieldKey.DISC_NO));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
if (StringUtils.isEmpty(tag.getFirst(org.jaudiotagger.tag.FieldKey.TITLE))) {
|
||||
data.setTitle(file.getName());
|
||||
} else {
|
||||
data.setTitle(tag.getFirst(org.jaudiotagger.tag.FieldKey.TITLE));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
data.setTitle(file.getName());
|
||||
}
|
||||
try {
|
||||
data.setTrack(tag.getFirst(org.jaudiotagger.tag.FieldKey.TRACK));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
try {
|
||||
data.setYear(tag.getFirst(org.jaudiotagger.tag.FieldKey.YEAR));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
data.setFile(file.getAbsolutePath());
|
||||
data.setIsdir(file.isDirectory() ? 1 : 0);
|
||||
data.setLastdir(file.getParentFile().getParent());
|
||||
|
||||
org.jaudiotagger.audio.AudioHeader header = audioFile.getAudioHeader();
|
||||
data.setBitrate(Integer.parseInt(header.getBitRate()));
|
||||
data.setSamplerate(Integer.parseInt(header.getSampleRate()));
|
||||
data.setNoofsamples(Long.parseLong(header.getSampleRateAsNumber() + ""));
|
||||
data.setChannelcount(Integer.parseInt(header.getChannels()));
|
||||
data.setEncodingtype(header.getEncodingType() + "");
|
||||
data.setDurationasdouble(Double.parseDouble(header.getTrackLength() + ""));
|
||||
data.setLossless(header.isLossless() ? 1 : 0);
|
||||
data.setVariablebitrate(header.isVariableBitRate() ? 1 : 0);
|
||||
try {
|
||||
data.setMd5(header.getClass().getMethod("getMd5").invoke(header).toString());
|
||||
} catch (Exception ignored) {
|
||||
data.setMd5(Tools.getFileMD5(file));
|
||||
}
|
||||
return data;
|
||||
} catch (Exception e) {
|
||||
return getMetadataOfFFmpeg(file);
|
||||
}
|
||||
}
|
||||
|
||||
private MusicData getMetadataOfFFmpeg(File file) {
|
||||
MusicData data;
|
||||
try {
|
||||
data = new MusicData();
|
||||
FFprobe fFprobe = new FFprobe((String) ConfigTools.load(ConfigTools.CONFIG, "ffprobe"));
|
||||
FFmpegProbeResult result = fFprobe.probe(file.getAbsolutePath());
|
||||
FFmpegFormat format = result.getFormat();
|
||||
FFmpegStream stream = null;
|
||||
for (FFmpegStream tmp : result.getStreams()) {
|
||||
if (tmp.index == 0) {
|
||||
stream = tmp;
|
||||
}
|
||||
}
|
||||
Map<String, String> tag = format.tags;
|
||||
data.setTitle(getTitle(tag));
|
||||
data.setAlbum(getAlbum(tag));
|
||||
data.setArtist(getArtist(tag));
|
||||
data.setDiscNo(tag.get("disc") == null ? tag.get("disc".toUpperCase()) : tag.get("disc"));
|
||||
data.setTrack(tag.get("track") == null ? tag.get("track".toUpperCase()) : tag.get("track"));
|
||||
data.setYear(getYear(tag));
|
||||
data.setArtistSort(tag.get("album_artist") == null ? tag.get("album_artist".toUpperCase()) : tag.get("album_artist"));
|
||||
data.setDurationasdouble(format.duration);
|
||||
data.setBitrate((int) (format.bit_rate / 1000));
|
||||
if (stream != null) {
|
||||
if (data.getBitrate() == 0)
|
||||
data.setBitrate((int) (stream.bit_rate / 1000));
|
||||
data.setChannelcount(stream.channels);
|
||||
data.setLossless(0);
|
||||
data.setSamplerate(stream.sample_rate);
|
||||
data.setNoofsamples(stream.duration_ts);
|
||||
}
|
||||
data.setEncodingtype(format.format_long_name);
|
||||
data.setComment("");
|
||||
data.setComposer("");
|
||||
data.setVariablebitrate(0);
|
||||
data.setFile(file.getAbsolutePath());
|
||||
data.setLastdir(file.getParentFile().getParent());
|
||||
data.setIsdir(file.isDirectory() ? 1 : 0);
|
||||
if (data.getYear() == null) {
|
||||
data.setYear("0000");
|
||||
}
|
||||
data.setMd5(Tools.getFileMD5(file));
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
data = new MusicData();
|
||||
data.setTitle(file.getName());
|
||||
data.setFile(file.getAbsolutePath());
|
||||
data.setIsdir(file.isDirectory() ? 1 : 0);
|
||||
data.setLastdir(file.getParentFile().getParent());
|
||||
data.setMd5(Tools.getFileMD5(file));
|
||||
QQBotManager.getInstance().sendMessage("添加音乐文件失败:\n" + data.toString() + "\n" + Tools.getExceptionString(e));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private String getTitle(Map<String, String> tag) {
|
||||
String title = tag.get("title");
|
||||
if (StringUtils.isEmpty(title)) {
|
||||
title = tag.get("TITLE");
|
||||
if (StringUtils.isEmpty(title)) {
|
||||
title = tag.get("Title");
|
||||
}
|
||||
}
|
||||
return title;
|
||||
}
|
||||
|
||||
private String getArtist(Map<String, String> tag) {
|
||||
String title = tag.get("artist");
|
||||
if (StringUtils.isEmpty(title)) {
|
||||
title = tag.get("ARTIST");
|
||||
if (StringUtils.isEmpty(title)) {
|
||||
title = tag.get("Artist");
|
||||
}
|
||||
}
|
||||
return title;
|
||||
}
|
||||
|
||||
private String getAlbum(Map<String, String> tag) {
|
||||
String title = tag.get("album");
|
||||
if (StringUtils.isEmpty(title)) {
|
||||
title = tag.get("ALBUM");
|
||||
if (StringUtils.isEmpty(title)) {
|
||||
title = tag.get("Album");
|
||||
}
|
||||
}
|
||||
return title;
|
||||
}
|
||||
|
||||
private String getYear(Map<String, String> tag) {
|
||||
String title = tag.get("year");
|
||||
if (StringUtils.isEmpty(title)) {
|
||||
title = tag.get("YEAR");
|
||||
if (StringUtils.isEmpty(title)) {
|
||||
title = tag.get("Year");
|
||||
}
|
||||
}
|
||||
return title;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MusicData> findOfTitle(String title) {
|
||||
return find(title, FIND_TITLE);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<MusicData> findOfArtist(String by) {
|
||||
return find(by, FIND_ARTIST);
|
||||
}
|
||||
|
||||
public List<MusicData> getMusicList() {
|
||||
return musicDataDao.selectByExample(new MusicDataExample());
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getLength() {
|
||||
return musicDataDao.selectByExample(new MusicDataExample()).size();
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isScan() {
|
||||
return isScan;
|
||||
}
|
||||
|
||||
private List<MusicData> find(String title, int type) {
|
||||
List<MusicData> list;
|
||||
MusicDataExample example = new MusicDataExample();
|
||||
if (type == FIND_TITLE) {
|
||||
example.createCriteria().andTitleEqualTo(title);
|
||||
} else if (type == FIND_ARTIST) {
|
||||
example.createCriteria().andArtistEqualTo(title);
|
||||
}
|
||||
list = musicDataDao.selectByExample(example);
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getMusicPath() {
|
||||
return musicPath;
|
||||
}
|
||||
|
||||
public void setMusicPath(String musicPath) {
|
||||
this.musicPath = musicPath;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] readImage(String path) throws Exception {
|
||||
File file = new File(path);
|
||||
AudioFile audioFile = null;
|
||||
audioFile = AudioFileIO.read(file);
|
||||
Tag tag = audioFile.getTag().or(NullTag.INSTANCE);
|
||||
byte[] bytes = tag.getFirstArtwork().or(NullArtwork.INSTANCE).getBinaryData();
|
||||
if (bytes.length == 0) {
|
||||
return readImageFile(file);
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
private byte[] readImageFile(File file) throws Exception {
|
||||
String path = file.getAbsolutePath().replace(file.getName(), "");
|
||||
File img = new File(path, "cover.jpg");
|
||||
if (!img.exists()) {
|
||||
img = new File(path, "Cover.jpg");
|
||||
if (!img.exists()) {
|
||||
img = new File(path, "COVER.jpg");
|
||||
if (!img.exists()) {
|
||||
throw new NullPointerException("没有cover文件");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Files.readAllBytes(Paths.get(img.getAbsolutePath()));
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
File file = new File("Z:\\音乐\\总之就是非常酸\\ED\\カノエラナ - 月と星空\\カノエラナ.wav");
|
||||
file = new File("Z:\\音乐\\终将成为你\\[OP]君にふれて\\rise.flac");
|
||||
// file = new File("Z:\\音乐\\周董\\2012 十二新作\\03 公公偏头痛.ape");
|
||||
System.out.println(new MusicToolsServiceImpl().getMetadataOfFFmpeg(file));
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
339
src/main/java/com/yutou/nas/utils/QQBotManager.java
Normal file
339
src/main/java/com/yutou/nas/utils/QQBotManager.java
Normal file
@@ -0,0 +1,339 @@
|
||||
package com.yutou.nas.utils;
|
||||
|
||||
import com.yutou.nas.NasApplication;
|
||||
import com.yutou.nas.bangumi.BangumiTools;
|
||||
import com.yutou.nas.interfaces.DownloadInterface;
|
||||
import com.yutou.nas.other.QQAudio;
|
||||
import com.yutou.nas.other.QQSetu;
|
||||
import net.mamoe.mirai.Bot;
|
||||
import net.mamoe.mirai.BotFactory;
|
||||
import net.mamoe.mirai.event.GlobalEventChannel;
|
||||
import net.mamoe.mirai.event.events.GroupMessageEvent;
|
||||
import net.mamoe.mirai.message.data.Image;
|
||||
import net.mamoe.mirai.message.data.MessageChainBuilder;
|
||||
import net.mamoe.mirai.utils.BotConfiguration;
|
||||
import net.mamoe.mirai.utils.ExternalResource;
|
||||
|
||||
import java.io.File;
|
||||
import java.lang.reflect.Field;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.function.Consumer;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class QQBotManager {
|
||||
|
||||
|
||||
private static class QQCommands {
|
||||
private final static String QQ_HELP = "!help";
|
||||
private final static String QQ_UPDATE_IP = "!更新ip";
|
||||
private final static String QQ_GET_IP = "!ip";
|
||||
private final static String QQ_OPEN_PC = "!开机";
|
||||
private final static String QQ_GET_VERSION = "!version";
|
||||
private final static String QQ_CMD = "!cmd";
|
||||
private final static String QQ_BANGUMI_TODAY = "!今日动画";
|
||||
private final static String QQ_BANGUMI_LIST = "!新番";
|
||||
private final static String QQ_BANGUMI_SUB = "!查动画";
|
||||
private final static String QQ_AUDIO = "!语音";
|
||||
private final static String QQ_AUDIO_OPEN_LAMP = "!开灯";
|
||||
private final static String QQ_AUDIO_OPEN_AIR = "!开空调";
|
||||
}
|
||||
|
||||
private static QQBotManager botManager = null;
|
||||
private Bot bot;
|
||||
private static final long qqGroup = 891655174L;
|
||||
private boolean isLogin = false;
|
||||
private static boolean isInit = false;
|
||||
|
||||
|
||||
private QQBotManager() {
|
||||
Object isRun = ConfigTools.load(ConfigTools.CONFIG, "qq_bot");
|
||||
if (isRun != null && (boolean) isRun) {
|
||||
isLogin = true;
|
||||
isInit = true;
|
||||
init();
|
||||
}
|
||||
}
|
||||
|
||||
private void init() {
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
long qq = 2476945931L;
|
||||
String password = "zhang34864394";
|
||||
if (ConfigTools.load(ConfigTools.CONFIG, "model").equals("dev")) {
|
||||
qq = 3620756944L;
|
||||
password = "UAs6YBYMyxJU";
|
||||
}
|
||||
|
||||
bot = BotFactory.INSTANCE.newBot(qq, password, new BotConfiguration() {
|
||||
{
|
||||
setProtocol(MiraiProtocol.ANDROID_PAD);
|
||||
fileBasedDeviceInfo("qq_bot_devices_info.json");
|
||||
if (ConfigTools.load(ConfigTools.CONFIG, "model").equals("nas")) {
|
||||
noBotLog();
|
||||
noNetworkLog();
|
||||
}
|
||||
}
|
||||
});
|
||||
//Events.registerEvents(bot, new MessageListener());
|
||||
GlobalEventChannel.INSTANCE.subscribeAlways(GroupMessageEvent.class, new MessageListener());
|
||||
bot.login();
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
String str = sendMessage("姬妻酱上线拉~");
|
||||
System.out.println(str);
|
||||
|
||||
}
|
||||
}).start();
|
||||
bot.join();
|
||||
|
||||
}
|
||||
}).start();
|
||||
|
||||
}
|
||||
|
||||
public static QQBotManager getInstance() {
|
||||
if (botManager == null && !isInit) {
|
||||
botManager = new QQBotManager();
|
||||
}
|
||||
return botManager;
|
||||
}
|
||||
|
||||
public boolean isLogin() {
|
||||
return isLogin;
|
||||
}
|
||||
|
||||
private Image getImage(File file) {
|
||||
if (bot != null) {
|
||||
return Objects.requireNonNull(bot.getGroup(qqGroup)).uploadImage(ExternalResource.create(file));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String getNotLoginQQ() {
|
||||
return "没有登录QQ";
|
||||
}
|
||||
|
||||
public void reportToDayBangumi() {
|
||||
getInstance().sendMessage(BangumiTools.reportToDayBangumi());
|
||||
}
|
||||
|
||||
public String sendMessage(String text) {
|
||||
if (bot != null) {
|
||||
try {
|
||||
return Objects.requireNonNull(bot.getGroup(qqGroup)).sendMessage(text).toString();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return getNotLoginQQ();
|
||||
}
|
||||
|
||||
public String sendMessage(Long group, String text) {
|
||||
if (bot != null) {
|
||||
try {
|
||||
return Objects.requireNonNull(bot.getGroup(group)).sendMessage(text).toString();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
return getNotLoginQQ();
|
||||
}
|
||||
|
||||
public void sendMessage(Long group, MessageChainBuilder builder) {
|
||||
if (bot != null) {
|
||||
Objects.requireNonNull(bot.getGroup(group)).sendMessage(builder.asMessageChain());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public String sendMessage(File imageFile, String text) {
|
||||
try {
|
||||
if (bot != null) {
|
||||
Image image = getImage(imageFile);
|
||||
MessageChainBuilder builder = new MessageChainBuilder();
|
||||
if (image != null) {
|
||||
builder.append(image);
|
||||
}
|
||||
builder.append(text);
|
||||
return Objects.requireNonNull(bot.getGroup(qqGroup)).sendMessage(builder.asMessageChain()).toString();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
return getNotLoginQQ();
|
||||
}
|
||||
|
||||
public String sendMessage(List<File> imgs, String text) {
|
||||
if (bot != null) {
|
||||
MessageChainBuilder builder = new MessageChainBuilder();
|
||||
for (File img : imgs) {
|
||||
builder.append(Objects.requireNonNull(getImage(img)));
|
||||
}
|
||||
builder.append(text);
|
||||
return Objects.requireNonNull(bot.getGroup(qqGroup)).sendMessage(builder.asMessageChain()).toString();
|
||||
}
|
||||
return getNotLoginQQ();
|
||||
}
|
||||
|
||||
public static List<String> getImages(String str) {
|
||||
List<String> list = new ArrayList<>();
|
||||
String regex = "<img(.*?)/img>";
|
||||
Pattern pattern = Pattern.compile(regex);
|
||||
Matcher matcher = pattern.matcher(str);
|
||||
while (matcher.find()) {
|
||||
list.add(matcher.group().replace("<img", "")
|
||||
.replace("/img>", "")
|
||||
.trim());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
getInstance();
|
||||
}
|
||||
|
||||
private static class MessageListener implements Consumer<GroupMessageEvent> {
|
||||
|
||||
|
||||
@Override
|
||||
public void accept(GroupMessageEvent event) {
|
||||
String msg = event.getMessage().contentToString();
|
||||
switch (event.getGroup().getId() + "") {
|
||||
case qqGroup + "":
|
||||
myGroup(msg);
|
||||
case "570197155":
|
||||
new QQSetu().setu(msg, event);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
private void myGroup(String msg) {
|
||||
msg = msg.replace("!", "!").toLowerCase();
|
||||
switch (msg) {
|
||||
case QQCommands.QQ_OPEN_PC:
|
||||
RedisTools.Consumer.system("openPC", null);
|
||||
String time = new SimpleDateFormat("HH").format(new Date());
|
||||
if (Integer.parseInt(time) < 18) {
|
||||
break;
|
||||
}
|
||||
case QQCommands.QQ_AUDIO_OPEN_LAMP:
|
||||
QQAudio.playText("小爱同学,开灯");
|
||||
break;
|
||||
case QQCommands.QQ_AUDIO_OPEN_AIR:
|
||||
QQAudio.playText("小爱同学,开空调");
|
||||
break;
|
||||
case QQCommands.QQ_UPDATE_IP:
|
||||
RedisTools.Consumer.system("updateIP", null);
|
||||
break;
|
||||
case QQCommands.QQ_GET_IP:
|
||||
RedisTools.Consumer.bot("getip");
|
||||
break;
|
||||
case QQCommands.QQ_GET_VERSION:
|
||||
sendVersion();
|
||||
break;
|
||||
case QQCommands.QQ_BANGUMI_TODAY:
|
||||
QQBotManager.getInstance().sendMessage(BangumiTools.reportToDayBangumi());
|
||||
break;
|
||||
case QQCommands.QQ_BANGUMI_LIST:
|
||||
getInstance().sendMessage("获取中...");
|
||||
getInstance().sendMessage(BangumiTools.reportBangumiList());
|
||||
break;
|
||||
|
||||
case QQCommands.QQ_HELP:
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (Field field : QQCommands.class.getDeclaredFields()) {
|
||||
try {
|
||||
field.setAccessible(true);
|
||||
builder.append(field.get(null)).append("\n");
|
||||
} catch (IllegalAccessException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
getInstance().sendMessage(builder.toString());
|
||||
break;
|
||||
default:
|
||||
if (msg.startsWith(QQCommands.QQ_CMD)) {
|
||||
RedisTools.Consumer.system("cmd", msg.replace(QQCommands.QQ_CMD, ""));
|
||||
} else if (msg.startsWith(QQCommands.QQ_BANGUMI_SUB)) {
|
||||
String info = null;
|
||||
try {
|
||||
int id = Integer.parseInt(msg.replace(QQCommands.QQ_BANGUMI_SUB, "").trim());
|
||||
info = BangumiTools.reportBangumiInfo(id);
|
||||
} catch (Exception e) {
|
||||
String key = msg.replace(QQCommands.QQ_BANGUMI_SUB, "").trim();
|
||||
info = BangumiTools.reportSearchBangumi(key);
|
||||
}
|
||||
List<String> imgs = new ArrayList<>();
|
||||
if (info.contains("<img") && info.contains(" /img>")) {
|
||||
imgs = getImages(info);
|
||||
for (String img : imgs) {
|
||||
info = info.replace("<img " + img + " /img>", "");
|
||||
}
|
||||
}
|
||||
sendImagesMsg(imgs, info);
|
||||
} else if (msg.startsWith(QQCommands.QQ_AUDIO)) {
|
||||
QQAudio.playText(msg.replace(QQCommands.QQ_AUDIO, ""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
private List<File> files;
|
||||
private int index = 0;
|
||||
|
||||
private void sendImagesMsg(List<String> imgs, String text) {
|
||||
files = new ArrayList<>();
|
||||
index = 0;
|
||||
if (imgs.size() == 0) {
|
||||
getInstance().sendMessage(text);
|
||||
return;
|
||||
}
|
||||
for (String img : imgs) {
|
||||
Tools.download(img, new DownloadInterface() {
|
||||
@Override
|
||||
public void onDownload(String file) {
|
||||
super.onDownload(file);
|
||||
files.add(new File(file));
|
||||
send(imgs.size(), text);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Exception e) {
|
||||
super.onError(e);
|
||||
index++;
|
||||
send(imgs.size(), text);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private void send(int size, String text) {
|
||||
if ((files.size() + index) == size) {
|
||||
String str = getInstance().sendMessage(files, text);
|
||||
System.out.println("str = " + str);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendVersion() {
|
||||
String localVersion = NasApplication.version;
|
||||
String serverVersion = HttpTools.get("http://tools.yutou233.cn:8000/public/version.do?token=zIrsh9TUZP2lfRW753PannG49E7VJvor");
|
||||
String msg = "本地版本:" + localVersion + "\n" + "服务器版本:" + serverVersion;
|
||||
QQBotManager.getInstance().sendMessage(msg);
|
||||
Tools.sendServer("服务版本查询", msg);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
298
src/main/java/com/yutou/nas/utils/RedisTools.java
Normal file
298
src/main/java/com/yutou/nas/utils/RedisTools.java
Normal file
@@ -0,0 +1,298 @@
|
||||
package com.yutou.nas.utils;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisPoolConfig;
|
||||
import redis.clients.jedis.JedisPubSub;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.InputStreamReader;
|
||||
import java.util.Properties;
|
||||
import java.util.Set;
|
||||
|
||||
|
||||
public class RedisTools {
|
||||
private static boolean isNotInstallRedis = false;
|
||||
private static String host;
|
||||
private static int port;
|
||||
public static int TOKEN_TIMEOUT_DEFAULT = 360;
|
||||
|
||||
private RedisTools() {
|
||||
|
||||
}
|
||||
|
||||
// 写成静态代码块形式,只加载一次,节省资源
|
||||
static {
|
||||
//Properties properties = PropertyUtil.loadProperties("jedis.properties");
|
||||
//host = properties.getProperty("redis.host");
|
||||
//port = Integer.valueOf(properties.getProperty("redis.port"));
|
||||
host = "127.0.0.1";
|
||||
port = 6379;
|
||||
}
|
||||
|
||||
public static boolean set(int dbIndex, String key, String value) {
|
||||
try {
|
||||
if (isNotInstallRedis) {
|
||||
return false;
|
||||
}
|
||||
Jedis jedis = getRedis();
|
||||
jedis.select(dbIndex);
|
||||
String ret = jedis.set(key, value);
|
||||
System.out.println("Redis set =" + ret);
|
||||
jedis.close();
|
||||
} catch (Exception e) {
|
||||
// TODO: handle exception
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static boolean set(String key, String value) {
|
||||
return set(0, key, value);
|
||||
}
|
||||
|
||||
public static boolean set(String key, String value, int timeout) {
|
||||
try {
|
||||
if (isNotInstallRedis) {
|
||||
return false;
|
||||
}
|
||||
Jedis jedis = getRedis();
|
||||
if (timeout == -1) {
|
||||
jedis.set(key, value);
|
||||
} else {
|
||||
jedis.setex(key, timeout, value);
|
||||
}
|
||||
jedis.close();
|
||||
} catch (Exception e) {
|
||||
// TODO: handle exception
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static String get(String key, int dbIndex) {
|
||||
String value = "-999";
|
||||
if (isNotInstallRedis) {
|
||||
return value;
|
||||
}
|
||||
try (Jedis jedis = getRedis()) {
|
||||
jedis.select(dbIndex);
|
||||
value = jedis.get(key);
|
||||
jedis.close();
|
||||
} catch (Exception e) {
|
||||
// TODO: handle exception
|
||||
// e.printStackTrace();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
public static String get(String key) {
|
||||
return get(key, 0);
|
||||
}
|
||||
|
||||
public static boolean remove(String key) {
|
||||
return remove(key,0);
|
||||
}
|
||||
|
||||
public static void removeLoginState(String uid) {
|
||||
Jedis jedis = getRedis();
|
||||
Set<String> keys = jedis.keys("*");
|
||||
for (String string : keys) {
|
||||
if (string.equals(uid)) {
|
||||
jedis.del(string);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static String ping() {
|
||||
Jedis jedis = getRedis();
|
||||
String tmp = jedis.ping();
|
||||
jedis.close();
|
||||
return tmp;
|
||||
}
|
||||
|
||||
public static boolean exists(String key, String value) {
|
||||
if (isNotInstallRedis) {
|
||||
return false;
|
||||
}
|
||||
Jedis jedis = getRedis();
|
||||
boolean flag = value.equals(jedis.get(key));
|
||||
jedis.close();
|
||||
return flag;
|
||||
}
|
||||
|
||||
public static Jedis getRedis() {
|
||||
return new Jedis(host, port);
|
||||
}
|
||||
|
||||
public static boolean remove(String key, int index) {
|
||||
if (isNotInstallRedis) {
|
||||
return false;
|
||||
}
|
||||
Jedis jedis = getRedis();
|
||||
jedis.select(index);
|
||||
Long i = jedis.del(key);
|
||||
jedis.close();
|
||||
if (i > 0) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static class PropertyUtil {
|
||||
|
||||
// 加载property文件到io流里面
|
||||
public static Properties loadProperties(String propertyFile) {
|
||||
Properties properties = new Properties();
|
||||
try {
|
||||
InputStream is = PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFile);
|
||||
if (is == null) {
|
||||
is = PropertyUtil.class.getClassLoader().getResourceAsStream(propertyFile);
|
||||
}
|
||||
properties.load(is);
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return properties;
|
||||
}
|
||||
}
|
||||
|
||||
private static Jedis getPoolRedis() {
|
||||
if (isNotInstallRedis) {
|
||||
return null;
|
||||
}
|
||||
JedisPoolConfig poolConfig = new JedisPoolConfig();
|
||||
poolConfig.setMaxIdle(0);
|
||||
poolConfig.setMaxWaitMillis(1000);
|
||||
JedisPool pool = new JedisPool(poolConfig, host);
|
||||
return pool.getResource();
|
||||
}
|
||||
|
||||
public static void pullMsg(String channel, String msg) {
|
||||
System.out.println("1");
|
||||
Jedis jedis = getPoolRedis();
|
||||
System.out.println("2");
|
||||
jedis.publish(channel, msg);
|
||||
System.out.println("3");
|
||||
jedis.close();
|
||||
System.out.println("4");
|
||||
}
|
||||
|
||||
private static boolean init = false;
|
||||
|
||||
public static void initRedisPoolSub() {
|
||||
if (init)
|
||||
return;
|
||||
init = true;
|
||||
System.out.println("初始化订阅");
|
||||
new Thread(new Runnable() {
|
||||
@Override
|
||||
public void run() {
|
||||
Jedis jedis = getPoolRedis();
|
||||
if (jedis != null)
|
||||
jedis.psubscribe(new Consumer(), "*");
|
||||
}
|
||||
}).start();
|
||||
|
||||
}
|
||||
|
||||
protected static class Consumer extends JedisPubSub {
|
||||
@Override
|
||||
public void onPMessage(String pattern, String channel, String message) {
|
||||
super.onPMessage(pattern, channel, message);
|
||||
System.out.println("onPMessage: channel=" + channel + " msg=" + message + " pattern=" + pattern);
|
||||
switch (channel) {
|
||||
case "system":
|
||||
switch (message) {
|
||||
case "openPC":
|
||||
system("openPC", null);
|
||||
break;
|
||||
case "updateIP":
|
||||
system("updateIP", null);
|
||||
break;
|
||||
}
|
||||
break;
|
||||
case "bot":
|
||||
bot(message);
|
||||
break;
|
||||
case "cmd":
|
||||
system("cmd", message);
|
||||
break;
|
||||
case "msg":
|
||||
Tools.sendServer("来自服务姬的通知~",message);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onMessage(String channel, String message) {
|
||||
super.onMessage(channel, message);
|
||||
System.out.println("onMessage: channel=" + channel + " msg=" + message);
|
||||
}
|
||||
|
||||
public static void system(String type, String value) {
|
||||
try {
|
||||
String exec = null;
|
||||
switch (type) {
|
||||
case "openPC":
|
||||
exec = "wakeonlan 00:D8:61:6F:02:2F";
|
||||
break;
|
||||
case "cmd":
|
||||
exec = value;
|
||||
break;
|
||||
case "updateIP":
|
||||
exec = "python3 /media/yutou/4t/public/Python/tools/ip.py";
|
||||
break;
|
||||
}
|
||||
if (exec != null) {
|
||||
Process process = Runtime.getRuntime().exec(exec);
|
||||
processOut(process.getInputStream());
|
||||
processOut(process.getErrorStream());
|
||||
process.destroy();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static void bot(String value) {
|
||||
switch (value) {
|
||||
case "getip":
|
||||
JSONObject json = JSONObject.parseObject(HttpTools.get("https://api.asilu.com/ip/"));
|
||||
String ip = json.getString("ip");
|
||||
QQBotManager.getInstance().sendMessage("服务器IP:\n" + ip);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
public static void processOut(InputStream inputStream) {
|
||||
|
||||
String tmp;
|
||||
StringBuilder str = new StringBuilder("null");
|
||||
try {
|
||||
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
|
||||
while ((tmp = reader.readLine()) != null) {
|
||||
str.append(tmp).append("\n");
|
||||
}
|
||||
reader.close();
|
||||
inputStream.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
System.out.println("cmd > " + str);
|
||||
QQBotManager.getInstance().sendMessage(str.toString());
|
||||
System.out.println("线程结束");
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
RedisTools.pullMsg("msg", "abc");
|
||||
}
|
||||
}
|
||||
385
src/main/java/com/yutou/nas/utils/Tools.java
Normal file
385
src/main/java/com/yutou/nas/utils/Tools.java
Normal file
@@ -0,0 +1,385 @@
|
||||
package com.yutou.nas.utils;
|
||||
|
||||
import com.alibaba.fastjson.JSONArray;
|
||||
import com.yutou.nas.Controllers.UpdateIp;
|
||||
import com.yutou.nas.interfaces.DownloadInterface;
|
||||
import org.springframework.core.io.FileSystemResource;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.servlet.http.Cookie;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
import java.io.*;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Base64;
|
||||
import java.util.Date;
|
||||
import java.util.Random;
|
||||
|
||||
public class Tools {
|
||||
/**
|
||||
* 设置Cookie
|
||||
*
|
||||
* @param response
|
||||
* @param key
|
||||
* @param value
|
||||
* @param time
|
||||
*/
|
||||
public static void setCookie(HttpServletResponse response, String key, String value, int time) {
|
||||
Cookie cookie = new Cookie(key, value);
|
||||
if (time != -1) {
|
||||
cookie.setMaxAge(time);
|
||||
}
|
||||
cookie.setPath("/");
|
||||
response.addCookie(cookie);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Cookie
|
||||
*
|
||||
* @param request
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Cookie getCookie(HttpServletRequest request, String key) {
|
||||
Cookie[] cookies = request.getCookies();
|
||||
try {
|
||||
for (Cookie cookie : cookies) {
|
||||
if (key != null && cookie.getName().equals(key)) {
|
||||
return cookie;
|
||||
}
|
||||
}
|
||||
} catch (Exception ignored) {
|
||||
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除Cookie
|
||||
*
|
||||
* @param request
|
||||
* @param response
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static String deleteCookie(HttpServletRequest request, HttpServletResponse response, String key) {
|
||||
for (Cookie cookie : request.getCookies()) {
|
||||
if (cookie.getName().equals(key)) {
|
||||
System.out.println("删除key=" + key);
|
||||
cookie.setMaxAge(0);
|
||||
cookie.setPath("/");
|
||||
cookie.setValue(null);
|
||||
response.addCookie(cookie);
|
||||
}
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static void sendServer(String title, String msg) {
|
||||
try {
|
||||
System.out.println("title=" + title + " msg=" + msg);
|
||||
HttpTools.post("https://sctapi.ftqq.com/SCT2619Tpqu93OYtQCrK4LOZYEfr2irm.send",
|
||||
("title="+URLEncoder.encode(title, "UTF-8") + "&desp=" + URLEncoder.encode(msg, "UTF-8")).getBytes(StandardCharsets.UTF_8),
|
||||
null);
|
||||
if (ConfigTools.load(ConfigTools.CONFIG, "model").equals("nas")) {
|
||||
String img = null;
|
||||
msg = msg.replace("<br/>", "\n");
|
||||
if (msg.contains("![logo]")) {
|
||||
try {
|
||||
img = msg.split("!\\[logo\\]\\(")[1].split("\\)")[0];
|
||||
msg = msg.replace("", "");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (img == null) {
|
||||
QQBotManager.getInstance().sendMessage(title + "\n" + msg);
|
||||
} else {
|
||||
String finalMsg = msg;
|
||||
String finalImg = img;
|
||||
if (QQBotManager.getInstance().isLogin()) {
|
||||
download(img, new DownloadInterface() {
|
||||
@Override
|
||||
public void onDownload(String file) {
|
||||
super.onDownload(file);
|
||||
QQBotManager.getInstance().sendMessage(new File(file), title + "\n" + finalMsg);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onError(Exception e) {
|
||||
super.onError(e);
|
||||
QQBotManager.getInstance().sendMessage(title + "\n" + finalMsg + "\n" + finalImg);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
} else if (!StringUtils.isEmpty(UpdateIp.nas_ip)) {
|
||||
String img = null;
|
||||
msg = msg.replace("<br/>", "\n");
|
||||
if (msg.contains("![logo]")) {
|
||||
try {
|
||||
img = msg.split("!\\[logo\\]\\(")[1].split("\\)")[0];
|
||||
msg = msg.replace("", "");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
String url;
|
||||
if (img == null) {
|
||||
url = "http://" + UpdateIp.nas_ip + ":8000/qq/bot/send.do?msg=" + URLEncoder.encode((title + "\n" + msg), "UTF-8") + "&token=zIrsh9TUZP2lfRW753PannG49E7VJvor";
|
||||
} else {
|
||||
url = "http://" + UpdateIp.nas_ip + ":8000/qq/bot/send.do?msg=" + URLEncoder.encode((title + "\n" + msg), "UTF-8")
|
||||
+ "&imgUrl=" + img
|
||||
+ "&token=zIrsh9TUZP2lfRW753PannG49E7VJvor";
|
||||
}
|
||||
System.out.println(url);
|
||||
HttpTools.get(url);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取项目路径
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public static String getPath(HttpServletRequest request) {
|
||||
return request.getServletContext().getRealPath("/") + "/";
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取客户端IP
|
||||
*
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public static String getRemoteAddress(HttpServletRequest request) {
|
||||
String ip = request.getHeader("x-forwarded-for");
|
||||
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
|
||||
ip = request.getHeader("Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
|
||||
ip = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
if (ip == null || ip.length() == 0 || ip.equalsIgnoreCase("unknown")) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
return ip;
|
||||
}
|
||||
|
||||
/**
|
||||
* N以内的不重复随机数
|
||||
*
|
||||
* @param min 最小值
|
||||
* @param max 最大值
|
||||
* @param n
|
||||
* @return
|
||||
*/
|
||||
public static int[] randomCommon(int min, int max, int n) {
|
||||
int len = max - min + 1;
|
||||
if (max < min || n > len) {
|
||||
return new int[0];
|
||||
}
|
||||
// 初始化给定范围的待选数组
|
||||
int[] source = new int[len];
|
||||
for (int i = min; i < min + len; i++) {
|
||||
source[i - min] = i;
|
||||
}
|
||||
int[] result = new int[n];
|
||||
Random rd = new Random();
|
||||
int index = 0;
|
||||
for (int i = 0; i < result.length; i++) {
|
||||
// 待选数组0到(len-2)随机一个下标
|
||||
index = Math.abs(rd.nextInt() % len--);
|
||||
// 将随机到的数放入结果集
|
||||
result[i] = source[index];
|
||||
// 将待选数组中被随机到的数,用待选数组(len-1)下标对应的数替换
|
||||
source[index] = source[len];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static int checkWebLogin(HttpServletRequest request) {
|
||||
JSONArray array = new JSONArray();
|
||||
if (RedisTools.get("bean") != null) {
|
||||
array = JSONArray.parseArray(RedisTools.get("bean"));
|
||||
}
|
||||
if (array.contains(Tools.getRemoteAddress(request))) {
|
||||
System.out.println("IP已被封禁");
|
||||
return -100;
|
||||
}
|
||||
Cookie cookie = Tools.getCookie(request, "user");
|
||||
if (cookie == null) {
|
||||
return -1;
|
||||
}
|
||||
if (RedisTools.get(cookie.getValue()).equals("ok")) {
|
||||
return 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存上传的文件
|
||||
*
|
||||
* @param path 路径
|
||||
* @param file 文件
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static String createFile(String path, MultipartFile file, String newFileName) throws Exception {
|
||||
String savePath = new File("").getAbsolutePath() + File.separator + "html" + File.separator + path;
|
||||
File servicePath = new File(savePath);
|
||||
if (!servicePath.exists()) {
|
||||
servicePath.mkdirs();
|
||||
}
|
||||
String fileName = file.getOriginalFilename();
|
||||
if (newFileName != null) {
|
||||
fileName = newFileName;
|
||||
}
|
||||
File saveFile = new File(savePath + "/" + fileName);
|
||||
if (saveFile.exists()) {
|
||||
if (!saveFile.delete()) {
|
||||
saveFile = new File(savePath + "/" + fileName.replace(".", "_" + new Date().getTime() + "."));
|
||||
}
|
||||
}
|
||||
file.transferTo(saveFile);
|
||||
fileName = URLEncoder.encode(fileName, "UTF-8");
|
||||
System.out.println("上传文件保存路径:" + saveFile.getAbsolutePath());
|
||||
return path + fileName;
|
||||
}
|
||||
|
||||
public static void download(String url, DownloadInterface downloadInterface) {
|
||||
try {
|
||||
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
|
||||
connection.addRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97 Safari/537.36");
|
||||
connection.disconnect();
|
||||
new File("tmp").mkdirs();
|
||||
File file = new File("tmp" + File.separator + url.trim().split("/")[url.trim().split("/").length - 1]);
|
||||
if (file.exists()) {
|
||||
file.delete();
|
||||
}
|
||||
FileOutputStream outputStream = new FileOutputStream(file);
|
||||
InputStream inputStream = connection.getInputStream();
|
||||
byte[] bytes = new byte[4096];
|
||||
int len;
|
||||
while ((len = inputStream.read(bytes)) != -1) {
|
||||
outputStream.write(bytes, 0, len);
|
||||
outputStream.flush();
|
||||
}
|
||||
outputStream.close();
|
||||
inputStream.close();
|
||||
downloadInterface.onDownload(file.getAbsolutePath());
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
downloadInterface.onError(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造给前端的文件
|
||||
*
|
||||
* @param file 文件路径
|
||||
* @return 前端获取的文件
|
||||
*/
|
||||
public static ResponseEntity<FileSystemResource> getFile(File file) {
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
|
||||
try {
|
||||
headers.add("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
headers.add("Content-Disposition", "attachment; filename=" + file.getName());
|
||||
}
|
||||
headers.add("Pragma", "no-cache");
|
||||
headers.add("Expires", "0");
|
||||
headers.add("Last-Modified", new Date().toString());
|
||||
headers.add("ETag", String.valueOf(System.currentTimeMillis()));
|
||||
return ResponseEntity.ok().headers(headers).contentLength(file.length()).contentType(MediaType.parseMediaType("application/octet-stream")).body(new FileSystemResource(file));
|
||||
}
|
||||
|
||||
public static String getFileMD5(File file) {
|
||||
if (!file.isFile()) {
|
||||
return null;
|
||||
}
|
||||
MessageDigest digest = null;
|
||||
FileInputStream in = null;
|
||||
byte buffer[] = new byte[1024];
|
||||
int len;
|
||||
try {
|
||||
digest = MessageDigest.getInstance("MD5");
|
||||
in = new FileInputStream(file);
|
||||
while ((len = in.read(buffer, 0, 1024)) != -1) {
|
||||
digest.update(buffer, 0, len);
|
||||
}
|
||||
in.close();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
return null;
|
||||
}
|
||||
return bytesToHexString(digest.digest());
|
||||
}
|
||||
|
||||
private static String bytesToHexString(byte[] src) {
|
||||
StringBuilder stringBuilder = new StringBuilder("");
|
||||
if (src == null || src.length <= 0) {
|
||||
return null;
|
||||
}
|
||||
for (byte aSrc : src) {
|
||||
int v = aSrc & 0xFF;
|
||||
String hv = Integer.toHexString(v);
|
||||
if (hv.length() < 2) {
|
||||
stringBuilder.append(0);
|
||||
}
|
||||
stringBuilder.append(hv);
|
||||
}
|
||||
return stringBuilder.toString();
|
||||
}
|
||||
|
||||
public static String base64ToString(String base) {
|
||||
base = base.replace(" ", "+");
|
||||
try {
|
||||
base = new String(Base64.getDecoder().decode(base.replace("\r\n", "").getBytes()));
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
base = URLDecoder.decode(base, "UTF-8");
|
||||
base = base.replace(" ", "+");
|
||||
base = new String(Base64.getDecoder().decode(base.replace("\r\n", "").getBytes()));
|
||||
} catch (Exception e1) {
|
||||
e1.printStackTrace();
|
||||
}
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
/**
|
||||
* 异常输出
|
||||
*
|
||||
* @param e 异常
|
||||
* @return
|
||||
*/
|
||||
public static String getExceptionString(Exception e) {
|
||||
StringWriter writer = new StringWriter();
|
||||
PrintWriter printWriter = new PrintWriter(writer);
|
||||
e.printStackTrace(printWriter);
|
||||
printWriter.close();
|
||||
return writer.toString();
|
||||
}
|
||||
|
||||
public static String getToDayTime() {
|
||||
return new SimpleDateFormat("yyyy-MM-dd").format(new Date());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user