1
0
mirror of https://git.sr.ht/~cadence/bibliogram synced 2024-11-16 21:27:30 +00:00
bibliogram/src/lib/structures/Assistant.js

61 lines
2.4 KiB
JavaScript
Raw Normal View History

2020-04-07 06:30:00 +00:00
const {request} = require("../utils/request")
const constants = require("../constants")
class Assistant {
2020-04-12 14:52:04 +00:00
constructor(origin, key) {
2020-04-07 06:30:00 +00:00
this.origin = origin
2020-04-12 14:52:04 +00:00
this.key = key
2020-04-07 06:30:00 +00:00
this.lastRequest = 0
this.lastRequestStatus = constants.symbols.assistant_statuses.NONE
}
available() {
if (this.lastRequestStatus === constants.symbols.assistant_statuses.OFFLINE) {
2020-04-12 14:52:04 +00:00
return Date.now() - this.lastRequest > constants.use_assistant.offline_request_cooldown
2020-04-07 06:30:00 +00:00
} else if (this.lastRequestStatus === constants.symbols.assistant_statuses.BLOCKED) {
2020-04-12 14:52:04 +00:00
return Date.now() - this.lastRequest > constants.use_assistant.blocked_request_cooldown
} else if (this.lastRequestStatus === constants.symbols.assistant_statuses.NOT_AUTHENTICATED) {
return false
2020-04-07 06:30:00 +00:00
} else {
return true
}
}
requestUser(username) {
this.lastRequest = Date.now()
return new Promise((resolve, reject) => {
2020-04-12 14:52:04 +00:00
const url = new URL(`${this.origin}/api/user/v1/${username}`)
if (this.key !== null) url.searchParams.append("key", this.key)
request(url.toString()).json().then(root => {
2020-04-07 06:33:35 +00:00
// console.log(root)
2020-04-07 06:30:00 +00:00
if (root.status === "ok") {
this.lastRequestStatus = constants.symbols.assistant_statuses.OK
resolve(root.data.user)
2020-04-08 03:11:49 +00:00
} else { // "fail"
if (root.identifier === "NOT_FOUND") {
this.lastRequestStatus = constants.symbols.assistant_statuses.OK
reject(constants.symbols.NOT_FOUND)
} else if (root.identifier === "AGE_RESTRICTED") {
this.lastRequestStatus = constants.symbols.assistant_statuses.OK
reject(constants.symbols.extractor_results.AGE_RESTRICTED)
2020-04-12 14:52:04 +00:00
} else if (root.identifier === "NOT_AUTHENTICATED") {
this.lastRequestStatus = constants.symbols.assistant_statuses.NOT_AUTHENTICATED
reject(constants.symbols.assistant_statuses.NOT_AUTHENTICATED)
2020-04-08 03:11:49 +00:00
} else { // blocked
this.lastRequestStatus = constants.symbols.assistant_statuses.BLOCKED
reject(constants.symbols.assistant_statuses.BLOCKED)
}
2020-04-07 06:30:00 +00:00
}
}).catch(error => {
2020-04-09 14:02:43 +00:00
// this catches network errors, parse errors, and property access errors.
// all of these mean that the user API didn't behave in an expected manner, probably because the server is doing something else
2020-04-07 06:33:35 +00:00
// console.error(error)
2020-04-07 06:30:00 +00:00
this.lastRequestStatus = constants.symbols.assistant_statuses.OFFLINE
reject(constants.symbols.assistant_statuses.OFFLINE)
})
})
}
}
module.exports = Assistant