mirror of
https://github.com/LLOneBot/LLOneBot.git
synced 2024-11-22 01:56:33 +00:00
style: format
This commit is contained in:
4434
package-lock.json
generated
4434
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -14,7 +14,6 @@
|
||||
"author": "",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"electron-vite": "^2.0.0",
|
||||
"express": "^4.18.2",
|
||||
"fluent-ffmpeg": "^2.1.2",
|
||||
"music-metadata": "^8.1.4",
|
||||
@@ -29,9 +28,15 @@
|
||||
"@types/node": "^20.11.24",
|
||||
"@types/uuid": "^9.0.8",
|
||||
"@types/ws": "^8.5.10",
|
||||
"@typescript-eslint/eslint-plugin": "^6.4.0",
|
||||
"electron": "^29.0.1",
|
||||
"electron-vite": "^2.0.0",
|
||||
"eslint": "^8.0.1",
|
||||
"eslint-plugin-import": "^2.25.2",
|
||||
"eslint-plugin-n": "^15.0.0 || ^16.0.0 ",
|
||||
"eslint-plugin-promise": "^6.0.0",
|
||||
"ts-node": "^10.9.2",
|
||||
"typescript": "^5.2.2",
|
||||
"typescript": "*",
|
||||
"vite": "^5.1.4",
|
||||
"vite-plugin-cp": "^4.0.8"
|
||||
}
|
||||
|
@@ -1,20 +1,22 @@
|
||||
import fs from "fs";
|
||||
import path from"path";
|
||||
import {version} from "../src/version";
|
||||
const manifestPath = path.join(__dirname, "../manifest.json");
|
||||
function readManifest(): any{
|
||||
if (fs.existsSync(manifestPath)){
|
||||
return JSON.parse(fs.readFileSync(manifestPath, "utf-8"));
|
||||
import fs from 'fs'
|
||||
import path from 'path'
|
||||
import { version } from '../src/version'
|
||||
|
||||
const manifestPath = path.join(__dirname, '../manifest.json')
|
||||
|
||||
function readManifest (): any {
|
||||
if (fs.existsSync(manifestPath)) {
|
||||
return JSON.parse(fs.readFileSync(manifestPath, 'utf-8'))
|
||||
}
|
||||
}
|
||||
|
||||
function writeManifest(manifest: any){
|
||||
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2));
|
||||
function writeManifest (manifest: any) {
|
||||
fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2))
|
||||
}
|
||||
|
||||
let manifest = readManifest();
|
||||
if (version !== manifest.version){
|
||||
manifest.version = version;
|
||||
manifest.name = `LLOneBot v${version}`;
|
||||
writeManifest(manifest);
|
||||
const manifest = readManifest()
|
||||
if (version !== manifest.version) {
|
||||
manifest.version = version
|
||||
manifest.name = `LLOneBot v${version}`
|
||||
writeManifest(manifest)
|
||||
}
|
@@ -1,7 +1,5 @@
|
||||
import {Peer} from "../ntqqapi/ntcall";
|
||||
|
||||
export const CHANNEL_GET_CONFIG = "llonebot_get_config"
|
||||
export const CHANNEL_SET_CONFIG = "llonebot_set_config"
|
||||
export const CHANNEL_LOG = "llonebot_log"
|
||||
export const CHANNEL_ERROR = "llonebot_error"
|
||||
export const CHANNEL_SELECT_FILE = "llonebot_select_ffmpeg"
|
||||
export const CHANNEL_GET_CONFIG = 'llonebot_get_config'
|
||||
export const CHANNEL_SET_CONFIG = 'llonebot_set_config'
|
||||
export const CHANNEL_LOG = 'llonebot_log'
|
||||
export const CHANNEL_ERROR = 'llonebot_error'
|
||||
export const CHANNEL_SELECT_FILE = 'llonebot_select_ffmpeg'
|
||||
|
@@ -1,8 +1,8 @@
|
||||
import fs from "fs";
|
||||
import {Config, OB11Config} from "./types";
|
||||
import {Config, OB11Config} from './types';
|
||||
import {mergeNewProperties} from "./utils";
|
||||
|
||||
export const HOOK_LOG= false;
|
||||
export const HOOK_LOG = false;
|
||||
|
||||
export class ConfigUtil {
|
||||
private readonly configPath: string;
|
||||
@@ -12,7 +12,7 @@ export class ConfigUtil {
|
||||
this.configPath = configPath;
|
||||
}
|
||||
|
||||
getConfig(cache=true) {
|
||||
getConfig(cache = true) {
|
||||
if (this.config && cache) {
|
||||
return this.config;
|
||||
}
|
||||
|
@@ -1,40 +1,39 @@
|
||||
import {NTQQApi} from '../ntqqapi/ntcall';
|
||||
import {NTQQApi} from '../ntqqapi/ntcall'
|
||||
import {
|
||||
FileElement,
|
||||
Friend,
|
||||
FriendRequest,
|
||||
Group,
|
||||
GroupMember,
|
||||
GroupNotify,
|
||||
PicElement, PttElement,
|
||||
RawMessage,
|
||||
SelfInfo, VideoElement
|
||||
} from "../ntqqapi/types";
|
||||
import {FileCache, LLOneBotError} from "./types";
|
||||
export let selfInfo: SelfInfo = {
|
||||
uid: "",
|
||||
uin: "",
|
||||
nick: "",
|
||||
online: true,
|
||||
}
|
||||
export let groups: Group[] = []
|
||||
export let friends: Friend[] = []
|
||||
export let msgHistory: Record<string, RawMessage> = {} // msgId: RawMessage
|
||||
export let groupNotifies: Map<string, GroupNotify> = new Map<string, GroupNotify>();
|
||||
export let friendRequests: Map<number, FriendRequest> = new Map<number, FriendRequest>();
|
||||
export let llonebotError: LLOneBotError = {
|
||||
ffmpegError: "",
|
||||
otherError: ""
|
||||
}
|
||||
let globalMsgId = Math.floor(Date.now() / 1000);
|
||||
type Friend,
|
||||
type FriendRequest,
|
||||
type Group,
|
||||
type GroupMember,
|
||||
type GroupNotify,
|
||||
type RawMessage,
|
||||
type SelfInfo
|
||||
} from '../ntqqapi/types'
|
||||
import {type FileCache, type LLOneBotError} from './types'
|
||||
|
||||
export let fileCache: Map<string, FileCache> = new Map();
|
||||
export const selfInfo: SelfInfo = {
|
||||
uid: '',
|
||||
uin: '',
|
||||
nick: '',
|
||||
online: true
|
||||
}
|
||||
export const groups: Group[] = []
|
||||
export const friends: Friend[] = []
|
||||
export const msgHistory: Record<string, RawMessage> = {} // msgId: RawMessage
|
||||
export const groupNotifies: Map<string, GroupNotify> = new Map<string, GroupNotify>()
|
||||
export const friendRequests: Map<number, FriendRequest> = new Map<number, FriendRequest>()
|
||||
export const llonebotError: LLOneBotError = {
|
||||
ffmpegError: '',
|
||||
otherError: ''
|
||||
}
|
||||
let globalMsgId = Math.floor(Date.now() / 1000)
|
||||
|
||||
export const fileCache = new Map<string, FileCache>()
|
||||
|
||||
export function addHistoryMsg(msg: RawMessage): boolean {
|
||||
let existMsg = msgHistory[msg.msgId]
|
||||
const existMsg = msgHistory[msg.msgId]
|
||||
if (existMsg) {
|
||||
Object.assign(existMsg, msg)
|
||||
msg.msgShortId = existMsg.msgShortId;
|
||||
msg.msgShortId = existMsg.msgShortId
|
||||
return false
|
||||
}
|
||||
msg.msgShortId = ++globalMsgId
|
||||
@@ -47,9 +46,8 @@ export function getHistoryMsgByShortId(shortId: number | string) {
|
||||
return Object.values(msgHistory).find(msg => msg.msgShortId.toString() == shortId.toString())
|
||||
}
|
||||
|
||||
|
||||
export async function getFriend(qq: string): Promise<Friend | undefined> {
|
||||
let friend = friends.find(friend => friend.uin === qq)
|
||||
const friend = friends.find(friend => friend.uin === qq)
|
||||
// if (!friend){
|
||||
// friends = (await NTQQApi.getFriends(true))
|
||||
// friend = friends.find(friend => friend.uin === qq)
|
||||
@@ -58,7 +56,7 @@ export async function getFriend(qq: string): Promise<Friend | undefined> {
|
||||
}
|
||||
|
||||
export async function getGroup(qq: string): Promise<Group | undefined> {
|
||||
let group = groups.find(group => group.groupCode === qq)
|
||||
const group = groups.find(group => group.groupCode === qq)
|
||||
// if (!group){
|
||||
// groups = await NTQQApi.getGroups(true);
|
||||
// group = groups.find(group => group.groupCode === qq)
|
||||
@@ -67,9 +65,9 @@ export async function getGroup(qq: string): Promise<Group | undefined> {
|
||||
}
|
||||
|
||||
export async function getGroupMember(groupQQ: string | number, memberQQ: string | number, memberUid: string = null) {
|
||||
groupQQ = groupQQ.toString();
|
||||
if (memberQQ){
|
||||
memberQQ = memberQQ.toString();
|
||||
groupQQ = groupQQ.toString()
|
||||
if (memberQQ) {
|
||||
memberQQ = memberQQ.toString()
|
||||
}
|
||||
const group = await getGroup(groupQQ)
|
||||
if (group) {
|
||||
@@ -82,7 +80,7 @@ export async function getGroupMember(groupQQ: string | number, memberQQ: string
|
||||
let member = group.members?.find(filterFunc)
|
||||
if (!member) {
|
||||
const _members = await NTQQApi.getGroupMembers(groupQQ)
|
||||
if (_members.length) {
|
||||
if (_members.length > 0) {
|
||||
group.members = _members
|
||||
}
|
||||
member = group.members?.find(filterFunc)
|
||||
@@ -91,21 +89,16 @@ export async function getGroupMember(groupQQ: string | number, memberQQ: string
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
export function getHistoryMsgBySeq(seq: string) {
|
||||
return Object.values(msgHistory).find(msg => msg.msgSeq === seq)
|
||||
}
|
||||
|
||||
|
||||
export let uidMaps: Record<string, string> = {} // 一串加密的字符串(uid) -> qq号
|
||||
export const uidMaps: Record<string, string> = {} // 一串加密的字符串(uid) -> qq号
|
||||
|
||||
export function getUidByUin(uin: string) {
|
||||
for (const key in uidMaps) {
|
||||
if (uidMaps[key] === uin) {
|
||||
return key;
|
||||
return key
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import express, {Express, Request, Response, json} from "express";
|
||||
import express, {Express, json, Request, Response} from "express";
|
||||
import {getConfigUtil, log} from "../utils";
|
||||
import http from "http";
|
||||
|
||||
@@ -45,13 +45,13 @@ export abstract class HttpServerBase {
|
||||
}
|
||||
|
||||
stop() {
|
||||
if (this.server){
|
||||
if (this.server) {
|
||||
this.server.close()
|
||||
this.server = null;
|
||||
}
|
||||
}
|
||||
|
||||
restart(port: number){
|
||||
restart(port: number) {
|
||||
this.stop()
|
||||
this.start(port)
|
||||
}
|
||||
@@ -63,20 +63,20 @@ export abstract class HttpServerBase {
|
||||
url = "/" + url
|
||||
}
|
||||
|
||||
if (!this.expressAPP[method]){
|
||||
if (!this.expressAPP[method]) {
|
||||
const err = `${this.name} register router failed,${method} not exist`;
|
||||
log(err);
|
||||
throw err;
|
||||
}
|
||||
this.expressAPP[method](url, this.authorize, async (req: Request, res: Response) => {
|
||||
let payload = req.body;
|
||||
if (method == "get"){
|
||||
if (method == "get") {
|
||||
payload = req.query
|
||||
}
|
||||
log("收到http请求", url, payload);
|
||||
try{
|
||||
try {
|
||||
res.send(await handler(res, payload))
|
||||
}catch (e) {
|
||||
} catch (e) {
|
||||
this.handleFailed(res, payload, e.stack.toString())
|
||||
}
|
||||
});
|
||||
|
@@ -15,7 +15,7 @@ class WebsocketClientBase {
|
||||
}
|
||||
}
|
||||
|
||||
onMessage(msg: string){
|
||||
onMessage(msg: string) {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -29,11 +29,11 @@ export class WebsocketServerBase {
|
||||
|
||||
start(port: number) {
|
||||
this.ws = new WebSocketServer({port});
|
||||
this.ws.on("connection", (wsClient, req)=>{
|
||||
this.ws.on("connection", (wsClient, req) => {
|
||||
const url = req.url.split("?").shift()
|
||||
this.authorize(wsClient, req);
|
||||
this.onConnect(wsClient, url, req);
|
||||
wsClient.on("message", async (msg)=>{
|
||||
wsClient.on("message", async (msg) => {
|
||||
this.onMessage(wsClient, url, msg.toString())
|
||||
})
|
||||
})
|
||||
@@ -45,7 +45,8 @@ export class WebsocketServerBase {
|
||||
});
|
||||
this.ws = null;
|
||||
}
|
||||
restart(port: number){
|
||||
|
||||
restart(port: number) {
|
||||
this.stop();
|
||||
this.start(port);
|
||||
}
|
||||
@@ -85,7 +86,7 @@ export class WebsocketServerBase {
|
||||
|
||||
}
|
||||
|
||||
onMessage(wsClient: WebSocket, url: string, msg: string) {
|
||||
onMessage(wsClient: WebSocket, url: string, msg: string) {
|
||||
|
||||
}
|
||||
|
||||
|
@@ -1,40 +1,37 @@
|
||||
import {FileElement, PicElement, PttElement, VideoElement} from "../ntqqapi/types";
|
||||
|
||||
export interface OB11Config {
|
||||
httpPort: number
|
||||
httpHosts: string[]
|
||||
wsPort: number
|
||||
wsHosts: string[]
|
||||
enableHttp?: boolean
|
||||
enableHttpPost?: boolean
|
||||
enableWs?: boolean
|
||||
enableWsReverse?: boolean
|
||||
messagePostFormat?: 'array' | 'string'
|
||||
httpPort: number
|
||||
httpHosts: string[]
|
||||
wsPort: number
|
||||
wsHosts: string[]
|
||||
enableHttp?: boolean
|
||||
enableHttpPost?: boolean
|
||||
enableWs?: boolean
|
||||
enableWsReverse?: boolean
|
||||
messagePostFormat?: 'array' | 'string'
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
ob11: OB11Config
|
||||
token?: string
|
||||
heartInterval?: number // ms
|
||||
enableLocalFile2Url?: boolean // 开启后,本地文件路径图片会转成http链接, 语音会转成base64
|
||||
debug?: boolean
|
||||
reportSelfMessage?: boolean
|
||||
log?: boolean
|
||||
autoDeleteFile?: boolean
|
||||
autoDeleteFileSecond?: number
|
||||
ffmpeg?: string // ffmpeg路径
|
||||
ob11: OB11Config
|
||||
token?: string
|
||||
heartInterval?: number // ms
|
||||
enableLocalFile2Url?: boolean // 开启后,本地文件路径图片会转成http链接, 语音会转成base64
|
||||
debug?: boolean
|
||||
reportSelfMessage?: boolean
|
||||
log?: boolean
|
||||
autoDeleteFile?: boolean
|
||||
autoDeleteFileSecond?: number
|
||||
ffmpeg?: string // ffmpeg路径
|
||||
}
|
||||
|
||||
export type LLOneBotError = {
|
||||
ffmpegError?: string
|
||||
otherError?: string
|
||||
export interface LLOneBotError {
|
||||
ffmpegError?: string
|
||||
otherError?: string
|
||||
}
|
||||
|
||||
|
||||
export interface FileCache{
|
||||
fileName: string,
|
||||
filePath: string,
|
||||
fileSize: string,
|
||||
url?: string,
|
||||
downloadFunc?: () => Promise<void>;
|
||||
export interface FileCache {
|
||||
fileName: string
|
||||
filePath: string
|
||||
fileSize: string
|
||||
url?: string
|
||||
downloadFunc?: () => Promise<void>
|
||||
}
|
@@ -33,7 +33,7 @@ function truncateString(obj: any, maxLength = 500) {
|
||||
|
||||
export function log(...msg: any[]) {
|
||||
if (!getConfigUtil().getConfig().log) {
|
||||
return
|
||||
return //console.log(...msg);
|
||||
}
|
||||
let currentDateTime = new Date().toLocaleString();
|
||||
const date = new Date();
|
||||
@@ -195,9 +195,9 @@ export async function encodeSilk(filePath: string) {
|
||||
const pttPath = path.join(CONFIG_DIR, uuidv4());
|
||||
if (getFileHeader(filePath) !== "02232153494c4b") {
|
||||
log(`语音文件${filePath}需要转换成silk`)
|
||||
const isWav = await isWavFile(filePath);
|
||||
const _isWav = await isWavFile(filePath);
|
||||
const wavPath = pttPath + ".wav"
|
||||
if (!isWav) {
|
||||
if (!_isWav) {
|
||||
log(`语音文件${filePath}正在转换成wav`)
|
||||
// let voiceData = await fsp.readFile(filePath)
|
||||
await new Promise((resolve, reject) => {
|
||||
|
12
src/global.d.ts
vendored
12
src/global.d.ts
vendored
@@ -1,10 +1,8 @@
|
||||
import {LLOneBot} from "./preload";
|
||||
|
||||
|
||||
import { type LLOneBot } from './preload'
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
llonebot: LLOneBot;
|
||||
LiteLoader: any;
|
||||
}
|
||||
interface Window {
|
||||
llonebot: LLOneBot
|
||||
LiteLoader: any
|
||||
}
|
||||
}
|
@@ -141,7 +141,7 @@ function onLoad() {
|
||||
// 检查ffmpeg
|
||||
if (arg.ffmpeg) {
|
||||
checkFfmpeg(arg.ffmpeg).then(success => {
|
||||
if (success){
|
||||
if (success) {
|
||||
llonebotError.ffmpegError = ''
|
||||
}
|
||||
})
|
||||
@@ -254,8 +254,8 @@ function onLoad() {
|
||||
continue;
|
||||
}
|
||||
let existNotify = groupNotifies[notify.seq];
|
||||
if (existNotify){
|
||||
if (Date.now() - existNotify.time < 3000){
|
||||
if (existNotify) {
|
||||
if (Date.now() - existNotify.time < 3000) {
|
||||
continue
|
||||
}
|
||||
}
|
||||
@@ -298,8 +298,7 @@ function onLoad() {
|
||||
groupRequestEvent.comment = notify.postscript;
|
||||
groupRequestEvent.flag = notify.seq;
|
||||
postOB11Event(groupRequestEvent);
|
||||
}
|
||||
else if(notify.type == GroupNotifyTypes.INVITE_ME){
|
||||
} else if (notify.type == GroupNotifyTypes.INVITE_ME) {
|
||||
let groupInviteEvent = new OB11GroupRequestEvent();
|
||||
groupInviteEvent.group_id = parseInt(notify.group.groupCode);
|
||||
let user_id = (await NTQQApi.getUserDetailInfo(notify.user2.uid))?.uin
|
||||
@@ -368,16 +367,18 @@ function onLoad() {
|
||||
let getSelfNickCount = 0;
|
||||
const init = async () => {
|
||||
try {
|
||||
log("start get self info")
|
||||
const _ = await NTQQApi.getSelfInfo();
|
||||
log("get self info api result:", _);
|
||||
Object.assign(selfInfo, _);
|
||||
selfInfo.nick = selfInfo.uin;
|
||||
log("get self simple info", _);
|
||||
} catch (e) {
|
||||
log("retry get self info");
|
||||
log("retry get self info", e);
|
||||
}
|
||||
log("self info", selfInfo);
|
||||
if (selfInfo.uin) {
|
||||
try {
|
||||
const userInfo = (await NTQQApi.getUserInfo(selfInfo.uid));
|
||||
const userInfo = (await NTQQApi.getUserDetailInfo(selfInfo.uid));
|
||||
log("self info", userInfo);
|
||||
if (userInfo) {
|
||||
selfInfo.nick = userInfo.nick;
|
||||
|
@@ -1,71 +1,71 @@
|
||||
import {BrowserWindow} from 'electron';
|
||||
import {getConfigUtil, log, sleep} from "../common/utils";
|
||||
import {NTQQApi, NTQQApiClass, sendMessagePool} from "./ntcall";
|
||||
import {Group, RawMessage, User} from "./types";
|
||||
import {addHistoryMsg, friends, groups, msgHistory, selfInfo} from "../common/data";
|
||||
import {OB11GroupDecreaseEvent} from "../onebot11/event/notice/OB11GroupDecreaseEvent";
|
||||
import {OB11GroupIncreaseEvent} from "../onebot11/event/notice/OB11GroupIncreaseEvent";
|
||||
import {v4 as uuidv4} from "uuid"
|
||||
import {postOB11Event} from "../onebot11/server/postOB11Event";
|
||||
import {HOOK_LOG} from "../common/config";
|
||||
import fs from "fs";
|
||||
import {type BrowserWindow} from 'electron'
|
||||
import {getConfigUtil, log, sleep} from '../common/utils'
|
||||
import {NTQQApi, type NTQQApiClass, sendMessagePool} from './ntcall'
|
||||
import {type Group, type RawMessage, type User} from './types'
|
||||
import {addHistoryMsg, friends, groups, msgHistory, selfInfo} from '../common/data'
|
||||
import {OB11GroupDecreaseEvent} from '../onebot11/event/notice/OB11GroupDecreaseEvent'
|
||||
import {OB11GroupIncreaseEvent} from '../onebot11/event/notice/OB11GroupIncreaseEvent'
|
||||
import {v4 as uuidv4} from 'uuid'
|
||||
import {postOB11Event} from '../onebot11/server/postOB11Event'
|
||||
import {HOOK_LOG} from '../common/config'
|
||||
import fs from 'fs'
|
||||
|
||||
export let hookApiCallbacks: Record<string, (apiReturn: any) => void> = {}
|
||||
export const hookApiCallbacks: Record<string, (apiReturn: any) => void> = {}
|
||||
|
||||
export enum ReceiveCmd {
|
||||
UPDATE_MSG = "nodeIKernelMsgListener/onMsgInfoListUpdate",
|
||||
NEW_MSG = "nodeIKernelMsgListener/onRecvMsg",
|
||||
SELF_SEND_MSG = "nodeIKernelMsgListener/onAddSendMsg",
|
||||
USER_INFO = "nodeIKernelProfileListener/onProfileSimpleChanged",
|
||||
USER_DETAIL_INFO = "nodeIKernelProfileListener/onProfileDetailInfoChanged",
|
||||
GROUPS = "nodeIKernelGroupListener/onGroupListUpdate",
|
||||
GROUPS_UNIX = "onGroupListUpdate",
|
||||
FRIENDS = "onBuddyListChange",
|
||||
MEDIA_DOWNLOAD_COMPLETE = "nodeIKernelMsgListener/onRichMediaDownloadComplete",
|
||||
UNREAD_GROUP_NOTIFY = "nodeIKernelGroupListener/onGroupNotifiesUnreadCountUpdated",
|
||||
GROUP_NOTIFY = "nodeIKernelGroupListener/onGroupSingleScreenNotifies",
|
||||
FRIEND_REQUEST = "nodeIKernelBuddyListener/onBuddyReqChange",
|
||||
SELF_STATUS = "nodeIKernelProfileListener/onSelfStatusChanged",
|
||||
UPDATE_MSG = 'nodeIKernelMsgListener/onMsgInfoListUpdate',
|
||||
NEW_MSG = 'nodeIKernelMsgListener/onRecvMsg',
|
||||
SELF_SEND_MSG = 'nodeIKernelMsgListener/onAddSendMsg',
|
||||
USER_INFO = 'nodeIKernelProfileListener/onProfileSimpleChanged',
|
||||
USER_DETAIL_INFO = 'nodeIKernelProfileListener/onProfileDetailInfoChanged',
|
||||
GROUPS = 'nodeIKernelGroupListener/onGroupListUpdate',
|
||||
GROUPS_UNIX = 'onGroupListUpdate',
|
||||
FRIENDS = 'onBuddyListChange',
|
||||
MEDIA_DOWNLOAD_COMPLETE = 'nodeIKernelMsgListener/onRichMediaDownloadComplete',
|
||||
UNREAD_GROUP_NOTIFY = 'nodeIKernelGroupListener/onGroupNotifiesUnreadCountUpdated',
|
||||
GROUP_NOTIFY = 'nodeIKernelGroupListener/onGroupSingleScreenNotifies',
|
||||
FRIEND_REQUEST = 'nodeIKernelBuddyListener/onBuddyReqChange',
|
||||
SELF_STATUS = 'nodeIKernelProfileListener/onSelfStatusChanged',
|
||||
}
|
||||
|
||||
interface NTQQApiReturnData<PayloadType = unknown> extends Array<any> {
|
||||
0: {
|
||||
"type": "request",
|
||||
"eventName": NTQQApiClass,
|
||||
"callbackId"?: string
|
||||
},
|
||||
'type': 'request'
|
||||
'eventName': NTQQApiClass
|
||||
'callbackId'?: string
|
||||
}
|
||||
1:
|
||||
{
|
||||
cmdName: ReceiveCmd,
|
||||
cmdType: "event",
|
||||
Array<{
|
||||
cmdName: ReceiveCmd
|
||||
cmdType: 'event'
|
||||
payload: PayloadType
|
||||
}[]
|
||||
}>
|
||||
}
|
||||
|
||||
let receiveHooks: Array<{
|
||||
method: ReceiveCmd,
|
||||
const receiveHooks: Array<{
|
||||
method: ReceiveCmd
|
||||
hookFunc: ((payload: any) => void | Promise<void>)
|
||||
id: string
|
||||
}> = []
|
||||
|
||||
export function hookNTQQApiReceive(window: BrowserWindow) {
|
||||
const originalSend = window.webContents.send;
|
||||
const originalSend = window.webContents.send
|
||||
const patchSend = (channel: string, ...args: NTQQApiReturnData) => {
|
||||
HOOK_LOG && log(`received ntqq api message: ${channel}`, JSON.stringify(args))
|
||||
if (args?.[1] instanceof Array) {
|
||||
for (let receiveData of args?.[1]) {
|
||||
const ntQQApiMethodName = receiveData.cmdName;
|
||||
for (const receiveData of args?.[1]) {
|
||||
const ntQQApiMethodName = receiveData.cmdName
|
||||
// log(`received ntqq api message: ${channel} ${ntQQApiMethodName}`, JSON.stringify(receiveData))
|
||||
for (let hook of receiveHooks) {
|
||||
for (const hook of receiveHooks) {
|
||||
if (hook.method === ntQQApiMethodName) {
|
||||
new Promise((resolve, reject) => {
|
||||
try {
|
||||
let _ = hook.hookFunc(receiveData.payload)
|
||||
if (hook.hookFunc.constructor.name === "AsyncFunction") {
|
||||
const _ = hook.hookFunc(receiveData.payload)
|
||||
if (hook.hookFunc.constructor.name === 'AsyncFunction') {
|
||||
(_ as Promise<void>).then()
|
||||
}
|
||||
} catch (e) {
|
||||
log("hook error", e, receiveData.payload)
|
||||
log('hook error', e, receiveData.payload)
|
||||
}
|
||||
}).then()
|
||||
}
|
||||
@@ -74,35 +74,35 @@ export function hookNTQQApiReceive(window: BrowserWindow) {
|
||||
}
|
||||
if (args[0]?.callbackId) {
|
||||
// log("hookApiCallback", hookApiCallbacks, args)
|
||||
const callbackId = args[0].callbackId;
|
||||
const callbackId = args[0].callbackId
|
||||
if (hookApiCallbacks[callbackId]) {
|
||||
// log("callback found")
|
||||
new Promise((resolve, reject) => {
|
||||
hookApiCallbacks[callbackId](args[1]);
|
||||
hookApiCallbacks[callbackId](args[1])
|
||||
}).then()
|
||||
delete hookApiCallbacks[callbackId];
|
||||
delete hookApiCallbacks[callbackId]
|
||||
}
|
||||
}
|
||||
return originalSend.call(window.webContents, channel, ...args);
|
||||
return originalSend.call(window.webContents, channel, ...args)
|
||||
}
|
||||
window.webContents.send = patchSend;
|
||||
window.webContents.send = patchSend
|
||||
}
|
||||
|
||||
export function hookNTQQApiCall(window: BrowserWindow) {
|
||||
// 监听调用NTQQApi
|
||||
let webContents = window.webContents as any;
|
||||
const ipc_message_proxy = webContents._events["-ipc-message"]?.[0] || webContents._events["-ipc-message"];
|
||||
const webContents = window.webContents as any
|
||||
const ipc_message_proxy = webContents._events['-ipc-message']?.[0] || webContents._events['-ipc-message']
|
||||
|
||||
const proxyIpcMsg = new Proxy(ipc_message_proxy, {
|
||||
apply(target, thisArg, args) {
|
||||
HOOK_LOG && log("call NTQQ api", thisArg, args);
|
||||
return target.apply(thisArg, args);
|
||||
},
|
||||
});
|
||||
if (webContents._events["-ipc-message"]?.[0]) {
|
||||
webContents._events["-ipc-message"][0] = proxyIpcMsg;
|
||||
HOOK_LOG && log('call NTQQ api', thisArg, args)
|
||||
return target.apply(thisArg, args)
|
||||
}
|
||||
})
|
||||
if (webContents._events['-ipc-message']?.[0]) {
|
||||
webContents._events['-ipc-message'][0] = proxyIpcMsg
|
||||
} else {
|
||||
webContents._events["-ipc-message"] = proxyIpcMsg;
|
||||
webContents._events['-ipc-message'] = proxyIpcMsg
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,29 +113,29 @@ export function registerReceiveHook<PayloadType>(method: ReceiveCmd, hookFunc: (
|
||||
hookFunc,
|
||||
id
|
||||
})
|
||||
return id;
|
||||
return id
|
||||
}
|
||||
|
||||
export function removeReceiveHook(id: string) {
|
||||
const index = receiveHooks.findIndex(h => h.id === id)
|
||||
receiveHooks.splice(index, 1);
|
||||
receiveHooks.splice(index, 1)
|
||||
}
|
||||
|
||||
async function updateGroups(_groups: Group[], needUpdate: boolean = true) {
|
||||
for (let group of _groups) {
|
||||
let existGroup = groups.find(g => g.groupCode == group.groupCode);
|
||||
for (const group of _groups) {
|
||||
let existGroup = groups.find(g => g.groupCode == group.groupCode)
|
||||
if (existGroup) {
|
||||
Object.assign(existGroup, group);
|
||||
Object.assign(existGroup, group)
|
||||
} else {
|
||||
groups.push(group);
|
||||
existGroup = group;
|
||||
groups.push(group)
|
||||
existGroup = group
|
||||
}
|
||||
|
||||
if (needUpdate) {
|
||||
const members = await NTQQApi.getGroupMembers(group.groupCode);
|
||||
const members = await NTQQApi.getGroupMembers(group.groupCode)
|
||||
|
||||
if (members) {
|
||||
existGroup.members = members;
|
||||
existGroup.members = members
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -143,84 +143,83 @@ async function updateGroups(_groups: Group[], needUpdate: boolean = true) {
|
||||
|
||||
async function processGroupEvent(payload) {
|
||||
try {
|
||||
const newGroupList = payload.groupList;
|
||||
const newGroupList = payload.groupList
|
||||
for (const group of newGroupList) {
|
||||
let existGroup = groups.find(g => g.groupCode == group.groupCode);
|
||||
const existGroup = groups.find(g => g.groupCode == group.groupCode)
|
||||
if (existGroup) {
|
||||
if (existGroup.memberCount > group.memberCount) {
|
||||
const oldMembers = existGroup.members;
|
||||
const oldMembers = existGroup.members
|
||||
|
||||
await sleep(200); // 如果请求QQ API的速度过快,通常无法正确拉取到最新的群信息,因此这里人为引入一个延时
|
||||
const newMembers = await NTQQApi.getGroupMembers(group.groupCode);
|
||||
await sleep(200) // 如果请求QQ API的速度过快,通常无法正确拉取到最新的群信息,因此这里人为引入一个延时
|
||||
const newMembers = await NTQQApi.getGroupMembers(group.groupCode)
|
||||
|
||||
group.members = newMembers;
|
||||
const newMembersSet = new Set<string>(); // 建立索引降低时间复杂度
|
||||
group.members = newMembers
|
||||
const newMembersSet = new Set<string>() // 建立索引降低时间复杂度
|
||||
|
||||
for (const member of newMembers) {
|
||||
newMembersSet.add(member.uin);
|
||||
newMembersSet.add(member.uin)
|
||||
}
|
||||
|
||||
for (const member of oldMembers) {
|
||||
if (!newMembersSet.has(member.uin)) {
|
||||
postOB11Event(new OB11GroupDecreaseEvent(group.groupCode, parseInt(member.uin)));
|
||||
break;
|
||||
postOB11Event(new OB11GroupDecreaseEvent(group.groupCode, parseInt(member.uin)))
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
} else if (existGroup.memberCount < group.memberCount) {
|
||||
const oldMembers = existGroup.members;
|
||||
const oldMembersSet = new Set<string>();
|
||||
const oldMembers = existGroup.members
|
||||
const oldMembersSet = new Set<string>()
|
||||
for (const member of oldMembers) {
|
||||
oldMembersSet.add(member.uin);
|
||||
oldMembersSet.add(member.uin)
|
||||
}
|
||||
|
||||
await sleep(200);
|
||||
const newMembers = await NTQQApi.getGroupMembers(group.groupCode);
|
||||
await sleep(200)
|
||||
const newMembers = await NTQQApi.getGroupMembers(group.groupCode)
|
||||
|
||||
group.members = newMembers;
|
||||
group.members = newMembers
|
||||
for (const member of newMembers) {
|
||||
if (!oldMembersSet.has(member.uin)) {
|
||||
postOB11Event(new OB11GroupIncreaseEvent(group.groupCode, parseInt(member.uin)));
|
||||
break;
|
||||
postOB11Event(new OB11GroupIncreaseEvent(group.groupCode, parseInt(member.uin)))
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateGroups(newGroupList, false).then();
|
||||
updateGroups(newGroupList, false).then()
|
||||
} catch (e) {
|
||||
updateGroups(payload.groupList).then();
|
||||
console.log(e);
|
||||
updateGroups(payload.groupList).then()
|
||||
console.log(e)
|
||||
}
|
||||
}
|
||||
|
||||
registerReceiveHook<{ groupList: Group[], updateType: number }>(ReceiveCmd.GROUPS, (payload) => {
|
||||
if (payload.updateType != 2) {
|
||||
updateGroups(payload.groupList).then();
|
||||
updateGroups(payload.groupList).then()
|
||||
} else {
|
||||
if (process.platform == "win32") {
|
||||
processGroupEvent(payload).then();
|
||||
if (process.platform == 'win32') {
|
||||
processGroupEvent(payload).then()
|
||||
}
|
||||
}
|
||||
})
|
||||
registerReceiveHook<{ groupList: Group[], updateType: number }>(ReceiveCmd.GROUPS_UNIX, (payload) => {
|
||||
if (payload.updateType != 2) {
|
||||
updateGroups(payload.groupList).then();
|
||||
updateGroups(payload.groupList).then()
|
||||
} else {
|
||||
if (process.platform != "win32") {
|
||||
processGroupEvent(payload).then();
|
||||
if (process.platform != 'win32') {
|
||||
processGroupEvent(payload).then()
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
registerReceiveHook<{
|
||||
data: { categoryId: number, categroyName: string, categroyMbCount: number, buddyList: User[] }[]
|
||||
data: Array<{ categoryId: number, categroyName: string, categroyMbCount: number, buddyList: User[] }>
|
||||
}>(ReceiveCmd.FRIENDS, payload => {
|
||||
for (const fData of payload.data) {
|
||||
const _friends = fData.buddyList;
|
||||
for (let friend of _friends) {
|
||||
let existFriend = friends.find(f => f.uin == friend.uin)
|
||||
const _friends = fData.buddyList
|
||||
for (const friend of _friends) {
|
||||
const existFriend = friends.find(f => f.uin == friend.uin)
|
||||
if (!existFriend) {
|
||||
friends.push(friend)
|
||||
} else {
|
||||
@@ -230,8 +229,8 @@ registerReceiveHook<{
|
||||
}
|
||||
})
|
||||
|
||||
registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload) => {
|
||||
const {autoDeleteFile, autoDeleteFileSecond} = getConfigUtil().getConfig();
|
||||
registerReceiveHook<{ msgList: RawMessage[] }>(ReceiveCmd.NEW_MSG, (payload) => {
|
||||
const {autoDeleteFile, autoDeleteFileSecond} = getConfigUtil().getConfig()
|
||||
for (const message of payload.msgList) {
|
||||
// log("收到新消息,push到历史记录", message)
|
||||
addHistoryMsg(message)
|
||||
@@ -241,43 +240,43 @@ registerReceiveHook<{ msgList: Array<RawMessage> }>(ReceiveCmd.NEW_MSG, (payload
|
||||
}
|
||||
for (const msgElement of message.elements) {
|
||||
setTimeout(() => {
|
||||
const picPath = msgElement.picElement?.sourcePath;
|
||||
const pttPath = msgElement.pttElement?.filePath;
|
||||
const pathList = [picPath, pttPath];
|
||||
if (msgElement.picElement){
|
||||
pathList.push(...Object.values(msgElement.picElement.thumbPath));
|
||||
const picPath = msgElement.picElement?.sourcePath
|
||||
const pttPath = msgElement.pttElement?.filePath
|
||||
const pathList = [picPath, pttPath]
|
||||
if (msgElement.picElement) {
|
||||
pathList.push(...Object.values(msgElement.picElement.thumbPath))
|
||||
}
|
||||
// log("需要清理的文件", pathList);
|
||||
for (const path of pathList) {
|
||||
if (path) {
|
||||
fs.unlink(picPath, () => {
|
||||
log("删除文件成功", path)
|
||||
});
|
||||
log('删除文件成功', path)
|
||||
})
|
||||
}
|
||||
}
|
||||
}, autoDeleteFileSecond * 1000)
|
||||
}
|
||||
}
|
||||
const msgIds = Object.keys(msgHistory);
|
||||
const msgIds = Object.keys(msgHistory)
|
||||
if (msgIds.length > 30000) {
|
||||
delete msgHistory[msgIds.sort()[0]]
|
||||
}
|
||||
})
|
||||
|
||||
registerReceiveHook<{ msgRecord: RawMessage }>(ReceiveCmd.SELF_SEND_MSG, ({msgRecord}) => {
|
||||
const message = msgRecord;
|
||||
const peerUid = message.peerUid;
|
||||
const message = msgRecord
|
||||
const peerUid = message.peerUid
|
||||
// log("收到自己发送成功的消息", Object.keys(sendMessagePool), message);
|
||||
const sendCallback = sendMessagePool[peerUid];
|
||||
const sendCallback = sendMessagePool[peerUid]
|
||||
if (sendCallback) {
|
||||
try {
|
||||
sendCallback(message);
|
||||
sendCallback(message)
|
||||
} catch (e) {
|
||||
log("receive self msg error", e.stack)
|
||||
log('receive self msg error', e.stack)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
registerReceiveHook<{info: {status: number}}>(ReceiveCmd.SELF_STATUS, (info)=>{
|
||||
selfInfo.online = info.info.status !== 20;
|
||||
registerReceiveHook<{ info: { status: number } }>(ReceiveCmd.SELF_STATUS, (info) => {
|
||||
selfInfo.online = info.info.status !== 20
|
||||
})
|
@@ -1,26 +1,25 @@
|
||||
import {ipcMain} from "electron";
|
||||
import {hookApiCallbacks, ReceiveCmd, registerReceiveHook, removeReceiveHook} from "./hook";
|
||||
import {log, sleep} from "../common/utils";
|
||||
import {ipcMain} from 'electron'
|
||||
import {hookApiCallbacks, ReceiveCmd, registerReceiveHook, removeReceiveHook} from './hook'
|
||||
import {log, sleep} from '../common/utils'
|
||||
import {
|
||||
ChatType,
|
||||
type ChatType,
|
||||
ElementType,
|
||||
Friend,
|
||||
FriendRequest,
|
||||
Group,
|
||||
GroupMember,
|
||||
GroupMemberRole,
|
||||
GroupNotifies,
|
||||
GroupNotify,
|
||||
GroupRequestOperateTypes,
|
||||
RawMessage,
|
||||
SelfInfo,
|
||||
SendMessageElement,
|
||||
User
|
||||
} from "./types";
|
||||
import * as fs from "node:fs";
|
||||
import {addHistoryMsg, friendRequests, groupNotifies, msgHistory, selfInfo} from "../common/data";
|
||||
import {v4 as uuidv4} from "uuid"
|
||||
import path from "path";
|
||||
type Friend,
|
||||
type FriendRequest,
|
||||
type Group, GroupMember,
|
||||
type GroupMemberRole,
|
||||
type GroupNotifies,
|
||||
type GroupNotify,
|
||||
type GroupRequestOperateTypes,
|
||||
type RawMessage,
|
||||
type SelfInfo,
|
||||
type SendMessageElement,
|
||||
type User
|
||||
} from './types'
|
||||
import * as fs from 'node:fs'
|
||||
import {addHistoryMsg, friendRequests, groupNotifies, msgHistory, selfInfo} from '../common/data'
|
||||
import {v4 as uuidv4} from 'uuid'
|
||||
import path from 'path'
|
||||
|
||||
interface IPCReceiveEvent {
|
||||
eventName: string
|
||||
@@ -35,88 +34,88 @@ export type IPCReceiveDetail = [
|
||||
]
|
||||
|
||||
export enum NTQQApiClass {
|
||||
NT_API = "ns-ntApi",
|
||||
FS_API = "ns-FsApi",
|
||||
GLOBAL_DATA = "ns-GlobalDataApi"
|
||||
NT_API = 'ns-ntApi',
|
||||
FS_API = 'ns-FsApi',
|
||||
GLOBAL_DATA = 'ns-GlobalDataApi'
|
||||
}
|
||||
|
||||
export enum NTQQApiMethod {
|
||||
LIKE_FRIEND = "nodeIKernelProfileLikeService/setBuddyProfileLike",
|
||||
SELF_INFO = "fetchAuthData",
|
||||
FRIENDS = "nodeIKernelBuddyService/getBuddyList",
|
||||
GROUPS = "nodeIKernelGroupService/getGroupList",
|
||||
GROUP_MEMBER_SCENE = "nodeIKernelGroupService/createMemberListScene",
|
||||
GROUP_MEMBERS = "nodeIKernelGroupService/getNextMemberList",
|
||||
USER_INFO = "nodeIKernelProfileService/getUserSimpleInfo",
|
||||
USER_DETAIL_INFO = "nodeIKernelProfileService/getUserDetailInfo",
|
||||
FILE_TYPE = "getFileType",
|
||||
FILE_MD5 = "getFileMd5",
|
||||
FILE_COPY = "copyFile",
|
||||
IMAGE_SIZE = "getImageSizeFromPath",
|
||||
FILE_SIZE = "getFileSize",
|
||||
MEDIA_FILE_PATH = "nodeIKernelMsgService/getRichMediaFilePathForGuild",
|
||||
RECALL_MSG = "nodeIKernelMsgService/recallMsg",
|
||||
SEND_MSG = "nodeIKernelMsgService/sendMsg",
|
||||
DOWNLOAD_MEDIA = "nodeIKernelMsgService/downloadRichMedia",
|
||||
MULTI_FORWARD_MSG = "nodeIKernelMsgService/multiForwardMsgWithComment", // 合并转发
|
||||
GET_GROUP_NOTICE = "nodeIKernelGroupService/getSingleScreenNotifies",
|
||||
HANDLE_GROUP_REQUEST = "nodeIKernelGroupService/operateSysNotify",
|
||||
QUIT_GROUP = "nodeIKernelGroupService/quitGroup",
|
||||
LIKE_FRIEND = 'nodeIKernelProfileLikeService/setBuddyProfileLike',
|
||||
SELF_INFO = 'fetchAuthData',
|
||||
FRIENDS = 'nodeIKernelBuddyService/getBuddyList',
|
||||
GROUPS = 'nodeIKernelGroupService/getGroupList',
|
||||
GROUP_MEMBER_SCENE = 'nodeIKernelGroupService/createMemberListScene',
|
||||
GROUP_MEMBERS = 'nodeIKernelGroupService/getNextMemberList',
|
||||
USER_INFO = 'nodeIKernelProfileService/getUserSimpleInfo',
|
||||
USER_DETAIL_INFO = 'nodeIKernelProfileService/getUserDetailInfo',
|
||||
FILE_TYPE = 'getFileType',
|
||||
FILE_MD5 = 'getFileMd5',
|
||||
FILE_COPY = 'copyFile',
|
||||
IMAGE_SIZE = 'getImageSizeFromPath',
|
||||
FILE_SIZE = 'getFileSize',
|
||||
MEDIA_FILE_PATH = 'nodeIKernelMsgService/getRichMediaFilePathForGuild',
|
||||
RECALL_MSG = 'nodeIKernelMsgService/recallMsg',
|
||||
SEND_MSG = 'nodeIKernelMsgService/sendMsg',
|
||||
DOWNLOAD_MEDIA = 'nodeIKernelMsgService/downloadRichMedia',
|
||||
MULTI_FORWARD_MSG = 'nodeIKernelMsgService/multiForwardMsgWithComment', // 合并转发
|
||||
GET_GROUP_NOTICE = 'nodeIKernelGroupService/getSingleScreenNotifies',
|
||||
HANDLE_GROUP_REQUEST = 'nodeIKernelGroupService/operateSysNotify',
|
||||
QUIT_GROUP = 'nodeIKernelGroupService/quitGroup',
|
||||
// READ_FRIEND_REQUEST = "nodeIKernelBuddyListener/onDoubtBuddyReqUnreadNumChange"
|
||||
HANDLE_FRIEND_REQUEST = "nodeIKernelBuddyService/approvalFriendRequest",
|
||||
KICK_MEMBER = "nodeIKernelGroupService/kickMember",
|
||||
MUTE_MEMBER = "nodeIKernelGroupService/setMemberShutUp",
|
||||
MUTE_GROUP = "nodeIKernelGroupService/setGroupShutUp",
|
||||
SET_MEMBER_CARD = "nodeIKernelGroupService/modifyMemberCardName",
|
||||
SET_MEMBER_ROLE = "nodeIKernelGroupService/modifyMemberRole",
|
||||
PUBLISH_GROUP_BULLETIN = "nodeIKernelGroupService/publishGroupBulletinBulletin",
|
||||
SET_GROUP_NAME = "nodeIKernelGroupService/modifyGroupName",
|
||||
HANDLE_FRIEND_REQUEST = 'nodeIKernelBuddyService/approvalFriendRequest',
|
||||
KICK_MEMBER = 'nodeIKernelGroupService/kickMember',
|
||||
MUTE_MEMBER = 'nodeIKernelGroupService/setMemberShutUp',
|
||||
MUTE_GROUP = 'nodeIKernelGroupService/setGroupShutUp',
|
||||
SET_MEMBER_CARD = 'nodeIKernelGroupService/modifyMemberCardName',
|
||||
SET_MEMBER_ROLE = 'nodeIKernelGroupService/modifyMemberRole',
|
||||
PUBLISH_GROUP_BULLETIN = 'nodeIKernelGroupService/publishGroupBulletinBulletin',
|
||||
SET_GROUP_NAME = 'nodeIKernelGroupService/modifyGroupName',
|
||||
}
|
||||
|
||||
enum NTQQApiChannel {
|
||||
IPC_UP_2 = "IPC_UP_2",
|
||||
IPC_UP_3 = "IPC_UP_3",
|
||||
IPC_UP_1 = "IPC_UP_1",
|
||||
IPC_UP_2 = 'IPC_UP_2',
|
||||
IPC_UP_3 = 'IPC_UP_3',
|
||||
IPC_UP_1 = 'IPC_UP_1',
|
||||
}
|
||||
|
||||
export interface Peer {
|
||||
chatType: ChatType
|
||||
peerUid: string // 如果是群聊uid为群号,私聊uid就是加密的字符串
|
||||
guildId?: ""
|
||||
peerUid: string // 如果是群聊uid为群号,私聊uid就是加密的字符串
|
||||
guildId?: ''
|
||||
}
|
||||
|
||||
interface NTQQApiParams {
|
||||
methodName: NTQQApiMethod | string,
|
||||
className?: NTQQApiClass,
|
||||
channel?: NTQQApiChannel,
|
||||
methodName: NTQQApiMethod | string
|
||||
className?: NTQQApiClass
|
||||
channel?: NTQQApiChannel
|
||||
classNameIsRegister?: boolean
|
||||
args?: unknown[],
|
||||
cbCmd?: ReceiveCmd | null,
|
||||
cmdCB?: (payload: any) => boolean;
|
||||
afterFirstCmd?: boolean, // 是否在methodName调用完之后再去hook cbCmd
|
||||
timeoutSecond?: number,
|
||||
args?: unknown[]
|
||||
cbCmd?: ReceiveCmd | null
|
||||
cmdCB?: (payload: any) => boolean
|
||||
afterFirstCmd?: boolean // 是否在methodName调用完之后再去hook cbCmd
|
||||
timeoutSecond?: number
|
||||
}
|
||||
|
||||
function callNTQQApi<ReturnType>(params: NTQQApiParams) {
|
||||
async function callNTQQApi<ReturnType>(params: NTQQApiParams) {
|
||||
let {
|
||||
className, methodName, channel, args,
|
||||
cbCmd, timeoutSecond: timeout,
|
||||
classNameIsRegister, cmdCB, afterFirstCmd
|
||||
} = params;
|
||||
className = className ?? NTQQApiClass.NT_API;
|
||||
channel = channel ?? NTQQApiChannel.IPC_UP_2;
|
||||
args = args ?? [];
|
||||
timeout = timeout ?? 5;
|
||||
afterFirstCmd = afterFirstCmd ?? true;
|
||||
const uuid = uuidv4();
|
||||
} = params
|
||||
className = className ?? NTQQApiClass.NT_API
|
||||
channel = channel ?? NTQQApiChannel.IPC_UP_2
|
||||
args = args ?? []
|
||||
timeout = timeout ?? 5
|
||||
afterFirstCmd = afterFirstCmd ?? true
|
||||
const uuid = uuidv4()
|
||||
// log("callNTQQApi", channel, className, methodName, args, uuid)
|
||||
return new Promise((resolve: (data: ReturnType) => void, reject) => {
|
||||
return await new Promise((resolve: (data: ReturnType) => void, reject) => {
|
||||
// log("callNTQQApiPromise", channel, className, methodName, args, uuid)
|
||||
const _timeout = timeout * 1000
|
||||
let success = false
|
||||
let eventName = className + "-" + channel[channel.length - 1];
|
||||
let eventName = className + '-' + channel[channel.length - 1]
|
||||
if (classNameIsRegister) {
|
||||
eventName += "-register";
|
||||
eventName += '-register'
|
||||
}
|
||||
const apiArgs = [methodName, ...args]
|
||||
if (!cbCmd) {
|
||||
@@ -124,40 +123,40 @@ function callNTQQApi<ReturnType>(params: NTQQApiParams) {
|
||||
hookApiCallbacks[uuid] = (r: ReturnType) => {
|
||||
success = true
|
||||
resolve(r)
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// 这里的callback比较特殊,QQ后端先返回是否调用成功,再返回一条结果数据
|
||||
const secondCallback = () => {
|
||||
const hookId = registerReceiveHook<ReturnType>(cbCmd, (payload) => {
|
||||
// log(methodName, "second callback", cbCmd, payload, cmdCB);
|
||||
if (!!cmdCB) {
|
||||
if (cmdCB) {
|
||||
if (cmdCB(payload)) {
|
||||
removeReceiveHook(hookId);
|
||||
removeReceiveHook(hookId)
|
||||
success = true
|
||||
resolve(payload);
|
||||
resolve(payload)
|
||||
}
|
||||
} else {
|
||||
removeReceiveHook(hookId);
|
||||
removeReceiveHook(hookId)
|
||||
success = true
|
||||
resolve(payload);
|
||||
resolve(payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
!afterFirstCmd && secondCallback();
|
||||
!afterFirstCmd && secondCallback()
|
||||
hookApiCallbacks[uuid] = (result: GeneralCallResult) => {
|
||||
log(`${methodName} callback`, result)
|
||||
if (result?.result == 0 || result === undefined) {
|
||||
afterFirstCmd && secondCallback();
|
||||
afterFirstCmd && secondCallback()
|
||||
} else {
|
||||
success = true
|
||||
reject(`ntqq api call failed, ${result.errMsg}`);
|
||||
reject(`ntqq api call failed, ${result.errMsg}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
setTimeout(() => {
|
||||
// log("ntqq api timeout", success, channel, className, methodName)
|
||||
if (!success) {
|
||||
log(`ntqq api timeout ${channel}, ${eventName}, ${methodName}`, apiArgs);
|
||||
log(`ntqq api timeout ${channel}, ${eventName}, ${methodName}`, apiArgs)
|
||||
reject(`ntqq api timeout ${channel}, ${eventName}, ${methodName}, ${apiArgs}`)
|
||||
}
|
||||
}, _timeout)
|
||||
@@ -171,19 +170,17 @@ function callNTQQApi<ReturnType>(params: NTQQApiParams) {
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
export let sendMessagePool: Record<string, ((sendSuccessMsg: RawMessage) => void) | null> = {}// peerUid: callbackFunnc
|
||||
export const sendMessagePool: Record<string, ((sendSuccessMsg: RawMessage) => void) | null> = {}// peerUid: callbackFunnc
|
||||
|
||||
interface GeneralCallResult {
|
||||
result: number, // 0: success
|
||||
result: number // 0: success
|
||||
errMsg: string
|
||||
}
|
||||
|
||||
|
||||
export class NTQQApi {
|
||||
// static likeFriend = defineNTQQApi<void>(NTQQApiChannel.IPC_UP_2, NTQQApiClass.NT_API, NTQQApiMethod.LIKE_FRIEND)
|
||||
static likeFriend(uid: string, count = 1) {
|
||||
return callNTQQApi<GeneralCallResult>({
|
||||
static async likeFriend(uid: string, count = 1) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.LIKE_FRIEND,
|
||||
args: [{
|
||||
doLikeUserInfo: {
|
||||
@@ -196,10 +193,12 @@ export class NTQQApi {
|
||||
})
|
||||
}
|
||||
|
||||
static getSelfInfo() {
|
||||
return callNTQQApi<SelfInfo>({
|
||||
static async getSelfInfo() {
|
||||
return await callNTQQApi<SelfInfo>({
|
||||
className: NTQQApiClass.GLOBAL_DATA,
|
||||
methodName: NTQQApiMethod.SELF_INFO, timeoutSecond: 2
|
||||
// channel: NTQQApiChannel.IPC_UP_3,
|
||||
methodName: NTQQApiMethod.SELF_INFO,
|
||||
timeoutSecond: 2
|
||||
})
|
||||
}
|
||||
|
||||
@@ -234,19 +233,19 @@ export class NTQQApi {
|
||||
|
||||
static async getFriends(forced = false) {
|
||||
const data = await callNTQQApi<{
|
||||
data: {
|
||||
categoryId: number,
|
||||
categroyName: string,
|
||||
categroyMbCount: number,
|
||||
data: Array<{
|
||||
categoryId: number
|
||||
categroyName: string
|
||||
categroyMbCount: number
|
||||
buddyList: Friend[]
|
||||
}[]
|
||||
}>
|
||||
}>(
|
||||
{
|
||||
methodName: NTQQApiMethod.FRIENDS,
|
||||
args: [{force_update: forced}, undefined],
|
||||
cbCmd: ReceiveCmd.FRIENDS
|
||||
})
|
||||
let _friends: Friend[] = [];
|
||||
const _friends: Friend[] = []
|
||||
for (const fData of data.data) {
|
||||
_friends.push(...fData.buddyList)
|
||||
}
|
||||
@@ -255,22 +254,22 @@ export class NTQQApi {
|
||||
|
||||
static async getGroups(forced = false) {
|
||||
let cbCmd = ReceiveCmd.GROUPS
|
||||
if (process.platform != "win32") {
|
||||
if (process.platform != 'win32') {
|
||||
cbCmd = ReceiveCmd.GROUPS_UNIX
|
||||
}
|
||||
const result = await callNTQQApi<{
|
||||
updateType: number,
|
||||
updateType: number
|
||||
groupList: Group[]
|
||||
}>({methodName: NTQQApiMethod.GROUPS, args: [{force_update: forced}, undefined], cbCmd})
|
||||
return result.groupList
|
||||
}
|
||||
|
||||
static async getGroupMembers(groupQQ: string, num = 3000) {
|
||||
static async getGroupMembers(groupQQ: string, num = 3000): Promise<GroupMember[]> {
|
||||
const sceneId = await callNTQQApi({
|
||||
methodName: NTQQApiMethod.GROUP_MEMBER_SCENE,
|
||||
args: [{
|
||||
groupCode: groupQQ,
|
||||
scene: "groupMemberList_MainWindow"
|
||||
scene: 'groupMemberList_MainWindow'
|
||||
}]
|
||||
})
|
||||
// log("get group member sceneId", sceneId);
|
||||
@@ -280,16 +279,16 @@ export class NTQQApi {
|
||||
}>({
|
||||
methodName: NTQQApiMethod.GROUP_MEMBERS,
|
||||
args: [{
|
||||
sceneId: sceneId,
|
||||
num: num
|
||||
sceneId,
|
||||
num
|
||||
},
|
||||
null
|
||||
]
|
||||
})
|
||||
// log("members info", typeof result.result.infos, Object.keys(result.result.infos))
|
||||
let values = result.result.infos.values()
|
||||
const values = result.result.infos.values()
|
||||
|
||||
let members = Array.from(values) as GroupMember[]
|
||||
const members: GroupMember[] = Array.from(values)
|
||||
for (const member of members) {
|
||||
// uidMaps[member.uid] = member.uin;
|
||||
}
|
||||
@@ -303,73 +302,74 @@ export class NTQQApi {
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
static getFileType(filePath: string) {
|
||||
return callNTQQApi<{ ext: string }>({
|
||||
static async getFileType(filePath: string) {
|
||||
return await callNTQQApi<{ ext: string }>({
|
||||
className: NTQQApiClass.FS_API, methodName: NTQQApiMethod.FILE_TYPE, args: [filePath]
|
||||
})
|
||||
}
|
||||
|
||||
static getFileMd5(filePath: string) {
|
||||
return callNTQQApi<string>({
|
||||
static async getFileMd5(filePath: string) {
|
||||
return await callNTQQApi<string>({
|
||||
className: NTQQApiClass.FS_API,
|
||||
methodName: NTQQApiMethod.FILE_MD5,
|
||||
args: [filePath]
|
||||
})
|
||||
}
|
||||
|
||||
static copyFile(filePath: string, destPath: string) {
|
||||
return callNTQQApi<string>({
|
||||
className: NTQQApiClass.FS_API, methodName: NTQQApiMethod.FILE_COPY, args: [{
|
||||
static async copyFile(filePath: string, destPath: string) {
|
||||
return await callNTQQApi<string>({
|
||||
className: NTQQApiClass.FS_API,
|
||||
methodName: NTQQApiMethod.FILE_COPY,
|
||||
args: [{
|
||||
fromPath: filePath,
|
||||
toPath: destPath
|
||||
}]
|
||||
})
|
||||
}
|
||||
|
||||
static getImageSize(filePath: string) {
|
||||
return callNTQQApi<{ width: number, height: number }>({
|
||||
static async getImageSize(filePath: string) {
|
||||
return await callNTQQApi<{ width: number, height: number }>({
|
||||
className: NTQQApiClass.FS_API, methodName: NTQQApiMethod.IMAGE_SIZE, args: [filePath]
|
||||
})
|
||||
}
|
||||
|
||||
static getFileSize(filePath: string) {
|
||||
return callNTQQApi<number>({
|
||||
static async getFileSize(filePath: string) {
|
||||
return await callNTQQApi<number>({
|
||||
className: NTQQApiClass.FS_API, methodName: NTQQApiMethod.FILE_SIZE, args: [filePath]
|
||||
})
|
||||
}
|
||||
|
||||
// 上传文件到QQ的文件夹
|
||||
static async uploadFile(filePath: string, elementType: ElementType = ElementType.PIC) {
|
||||
const md5 = await NTQQApi.getFileMd5(filePath);
|
||||
const md5 = await NTQQApi.getFileMd5(filePath)
|
||||
let ext = (await NTQQApi.getFileType(filePath))?.ext
|
||||
if (ext) {
|
||||
ext = "." + ext
|
||||
ext = '.' + ext
|
||||
} else {
|
||||
ext = ""
|
||||
ext = ''
|
||||
}
|
||||
let fileName = `${path.basename(filePath)}`;
|
||||
if (fileName.indexOf(".") === -1) {
|
||||
fileName += ext;
|
||||
let fileName = `${path.basename(filePath)}`
|
||||
if (!fileName.includes('.')) {
|
||||
fileName += ext
|
||||
}
|
||||
const mediaPath = await callNTQQApi<string>({
|
||||
methodName: NTQQApiMethod.MEDIA_FILE_PATH,
|
||||
args: [{
|
||||
path_info: {
|
||||
md5HexStr: md5,
|
||||
fileName: fileName,
|
||||
elementType: elementType,
|
||||
fileName,
|
||||
elementType,
|
||||
elementSubType: 0,
|
||||
thumbSize: 0,
|
||||
needCreate: true,
|
||||
downloadType: 1,
|
||||
file_uuid: ""
|
||||
file_uuid: ''
|
||||
}
|
||||
}]
|
||||
})
|
||||
log("media path", mediaPath)
|
||||
await NTQQApi.copyFile(filePath, mediaPath);
|
||||
const fileSize = await NTQQApi.getFileSize(filePath);
|
||||
log('media path', mediaPath)
|
||||
await NTQQApi.copyFile(filePath, mediaPath)
|
||||
const fileSize = await NTQQApi.getFileSize(filePath)
|
||||
return {
|
||||
md5,
|
||||
fileName,
|
||||
@@ -386,16 +386,16 @@ export class NTQQApi {
|
||||
const apiParams = [
|
||||
{
|
||||
getReq: {
|
||||
msgId: msgId,
|
||||
chatType: chatType,
|
||||
peerUid: peerUid,
|
||||
elementId: elementId,
|
||||
msgId,
|
||||
chatType,
|
||||
peerUid,
|
||||
elementId,
|
||||
thumbSize: 0,
|
||||
downloadType: 1,
|
||||
filePath: thumbPath,
|
||||
},
|
||||
filePath: thumbPath
|
||||
}
|
||||
},
|
||||
undefined,
|
||||
undefined
|
||||
]
|
||||
// log("需要下载media", sourcePath);
|
||||
await callNTQQApi({
|
||||
@@ -404,15 +404,16 @@ export class NTQQApi {
|
||||
cbCmd: ReceiveCmd.MEDIA_DOWNLOAD_COMPLETE,
|
||||
cmdCB: (payload: { notifyInfo: { filePath: string } }) => {
|
||||
// log("media 下载完成判断", payload.notifyInfo.filePath, sourcePath);
|
||||
return payload.notifyInfo.filePath == sourcePath;
|
||||
return payload.notifyInfo.filePath == sourcePath
|
||||
}
|
||||
})
|
||||
return sourcePath
|
||||
}
|
||||
|
||||
static recallMsg(peer: Peer, msgIds: string[]) {
|
||||
return callNTQQApi({
|
||||
methodName: NTQQApiMethod.RECALL_MSG, args: [{
|
||||
static async recallMsg(peer: Peer, msgIds: string[]) {
|
||||
return await callNTQQApi({
|
||||
methodName: NTQQApiMethod.RECALL_MSG,
|
||||
args: [{
|
||||
peer,
|
||||
msgIds
|
||||
}, null]
|
||||
@@ -420,43 +421,43 @@ export class NTQQApi {
|
||||
}
|
||||
|
||||
static async sendMsg(peer: Peer, msgElements: SendMessageElement[], waitComplete = false, timeout = 10000) {
|
||||
const peerUid = peer.peerUid;
|
||||
const peerUid = peer.peerUid
|
||||
|
||||
// 等待上一个相同的peer发送完
|
||||
let checkLastSendUsingTime = 0;
|
||||
let checkLastSendUsingTime = 0
|
||||
const waitLastSend = async () => {
|
||||
if (checkLastSendUsingTime > timeout) {
|
||||
throw ("发送超时")
|
||||
throw ('发送超时')
|
||||
}
|
||||
let lastSending = sendMessagePool[peer.peerUid]
|
||||
const lastSending = sendMessagePool[peer.peerUid]
|
||||
if (lastSending) {
|
||||
// log("有正在发送的消息,等待中...")
|
||||
await sleep(500);
|
||||
checkLastSendUsingTime += 500;
|
||||
return await waitLastSend();
|
||||
await sleep(500)
|
||||
checkLastSendUsingTime += 500
|
||||
return await waitLastSend()
|
||||
} else {
|
||||
return;
|
||||
|
||||
}
|
||||
}
|
||||
await waitLastSend();
|
||||
await waitLastSend()
|
||||
|
||||
let sentMessage: RawMessage = null;
|
||||
let sentMessage: RawMessage = null
|
||||
sendMessagePool[peerUid] = async (rawMessage: RawMessage) => {
|
||||
delete sendMessagePool[peerUid];
|
||||
sentMessage = rawMessage;
|
||||
delete sendMessagePool[peerUid]
|
||||
sentMessage = rawMessage
|
||||
}
|
||||
|
||||
let checkSendCompleteUsingTime = 0;
|
||||
let checkSendCompleteUsingTime = 0
|
||||
const checkSendComplete = async (): Promise<RawMessage> => {
|
||||
if (sentMessage && msgHistory[sentMessage.msgId]?.sendStatus == 2) {
|
||||
// log(`给${peerUid}发送消息成功`)
|
||||
return sentMessage;
|
||||
return sentMessage
|
||||
} else {
|
||||
checkSendCompleteUsingTime += 500;
|
||||
checkSendCompleteUsingTime += 500
|
||||
if (checkSendCompleteUsingTime > timeout) {
|
||||
throw ("发送超时")
|
||||
throw ('发送超时')
|
||||
}
|
||||
await sleep(500);
|
||||
await sleep(500)
|
||||
return await checkSendComplete()
|
||||
}
|
||||
}
|
||||
@@ -464,16 +465,17 @@ export class NTQQApi {
|
||||
callNTQQApi({
|
||||
methodName: NTQQApiMethod.SEND_MSG,
|
||||
args: [{
|
||||
msgId: "0",
|
||||
peer, msgElements,
|
||||
msgAttributeInfos: new Map(),
|
||||
msgId: '0',
|
||||
peer,
|
||||
msgElements,
|
||||
msgAttributeInfos: new Map()
|
||||
}, null]
|
||||
}).then()
|
||||
return checkSendComplete();
|
||||
return await checkSendComplete()
|
||||
}
|
||||
|
||||
static multiForwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) {
|
||||
let msgInfos = msgIds.map(id => {
|
||||
static async multiForwardMsg(srcPeer: Peer, destPeer: Peer, msgIds: string[]) {
|
||||
const msgInfos = msgIds.map(id => {
|
||||
return {msgId: id, senderShowName: selfInfo.nick}
|
||||
})
|
||||
const apiArgs = [
|
||||
@@ -484,42 +486,42 @@ export class NTQQApi {
|
||||
commentElements: [],
|
||||
msgAttributeInfos: new Map()
|
||||
},
|
||||
null,
|
||||
null
|
||||
]
|
||||
return new Promise<RawMessage>((resolve, reject) => {
|
||||
return await new Promise<RawMessage>((resolve, reject) => {
|
||||
let complete = false
|
||||
setTimeout(() => {
|
||||
if (!complete) {
|
||||
reject("转发消息超时");
|
||||
reject('转发消息超时')
|
||||
}
|
||||
}, 5000)
|
||||
registerReceiveHook(ReceiveCmd.SELF_SEND_MSG, (payload: { msgRecord: RawMessage }) => {
|
||||
const msg = payload.msgRecord;
|
||||
const msg = payload.msgRecord
|
||||
// 需要判断它是转发的消息,并且识别到是当前转发的这一条
|
||||
const arkElement = msg.elements.find(ele => ele.arkElement)
|
||||
if (!arkElement) {
|
||||
// log("收到的不是转发消息")
|
||||
return
|
||||
}
|
||||
const forwardData: any = JSON.parse(arkElement.arkElement.bytesData);
|
||||
if (forwardData.app != "com.tencent.multimsg") {
|
||||
const forwardData: any = JSON.parse(arkElement.arkElement.bytesData)
|
||||
if (forwardData.app != 'com.tencent.multimsg') {
|
||||
return
|
||||
}
|
||||
if (msg.peerUid == destPeer.peerUid && msg.senderUid == selfInfo.uid) {
|
||||
complete = true;
|
||||
complete = true
|
||||
addHistoryMsg(msg)
|
||||
resolve(msg);
|
||||
log("转发消息成功:", payload)
|
||||
resolve(msg)
|
||||
log('转发消息成功:', payload)
|
||||
}
|
||||
})
|
||||
callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.MULTI_FORWARD_MSG,
|
||||
args: apiArgs
|
||||
}).then(result => {
|
||||
log("转发消息结果:", result, apiArgs)
|
||||
log('转发消息结果:', result, apiArgs)
|
||||
if (result.result !== 0) {
|
||||
complete = true;
|
||||
reject("转发消息失败," + JSON.stringify(result));
|
||||
complete = true
|
||||
reject('转发消息失败,' + JSON.stringify(result))
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -530,56 +532,56 @@ export class NTQQApi {
|
||||
// 加群通知,退出通知,需要管理员权限
|
||||
callNTQQApi<GeneralCallResult>({
|
||||
methodName: ReceiveCmd.GROUP_NOTIFY,
|
||||
classNameIsRegister: true,
|
||||
classNameIsRegister: true
|
||||
}).then()
|
||||
return await callNTQQApi<GroupNotifies>({
|
||||
methodName: NTQQApiMethod.GET_GROUP_NOTICE,
|
||||
cbCmd: ReceiveCmd.GROUP_NOTIFY,
|
||||
afterFirstCmd: false,
|
||||
args: [
|
||||
{"doubt": false, "startSeq": "", "number": 14},
|
||||
{doubt: false, startSeq: '', number: 14},
|
||||
null
|
||||
]
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
static async handleGroupRequest(seq: string, operateType: GroupRequestOperateTypes, reason?: string) {
|
||||
const notify: GroupNotify = groupNotifies[seq];
|
||||
const notify: GroupNotify = groupNotifies[seq]
|
||||
if (!notify) {
|
||||
throw `${seq}对应的加群通知不存在`
|
||||
}
|
||||
delete groupNotifies[seq];
|
||||
delete groupNotifies[seq]
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.HANDLE_GROUP_REQUEST,
|
||||
args: [
|
||||
{
|
||||
"doubt": false,
|
||||
"operateMsg": {
|
||||
"operateType": operateType, // 2 拒绝
|
||||
"targetMsg": {
|
||||
"seq": seq, // 通知序列号
|
||||
"type": notify.type,
|
||||
"groupCode": notify.group.groupCode,
|
||||
"postscript": reason
|
||||
doubt: false,
|
||||
operateMsg: {
|
||||
operateType, // 2 拒绝
|
||||
targetMsg: {
|
||||
seq, // 通知序列号
|
||||
type: notify.type,
|
||||
groupCode: notify.group.groupCode,
|
||||
postscript: reason
|
||||
}
|
||||
}
|
||||
},
|
||||
null
|
||||
]
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
static async quitGroup(groupQQ: string) {
|
||||
await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.QUIT_GROUP,
|
||||
args: [
|
||||
{"groupCode": groupQQ},
|
||||
{groupCode: groupQQ},
|
||||
null
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
static async handleFriendRequest(sourceId: number, accept: boolean,) {
|
||||
static async handleFriendRequest(sourceId: number, accept: boolean) {
|
||||
const request: FriendRequest = friendRequests[sourceId]
|
||||
if (!request) {
|
||||
throw `sourceId ${sourceId}, 对应的好友请求不存在`
|
||||
@@ -588,20 +590,20 @@ export class NTQQApi {
|
||||
methodName: NTQQApiMethod.HANDLE_FRIEND_REQUEST,
|
||||
args: [
|
||||
{
|
||||
"approvalInfo": {
|
||||
"friendUid": request.friendUid,
|
||||
"reqTime": request.reqTime,
|
||||
approvalInfo: {
|
||||
friendUid: request.friendUid,
|
||||
reqTime: request.reqTime,
|
||||
accept
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
delete friendRequests[sourceId];
|
||||
return result;
|
||||
delete friendRequests[sourceId]
|
||||
return result
|
||||
}
|
||||
|
||||
static kickMember(groupQQ: string, kickUids: string[], refuseForever: boolean = false, kickReason: string = "") {
|
||||
return callNTQQApi<GeneralCallResult>(
|
||||
static async kickMember(groupQQ: string, kickUids: string[], refuseForever: boolean = false, kickReason: string = '') {
|
||||
return await callNTQQApi<GeneralCallResult>(
|
||||
{
|
||||
methodName: NTQQApiMethod.KICK_MEMBER,
|
||||
args: [
|
||||
@@ -609,30 +611,30 @@ export class NTQQApi {
|
||||
groupCode: groupQQ,
|
||||
kickUids,
|
||||
refuseForever,
|
||||
kickReason,
|
||||
kickReason
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
static banMember(groupQQ: string, memList: { uid: string, timeStamp: number }[]) {
|
||||
static async banMember(groupQQ: string, memList: Array<{ uid: string, timeStamp: number }>) {
|
||||
// timeStamp为秒数, 0为解除禁言
|
||||
return callNTQQApi<GeneralCallResult>(
|
||||
return await callNTQQApi<GeneralCallResult>(
|
||||
{
|
||||
methodName: NTQQApiMethod.MUTE_MEMBER,
|
||||
args: [
|
||||
{
|
||||
groupCode: groupQQ,
|
||||
memList,
|
||||
memList
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
static banGroup(groupQQ: string, shutUp: boolean) {
|
||||
return callNTQQApi<GeneralCallResult>({
|
||||
static async banGroup(groupQQ: string, shutUp: boolean) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.MUTE_GROUP,
|
||||
args: [
|
||||
{
|
||||
@@ -643,8 +645,8 @@ export class NTQQApi {
|
||||
})
|
||||
}
|
||||
|
||||
static setMemberCard(groupQQ: string, memberUid: string, cardName: string) {
|
||||
return callNTQQApi<GeneralCallResult>({
|
||||
static async setMemberCard(groupQQ: string, memberUid: string, cardName: string) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.SET_MEMBER_CARD,
|
||||
args: [
|
||||
{
|
||||
@@ -656,8 +658,8 @@ export class NTQQApi {
|
||||
})
|
||||
}
|
||||
|
||||
static setMemberRole(groupQQ: string, memberUid: string, role: GroupMemberRole) {
|
||||
return callNTQQApi<GeneralCallResult>({
|
||||
static async setMemberRole(groupQQ: string, memberUid: string, role: GroupMemberRole) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.SET_MEMBER_ROLE,
|
||||
args: [
|
||||
{
|
||||
@@ -669,8 +671,8 @@ export class NTQQApi {
|
||||
})
|
||||
}
|
||||
|
||||
static setGroupName(groupQQ: string, groupName: string) {
|
||||
return callNTQQApi<GeneralCallResult>({
|
||||
static async setGroupName(groupQQ: string, groupName: string) {
|
||||
return await callNTQQApi<GeneralCallResult>({
|
||||
methodName: NTQQApiMethod.SET_GROUP_NAME,
|
||||
args: [
|
||||
{
|
||||
|
@@ -249,7 +249,7 @@ export interface VideoElement {
|
||||
"thumbHeight": number,
|
||||
"busiType": 0, // 未知
|
||||
"subBusiType": 0, // 未知
|
||||
"thumbPath": Map<number,any>,
|
||||
"thumbPath": Map<number, any>,
|
||||
"transferStatus": 0, // 未知
|
||||
"progress": 0, // 下载进度?
|
||||
"invalidState": 0, // 未知
|
||||
|
@@ -4,6 +4,7 @@ import {OB11Return} from "../types";
|
||||
|
||||
class BaseAction<PayloadType, ReturnDataType> {
|
||||
actionName: ActionName
|
||||
|
||||
protected async check(payload: PayloadType): Promise<BaseCheckResult> {
|
||||
return {
|
||||
valid: true,
|
||||
|
@@ -1,10 +1,10 @@
|
||||
import {ActionName} from "./types";
|
||||
import CanSendRecord from "./CanSendRecord";
|
||||
|
||||
interface ReturnType{
|
||||
interface ReturnType {
|
||||
yes: boolean
|
||||
}
|
||||
|
||||
export default class CanSendImage extends CanSendRecord{
|
||||
export default class CanSendImage extends CanSendRecord {
|
||||
actionName = ActionName.CanSendImage
|
||||
}
|
@@ -1,14 +1,14 @@
|
||||
import BaseAction from "./BaseAction";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
interface ReturnType{
|
||||
interface ReturnType {
|
||||
yes: boolean
|
||||
}
|
||||
|
||||
export default class CanSendRecord extends BaseAction<any, ReturnType>{
|
||||
export default class CanSendRecord extends BaseAction<any, ReturnType> {
|
||||
actionName = ActionName.CanSendRecord
|
||||
|
||||
protected async _handle(payload): Promise<ReturnType>{
|
||||
protected async _handle(payload): Promise<ReturnType> {
|
||||
return {
|
||||
yes: true
|
||||
}
|
||||
|
@@ -1,24 +1,24 @@
|
||||
import BaseAction from "./BaseAction";
|
||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
||||
import {friends} from "../../common/data";
|
||||
import {ActionName} from "./types";
|
||||
import {log} from "../../common/utils";
|
||||
|
||||
interface Payload{
|
||||
interface Payload {
|
||||
method: string,
|
||||
args: any[],
|
||||
}
|
||||
|
||||
export default class Debug extends BaseAction<Payload, any>{
|
||||
export default class Debug extends BaseAction<Payload, any> {
|
||||
actionName = ActionName.Debug
|
||||
|
||||
protected async _handle(payload: Payload): Promise<any> {
|
||||
log("debug call ntqq api", payload);
|
||||
const method = NTQQApi[payload.method]
|
||||
if (!method){
|
||||
if (!method) {
|
||||
throw `${method} 不存在`
|
||||
}
|
||||
const result = method(...payload.args);
|
||||
if (method.constructor.name === "AsyncFunction"){
|
||||
if (method.constructor.name === "AsyncFunction") {
|
||||
return await result
|
||||
}
|
||||
return result
|
||||
|
@@ -10,7 +10,7 @@ interface Payload {
|
||||
class DeleteMsg extends BaseAction<Payload, void> {
|
||||
actionName = ActionName.DeleteMsg
|
||||
|
||||
protected async _handle(payload:Payload){
|
||||
protected async _handle(payload: Payload) {
|
||||
let msg = getHistoryMsgByShortId(payload.message_id)
|
||||
await NTQQApi.recallMsg({
|
||||
chatType: msg.chatType,
|
||||
|
@@ -3,11 +3,11 @@ import {fileCache} from "../../common/data";
|
||||
import {getConfigUtil} from "../../common/utils";
|
||||
import fs from "fs/promises";
|
||||
|
||||
export interface GetFilePayload{
|
||||
export interface GetFilePayload {
|
||||
file: string // 文件名
|
||||
}
|
||||
|
||||
export interface GetFileResponse{
|
||||
export interface GetFileResponse {
|
||||
file?: string // path
|
||||
url?: string
|
||||
file_size?: string
|
||||
@@ -16,7 +16,7 @@ export interface GetFileResponse{
|
||||
}
|
||||
|
||||
|
||||
export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse>{
|
||||
export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse> {
|
||||
protected async _handle(payload: GetFilePayload): Promise<GetFileResponse> {
|
||||
const cache = fileCache.get(payload.file)
|
||||
const {autoDeleteFile, enableLocalFile2Url, autoDeleteFileSecond} = getConfigUtil().getConfig()
|
||||
@@ -26,7 +26,7 @@ export class GetFileBase extends BaseAction<GetFilePayload, GetFileResponse>{
|
||||
if (cache.downloadFunc) {
|
||||
await cache.downloadFunc()
|
||||
}
|
||||
let res : GetFileResponse= {
|
||||
let res: GetFileResponse = {
|
||||
file: cache.filePath,
|
||||
url: cache.url,
|
||||
file_size: cache.fileSize,
|
||||
|
@@ -8,7 +8,7 @@ import {ActionName} from "./types";
|
||||
class GetFriendList extends BaseAction<null, OB11User[]> {
|
||||
actionName = ActionName.GetFriendList
|
||||
|
||||
protected async _handle(payload: null){
|
||||
protected async _handle(payload: null) {
|
||||
return OB11Constructor.friends(friends);
|
||||
}
|
||||
}
|
||||
|
@@ -8,7 +8,7 @@ import {ActionName} from "./types";
|
||||
class GetGroupList extends BaseAction<null, OB11Group[]> {
|
||||
actionName = ActionName.GetGroupList
|
||||
|
||||
protected async _handle(payload: null){
|
||||
protected async _handle(payload: null) {
|
||||
return OB11Constructor.groups(groups);
|
||||
}
|
||||
}
|
||||
|
@@ -13,13 +13,12 @@ export interface PayloadType {
|
||||
class GetGroupMemberInfo extends BaseAction<PayloadType, OB11GroupMember> {
|
||||
actionName = ActionName.GetGroupMemberInfo
|
||||
|
||||
protected async _handle(payload: PayloadType){
|
||||
protected async _handle(payload: PayloadType) {
|
||||
const member = await getGroupMember(payload.group_id.toString(), payload.user_id.toString())
|
||||
if (member) {
|
||||
return OB11Constructor.groupMember(payload.group_id.toString(), member)
|
||||
}
|
||||
else {
|
||||
throw(`群成员${payload.user_id}不存在`)
|
||||
} else {
|
||||
throw (`群成员${payload.user_id}不存在`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -13,15 +13,14 @@ export interface PayloadType {
|
||||
class GetGroupMemberList extends BaseAction<PayloadType, OB11GroupMember[]> {
|
||||
actionName = ActionName.GetGroupMemberList
|
||||
|
||||
protected async _handle(payload: PayloadType){
|
||||
protected async _handle(payload: PayloadType) {
|
||||
const group = await getGroup(payload.group_id.toString());
|
||||
if (group) {
|
||||
if (!group.members?.length) {
|
||||
group.members = await NTQQApi.getGroupMembers(payload.group_id.toString())
|
||||
}
|
||||
return OB11Constructor.groupMembers(group);
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
throw (`群${payload.group_id}不存在`)
|
||||
}
|
||||
}
|
||||
|
@@ -1,8 +1,9 @@
|
||||
import BaseAction from "./BaseAction";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
export default class GetGuildList extends BaseAction<null, null>{
|
||||
export default class GetGuildList extends BaseAction<null, null> {
|
||||
actionName = ActionName.GetGuildList
|
||||
|
||||
protected async _handle(payload: null): Promise<null> {
|
||||
return null;
|
||||
}
|
||||
|
@@ -2,6 +2,6 @@ import {GetFileBase} from "./GetFile";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
|
||||
export default class GetImage extends GetFileBase{
|
||||
export default class GetImage extends GetFileBase {
|
||||
actionName = ActionName.GetImage
|
||||
}
|
@@ -8,7 +8,7 @@ import {ActionName} from "./types";
|
||||
class GetLoginInfo extends BaseAction<null, OB11User> {
|
||||
actionName = ActionName.GetLoginInfo
|
||||
|
||||
protected async _handle(payload: null){
|
||||
protected async _handle(payload: null) {
|
||||
return OB11Constructor.selfInfo(selfInfo);
|
||||
}
|
||||
}
|
||||
|
@@ -14,17 +14,17 @@ export type ReturnDataType = OB11Message
|
||||
class GetMsg extends BaseAction<PayloadType, OB11Message> {
|
||||
actionName = ActionName.GetMsg
|
||||
|
||||
protected async _handle(payload: PayloadType){
|
||||
protected async _handle(payload: PayloadType) {
|
||||
// log("history msg ids", Object.keys(msgHistory));
|
||||
if (!payload.message_id){
|
||||
throw("参数message_id不能为空")
|
||||
if (!payload.message_id) {
|
||||
throw ("参数message_id不能为空")
|
||||
}
|
||||
const msg = getHistoryMsgByShortId(payload.message_id)
|
||||
if (msg) {
|
||||
const msgData = await OB11Constructor.message(msg);
|
||||
return msgData
|
||||
} else {
|
||||
throw("消息不存在")
|
||||
throw ("消息不存在")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@@ -1,15 +1,15 @@
|
||||
import {GetFileBase, GetFilePayload, GetFileResponse} from "./GetFile";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
interface Payload extends GetFilePayload{
|
||||
interface Payload extends GetFilePayload {
|
||||
out_format: 'mp3' | 'amr' | 'wma' | 'm4a' | 'spx' | 'ogg' | 'wav' | 'flac'
|
||||
}
|
||||
|
||||
export default class GetRecord extends GetFileBase{
|
||||
export default class GetRecord extends GetFileBase {
|
||||
actionName = ActionName.GetRecord
|
||||
|
||||
protected async _handle(payload: Payload): Promise<GetFileResponse> {
|
||||
let res = super._handle(payload);
|
||||
let res = super._handle(payload);
|
||||
return res;
|
||||
}
|
||||
}
|
@@ -6,6 +6,7 @@ import {selfInfo} from "../../common/data";
|
||||
|
||||
export default class GetStatus extends BaseAction<any, OB11Status> {
|
||||
actionName = ActionName.GetStatus
|
||||
|
||||
protected async _handle(payload: any): Promise<OB11Status> {
|
||||
return {
|
||||
online: selfInfo.online,
|
||||
|
@@ -3,8 +3,9 @@ import {OB11Version} from "../types";
|
||||
import {ActionName} from "./types";
|
||||
import {version} from "../../version";
|
||||
|
||||
export default class GetVersionInfo extends BaseAction<any, OB11Version>{
|
||||
export default class GetVersionInfo extends BaseAction<any, OB11Version> {
|
||||
actionName = ActionName.GetVersionInfo
|
||||
|
||||
protected async _handle(payload: any): Promise<OB11Version> {
|
||||
return {
|
||||
app_name: "LLOneBot",
|
||||
|
@@ -2,7 +2,7 @@ import SendMsg from "./SendMsg";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
|
||||
class SendGroupMsg extends SendMsg{
|
||||
class SendGroupMsg extends SendMsg {
|
||||
actionName = ActionName.SendGroupMsg
|
||||
}
|
||||
|
||||
|
@@ -2,7 +2,6 @@ import BaseAction from "./BaseAction";
|
||||
import {getFriend} from "../../common/data";
|
||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
||||
import {ActionName} from "./types";
|
||||
import { log } from "../../common/utils";
|
||||
|
||||
interface Payload {
|
||||
user_id: number,
|
||||
@@ -20,7 +19,7 @@ export default class SendLike extends BaseAction<Payload, null> {
|
||||
}
|
||||
try {
|
||||
let result = await NTQQApi.likeFriend(friend.uid, parseInt(payload.times.toString()) || 1);
|
||||
if (result.result !== 0){
|
||||
if (result.result !== 0) {
|
||||
throw result.errMsg
|
||||
}
|
||||
} catch (e) {
|
||||
|
@@ -4,7 +4,7 @@ import {GroupNotify, GroupRequestOperateTypes} from "../../ntqqapi/types";
|
||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
interface Payload{
|
||||
interface Payload {
|
||||
flag: string,
|
||||
// sub_type: "add" | "invite",
|
||||
// type: "add" | "invite"
|
||||
@@ -12,17 +12,18 @@ interface Payload{
|
||||
reason: string
|
||||
}
|
||||
|
||||
export default class SetGroupAddRequest extends BaseAction<Payload, null>{
|
||||
export default class SetGroupAddRequest extends BaseAction<Payload, null> {
|
||||
actionName = ActionName.SetGroupAddRequest
|
||||
|
||||
protected async _handle(payload: Payload): Promise<null> {
|
||||
const seq = payload.flag.toString();
|
||||
const notify: GroupNotify = groupNotifies[seq]
|
||||
try{
|
||||
try {
|
||||
await NTQQApi.handleGroupRequest(seq,
|
||||
payload.approve ? GroupRequestOperateTypes.approve: GroupRequestOperateTypes.reject,
|
||||
payload.approve ? GroupRequestOperateTypes.approve : GroupRequestOperateTypes.reject,
|
||||
payload.reason
|
||||
)
|
||||
}catch (e) {
|
||||
)
|
||||
} catch (e) {
|
||||
throw e
|
||||
}
|
||||
return null
|
||||
|
@@ -4,17 +4,18 @@ import {getGroupMember} from "../../common/data";
|
||||
import {GroupMemberRole} from "../../ntqqapi/types";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
interface Payload{
|
||||
interface Payload {
|
||||
group_id: number,
|
||||
user_id: number,
|
||||
enable: boolean
|
||||
}
|
||||
|
||||
export default class SetGroupAdmin extends BaseAction<Payload, null>{
|
||||
export default class SetGroupAdmin extends BaseAction<Payload, null> {
|
||||
actionName = ActionName.SetGroupAdmin
|
||||
|
||||
protected async _handle(payload: Payload): Promise<null> {
|
||||
const member = await getGroupMember(payload.group_id, payload.user_id)
|
||||
if(!member){
|
||||
if (!member) {
|
||||
throw `群成员${payload.user_id}不存在`
|
||||
}
|
||||
await NTQQApi.setMemberRole(payload.group_id.toString(), member.uid, payload.enable ? GroupMemberRole.admin : GroupMemberRole.normal)
|
||||
|
@@ -3,21 +3,22 @@ import {NTQQApi} from "../../ntqqapi/ntcall";
|
||||
import {getGroupMember} from "../../common/data";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
interface Payload{
|
||||
interface Payload {
|
||||
group_id: number,
|
||||
user_id: number,
|
||||
duration: number
|
||||
}
|
||||
|
||||
export default class SetGroupBan extends BaseAction<Payload, null>{
|
||||
export default class SetGroupBan extends BaseAction<Payload, null> {
|
||||
actionName = ActionName.SetGroupBan
|
||||
|
||||
protected async _handle(payload: Payload): Promise<null> {
|
||||
const member = await getGroupMember(payload.group_id, payload.user_id)
|
||||
if(!member){
|
||||
if (!member) {
|
||||
throw `群成员${payload.user_id}不存在`
|
||||
}
|
||||
await NTQQApi.banMember(payload.group_id.toString(),
|
||||
[{uid:member.uid, timeStamp: parseInt(payload.duration.toString())}])
|
||||
[{uid: member.uid, timeStamp: parseInt(payload.duration.toString())}])
|
||||
return null
|
||||
}
|
||||
}
|
@@ -1,20 +1,20 @@
|
||||
import BaseAction from "./BaseAction";
|
||||
import {NTQQApi} from "../../ntqqapi/ntcall";
|
||||
import {getGroupMember} from "../../common/data";
|
||||
import {GroupMemberRole} from "../../ntqqapi/types";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
interface Payload{
|
||||
interface Payload {
|
||||
group_id: number,
|
||||
user_id: number,
|
||||
card: string
|
||||
}
|
||||
|
||||
export default class SetGroupCard extends BaseAction<Payload, null>{
|
||||
export default class SetGroupCard extends BaseAction<Payload, null> {
|
||||
actionName = ActionName.SetGroupCard
|
||||
|
||||
protected async _handle(payload: Payload): Promise<null> {
|
||||
const member = await getGroupMember(payload.group_id, payload.user_id)
|
||||
if(!member){
|
||||
if (!member) {
|
||||
throw `群成员${payload.user_id}不存在`
|
||||
}
|
||||
await NTQQApi.setMemberCard(payload.group_id.toString(), member.uid, payload.card || "")
|
||||
|
@@ -3,17 +3,18 @@ import {NTQQApi} from "../../ntqqapi/ntcall";
|
||||
import {getGroupMember} from "../../common/data";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
interface Payload{
|
||||
interface Payload {
|
||||
group_id: number,
|
||||
user_id: number,
|
||||
reject_add_request: boolean
|
||||
}
|
||||
|
||||
export default class SetGroupKick extends BaseAction<Payload, null>{
|
||||
export default class SetGroupKick extends BaseAction<Payload, null> {
|
||||
actionName = ActionName.SetGroupKick
|
||||
|
||||
protected async _handle(payload: Payload): Promise<null> {
|
||||
const member = await getGroupMember(payload.group_id, payload.user_id)
|
||||
if(!member){
|
||||
if (!member) {
|
||||
throw `群成员${payload.user_id}不存在`
|
||||
}
|
||||
await NTQQApi.kickMember(payload.group_id.toString(), [member.uid], !!payload.reject_add_request);
|
||||
|
@@ -3,18 +3,18 @@ import {NTQQApi} from "../../ntqqapi/ntcall";
|
||||
import {log} from "../../common/utils";
|
||||
import {ActionName} from "./types";
|
||||
|
||||
interface Payload{
|
||||
interface Payload {
|
||||
group_id: number,
|
||||
is_dismiss: boolean
|
||||
}
|
||||
|
||||
export default class SetGroupLeave extends BaseAction<Payload, any>{
|
||||
export default class SetGroupLeave extends BaseAction<Payload, any> {
|
||||
actionName = ActionName.SetGroupLeave
|
||||
|
||||
protected async _handle(payload: Payload): Promise<any> {
|
||||
try{
|
||||
try {
|
||||
await NTQQApi.quitGroup(payload.group_id.toString())
|
||||
}
|
||||
catch (e) {
|
||||
} catch (e) {
|
||||
log("退群失败", e)
|
||||
throw e
|
||||
}
|
||||
|
@@ -1,21 +1,22 @@
|
||||
import BaseAction from "../BaseAction";
|
||||
import {OB11GroupMember, OB11User} from "../../types";
|
||||
import {friends, getFriend, getGroupMember, groups} from "../../../common/data";
|
||||
import {OB11User} from "../../types";
|
||||
import {getFriend, getGroupMember, groups} from "../../../common/data";
|
||||
import {OB11Constructor} from "../../constructor";
|
||||
import {ActionName} from "../types";
|
||||
|
||||
|
||||
export default class GoCQHTTPGetStrangerInfo extends BaseAction<{user_id: number}, OB11User>{
|
||||
export default class GoCQHTTPGetStrangerInfo extends BaseAction<{ user_id: number }, OB11User> {
|
||||
actionName = ActionName.GoCQHTTP_GetStrangerInfo
|
||||
|
||||
protected async _handle(payload: { user_id: number }): Promise<OB11User> {
|
||||
const user_id = payload.user_id.toString()
|
||||
const friend = await getFriend(user_id)
|
||||
if (friend){
|
||||
if (friend) {
|
||||
return OB11Constructor.friend(friend);
|
||||
}
|
||||
for(const group of groups){
|
||||
for (const group of groups) {
|
||||
const member = await getGroupMember(group.groupCode, user_id)
|
||||
if (member){
|
||||
if (member) {
|
||||
return OB11Constructor.groupMember(group.groupCode, member) as OB11User
|
||||
}
|
||||
}
|
||||
|
@@ -1,15 +1,16 @@
|
||||
import SendMsg, {ReturnDataType} from "../SendMsg";
|
||||
import {OB11MessageMixType, OB11PostSendMsg} from "../../types";
|
||||
import {ActionName, BaseCheckResult} from "../types";
|
||||
import SendMsg from "../SendMsg";
|
||||
import {OB11PostSendMsg} from "../../types";
|
||||
import {ActionName} from "../types";
|
||||
|
||||
export class GoCQHTTPSendGroupForwardMsg extends SendMsg{
|
||||
export class GoCQHTTPSendGroupForwardMsg extends SendMsg {
|
||||
actionName = ActionName.GoCQHTTP_SendGroupForwardMsg;
|
||||
protected async check(payload: OB11PostSendMsg){
|
||||
|
||||
protected async check(payload: OB11PostSendMsg) {
|
||||
payload.message = this.convertMessage2List(payload.messages);
|
||||
return super.check(payload);
|
||||
}
|
||||
}
|
||||
|
||||
export class GoCQHTTPSendPrivateForwardMsg extends GoCQHTTPSendGroupForwardMsg{
|
||||
export class GoCQHTTPSendPrivateForwardMsg extends GoCQHTTPSendGroupForwardMsg {
|
||||
actionName = ActionName.GoCQHTTP_SendPrivateForwardMsg;
|
||||
}
|
@@ -1,15 +1,15 @@
|
||||
import GetGuildList from "./GetGuildList";
|
||||
|
||||
export type BaseCheckResult = ValidCheckResult | InvalidCheckResult
|
||||
|
||||
export interface ValidCheckResult {
|
||||
valid: true
|
||||
|
||||
[k: string | number]: any
|
||||
}
|
||||
|
||||
export interface InvalidCheckResult {
|
||||
valid: false
|
||||
message: string
|
||||
|
||||
[k: string | number]: any
|
||||
}
|
||||
|
||||
|
@@ -7,18 +7,18 @@ import {
|
||||
OB11MessageDataType,
|
||||
OB11User
|
||||
} from "./types";
|
||||
import { AtType, ChatType, Group, GroupMember, IMAGE_HTTP_HOST, RawMessage, SelfInfo, User } from '../ntqqapi/types';
|
||||
import {AtType, ChatType, Group, GroupMember, IMAGE_HTTP_HOST, RawMessage, SelfInfo, User} from '../ntqqapi/types';
|
||||
import {fileCache, getFriend, getGroupMember, getHistoryMsgBySeq, selfInfo} from '../common/data';
|
||||
import { file2base64, getConfigUtil, log } from "../common/utils";
|
||||
import { NTQQApi } from "../ntqqapi/ntcall";
|
||||
import { EventType } from "./event/OB11BaseEvent";
|
||||
import { encodeCQCode } from "./cqcode";
|
||||
import {getConfigUtil, log} from "../common/utils";
|
||||
import {NTQQApi} from "../ntqqapi/ntcall";
|
||||
import {EventType} from "./event/OB11BaseEvent";
|
||||
import {encodeCQCode} from "./cqcode";
|
||||
|
||||
|
||||
export class OB11Constructor {
|
||||
static async message(msg: RawMessage): Promise<OB11Message> {
|
||||
|
||||
const { enableLocalFile2Url, ob11: { messagePostFormat } } = getConfigUtil().getConfig()
|
||||
const {enableLocalFile2Url, ob11: {messagePostFormat}} = getConfigUtil().getConfig()
|
||||
const message_type = msg.chatType == ChatType.group ? "group" : "private";
|
||||
const resMsg: OB11Message = {
|
||||
self_id: parseInt(selfInfo.uin),
|
||||
@@ -110,9 +110,10 @@ export class OB11Constructor {
|
||||
fileSize: element.picElement.fileSize.toString(),
|
||||
url: IMAGE_HTTP_HOST + element.picElement.originImageUrl,
|
||||
downloadFunc: async () => {
|
||||
await NTQQApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
||||
element.elementId, element.picElement.thumbPath.get(0), element.picElement.sourcePath)
|
||||
}})
|
||||
await NTQQApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
||||
element.elementId, element.picElement.thumbPath.get(0), element.picElement.sourcePath)
|
||||
}
|
||||
})
|
||||
// 不在自动下载图片
|
||||
|
||||
} else if (element.videoElement) {
|
||||
@@ -128,7 +129,8 @@ export class OB11Constructor {
|
||||
downloadFunc: async () => {
|
||||
await NTQQApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
||||
element.elementId, element.videoElement.thumbPath.get(0), element.videoElement.filePath)
|
||||
}})
|
||||
}
|
||||
})
|
||||
// 怎么拿到url呢
|
||||
} else if (element.fileElement) {
|
||||
message_data["type"] = OB11MessageDataType.file;
|
||||
@@ -143,10 +145,10 @@ export class OB11Constructor {
|
||||
downloadFunc: async () => {
|
||||
await NTQQApi.downloadMedia(msg.msgId, msg.chatType, msg.peerUid,
|
||||
element.elementId, null, element.fileElement.filePath)
|
||||
}})
|
||||
}
|
||||
})
|
||||
// 怎么拿到url呢
|
||||
}
|
||||
else if (element.pttElement) {
|
||||
} else if (element.pttElement) {
|
||||
message_data["type"] = OB11MessageDataType.voice;
|
||||
message_data["data"]["file"] = element.pttElement.fileName
|
||||
message_data["data"]["path"] = element.pttElement.filePath
|
||||
|
@@ -1,4 +1,4 @@
|
||||
import { selfInfo } from "../../common/data";
|
||||
import {selfInfo} from "../../common/data";
|
||||
|
||||
export enum EventType {
|
||||
META = "meta_event",
|
||||
|
@@ -1,4 +1,3 @@
|
||||
import {OB11BaseNoticeEvent} from "./OB11BaseNoticeEvent";
|
||||
import {OB11GroupNoticeEvent} from "./OB11GroupNoticeEvent";
|
||||
|
||||
export class OB11GroupAdminNoticeEvent extends OB11GroupNoticeEvent {
|
||||
|
@@ -2,7 +2,7 @@ import {OB11GroupNoticeEvent} from "../notice/OB11GroupNoticeEvent";
|
||||
import {EventType} from "../OB11BaseEvent";
|
||||
|
||||
|
||||
export class OB11GroupRequestEvent extends OB11GroupNoticeEvent{
|
||||
export class OB11GroupRequestEvent extends OB11GroupNoticeEvent {
|
||||
post_type = EventType.REQUEST;
|
||||
request_type: "group" = "group";
|
||||
sub_type: "add" | "invite" = "add";
|
||||
|
@@ -6,6 +6,7 @@ import {actionHandlers} from "../action";
|
||||
|
||||
class OB11HTTPServer extends HttpServerBase {
|
||||
name = "OneBot V11 server"
|
||||
|
||||
handleFailed(res: Response, payload: any, e: any) {
|
||||
res.send(OB11Response.error(e.stack.toString(), 200))
|
||||
}
|
||||
@@ -20,7 +21,7 @@ class OB11HTTPServer extends HttpServerBase {
|
||||
export const ob11HTTPServer = new OB11HTTPServer();
|
||||
|
||||
for (const action of actionHandlers) {
|
||||
for(const method of ["post", "get"]){
|
||||
for (const method of ["post", "get"]) {
|
||||
ob11HTTPServer.registerRouter(method, action.actionName, (res, payload) => action.handle(payload))
|
||||
}
|
||||
}
|
||||
|
@@ -3,7 +3,7 @@ import {OB11Message} from "../types";
|
||||
import {selfInfo} from "../../common/data";
|
||||
import {OB11BaseMetaEvent} from "../event/meta/OB11BaseMetaEvent";
|
||||
import {OB11BaseNoticeEvent} from "../event/notice/OB11BaseNoticeEvent";
|
||||
import { WebSocket as WebSocketClass } from "ws";
|
||||
import {WebSocket as WebSocketClass} from "ws";
|
||||
import {wsReply} from "./ws/reply";
|
||||
|
||||
export type PostEventType = OB11Message | OB11BaseMetaEvent | OB11BaseNoticeEvent
|
||||
@@ -29,7 +29,7 @@ export function postWsEvent(event: PostEventType) {
|
||||
}
|
||||
}
|
||||
|
||||
export function postOB11Event(msg: PostEventType, reportSelf=false) {
|
||||
export function postOB11Event(msg: PostEventType, reportSelf = false) {
|
||||
const config = getConfigUtil().getConfig();
|
||||
// 判断msg是否是event
|
||||
if (!config.reportSelfMessage && !reportSelf) {
|
||||
|
@@ -9,7 +9,7 @@ import BaseAction from "../../action/BaseAction";
|
||||
import {actionMap} from "../../action";
|
||||
import {registerWsEventSender, unregisterWsEventSender} from "../postOB11Event";
|
||||
import {wsReply} from "./reply";
|
||||
import { WebSocket as WebSocketClass } from "ws";
|
||||
import {WebSocket as WebSocketClass} from "ws";
|
||||
|
||||
export let rwsList: ReverseWebsocket[] = [];
|
||||
|
||||
|
@@ -1,13 +1,12 @@
|
||||
import { WebSocket as WebSocketClass } from "ws";
|
||||
import {WebSocket as WebSocketClass} from "ws";
|
||||
import {OB11Response} from "../../action/utils";
|
||||
import {PostEventType} from "../postOB11Event";
|
||||
import {isNull, log} from "../../../common/utils";
|
||||
|
||||
export function wsReply(wsClient: WebSocketClass, data: OB11Response | PostEventType) {
|
||||
try {
|
||||
let packet = Object.assign({
|
||||
}, data);
|
||||
if (isNull(packet["echo"])){
|
||||
let packet = Object.assign({}, data);
|
||||
if (isNull(packet["echo"])) {
|
||||
delete packet["echo"];
|
||||
}
|
||||
wsClient.send(JSON.stringify(packet))
|
||||
|
@@ -54,13 +54,11 @@ export async function uri2local(uri: string, fileName: string = null) {
|
||||
} else {
|
||||
filePath = pathname
|
||||
}
|
||||
}
|
||||
else{
|
||||
} else {
|
||||
const cache = fileCache.get(uri)
|
||||
if (cache) {
|
||||
filePath = cache.filePath
|
||||
}
|
||||
else{
|
||||
} else {
|
||||
filePath = uri;
|
||||
}
|
||||
}
|
||||
|
397
src/renderer.ts
397
src/renderer.ts
@@ -1,20 +1,20 @@
|
||||
/// <reference path="./global.d.ts" />
|
||||
|
||||
|
||||
// 打开设置界面时触发
|
||||
|
||||
async function onSettingWindowCreated(view: Element) {
|
||||
window.llonebot.log("setting window created");
|
||||
const isEmpty = (value: any) => value === undefined || value === null || value === '';
|
||||
let config = await window.llonebot.getConfig()
|
||||
const httpClass = "http";
|
||||
const httpPostClass = "http-post";
|
||||
const wsClass = "ws";
|
||||
const reverseWSClass = "reverse-ws";
|
||||
const llonebotError = await window.llonebot.getError();
|
||||
window.llonebot.log("获取error" + JSON.stringify(llonebotError));
|
||||
function createHttpHostEleStr(host: string) {
|
||||
let eleStr = `
|
||||
async function onSettingWindowCreated (view: Element) {
|
||||
window.llonebot.log('setting window created')
|
||||
const isEmpty = (value: any) => value === undefined || value === null || value === ''
|
||||
const config = await window.llonebot.getConfig()
|
||||
const httpClass = 'http'
|
||||
const httpPostClass = 'http-post'
|
||||
const wsClass = 'ws'
|
||||
const reverseWSClass = 'reverse-ws'
|
||||
const llonebotError = await window.llonebot.getError()
|
||||
window.llonebot.log('获取error' + JSON.stringify(llonebotError))
|
||||
|
||||
function createHttpHostEleStr (host: string) {
|
||||
const eleStr = `
|
||||
<setting-item data-direction="row" class="hostItem vertical-list-item ${httpPostClass}">
|
||||
<h2>HTTP事件上报地址(http)</h2>
|
||||
<input class="httpHost input-text" type="text" value="${host}"
|
||||
@@ -22,11 +22,11 @@ async function onSettingWindowCreated(view: Element) {
|
||||
placeholder="如:http://127.0.0.1:8080/onebot/v11/http"/>
|
||||
</setting-item>
|
||||
`
|
||||
return eleStr
|
||||
}
|
||||
return eleStr
|
||||
}
|
||||
|
||||
function createWsHostEleStr(host: string) {
|
||||
let eleStr = `
|
||||
function createWsHostEleStr (host: string) {
|
||||
const eleStr = `
|
||||
<setting-item data-direction="row" class="hostItem vertical-list-item ${reverseWSClass}">
|
||||
<h2>反向websocket地址:</h2>
|
||||
<input class="wsHost input-text" type="text" value="${host}"
|
||||
@@ -34,20 +34,20 @@ async function onSettingWindowCreated(view: Element) {
|
||||
placeholder="如: ws://127.0.0.1:5410/onebot"/>
|
||||
</setting-item>
|
||||
`
|
||||
return eleStr
|
||||
}
|
||||
return eleStr
|
||||
}
|
||||
|
||||
let httpHostsEleStr = ""
|
||||
for (const host of config.ob11.httpHosts) {
|
||||
httpHostsEleStr += createHttpHostEleStr(host);
|
||||
}
|
||||
let httpHostsEleStr = ''
|
||||
for (const host of config.ob11.httpHosts) {
|
||||
httpHostsEleStr += createHttpHostEleStr(host)
|
||||
}
|
||||
|
||||
let wsHostsEleStr = ""
|
||||
for (const host of config.ob11.wsHosts) {
|
||||
wsHostsEleStr += createWsHostEleStr(host);
|
||||
}
|
||||
let wsHostsEleStr = ''
|
||||
for (const host of config.ob11.wsHosts) {
|
||||
wsHostsEleStr += createWsHostEleStr(host)
|
||||
}
|
||||
|
||||
let html = `
|
||||
const html = `
|
||||
<div class="config_view llonebot">
|
||||
<setting-section>
|
||||
<setting-panel id="llonebotError" style="display:${llonebotError.ffmpegError || llonebotError.otherError ? '' : 'none'}">
|
||||
@@ -68,7 +68,7 @@ async function onSettingWindowCreated(view: Element) {
|
||||
<div>
|
||||
<div>启用HTTP服务</div>
|
||||
</div>
|
||||
<setting-switch id="http" ${config.ob11.enableHttp ? "is-active" : ""}></setting-switch>
|
||||
<setting-switch id="http" ${config.ob11.enableHttp ? 'is-active' : ''}></setting-switch>
|
||||
</setting-item>
|
||||
<setting-item class="vertical-list-item ${httpClass}" data-direction="row" style="display: ${config.ob11.enableHttp ? '' : 'none'}">
|
||||
<setting-text>HTTP监听端口</setting-text>
|
||||
@@ -78,7 +78,7 @@ async function onSettingWindowCreated(view: Element) {
|
||||
<div>
|
||||
<div>启用HTTP事件上报</div>
|
||||
</div>
|
||||
<setting-switch id="httpPost" ${config.ob11.enableHttpPost ? "is-active" : ""}></setting-switch>
|
||||
<setting-switch id="httpPost" ${config.ob11.enableHttpPost ? 'is-active' : ''}></setting-switch>
|
||||
</setting-item>
|
||||
<div class="${httpPostClass}" style="display: ${config.ob11.enableHttpPost ? '' : 'none'}">
|
||||
<div >
|
||||
@@ -92,7 +92,7 @@ async function onSettingWindowCreated(view: Element) {
|
||||
<div>
|
||||
<div>启用正向Websocket协议</div>
|
||||
</div>
|
||||
<setting-switch id="websocket" ${config.ob11.enableWs ? "is-active" : ""}></setting-switch>
|
||||
<setting-switch id="websocket" ${config.ob11.enableWs ? 'is-active' : ''}></setting-switch>
|
||||
</setting-item>
|
||||
<setting-item class="vertical-list-item ${wsClass}" data-direction="row" style="display: ${config.ob11.enableWs ? '' : 'none'}">
|
||||
<setting-text>正向Websocket监听端口</setting-text>
|
||||
@@ -103,7 +103,7 @@ async function onSettingWindowCreated(view: Element) {
|
||||
<div>
|
||||
<div>启用反向Websocket协议</div>
|
||||
</div>
|
||||
<setting-switch id="websocketReverse" ${config.ob11.enableWsReverse ? "is-active" : ""}></setting-switch>
|
||||
<setting-switch id="websocketReverse" ${config.ob11.enableWsReverse ? 'is-active' : ''}></setting-switch>
|
||||
</setting-item>
|
||||
<div class="${reverseWSClass}" style="display: ${config.ob11.enableWsReverse ? '' : 'none'}">
|
||||
<div>
|
||||
@@ -137,8 +137,8 @@ async function onSettingWindowCreated(view: Element) {
|
||||
<setting-text data-type="secondary">如客户端无特殊需求推荐保持默认设置,两者的详细差异可参考 <a href="javascript:LiteLoader.api.openExternal('https://github.com/botuniverse/onebot-11/tree/master/message#readme');">OneBot v11 文档</a></setting-text>
|
||||
</div>
|
||||
<setting-select id="messagePostFormat">
|
||||
<setting-option data-value="array" ${config.ob11.messagePostFormat !== "string" ? "is-selected" : ""}>消息段</setting-option>
|
||||
<setting-option data-value="string" ${config.ob11.messagePostFormat === "string" ? "is-selected" : ""}>CQ码</setting-option>
|
||||
<setting-option data-value="array" ${config.ob11.messagePostFormat !== 'string' ? 'is-selected' : ''}>消息段</setting-option>
|
||||
<setting-option data-value="string" ${config.ob11.messagePostFormat === 'string' ? 'is-selected' : ''}>CQ码</setting-option>
|
||||
</setting-select>
|
||||
</setting-item>
|
||||
<setting-item data-direction="row" class="vertical-list-item">
|
||||
@@ -146,28 +146,28 @@ async function onSettingWindowCreated(view: Element) {
|
||||
<div>获取文件使用base64编码</div>
|
||||
<div class="tips">开启后,调用/get_image、/get_record时,获取不到url时添加一个base64字段</div>
|
||||
</div>
|
||||
<setting-switch id="switchFileUrl" ${config.enableLocalFile2Url ? "is-active" : ""}></setting-switch>
|
||||
<setting-switch id="switchFileUrl" ${config.enableLocalFile2Url ? 'is-active' : ''}></setting-switch>
|
||||
</setting-item>
|
||||
<setting-item data-direction="row" class="vertical-list-item">
|
||||
<div>
|
||||
<div>debug模式</div>
|
||||
<div class="tips">开启后上报消息添加raw字段附带原始消息</div>
|
||||
</div>
|
||||
<setting-switch id="debug" ${config.debug ? "is-active" : ""}></setting-switch>
|
||||
<setting-switch id="debug" ${config.debug ? 'is-active' : ''}></setting-switch>
|
||||
</setting-item>
|
||||
<setting-item data-direction="row" class="vertical-list-item">
|
||||
<div>
|
||||
<div>上报自身消息</div>
|
||||
<div class="tips">慎用,不然会自己和自己聊个不停</div>
|
||||
</div>
|
||||
<setting-switch id="reportSelfMessage" ${config.reportSelfMessage ? "is-active" : ""}></setting-switch>
|
||||
<setting-switch id="reportSelfMessage" ${config.reportSelfMessage ? 'is-active' : ''}></setting-switch>
|
||||
</setting-item>
|
||||
<setting-item data-direction="row" class="vertical-list-item">
|
||||
<div>
|
||||
<div>日志</div>
|
||||
<div class="tips">目录:${window.LiteLoader.plugins["LLOneBot"].path.data}</div>
|
||||
<div class="tips">目录:${window.LiteLoader.plugins.LLOneBot.path.data}</div>
|
||||
</div>
|
||||
<setting-switch id="log" ${config.log ? "is-active" : ""}></setting-switch>
|
||||
<setting-switch id="log" ${config.log ? 'is-active' : ''}></setting-switch>
|
||||
</setting-item>
|
||||
<setting-item data-direction="row" class="vertical-list-item">
|
||||
<div>
|
||||
@@ -179,7 +179,7 @@ async function onSettingWindowCreated(view: Element) {
|
||||
value="${config.autoDeleteFileSecond || 60}" type="number"/>秒后自动删除
|
||||
</div>
|
||||
</div>
|
||||
<setting-switch id="autoDeleteFile" ${config.autoDeleteFile ? "is-active" : ""}></setting-switch>
|
||||
<setting-switch id="autoDeleteFile" ${config.autoDeleteFile ? 'is-active' : ''}></setting-switch>
|
||||
</setting-item>
|
||||
</setting-panel>
|
||||
</setting-section>
|
||||
@@ -199,185 +199,182 @@ async function onSettingWindowCreated(view: Element) {
|
||||
</style>
|
||||
`
|
||||
|
||||
const parser = new DOMParser();
|
||||
const doc = parser.parseFromString(html, "text/html");
|
||||
const parser = new DOMParser()
|
||||
const doc = parser.parseFromString(html, 'text/html')
|
||||
|
||||
const getError = async ()=> {
|
||||
const llonebotError = await window.llonebot.getError();
|
||||
console.log(llonebotError);
|
||||
const llonebotErrorEle = document.getElementById("llonebotError");
|
||||
const ffmpegErrorEle = document.getElementById("ffmpegError");
|
||||
const otherErrorEle = document.getElementById("otherError");
|
||||
if (llonebotError.otherError || llonebotError.ffmpegError){
|
||||
llonebotErrorEle.style.display = ''
|
||||
}
|
||||
else{
|
||||
llonebotErrorEle.style.display = 'none'
|
||||
}
|
||||
if (llonebotError.ffmpegError) {
|
||||
const errContentEle = doc.querySelector("#ffmpegError .err-content")
|
||||
// const errContent = ffmpegErrorEle.getElementsByClassName("err-content")[0];
|
||||
errContentEle.textContent = llonebotError.ffmpegError;
|
||||
(ffmpegErrorEle as HTMLElement).style.display = ''
|
||||
}
|
||||
else{
|
||||
ffmpegErrorEle.style.display = ''
|
||||
}
|
||||
if (llonebotError.otherError) {
|
||||
const errContentEle = doc.querySelector("#otherError .err-content")
|
||||
errContentEle.textContent = llonebotError.otherError;
|
||||
otherErrorEle.style.display = ''
|
||||
}
|
||||
else{
|
||||
otherErrorEle.style.display = 'none'
|
||||
}
|
||||
const getError = async () => {
|
||||
const llonebotError = await window.llonebot.getError()
|
||||
console.log(llonebotError)
|
||||
const llonebotErrorEle = document.getElementById('llonebotError')
|
||||
const ffmpegErrorEle = document.getElementById('ffmpegError')
|
||||
const otherErrorEle = document.getElementById('otherError')
|
||||
if (llonebotError.otherError || llonebotError.ffmpegError) {
|
||||
llonebotErrorEle.style.display = ''
|
||||
} else {
|
||||
llonebotErrorEle.style.display = 'none'
|
||||
}
|
||||
if (llonebotError.ffmpegError) {
|
||||
const errContentEle = doc.querySelector('#ffmpegError .err-content')
|
||||
// const errContent = ffmpegErrorEle.getElementsByClassName("err-content")[0];
|
||||
errContentEle.textContent = llonebotError.ffmpegError;
|
||||
(ffmpegErrorEle).style.display = ''
|
||||
} else {
|
||||
ffmpegErrorEle.style.display = ''
|
||||
}
|
||||
if (llonebotError.otherError) {
|
||||
const errContentEle = doc.querySelector('#otherError .err-content')
|
||||
errContentEle.textContent = llonebotError.otherError
|
||||
otherErrorEle.style.display = ''
|
||||
} else {
|
||||
otherErrorEle.style.display = 'none'
|
||||
}
|
||||
}
|
||||
|
||||
function addHostEle (type: string, initValue: string = '') {
|
||||
let addressEle, hostItemsEle
|
||||
if (type === 'ws') {
|
||||
const addressDoc = parser.parseFromString(createWsHostEleStr(initValue), 'text/html')
|
||||
addressEle = addressDoc.querySelector('setting-item')
|
||||
hostItemsEle = document.getElementById('wsHostItems')
|
||||
} else {
|
||||
const addressDoc = parser.parseFromString(createHttpHostEleStr(initValue), 'text/html')
|
||||
addressEle = addressDoc.querySelector('setting-item')
|
||||
hostItemsEle = document.getElementById('httpHostItems')
|
||||
}
|
||||
|
||||
function addHostEle(type: string, initValue: string = "") {
|
||||
let addressEle, hostItemsEle;
|
||||
if (type === "ws") {
|
||||
let addressDoc = parser.parseFromString(createWsHostEleStr(initValue), "text/html");
|
||||
addressEle = addressDoc.querySelector("setting-item")
|
||||
hostItemsEle = document.getElementById("wsHostItems");
|
||||
} else {
|
||||
let addressDoc = parser.parseFromString(createHttpHostEleStr(initValue), "text/html");
|
||||
addressEle = addressDoc.querySelector("setting-item")
|
||||
hostItemsEle = document.getElementById("httpHostItems");
|
||||
}
|
||||
hostItemsEle.appendChild(addressEle)
|
||||
}
|
||||
|
||||
hostItemsEle.appendChild(addressEle);
|
||||
doc.getElementById('addHttpHost').addEventListener('click', () => {
|
||||
addHostEle('http')
|
||||
})
|
||||
doc.getElementById('addWsHost').addEventListener('click', () => {
|
||||
addHostEle('ws')
|
||||
})
|
||||
doc.getElementById('messagePostFormat').addEventListener('selected', (e: CustomEvent) => {
|
||||
config.ob11.messagePostFormat = e.detail && !isEmpty(e.detail.value) ? e.detail.value : 'array'
|
||||
window.llonebot.setConfig(config)
|
||||
})
|
||||
|
||||
function switchClick (eleId: string, configKey: string, _config = null) {
|
||||
if (!_config) {
|
||||
_config = config
|
||||
}
|
||||
doc.getElementById(eleId)?.addEventListener('click', (e) => {
|
||||
const switchEle = e.target as HTMLInputElement
|
||||
if (_config[configKey]) {
|
||||
_config[configKey] = false
|
||||
switchEle.removeAttribute('is-active')
|
||||
} else {
|
||||
_config[configKey] = true
|
||||
switchEle.setAttribute('is-active', '')
|
||||
}
|
||||
// 妈蛋,手动操作DOM越写越麻烦,要不用vue算了
|
||||
const keyClassMap = {
|
||||
enableHttp: httpClass,
|
||||
enableHttpPost: httpPostClass,
|
||||
enableWs: wsClass,
|
||||
enableWsReverse: reverseWSClass
|
||||
}
|
||||
for (const e of document.getElementsByClassName(keyClassMap[configKey])) {
|
||||
(e as HTMLElement).style.display = _config[configKey] ? '' : 'none'
|
||||
}
|
||||
|
||||
window.llonebot.setConfig(config)
|
||||
})
|
||||
}
|
||||
|
||||
doc.getElementById("addHttpHost").addEventListener("click", () => addHostEle("http"))
|
||||
doc.getElementById("addWsHost").addEventListener("click", () => addHostEle("ws"))
|
||||
doc.getElementById("messagePostFormat").addEventListener("selected", (e: CustomEvent) => {
|
||||
config.ob11.messagePostFormat = e.detail && !isEmpty(e.detail.value) ? e.detail.value : 'array';
|
||||
window.llonebot.setConfig(config);
|
||||
switchClick('http', 'enableHttp', config.ob11)
|
||||
switchClick('httpPost', 'enableHttpPost', config.ob11)
|
||||
switchClick('websocket', 'enableWs', config.ob11)
|
||||
switchClick('websocketReverse', 'enableWsReverse', config.ob11)
|
||||
switchClick('debug', 'debug')
|
||||
switchClick('switchFileUrl', 'enableLocalFile2Url')
|
||||
switchClick('reportSelfMessage', 'reportSelfMessage')
|
||||
switchClick('log', 'log')
|
||||
switchClick('autoDeleteFile', 'autoDeleteFile')
|
||||
|
||||
doc.getElementById('save')?.addEventListener('click',
|
||||
() => {
|
||||
const httpPortEle: HTMLInputElement = document.getElementById('httpPort') as HTMLInputElement
|
||||
const httpHostEles: HTMLCollectionOf<HTMLInputElement> = document.getElementsByClassName('httpHost') as HTMLCollectionOf<HTMLInputElement>
|
||||
const wsPortEle: HTMLInputElement = document.getElementById('wsPort') as HTMLInputElement
|
||||
const wsHostEles: HTMLCollectionOf<HTMLInputElement> = document.getElementsByClassName('wsHost') as HTMLCollectionOf<HTMLInputElement>
|
||||
const tokenEle = document.getElementById('token') as HTMLInputElement
|
||||
const ffmpegPathEle = document.getElementById('ffmpegPath') as HTMLInputElement
|
||||
|
||||
// 获取端口和host
|
||||
const httpPort = httpPortEle.value
|
||||
const httpHosts: string[] = []
|
||||
|
||||
for (const hostEle of httpHostEles) {
|
||||
const value = hostEle.value.trim()
|
||||
value && httpHosts.push(value)
|
||||
}
|
||||
|
||||
const wsPort = wsPortEle.value
|
||||
const token = tokenEle.value.trim()
|
||||
const wsHosts: string[] = []
|
||||
|
||||
for (const hostEle of wsHostEles) {
|
||||
const value = hostEle.value.trim()
|
||||
value && wsHosts.push(value)
|
||||
}
|
||||
|
||||
config.ob11.httpPort = parseInt(httpPort)
|
||||
config.ob11.httpHosts = httpHosts
|
||||
config.ob11.wsPort = parseInt(wsPort)
|
||||
config.ob11.wsHosts = wsHosts
|
||||
config.token = token
|
||||
config.ffmpeg = ffmpegPathEle.value.trim()
|
||||
window.llonebot.setConfig(config)
|
||||
setTimeout(() => {
|
||||
getError().then()
|
||||
}, 1000)
|
||||
alert('保存成功')
|
||||
})
|
||||
|
||||
function switchClick(eleId: string, configKey: string, _config = null) {
|
||||
if (!_config) {
|
||||
_config = config
|
||||
}
|
||||
doc.getElementById(eleId)?.addEventListener("click", (e) => {
|
||||
const switchEle = e.target as HTMLInputElement
|
||||
if (_config[configKey]) {
|
||||
_config[configKey] = false
|
||||
switchEle.removeAttribute("is-active")
|
||||
} else {
|
||||
_config[configKey] = true
|
||||
switchEle.setAttribute("is-active", "")
|
||||
}
|
||||
// 妈蛋,手动操作DOM越写越麻烦,要不用vue算了
|
||||
const keyClassMap = {
|
||||
"enableHttp": httpClass,
|
||||
"enableHttpPost": httpPostClass,
|
||||
"enableWs": wsClass,
|
||||
"enableWsReverse": reverseWSClass,
|
||||
}
|
||||
for (let e of document.getElementsByClassName(keyClassMap[configKey])) {
|
||||
e["style"].display = _config[configKey] ? "" : "none"
|
||||
}
|
||||
doc.getElementById('selectFFMPEG')?.addEventListener('click', () => {
|
||||
window.llonebot.selectFile().then(selectPath => {
|
||||
if (selectPath) {
|
||||
config.ffmpeg = (document.getElementById('ffmpegPath') as HTMLInputElement).value = selectPath
|
||||
// window.llonebot.setConfig(config);
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
window.llonebot.setConfig(config)
|
||||
})
|
||||
// 自动保存删除文件延时时间
|
||||
const autoDeleteMinEle = doc.getElementById('autoDeleteMin') as HTMLInputElement
|
||||
let st = null
|
||||
autoDeleteMinEle.addEventListener('change', () => {
|
||||
if (st) {
|
||||
clearTimeout(st)
|
||||
}
|
||||
st = setTimeout(() => {
|
||||
console.log('auto delete file minute change')
|
||||
config.autoDeleteFileSecond = parseInt(autoDeleteMinEle.value) || 1
|
||||
window.llonebot.setConfig(config)
|
||||
}, 1000)
|
||||
})
|
||||
|
||||
switchClick("http", "enableHttp", config.ob11);
|
||||
switchClick("httpPost", "enableHttpPost", config.ob11);
|
||||
switchClick("websocket", "enableWs", config.ob11);
|
||||
switchClick("websocketReverse", "enableWsReverse", config.ob11);
|
||||
switchClick("debug", "debug");
|
||||
switchClick("switchFileUrl", "enableLocalFile2Url");
|
||||
switchClick("reportSelfMessage", "reportSelfMessage");
|
||||
switchClick("log", "log");
|
||||
switchClick("autoDeleteFile", "autoDeleteFile");
|
||||
|
||||
doc.getElementById("save")?.addEventListener("click",
|
||||
() => {
|
||||
const httpPortEle: HTMLInputElement = document.getElementById("httpPort") as HTMLInputElement;
|
||||
const httpHostEles: HTMLCollectionOf<HTMLInputElement> = document.getElementsByClassName("httpHost") as HTMLCollectionOf<HTMLInputElement>;
|
||||
const wsPortEle: HTMLInputElement = document.getElementById("wsPort") as HTMLInputElement;
|
||||
const wsHostEles: HTMLCollectionOf<HTMLInputElement> = document.getElementsByClassName("wsHost") as HTMLCollectionOf<HTMLInputElement>;
|
||||
const tokenEle = document.getElementById("token") as HTMLInputElement;
|
||||
const ffmpegPathEle = document.getElementById("ffmpegPath") as HTMLInputElement;
|
||||
|
||||
// 获取端口和host
|
||||
const httpPort = httpPortEle.value
|
||||
let httpHosts: string[] = [];
|
||||
|
||||
for (const hostEle of httpHostEles) {
|
||||
const value = hostEle.value.trim();
|
||||
value && httpHosts.push(value);
|
||||
}
|
||||
|
||||
const wsPort = wsPortEle.value;
|
||||
const token = tokenEle.value.trim();
|
||||
let wsHosts: string[] = [];
|
||||
|
||||
for (const hostEle of wsHostEles) {
|
||||
const value = hostEle.value.trim();
|
||||
value && wsHosts.push(value);
|
||||
}
|
||||
|
||||
config.ob11.httpPort = parseInt(httpPort);
|
||||
config.ob11.httpHosts = httpHosts;
|
||||
config.ob11.wsPort = parseInt(wsPort);
|
||||
config.ob11.wsHosts = wsHosts;
|
||||
config.token = token;
|
||||
config.ffmpeg = ffmpegPathEle.value.trim();
|
||||
window.llonebot.setConfig(config);
|
||||
setTimeout(()=>{
|
||||
getError().then();
|
||||
}, 1000);
|
||||
alert("保存成功");
|
||||
})
|
||||
|
||||
doc.getElementById("selectFFMPEG")?.addEventListener("click", ()=>{
|
||||
window.llonebot.selectFile().then(selectPath=>{
|
||||
if (selectPath){
|
||||
config.ffmpeg = (document.getElementById("ffmpegPath") as HTMLInputElement).value = selectPath;
|
||||
// window.llonebot.setConfig(config);
|
||||
}
|
||||
});
|
||||
})
|
||||
|
||||
// 自动保存删除文件延时时间
|
||||
const autoDeleteMinEle = doc.getElementById("autoDeleteMin") as HTMLInputElement;
|
||||
let st = null;
|
||||
autoDeleteMinEle.addEventListener("change", ()=>{
|
||||
if (st){
|
||||
clearTimeout(st)
|
||||
}
|
||||
st = setTimeout(()=>{
|
||||
console.log("auto delete file minute change");
|
||||
config.autoDeleteFileSecond = parseInt(autoDeleteMinEle.value) || 1;
|
||||
window.llonebot.setConfig(config);
|
||||
}, 1000)
|
||||
})
|
||||
|
||||
doc.body.childNodes.forEach(node => {
|
||||
view.appendChild(node);
|
||||
});
|
||||
doc.body.childNodes.forEach(node => {
|
||||
view.appendChild(node)
|
||||
})
|
||||
}
|
||||
|
||||
function init () {
|
||||
const hash = location.hash
|
||||
if (hash === '#/blank') {
|
||||
|
||||
function init() {
|
||||
let hash = location.hash;
|
||||
if (hash === "#/blank") {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (location.hash === "#/blank") {
|
||||
(window as any).navigation.addEventListener("navigatesuccess", init, {once: true});
|
||||
if (location.hash === '#/blank') {
|
||||
(window as any).navigation.addEventListener('navigatesuccess', init, { once: true })
|
||||
} else {
|
||||
init();
|
||||
init()
|
||||
}
|
||||
|
||||
|
||||
export {
|
||||
onSettingWindowCreated
|
||||
onSettingWindowCreated
|
||||
}
|
||||
|
@@ -12,10 +12,10 @@
|
||||
},
|
||||
"include": [
|
||||
"src/*",
|
||||
"src/**/*",
|
||||
"scripts/*"
|
||||
],
|
||||
"exclude": [
|
||||
"node_modules",
|
||||
"src/common/types.ts"
|
||||
]
|
||||
}
|
Reference in New Issue
Block a user