md/src/api/file.js

243 lines
8.0 KiB
JavaScript
Raw Normal View History

2020-10-20 11:43:11 +00:00
import fetch from "./fetch";
2020-12-01 14:55:46 +08:00
import { githubConfig, giteeConfig } from "./config";
2020-11-08 20:24:30 +08:00
import CryptoJS from "crypto-js";
2020-10-20 11:43:11 +00:00
import OSS from "ali-oss";
import COS from "cos-js-sdk-v5";
import Buffer from "buffer-from";
import { v4 as uuidv4 } from "uuid";
2020-11-08 20:24:30 +08:00
import * as qiniu from "qiniu-js";
import { utf16to8, base64encode, safe64 } from "../assets/scripts/tokenTools";
2020-08-31 20:48:22 +08:00
2020-12-01 14:55:46 +08:00
function getConfig(useDefault, platform) {
const config = platform === "github" ? githubConfig : giteeConfig;
2020-12-01 11:12:18 +08:00
if (useDefault) {
2020-12-01 14:55:46 +08:00
const { username, repoList, branch, accessTokenList } = config;
const tokenIndex = Math.floor(Math.random() * accessTokenList.length);
const repoIndex = Math.floor(Math.random() * repoList.length);
const accessToken = accessTokenList[tokenIndex].replace("doocsmd", "");
const repo = repoList[repoIndex];
return { username, repo, branch, accessToken };
2020-12-01 11:12:18 +08:00
}
2020-12-01 14:55:46 +08:00
const customConfig = JSON.parse(localStorage.getItem(`${platform}Config`));
2020-12-01 11:12:18 +08:00
const repoUrl = customConfig.repo
2020-12-01 14:55:46 +08:00
.replace(`https://${platform}.com/`, "")
.replace(`http://${platform}.com/`, "")
.replace(`${platform}.com/`, "")
2020-10-20 11:43:11 +00:00
.split("/");
2020-12-01 11:12:18 +08:00
return {
username: repoUrl[0],
repo: repoUrl[1],
branch: customConfig.branch || "master",
accessToken: customConfig.accessToken,
};
2020-09-13 21:24:27 +08:00
}
2020-12-01 15:35:08 +08:00
function getDir() {
const date = new Date();
const year = date.getFullYear();
const month = (date.getMonth() + 1).toString().padStart(2, "0");
const day = date.getDate().toString().padStart(2, "0");
return `${year}/${month}/${day}`;
}
function getDateFilename(filename) {
const currentTimestamp = new Date().getTime();
const fileSuffix = filename.split(".")[1];
return `${currentTimestamp}-${uuidv4()}.${fileSuffix}`;
}
2020-12-01 14:55:46 +08:00
//-----------------------------------------------------------------------
// GitHub File Upload
//-----------------------------------------------------------------------
async function ghFileUpload(content, filename) {
2020-12-01 11:12:18 +08:00
const useDefault = localStorage.getItem("imgHost") === "default";
2020-12-01 21:06:42 +08:00
const { username, repo, branch, accessToken } = getConfig(
useDefault,
"github"
);
2020-12-01 11:12:18 +08:00
const dir = getDir();
2020-12-01 21:06:42 +08:00
const url = `https://api.github.com/repos/${username}/${repo}/contents/${dir}/`;
2020-11-12 19:22:52 +08:00
const dateFilename = getDateFilename(filename);
const res = await fetch({
2020-12-01 11:12:18 +08:00
url: url + dateFilename,
method: "put",
headers: {
2020-12-01 21:06:42 +08:00
Authorization: `token ${accessToken}`,
2020-12-01 11:12:18 +08:00
},
2020-08-29 11:55:16 +08:00
data: {
2020-12-01 21:06:42 +08:00
content,
branch,
message: `Upload by ${window.location.href}`,
2020-10-20 11:43:11 +00:00
},
2020-09-12 16:53:52 +08:00
});
2020-11-30 18:48:20 +08:00
2020-12-01 21:06:42 +08:00
const githubResourceUrl = `raw.githubusercontent.com/${username}/${repo}/${branch}/`;
const cdnResourceUrl = `cdn.jsdelivr.net/gh/${username}/${repo}@${branch}/`;
2020-12-01 11:12:18 +08:00
return useDefault
2020-10-20 11:43:11 +00:00
? res.content.download_url.replace(githubResourceUrl, cdnResourceUrl)
: res.content.download_url;
2020-05-01 21:30:25 +08:00
}
2020-11-30 23:48:22 +08:00
//-----------------------------------------------------------------------
// Gitee File Upload
//-----------------------------------------------------------------------
2020-11-12 09:47:06 +08:00
async function giteeUpload(content, filename) {
2020-12-01 21:06:42 +08:00
const useDefault = localStorage.getItem("imgHost") === "default";
const { username, repo, branch, accessToken } = getConfig(
useDefault,
"gitee"
2020-12-01 11:12:18 +08:00
);
2020-11-12 19:22:52 +08:00
const dir = getDir();
const dateFilename = getDateFilename(filename);
2020-12-01 21:06:42 +08:00
const url = `https://gitee.com/api/v5/repos/${username}/${repo}/contents/${dir}/${dateFilename}`;
2020-11-12 09:47:06 +08:00
const res = await fetch({
2020-12-01 11:12:18 +08:00
url,
2020-11-12 09:47:06 +08:00
method: "POST",
data: {
2020-12-01 21:06:42 +08:00
content,
branch,
access_token: accessToken,
2020-11-12 09:47:06 +08:00
message: `Upload by ${window.location.href}`,
},
});
return encodeURI(res.content.download_url);
}
2020-11-30 23:48:22 +08:00
//-----------------------------------------------------------------------
// Qiniu File Upload
//-----------------------------------------------------------------------
function getQiniuToken(accessKey, secretKey, putPolicy) {
const policy = JSON.stringify(putPolicy);
const encoded = base64encode(utf16to8(policy));
const hash = CryptoJS.HmacSHA1(encoded, secretKey);
const encodedSigned = hash.toString(CryptoJS.enc.Base64);
return `${accessKey}:${safe64(encodedSigned)}:${encoded}`;
}
async function qiniuUpload(file) {
2020-12-01 21:06:42 +08:00
const { accessKey, secretKey, bucket, region, path, domain } = JSON.parse(
localStorage.getItem("qiniuConfig")
2020-11-30 23:48:22 +08:00
);
2020-12-01 21:06:42 +08:00
const token = getQiniuToken(accessKey, secretKey, {
scope: bucket,
deadline: Math.trunc(new Date().getTime() / 1000) + 3600,
});
const dir = path ? `${path}/` : "";
2020-11-30 23:48:22 +08:00
const dateFilename = dir + getDateFilename(file.name);
const config = {
2020-12-01 21:06:42 +08:00
region,
2020-11-30 23:48:22 +08:00
};
const observable = qiniu.upload(file, dateFilename, token, {}, config);
return new Promise((resolve, reject) => {
observable.subscribe({
next: (result) => {
console.log(result);
},
error: (err) => {
reject(err.message);
},
complete: (result) => {
2020-12-01 21:06:42 +08:00
resolve(`${domain}/${result.key}`);
2020-11-30 23:48:22 +08:00
},
});
});
}
//-----------------------------------------------------------------------
// AliOSS File Upload
//-----------------------------------------------------------------------
async function aliOSSFileUpload(content, filename) {
2020-11-12 19:22:52 +08:00
const dateFilename = getDateFilename(filename);
2020-12-01 21:06:42 +08:00
const {
region,
bucket,
accessKeyId,
accessKeySecret,
cdnHost,
path,
} = JSON.parse(localStorage.getItem("aliOSSConfig"));
2020-10-20 11:43:11 +00:00
const buffer = Buffer(content, "base64");
2020-12-02 11:49:00 +08:00
const dir = `${path}/${dateFilename}`;
const client = new OSS({
region,
bucket,
accessKeyId,
accessKeySecret,
});
2020-09-12 16:53:52 +08:00
try {
const res = await client.put(dir, buffer);
2020-12-02 11:49:00 +08:00
if (cdnHost == "") return res.url;
return `${cdnHost}/${path == "" ? dateFilename : dir}`;
2020-09-12 16:53:52 +08:00
} catch (e) {
return Promise.reject(e);
}
}
2020-05-01 21:30:25 +08:00
2020-11-30 23:48:22 +08:00
//-----------------------------------------------------------------------
// TxCOS File Upload
//-----------------------------------------------------------------------
async function txCOSFileUpload(file) {
2020-11-12 19:22:52 +08:00
const dateFilename = getDateFilename(file.name);
2020-12-01 21:06:42 +08:00
const { secretId, secretKey, bucket, region, path, cdnHost } = JSON.parse(
localStorage.getItem("txCOSConfig")
);
2020-09-15 21:49:30 +08:00
const cos = new COS({
2020-12-01 21:06:42 +08:00
SecretId: secretId,
SecretKey: secretKey,
2020-09-15 21:49:30 +08:00
});
return new Promise((resolve, reject) => {
2020-10-20 11:43:11 +00:00
cos.putObject(
{
2020-12-01 21:06:42 +08:00
Bucket: bucket,
Region: region,
Key: `${path}/${dateFilename}`,
2020-10-20 11:43:11 +00:00
Body: file,
},
function (err, data) {
if (err) {
reject(err);
2020-12-01 21:06:42 +08:00
} else if (cdnHost) {
2020-10-20 11:43:11 +00:00
resolve(
2020-12-01 21:06:42 +08:00
path == ""
? `${cdnHost}/${dateFilename}`
: `${cdnHost}/${path}/${dateFilename}`
2020-10-20 11:43:11 +00:00
);
} else {
2020-11-30 18:48:20 +08:00
resolve(`https://${data.Location}`);
2020-10-20 11:43:11 +00:00
}
2020-09-15 21:49:30 +08:00
}
2020-10-20 11:43:11 +00:00
);
});
2020-09-15 21:49:30 +08:00
}
2020-12-01 11:12:18 +08:00
function fileUpload(content, file) {
const imgHost = localStorage.getItem("imgHost");
!imgHost && localStorage.setItem("imgHost", "default");
switch (imgHost) {
case "aliOSS":
return aliOSSFileUpload(content, file.name);
case "txCOS":
return txCOSFileUpload(file);
case "qiniu":
return qiniuUpload(file);
case "gitee":
return giteeUpload(content, file.name);
case "github":
return ghFileUpload(content, file.name);
default:
// return file.size / 1024 < 1024
// ? giteeUpload(content, file.name)
// : ghFileUpload(content, file.name);
return ghFileUpload(content, file.name);
}
}
2020-12-01 14:55:46 +08:00
export default {
fileUpload,
};