295 lines
12 KiB
JavaScript
295 lines
12 KiB
JavaScript
|
|
!(function (e, t) {
|
|
"object" == typeof exports && "undefined" != typeof module
|
|
? (module.exports = t(e))
|
|
: "function" == typeof define && define.amd
|
|
? define(t, e)
|
|
: ((e = "undefined" != typeof globalThis ? globalThis : e || self).http =
|
|
t(e));
|
|
})(this,
|
|
function (scope) {
|
|
if (!scope.axios) {
|
|
scope.require("/libs/axios/1.7.2/axios.min.js");
|
|
}
|
|
if (!scope.settings) {
|
|
scope.require("/settings.js");
|
|
};
|
|
const _original = axios;
|
|
// create an axios instance
|
|
const getToken = () => {
|
|
return localStorage.getItem("token");
|
|
}
|
|
const _axios = _original.create({
|
|
baseURL: settings.API_BASE, // url = base url + request url
|
|
// withCredentials: true, // send cookies when cross-domain requests
|
|
timeout: 1000 * 60 * 60 // request timeout
|
|
})
|
|
// request interceptor
|
|
_axios.interceptors.request.use(
|
|
config => {
|
|
// let each request carry token
|
|
// ['X-Token'] is a custom headers key
|
|
// please modify it according to the actual situation
|
|
config.headers['Authorization'] = getToken();
|
|
return config
|
|
},
|
|
error => {
|
|
// do something with request error
|
|
return Promise.reject(error)
|
|
}
|
|
)
|
|
var absoluteUrlRegex = /^(http(s?):)?\/\//;
|
|
// var downloadIFrame = document.createElement("iframe");
|
|
// Object.assign(downloadIFrame.style, { display: "none" });//创建一个隐藏的iframe 用于下载文件
|
|
_axios.download = function ({ url, fileName, validFileSize, params }) {
|
|
if (!absoluteUrlRegex.test(url)) {
|
|
if (url[0] == "/") url = url.substring(1);
|
|
url = _axios.defaults.baseURL + url;
|
|
}
|
|
var target = new URL(url);
|
|
Object.entries(params).forEach(([key, value]) => {
|
|
target.searchParams.append(key, value)
|
|
})
|
|
var downloadIFramesrc = target.toString();
|
|
/*
|
|
var a = document.createElement("a");
|
|
Object.assign(a,{
|
|
target:"_blank",
|
|
title:filename,
|
|
download:filename,
|
|
href:target.toString()
|
|
})
|
|
document.body.appendChild(a);
|
|
a.click();
|
|
a.remove();
|
|
URL.revokeObjectURL(a.download);*/
|
|
|
|
let isAborted = false;//标志位
|
|
let refreshIntervalId = null;
|
|
const xhr = new XMLHttpRequest();
|
|
xhr.open('GET', downloadIFramesrc, true);
|
|
// xhr.response = 'blob';
|
|
// xhr.responseType = "blob";
|
|
xhr.responseType = 'arraybuffer';
|
|
|
|
let startTime;
|
|
vm.fileManager.storage.downloadSwitch = true;
|
|
let timer;
|
|
let speedSum = 0;
|
|
|
|
// 设置初始状态
|
|
vm.fileManager.storage.speed = 0;
|
|
vm.fileManager.storage.percentage = 0;
|
|
vm.fileManager.storage.isfullfill = '正在下载';
|
|
|
|
xhr.onprogress = function (e) {
|
|
let thisLoaded = e.loaded;
|
|
speedSum += e.loaded;
|
|
vm.fileManager.storage.percentage = (thisLoaded / validFileSize * 100).toFixed(2);
|
|
if (!startTime) {
|
|
startTime = Date.now();
|
|
};
|
|
if (!timer) {
|
|
timer = setInterval(() => {
|
|
const currentTime = Date.now();
|
|
const bytesDelta = speedSum;
|
|
const deltaTime = (currentTime - startTime) / 1000;
|
|
if (deltaTime > 0) {
|
|
let speed = (bytesDelta / deltaTime / 1024).toFixed(2);//转换为mb/s
|
|
vm.fileManager.storage.speed = speed;
|
|
speedSum = 0;
|
|
}
|
|
}, 1000)
|
|
}
|
|
};
|
|
xhr.onload = function () {
|
|
if (xhr.status === 200) {
|
|
if (refreshIntervalId != null) {
|
|
clearInterval(refreshIntervalId);
|
|
};
|
|
const blob = new Blob([xhr.response], { type: 'application/octet-stream' });
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.download = fileName;
|
|
a.click();
|
|
URL.revokeObjectURL(url);
|
|
vm.fileManager.storage.isfullfill = "下载完成";
|
|
vm.onWorkSwitch(true);//打开开关
|
|
setTimeout(() => {
|
|
vm.currentDownload = null;
|
|
vm.fileManager.storage.downloadSwitch = false;
|
|
}, 2000)
|
|
}
|
|
};
|
|
refreshIntervalId = setInterval(() => {
|
|
if (vm.currentDownload == null && isAborted == false) {
|
|
xhr.abort();
|
|
isAborted = true;
|
|
if (xhr.readyState < 4) {
|
|
console.log("执行abort");
|
|
|
|
const blob = new Blob([xhr.response], { type: 'application/octet-stream' });
|
|
const url = URL.createObjectURL(blob);
|
|
const a = document.createElement('a');
|
|
a.href = url;
|
|
a.download = fileName;
|
|
a.click();
|
|
URL.revokeObjectURL(url);
|
|
vm.fileManager.storage.isfullfill = "下载完成";
|
|
vm.currentDownload = null;
|
|
vm.onWorkSwitch(true);//打开开关
|
|
setTimeout(() => {
|
|
vm.fileManager.storage.downloadSwitch = false;
|
|
}, 2000)
|
|
}
|
|
}
|
|
}, 1000);
|
|
xhr.send();
|
|
return Promise.resolve();
|
|
}
|
|
_axios.sync = function (opts) {
|
|
let { url, method, data } = opts;
|
|
if (url.indexOf("http://") == -1) {
|
|
if (url[0] == "/") url = url.substring(1);
|
|
url = settings.API_BASE + url;
|
|
}
|
|
var xhr = new XMLHttpRequest();
|
|
xhr.open(method, url, false);
|
|
xhr.setRequestHeader("Content-type", "application/json;charset=utf-8");
|
|
xhr.send(data);
|
|
var response = JSON.parse(xhr.responseText);
|
|
return response;
|
|
}
|
|
// response interceptor
|
|
_axios.interceptors.response.use(
|
|
/**
|
|
* If you want to get http information such as headers or status
|
|
* Please return response => response
|
|
*/
|
|
|
|
/**
|
|
* Determine the request status by custom code
|
|
* Here is just an example
|
|
* You can also judge the status by HTTP Status Code
|
|
*/
|
|
response => {
|
|
const res = response.data
|
|
// if the custom code is not 200, it is judged as an error.
|
|
const statusCode = res.code || res.Code || response.status;
|
|
if (statusCode !== 200) {
|
|
const message = res.message || res.Message;
|
|
|
|
false && console.log({
|
|
message: message || 'Error',
|
|
type: 'error',
|
|
duration: 5 * 1000
|
|
});
|
|
return Promise.reject(new Error(message || 'Error'))
|
|
} else {
|
|
return res
|
|
}
|
|
},
|
|
error => {
|
|
false && console.log({
|
|
message: error.message,
|
|
type: 'error',
|
|
duration: 5 * 1000
|
|
})
|
|
return Promise.reject(error)
|
|
}
|
|
)
|
|
|
|
_axios.socket = (function () {
|
|
// create an axios instance
|
|
const core = function () {
|
|
function SocketWorker(url, token) {
|
|
var _ctx = this.$ctx = { state: null };
|
|
this.socket = new WebSocket(url);
|
|
|
|
this.socket.onopen = function () {
|
|
postMessage({ "name": "onopen", "payload": null }, []);
|
|
}
|
|
this.socket.onclose = function (args) {
|
|
let { code, reason, type, target } = args;
|
|
let { url } = target;
|
|
postMessage({ "name": "onclose", "payload": { code, reason, type, url } });
|
|
console.log("closed", _ctx.state);
|
|
}
|
|
this.socket.onerror = function () {
|
|
postMessage({ "name": "onerror", "payload": null });
|
|
}
|
|
this.socket.onmessage = function (e) {
|
|
if (e.data.size < 32) return;
|
|
e.data.arrayBuffer().then(function (buffer) {
|
|
postMessage({ "name": "onmessage", "payload": buffer }, [buffer]);
|
|
});
|
|
}
|
|
}
|
|
SocketWorker.prototype.state = function (state) {
|
|
this.$ctx.state = state;
|
|
}
|
|
SocketWorker.prototype.close = function () {
|
|
if (this.socket) this.socket.close();
|
|
}
|
|
SocketWorker.prototype.postMessage = function () {
|
|
this.socket.postMessage(...arguments);
|
|
}
|
|
let _websocket;
|
|
addEventListener('message', function (e) {
|
|
let { name, payload } = e.data;
|
|
switch (name) {
|
|
case "create":
|
|
let { url, token, state } = payload;
|
|
_websocket = new SocketWorker(url, token);
|
|
break;
|
|
case "close":
|
|
_websocket?.close();
|
|
break;
|
|
default:
|
|
_websocket?.postMessage(e.data);
|
|
//?.取属性同时判断该属性是否存在
|
|
}
|
|
});
|
|
};
|
|
var blob = new Blob([`(${core})()`]);
|
|
var workurl = URL.createObjectURL(blob);
|
|
const create = (function (opts) {
|
|
let { url, callback, state } = opts;
|
|
if (url.indexOf("ws://") == -1) {
|
|
if (url[0] == "/") url = url.substring(1);
|
|
url = settings.WEBSOCKET_BASE + url;
|
|
}
|
|
var worker = new Worker(workurl);
|
|
URL.revokeObjectURL(workurl);
|
|
var receive = function (e) {
|
|
const { name, payload } = e.data;
|
|
handles.forEach(handle => handle(name, payload))
|
|
};
|
|
var handles = new Set();
|
|
if (callback) handles.add(callback);
|
|
|
|
worker.addEventListener('message', receive);
|
|
|
|
url = new URL(url);
|
|
url.searchParams.append("token", getToken());
|
|
worker.postMessage({ name: "create", payload: { url: url.href, state } });
|
|
|
|
return {
|
|
onmessage(handle) {
|
|
handles.add(handle);
|
|
},
|
|
postMessage() {
|
|
worker.postMessage(...arguments);
|
|
},
|
|
close() {
|
|
worker.postMessage({ name: "close" });
|
|
}
|
|
}
|
|
});
|
|
return create
|
|
})();
|
|
|
|
return _axios;
|
|
}
|
|
); |