2020-02-02 11:43:56 +00:00
|
|
|
const constants = require("../constants")
|
|
|
|
const {request} = require("./request")
|
|
|
|
|
|
|
|
class TorSwitcher {
|
|
|
|
constructor() {
|
|
|
|
this.torManager = null
|
|
|
|
}
|
|
|
|
|
|
|
|
setManager(torManager) {
|
|
|
|
this.torManager = torManager
|
|
|
|
}
|
|
|
|
|
2020-02-02 15:09:40 +00:00
|
|
|
canUseTor() {
|
|
|
|
return !!this.torManager
|
|
|
|
}
|
|
|
|
|
2020-02-02 11:43:56 +00:00
|
|
|
/**
|
|
|
|
* Request from the URL.
|
|
|
|
* The test function will be called with the response object.
|
|
|
|
* If the test function succeeds, its return value will be returned here.
|
|
|
|
* If the test function fails, its error will be rejected here.
|
|
|
|
* Only include rate limit logic in the test function!
|
|
|
|
* @param {string} url
|
2020-06-21 06:06:30 +00:00
|
|
|
* @param {(res: import("./request_backends/reference").GrabResponse) => any} test
|
|
|
|
* @returns {Promise<import("./request_backends/reference")>}
|
2020-02-02 11:43:56 +00:00
|
|
|
*/
|
2020-02-02 13:24:14 +00:00
|
|
|
request(type, url, test) {
|
|
|
|
if (this.torManager && constants.tor.for[type]) {
|
2020-02-02 11:43:56 +00:00
|
|
|
return this.torManager.request(url, test)
|
|
|
|
} else {
|
2020-03-15 06:50:29 +00:00
|
|
|
return request(url).check(test)
|
2020-02-02 11:43:56 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const switcher = new TorSwitcher()
|
|
|
|
|
2020-02-02 13:24:14 +00:00
|
|
|
if (constants.tor.enabled) {
|
2020-02-02 11:43:56 +00:00
|
|
|
require("./tor").then(torManager => {
|
|
|
|
if (torManager) switcher.setManager(torManager)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = switcher
|