108 lines
3.1 KiB
JavaScript
108 lines
3.1 KiB
JavaScript
import { basicApi } from './apiBasic'
|
||
import { Tools } from '../main/tools'
|
||
import { define } from '../define/define'
|
||
|
||
export class DiscordAPI {
|
||
constructor() {
|
||
this.tools = new Tools()
|
||
}
|
||
|
||
/**
|
||
* 通过设置的ID获取MJ API的任务
|
||
* @param {*} id
|
||
*/
|
||
async GetMJAPITaskByID(id, url, key) {
|
||
try {
|
||
let res
|
||
url = url.replace('${id}', id)
|
||
let headers = {
|
||
Authorization: key
|
||
}
|
||
if (url.includes(define.remotemj_api)) {
|
||
headers = {
|
||
'mj-api-secret': define.API
|
||
}
|
||
}
|
||
res = await basicApi.get(url, headers)
|
||
|
||
let progress =
|
||
res.data.progress && res.data.progress.length > 0
|
||
? parseInt(res.data.progress.slice(0, -1))
|
||
: 0
|
||
let status = res.data.status.toLowerCase()
|
||
// let code = (status == "success" || status == "in_progress" || status == "not_start") ? 1 : 0;
|
||
let code = status == 'failure' || status == 'cancel' ? 0 : 1
|
||
// 返回前端
|
||
let res_data = {
|
||
type: 'updated',
|
||
progress: progress,
|
||
category: 'api_mj',
|
||
image_click: res.data.imageUrl,
|
||
image_show: res.data.imageUrl,
|
||
message_id: res.data.id,
|
||
action: res.data.action,
|
||
status: status,
|
||
code: code
|
||
}
|
||
|
||
// 判断当前的API是哪个
|
||
if (url.includes('mjapi.deepwl.net')) {
|
||
if (res_data.code == 0) {
|
||
res_data['message'] = res.data.failReason
|
||
}
|
||
} else if (url.includes('api.ephone.ai')) {
|
||
// ePhoneAPI
|
||
if (res_data.code == 0) {
|
||
res_data['message'] = res.data.failReason
|
||
}
|
||
} else if (url.includes('laitool')) {
|
||
// laitool
|
||
if (res_data.code == 0) {
|
||
res_data['message'] = res.data.failReason
|
||
}
|
||
}
|
||
return res_data
|
||
} catch (error) {
|
||
throw error
|
||
}
|
||
}
|
||
|
||
/**
|
||
* MJ使用API进行生图
|
||
*/
|
||
async mjApiImagine(url, data, headers) {
|
||
try {
|
||
// 判断是不是需要垫图,将指定的图片转换为base64
|
||
for (let i = 0; data.base64Array && i < data.base64Array.length; i++) {
|
||
const element = data.base64Array[i]
|
||
// 将指定的图片转换为base64
|
||
// 判断图片是本地图片还是网络图片
|
||
if (element.indexOf('http') == -1) {
|
||
// 本地图片
|
||
let base64 = await this.tools.readFileBase64(element)
|
||
data.base64Array[i] = `data:image/png;base64,${base64}`
|
||
} else {
|
||
// 网络图片
|
||
// 请求对应的图片
|
||
let image_buffer = await basicApi.get(element)
|
||
// 将返回来的数据转为base64
|
||
let base64 = image_buffer.data.toString('base64')
|
||
data.base64Array[i] = `data:image/png;base64,${base64}`
|
||
}
|
||
}
|
||
|
||
let res = await basicApi.post(url, data, headers)
|
||
console.log(res)
|
||
let res_data = res.data
|
||
// 判断res_data 是不是json格式的字符串,是就序列化为json对象
|
||
if (typeof res_data == 'string') {
|
||
res_data = JSON.parse(res_data)
|
||
}
|
||
// 直接返回,错误信息外面判断
|
||
return res_data
|
||
} catch (error) {
|
||
throw error
|
||
}
|
||
}
|
||
}
|