fixes js http client

This commit is contained in:
huangjx
2022-05-04 11:59:31 +08:00
parent 840c672c09
commit f51ad10014
9 changed files with 127 additions and 42 deletions

View File

@@ -24,7 +24,7 @@
"private": true, "private": true,
"scripts": { "scripts": {
"build": "NODE_ENV=production webpack --progress --config webpack.app.js", "build": "NODE_ENV=production webpack --progress --config webpack.app.js",
"app": "NODE_ENV=development webpack --progress --config webpack.app.js", "test": "NODE_ENV=development webpack --progress --config webpack.app.js",
"watch": "NODE_ENV=development webpack --progress --watch --config webpack.app.js", "watch": "NODE_ENV=development webpack --progress --watch --config webpack.app.js",
"lint": "eslint --ext .js,.vue src", "lint": "eslint --ext .js,.vue src",
"lint:fix": "eslint --ext .js,.vue src --fix", "lint:fix": "eslint --ext .js,.vue src --fix",

View File

@@ -79,7 +79,7 @@ export default {
helper.info(message); helper.info(message);
} }
let url = formWrapper.getAttribute("action"); let url = formWrapper.getAttribute("action");
Http.getInstance(url) helper.httpClient(url)
.setData(formData) .setData(formData)
.setHandler(function (data) { .setHandler(function (data) {
successCallback(data, element); successCallback(data, element);
@@ -100,7 +100,7 @@ export default {
contentTable.getInstance().loading(); contentTable.getInstance().loading();
let url = formWrapper.getAttribute("action"); let url = formWrapper.getAttribute("action");
Http.getInstance(url) helper.httpClient(url)
.setData(formData) .setData(formData)
.setHandler(function (data) { .setHandler(function (data) {
if (data && data.title) { if (data && data.title) {
@@ -123,7 +123,7 @@ export default {
if (files) { if (files) {
let formWrapper = element.closest("form"); let formWrapper = element.closest("form");
let url = formWrapper.getAttribute("action"); let url = formWrapper.getAttribute("action");
return Http.getInstance(url) return helper.httpClient(url)
.setHandler(function (data) { .setHandler(function (data) {
successCallback(data, element); successCallback(data, element);
}) })

View File

@@ -29,7 +29,7 @@ const buttonHandler = (event, type) => {
console.log("gid is not set!"); console.log("gid is not set!");
} }
} }
Http.getInstance(url).setErrorHandler(function (xhr, textStatus, error) { helper.httpClient(url).setErrorHandler(function (xhr, textStatus, error) {
console.log(error); console.log(error);
}).setHandler(function (data) { }).setHandler(function (data) {
if (data.hasOwnProperty('error')) { if (data.hasOwnProperty('error')) {

View File

@@ -23,7 +23,7 @@ export default {
} }
let data = { ncd_downloader_dir: path }; let data = { ncd_downloader_dir: path };
let url = helper.generateUrl("/apps/ncdownloader/personal/save"); let url = helper.generateUrl("/apps/ncdownloader/personal/save");
Http.getInstance(url) helper.httpClient(url)
.setData(data) .setData(data)
.setHandler((data) => { .setHandler((data) => {
if (data.status) { if (data.status) {

View File

@@ -73,7 +73,7 @@ window.addEventListener('DOMContentLoaded', function () {
element.textContent = t("ncdownloader", "Stop Aria2"); element.textContent = t("ncdownloader", "Stop Aria2");
} }
} }
Http.getInstance(url).setHandler(function (data) { helper.httpClient(url).setHandler(function (data) {
callback(parent, oldHtml, data); callback(parent, oldHtml, data);
}).send(); }).send();
}) })

View File

@@ -3,49 +3,131 @@ type httpData = {
} }
type httpMethod = "POST" | "HEAD" | "GET"; type httpMethod = "POST" | "HEAD" | "GET";
type handler = (data: any) => void; type handler = (data: any) => void;
const Http = class { type httpClient = XMLHttpRequest;
type requestOptions = {
[key: string]: any;
headers: Headers;
}
export const Http = class {
data: httpData; data: httpData;
url: string; url: string;
method: httpMethod; method: httpMethod;
dataType: string; contentType: string;
xhr: XMLHttpRequest; client: httpClient;
handler: handler; handler: handler;
errorHandler: handler; errorHandler: handler;
legacyHttp: boolean;
headers: Headers
constructor(url: string) { constructor(url: string, legacyHttp: boolean = false) {
this.url = url; this.url = url;
this.method = 'POST'; this.method = 'POST';
this.data = null; this.data = null;
this.dataType = 'application/json'; this.contentType = 'application/json';
this.xhr = new XMLHttpRequest(); this.legacyHttp = legacyHttp
if (!legacyHttp) {
this.headers = new Headers();
}
} }
static getInstance(url: string) { isFetchAPISupported() {
return new Http(url); return (typeof fetch == 'function')
}
static create(url: string, legacyHttp: boolean = false) {
return new Http(url, legacyHttp);
} }
setData(data: httpData) { setData(data: httpData) {
this.data = data this.data = data
return this return this
} }
setDataType(value: string) { setContentType(value: string) {
this.dataType = value; this.contentType = value;
return this;
} }
send() { send() {
let token = this.getToken(); let token = this.getToken();
this.xhr.open(this.method, this.url); if (!this.isFetchAPISupported() || this.legacyHttp) {
this.xhr.setRequestHeader('requesttoken', token) this.client = new XMLHttpRequest();
this.xhr.setRequestHeader('OCS-APIREQUEST', 'true') this.client.open(this.method, this.url);
if (this.dataType) if (this.contentType)
this.xhr.setRequestHeader('Content-Type', this.dataType); this.setHeader('Content-Type', this.contentType);
let callback = this.handler; if (token) {
this.xhr.onload = () => { this.setHeader('requesttoken', token)
if (typeof callback === 'function') this.setHeader('OCS-APIREQUEST', 'true')
callback(JSON.parse(this.xhr.response)); }
let callback = this.handler;
this.client.onreadystatechange = () => {
if (this.client.readyState === XMLHttpRequest.DONE) {
let status = this.client.status;
const contentType = this.client.getResponseHeader("Content-Type")
if (status === 0 || (status >= 200 && status < 400)) {
if (typeof callback === 'function' && contentType.indexOf("application/json") !== -1) {
callback(JSON.parse(this.client.response));
}
else {
callback(this.client.response);
}
}
}
}
this.client.onerror = this.errorHandler;
let params = this.data ? JSON.stringify(this.data) : null
this.client.send(params);
} else {
let options = this.getRequestOpts();
fetch(options).then(response => {
if (response.status !== 200) {
console.log('Network failures. Status Code: ' + response.status);
return;
}
const contentType = response.headers.get('content-type');
if (contentType && contentType.indexOf("application/json") !== -1) {
response.json().then(data => {
this.handler(data)
})
} else {
response.text().then(data => {
this.handler(data)
})
}
}).catch(this.errorHandler)
} }
this.xhr.onerror = this.errorHandler;
this.xhr.send(JSON.stringify(this.data)); }
setHeader(key: string, val: string) {
if (this.legacyHttp) {
this.client.setRequestHeader(key, val)
} else {
this.headers.set(key, val);
}
}
appendHeader(key: string, val: string) {
this.headers.append(key, val);
}
getRequestOpts() {
this.setHeader('content-type', this.contentType);
let token;
if (token = this.getToken()) {
this.setHeader('requesttoken', token)
this.setHeader('OCS-APIREQUEST', 'true')
}
if (this.method == 'POST' && this.data) {
var body = JSON.stringify(this.data);
}
let options: requestOptions = {
headers: this.headers,
method: this.method,
body: body,
mode: 'cors',
cache: 'default'
}
return new Request(this.url, options);
} }
getToken() { getToken() {
return document.getElementsByTagName('head')[0].getAttribute('data-requesttoken') if (typeof document == "undefined") {
return null
}
return window.document.getElementsByTagName('head')[0].getAttribute('data-requesttoken')
} }
setUrl(url: string) { setUrl(url: string) {
this.url = url this.url = url
@@ -60,19 +142,19 @@ const Http = class {
return this; return this;
} }
setErrorHandler(handler: handler) { setErrorHandler(handler: handler) {
this.errorHandler = handler this.errorHandler = handler || function (error) { console.log(error) };
return this; return this;
} }
upload(file: File) { upload(file: File) {
const fd = new FormData(); const fd = new FormData();
this.xhr.open(this.method, this.url, true); this.client.open(this.method, this.url, true);
let callback = this.handler; let callback = this.handler;
this.xhr.onload = () => { this.client.onload = () => {
if (typeof callback === 'function') if (typeof callback === 'function')
callback(JSON.parse(this.xhr.response)); callback(JSON.parse(this.client.response));
} }
fd.append('torrentfile', file); fd.append('torrentfile', file);
return this.xhr.send(fd); return this.client.send(fd);
} }
} }

View File

@@ -44,7 +44,7 @@ window.addEventListener('DOMContentLoaded', function () {
OC_msg.finishedError('#ncdownloader-message-banner', 'invalid options: ' + badOptions.join(',')); OC_msg.finishedError('#ncdownloader-message-banner', 'invalid options: ' + badOptions.join(','));
return; return;
} }
Http.getInstance(url).setData(data).setHandler(function (data) { helper.httpClient(url).setData(data).setHandler(function (data) {
if (data.hasOwnProperty("error")) { if (data.hasOwnProperty("error")) {
OC_msg.finishedError('#ncdownloader-message-banner', data.error); OC_msg.finishedError('#ncdownloader-message-banner', data.error);
} else if (data.hasOwnProperty("message")) { } else if (data.hasOwnProperty("message")) {
@@ -115,7 +115,7 @@ window.addEventListener('DOMContentLoaded', function () {
e.preventDefault(); e.preventDefault();
this.parentNode.remove(); this.parentNode.remove();
}) })
Http.getInstance(generateUrl("/apps/ncdownloader/personal/aria2/get")).setHandler(function (data) { helper.httpClient(generateUrl("/apps/ncdownloader/personal/aria2/get")).setHandler(function (data) {
if (!data) { if (!data) {
return; return;
} }
@@ -127,7 +127,7 @@ window.addEventListener('DOMContentLoaded', function () {
settingsForm.getInstance().render(input); settingsForm.getInstance().render(input);
}).send(); }).send();
Http.getInstance(generateUrl("/apps/ncdownloader/personal/youtube-dl/get")).setHandler(function (data) { helper.httpClient(generateUrl("/apps/ncdownloader/personal/youtube-dl/get")).setHandler(function (data) {
if (!data) { if (!data) {
return; return;
} }

View File

@@ -70,7 +70,7 @@ export default {
data[name] = value ? 1 : 0; data[name] = value ? 1 : 0;
let path = (name == "ncd_disable_bt") ? "/admin/save" : "/personal/save"; let path = (name == "ncd_disable_bt") ? "/admin/save" : "/personal/save";
const url = helper.generateUrl(basePath + path); const url = helper.generateUrl(basePath + path);
Http.getInstance(url) helper.httpClient(url)
.setData(data) .setData(data)
.setHandler((resp) => { .setHandler((resp) => {
if (resp["message"]) { if (resp["message"]) {

View File

@@ -34,7 +34,7 @@ const helper = {
scanFolder(forceScan = false, path = "/apps/ncdownloader/scanfolder") { scanFolder(forceScan = false, path = "/apps/ncdownloader/scanfolder") {
let url = helper.generateUrl(path); let url = helper.generateUrl(path);
return new Promise((resolve) => { return new Promise((resolve) => {
Http.getInstance(url).setData({ "force": forceScan }).setHandler(function (data) { helper.httpClient(url).setData({ "force": forceScan }).setHandler(function (data) {
resolve(data.status); resolve(data.status);
}).send(); }).send();
}); });
@@ -48,7 +48,7 @@ const helper = {
refresh(path) { refresh(path) {
path = path || "/apps/ncdownloader/status/active"; path = path || "/apps/ncdownloader/status/active";
let url = helper.generateUrl(path); let url = helper.generateUrl(path);
Http.getInstance(url).setHandler(function (data) { helper.httpClient(url).setHandler(function (data) {
if (data && data.row) { if (data && data.row) {
contentTable.getInstance(data.title, data.row).create(); contentTable.getInstance(data.title, data.row).create();
} else { } else {
@@ -144,7 +144,7 @@ const helper = {
}, },
getCounters() { getCounters() {
let url = helper.generateUrl("apps/ncdownloader/counters"); let url = helper.generateUrl("apps/ncdownloader/counters");
Http.getInstance(url).setMethod("GET").setHandler(function (data) { helper.httpClient(url).setMethod("GET").setHandler(function (data) {
if (data["counter"]) if (data["counter"])
helper.updateCounter(data["counter"]); helper.updateCounter(data["counter"]);
}).send(); }).send();
@@ -299,10 +299,13 @@ const helper = {
getSettings(key, defaultValue = null, type = 2) { getSettings(key, defaultValue = null, type = 2) {
let url = helper.generateUrl("/apps/ncdownloader/getsettings"); let url = helper.generateUrl("/apps/ncdownloader/getsettings");
return new Promise(resolve => { return new Promise(resolve => {
Http.getInstance(url).setData({ name: key, type: type, default: defaultValue }).setHandler(data => { helper.httpClient(url).setData({ name: key, type: type, default: defaultValue }).setHandler(data => {
resolve(data) resolve(data)
}).send() }).send()
}) })
},
httpClient(url) {
return new Http.create(url, true)
} }
} }