准备上传oss做云备份

This commit is contained in:
yutou
2021-06-09 18:31:48 +08:00
parent e9ff6a0207
commit 44e0a866a3
11 changed files with 194 additions and 54 deletions

View File

@@ -1,5 +1,6 @@
package com.yutou.nas.utils;
import com.yutou.nas.Services.impl.MusicToolsServiceImpl;
import com.yutou.nas.other.QQSetu;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

View File

@@ -55,21 +55,23 @@ public class BTDownloadManager implements ApplicationContextAware {
JSONObject json = JSONObject.parseObject(_json);
download(item, json);
} else {
QQBotManager.getInstance().sendMessage(item.getTitle() + "\n下载失败");
QQBotManager.getInstance().sendMessage(item.getTitle() + "\n下载失败\n"+getDmhyUrl(item));
Log.i(item.getTitle() + "\n下载失败");
}
}
}
private String getRSSUrl(BangumiItem item) {
String url = "https://api.rss2json.com/v1/api.json?rss_url=%s&api_key=wtfm5pebya13pnl8rtu51wfgfpte0mb9sap1foll&count=500";
private String getDmhyUrl(BangumiItem item){
String dmhyUrl = "http://share.dmhy.org/topics/rss/page/1/rss.xml?keyword=%s%s%s&order=date-desc";
dmhyUrl = String.format(dmhyUrl,
item.getTitlekey().replace(" ", "+"),
"-1".equals(item.getCategories()) ? "" : String.format("&sort_id=%s", item.getCategories()),
"-1".equals(item.getAuthor()) ? "" : String.format("&team_id=%s", item.getAuthor()));
return dmhyUrl;
}
private String getRSSUrl(BangumiItem item) {
String url = "https://api.rss2json.com/v1/api.json?rss_url=%s&api_key=wtfm5pebya13pnl8rtu51wfgfpte0mb9sap1foll&count=500";
try {
return String.format(url, URLEncoder.encode(dmhyUrl, "UTF-8"));
return String.format(url, URLEncoder.encode(getDmhyUrl(item), "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return null;

View File

@@ -3,62 +3,72 @@ package com.yutou.nas.utils;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.util.HashSet;
import java.util.Set;
/**
* 配置和参数
*/
public class ConfigTools {
public static final String CONFIG="config.json";
public static final String DATA="data.json";
public static final String SQLITE="sqlite.json";
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 file = new File(CONFIG);
if (!file.exists()) {
file.createNewFile();
}
file=new File(DATA);
if(!file.exists()){
file = new File(DATA);
if (!file.exists()) {
file.createNewFile();
}
file=null;
}catch (Exception e){
file = null;
} catch (Exception e) {
e.printStackTrace();
}
}
public static Object load(String type,String key){
File file=new File(type);
public static Object load(String type, String key) {
return load(type, key, Object.class, null);
}
public static <T> T load(String type, String key, Class<T> t) {
return load(type, key, t, null);
}
public static <T> T load(String type, String key, Class<T> t, T def) {
File file = new File(type);
//com.yutou.nas.utils.Log.i(type+"配置文件地址:"+file.getAbsolutePath());
String src=readFile(file);
if(src!=null){
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 "";
JSONObject json = JSONObject.parseObject(src);
return json.getObject(key, t);
} catch (Exception e) {
}
}
return "";
return def;
}
public static boolean save(String type,String key,Object data){
File file=new File(type);
String src=readFile(file);
if(src==null){
src="{}";
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());
JSONObject json = JSONObject.parseObject(src);
json.put(key, data);
saveFile(file, json.toJSONString());
return false;
}
public static boolean saveFile(File file,String data){
public static boolean saveFile(File file, String data) {
try {
FileWriter writer=new FileWriter(file);
FileWriter writer = new FileWriter(file);
writer.write(data);
writer.flush();
writer.close();
@@ -68,12 +78,13 @@ public class ConfigTools {
return false;
}
}
public static String readFile(File file){
public static String readFile(File file) {
try {
BufferedReader reader=new BufferedReader(new FileReader(file));
BufferedReader reader = new BufferedReader(new FileReader(file));
String tmp;
StringBuilder str= new StringBuilder();
while ((tmp=reader.readLine())!=null){
StringBuilder str = new StringBuilder();
while ((tmp = reader.readLine()) != null) {
str.append(tmp);
}
reader.close();

View File

@@ -0,0 +1,10 @@
package com.yutou.nas.utils;
public class DepotManager {
private DepotManager(){
}
public static void scan(){
}
}

View File

@@ -1,30 +0,0 @@
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;
}

View File

@@ -6,7 +6,7 @@ public class Log {
}
public static void i(Object log) {
if ("true".equals(ConfigTools.load(ConfigTools.CONFIG, "logout"))) {
if (ConfigTools.load(ConfigTools.CONFIG, "logout",boolean.class,false)) {
System.out.printf("[%s]%s%n",
AppTools.getToDayNowTimeToString(),
log

View File

@@ -1,545 +0,0 @@
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();
com.yutou.nas.utils.Log.i("执行扫描:" + musicPath);
new Thread(() -> {
long startTime = System.currentTimeMillis();
QQBotManager.getInstance().sendMessage("开始扫描音乐夹");
isScan = true;
scan(new File(musicPath));
isScan = false;
com.yutou.nas.utils.Log.i("扫描完成");
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());
}
com.yutou.nas.utils.Log.i("查询地址:" + 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);
com.yutou.nas.utils.Log.i("扫描文件:"+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");
com.yutou.nas.utils.Log.i(new MusicToolsServiceImpl().getMetadataOfFFmpeg(file));
}
}

View File

@@ -0,0 +1,87 @@
package com.yutou.nas.utils;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.StorageClass;
import com.yutou.nas.interfaces.DownloadInterface;
import java.io.File;
import java.io.FileNotFoundException;
public class OSSManager {
public static final String TYPE_MUSIC = "oss-name-music";
public static final String TYPE_PHOTO = "oss-name-photo";
public static final String TYPE_DEPOT = "oss-name-depot";
private static OSS getOssClient() {
return new OSSClientBuilder().build(ConfigTools.load(ConfigTools.CONFIG, "oss-url", String.class),
ConfigTools.load(ConfigTools.CONFIG, "oss-id", String.class),
ConfigTools.load(ConfigTools.CONFIG, "oss-key", String.class));
}
private static void closeClient(OSS oss) {
oss.shutdown();
}
public static void upload(String type, String path, File... files) {
if (type.equals(TYPE_MUSIC) && !ConfigTools.load(ConfigTools.CONFIG, TYPE_MUSIC, boolean.class, false)) {
return;
}
if (type.equals(TYPE_PHOTO) && !ConfigTools.load(ConfigTools.CONFIG, TYPE_PHOTO, boolean.class, false)) {
return;
}
if (type.equals(TYPE_DEPOT) && !ConfigTools.load(ConfigTools.CONFIG, TYPE_DEPOT, boolean.class, false)) {
return;
}
new Thread(() -> {
OSS client = getOssClient();
for (File file : files) {
if (file.isDirectory()) {
continue;
}
String uploadPath = file.getAbsolutePath().replace(path, "").replace(File.separator, "/");
if (uploadPath.startsWith("/")) {
uploadPath = uploadPath.substring(1);
}
client.putObject(type, uploadPath, file);
}
closeClient(client);
}).start();
}
public static void download(String type, String path, DownloadInterface downloadInterface) {
new Thread(() -> {
OSS oss = getOssClient();
ObjectMetadata metadata = oss.getObjectMetadata(type, path);
if (metadata.getObjectStorageClass() == StorageClass.Archive) {
oss.restoreObject(type, path);
do {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
metadata = oss.getObjectMetadata(type, path);
} while (!metadata.isRestoreCompleted());
}
OSSObject obj = oss.getObject(type, path);
File file = StreamTools.streamSave(obj.getObjectContent());
if (file != null) {
downloadInterface.onDownload(file);
} else {
downloadInterface.onError(new FileNotFoundException("没有该文件"));
}
closeClient(oss);
}).start();
}
private static boolean isExist(String type,String path){
OSS oss=getOssClient();
boolean flag=oss.doesObjectExist(type,path,true);
closeClient(oss);
return flag;
}
}

View File

@@ -1,8 +1,6 @@
package com.yutou.nas.utils;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.*;
public class StreamTools {
public static String streamReadLine(InputStream stream) {
@@ -19,4 +17,25 @@ public class StreamTools {
}
return builder.toString();
}
public static File streamSave(InputStream stream) {
try {
if (stream != null) {
File file = new File("tmp" + File.separator + System.currentTimeMillis());
FileOutputStream outputStream = new FileOutputStream(file);
byte[] bytes = new byte[2048];
int len;
while ((len = stream.read(bytes)) > -1) {
outputStream.write(bytes, 0, len);
}
outputStream.flush();
stream.close();
outputStream.close();
return file;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}