chore: improve code quality

chore: improve code quality
This commit is contained in:
idranme
2024-09-05 21:53:10 +08:00
parent e185e700b7
commit f93e2b5a95
18 changed files with 109 additions and 398 deletions

View File

@@ -86,7 +86,7 @@ export class ConfigUtil {
// 迁移旧的配置到新配置,避免用户重新填写配置
const oldValue = oldConfig[oldKey]
if (oldValue) {
currentConfig[currentKey] = oldValue as any
Object.assign(currentConfig, { [currentKey]: oldValue })
delete oldConfig[oldKey]
}
}

View File

@@ -142,8 +142,8 @@ export async function uri2local(uri: string, filename?: string): Promise<Uri2Loc
const filePath = path.join(TEMP_DIR, filename)
await fsPromise.writeFile(filePath, res.data)
return { success: true, errMsg: '', fileName: filename, path: filePath, isLocal: false }
} catch (e: any) {
const errMsg = `${uri} 下载失败, ${e.message}`
} catch (e) {
const errMsg = `${uri} 下载失败, ${(e as Error).message}`
return { success: false, errMsg, fileName: '', path: '', isLocal: false }
}
}
@@ -175,7 +175,7 @@ export async function copyFolder(sourcePath: string, destPath: string) {
try {
const entries = await fsPromise.readdir(sourcePath, { withFileTypes: true })
await fsPromise.mkdir(destPath, { recursive: true })
for (let entry of entries) {
for (const entry of entries) {
const srcPath = path.join(sourcePath, entry.name)
const dstPath = path.join(destPath, entry.name)
if (entry.isDirectory()) {

View File

@@ -4,7 +4,7 @@ import { invoke, NTMethod, NTClass } from '../ntcall'
import { getSession } from '@/ntqqapi/wrapper'
import { BuddyListReqType, NodeIKernelProfileService } from '../services'
import { NTEventDispatch } from '@/common/utils/eventTask'
import { pick } from 'cosmokit'
import { Dict, pick } from 'cosmokit'
import { Service, Context } from 'cordis'
declare module 'cordis' {
@@ -19,7 +19,7 @@ export class NTQQFriendApi extends Service {
}
/** 大于或等于 26702 应使用 getBuddyV2 */
async getFriends(forced = false) {
async getFriends(_forced = false) {
const data = await invoke<{
data: {
categoryId: number
@@ -145,16 +145,16 @@ export class NTQQFriendApi extends Service {
const session = getSession()
if (session) {
const uids: string[] = []
const categoryMap: Map<string, any> = new Map()
const categoryMap: Map<string, Dict> = new Map()
const buddyService = session.getBuddyService()
const buddyListV2 = (await buddyService?.getBuddyListV2('0', BuddyListReqType.KNOMAL))?.data
const buddyListV2 = (await buddyService.getBuddyListV2('0', BuddyListReqType.KNOMAL)).data
uids.push(
...buddyListV2?.flatMap(item => {
...buddyListV2.flatMap(item => {
item.buddyUids.forEach(uid => {
categoryMap.set(uid, { categoryId: item.categoryId, categroyName: item.categroyName })
})
return item.buddyUids
})!)
}))
const data = await NTEventDispatch.CallNoListenerEvent<NodeIKernelProfileService['getCoreAndBaseInfo']>(
'NodeIKernelProfileService/getCoreAndBaseInfo', 5000, 'nodeStore', uids
)

View File

@@ -41,7 +41,7 @@ interface WebApiGroupMemberRet {
em: string
cache: number
adm_num: number
levelname: any
levelname: unknown
mems: WebApiGroupMember[]
count: number
svr_time: number
@@ -60,7 +60,7 @@ interface GroupEssenceMsg {
add_digest_uin: string
add_digest_nick: string
add_digest_time: number
msg_content: any[]
msg_content: unknown[]
can_be_removed: true
}
@@ -106,7 +106,7 @@ export class NTQQWebApi extends Service {
super(ctx, 'ntWebApi', true)
}
async getGroupMembers(GroupCode: string, cached: boolean = true): Promise<WebApiGroupMember[]> {
async getGroupMembers(groupCode: string): Promise<WebApiGroupMember[]> {
const memberData: Array<WebApiGroupMember> = new Array<WebApiGroupMember>()
const cookieObject = await this.ctx.ntUserApi.getCookies('qun.qq.com')
const cookieStr = this.cookieToString(cookieObject)
@@ -115,7 +115,7 @@ export class NTQQWebApi extends Service {
st: '0',
end: '40',
sort: '1',
gc: GroupCode,
gc: groupCode,
bkn: this.genBkn(cookieObject.skey)
})
const fastRet = await RequestUtil.HttpGetJson<WebApiGroupMemberRet>(`https://qun.qq.com/cgi-bin/qun_mgr/search_group_members?${params}`, 'POST', '', { 'Cookie': cookieStr })
@@ -160,11 +160,10 @@ export class NTQQWebApi extends Service {
//实现未缓存 考虑2h缓存
async getGroupHonorInfo(groupCode: string, getType: WebHonorType) {
const getDataInternal = async (Internal_groupCode: string, Internal_type: number) => {
let url = 'https://qun.qq.com/interactive/honorlist?gc=' + Internal_groupCode + '&type=' + Internal_type.toString()
let res = ''
const url = 'https://qun.qq.com/interactive/honorlist?gc=' + Internal_groupCode + '&type=' + Internal_type.toString()
let resJson
try {
res = await RequestUtil.HttpGetText(url, 'GET', '', { 'Cookie': cookieStr })
const res = await RequestUtil.HttpGetText(url, 'GET', '', { 'Cookie': cookieStr })
const match = res.match(/window\.__INITIAL_STATE__=(.*?);/)
if (match) {
resJson = JSON.parse(match[1].trim())
@@ -180,26 +179,26 @@ export class NTQQWebApi extends Service {
return undefined
}
let HonorInfo: any = { group_id: groupCode }
const honorInfo: Dict = { group_id: groupCode }
const cookieObject = await this.ctx.ntUserApi.getCookies('qun.qq.com')
const cookieStr = this.cookieToString(cookieObject)
if (getType === WebHonorType.TALKACTIVE || getType === WebHonorType.ALL) {
try {
let RetInternal = await getDataInternal(groupCode, 1)
const RetInternal = await getDataInternal(groupCode, 1)
if (!RetInternal) {
throw new Error('获取龙王信息失败')
}
HonorInfo.current_talkative = {
honorInfo.current_talkative = {
user_id: RetInternal[0]?.uin,
avatar: RetInternal[0]?.avatar,
nickname: RetInternal[0]?.name,
day_count: 0,
description: RetInternal[0]?.desc
}
HonorInfo.talkative_list = [];
honorInfo.talkative_list = [];
for (const talkative_ele of RetInternal) {
HonorInfo.talkative_list.push({
honorInfo.talkative_list.push({
user_id: talkative_ele?.uin,
avatar: talkative_ele?.avatar,
description: talkative_ele?.desc,
@@ -213,13 +212,13 @@ export class NTQQWebApi extends Service {
}
if (getType === WebHonorType.PERFROMER || getType === WebHonorType.ALL) {
try {
let RetInternal = await getDataInternal(groupCode, 2)
const RetInternal = await getDataInternal(groupCode, 2)
if (!RetInternal) {
throw new Error('获取群聊之火失败')
}
HonorInfo.performer_list = [];
honorInfo.performer_list = []
for (const performer_ele of RetInternal) {
HonorInfo.performer_list.push({
honorInfo.performer_list.push({
user_id: performer_ele?.uin,
nickname: performer_ele?.name,
avatar: performer_ele?.avatar,
@@ -232,13 +231,13 @@ export class NTQQWebApi extends Service {
}
if (getType === WebHonorType.PERFROMER || getType === WebHonorType.ALL) {
try {
let RetInternal = await getDataInternal(groupCode, 3)
const RetInternal = await getDataInternal(groupCode, 3)
if (!RetInternal) {
throw new Error('获取群聊炽焰失败')
}
HonorInfo.legend_list = []
honorInfo.legend_list = []
for (const legend_ele of RetInternal) {
HonorInfo.legend_list.push({
honorInfo.legend_list.push({
user_id: legend_ele?.uin,
nickname: legend_ele?.name,
avatar: legend_ele?.avatar,
@@ -251,13 +250,13 @@ export class NTQQWebApi extends Service {
}
if (getType === WebHonorType.EMOTION || getType === WebHonorType.ALL) {
try {
let RetInternal = await getDataInternal(groupCode, 6)
const RetInternal = await getDataInternal(groupCode, 6)
if (!RetInternal) {
throw new Error('获取快乐源泉失败')
}
HonorInfo.emotion_list = []
honorInfo.emotion_list = []
for (const emotion_ele of RetInternal) {
HonorInfo.emotion_list.push({
honorInfo.emotion_list.push({
user_id: emotion_ele?.uin,
nickname: emotion_ele?.name,
avatar: emotion_ele?.avatar,
@@ -270,9 +269,9 @@ export class NTQQWebApi extends Service {
}
//冒尖小春笋好像已经被tx扬了
if (getType === WebHonorType.EMOTION || getType === WebHonorType.ALL) {
HonorInfo.strong_newbie_list = []
honorInfo.strong_newbie_list = []
}
return HonorInfo
return honorInfo
}
async setGroupNotice(params: SetGroupNoticeParams): Promise<SetGroupNoticeRet> {

View File

@@ -62,8 +62,8 @@ class Core extends Service {
data: CategoryFriend[]
}>(ReceiveCmdS.FRIENDS, (payload) => {
type V2data = { userSimpleInfos: Map<string, SimpleInfo> }
let friendList: User[] = [];
if ((payload as any).userSimpleInfos) {
let friendList: User[] = []
if ('userSimpleInfos' in payload) {
friendList = Object.values((payload as unknown as V2data).userSimpleInfos).map((v: SimpleInfo) => {
return {
...v.coreInfo,
@@ -89,11 +89,11 @@ class Core extends Service {
for (const msgElement of message.elements) {
setTimeout(() => {
const picPath = msgElement.picElement?.sourcePath
const picThumbPath = [...msgElement.picElement?.thumbPath.values()]
const picThumbPath = [...(msgElement.picElement?.thumbPath ?? []).values()]
const pttPath = msgElement.pttElement?.filePath
const filePath = msgElement.fileElement?.filePath
const videoPath = msgElement.videoElement?.filePath
const videoThumbPath: string[] = [...msgElement.videoElement.thumbPath?.values()!]
const videoThumbPath = [...(msgElement.videoElement?.thumbPath ?? []).values()]
const pathList = [picPath, ...picThumbPath, pttPath, filePath, videoPath, ...videoThumbPath]
if (msgElement.picElement) {
pathList.push(...Object.values(msgElement.picElement.thumbPath))
@@ -126,15 +126,15 @@ class Core extends Service {
}[]
}>(ReceiveCmdS.RECENT_CONTACT, async (payload) => {
for (const recentContact of payload.changedRecentContactLists) {
for (const changedContact of recentContact.changedList) {
if (activatedPeerUids.includes(changedContact.id)) continue
activatedPeerUids.push(changedContact.id)
const peer = { peerUid: changedContact.id, chatType: changedContact.chatType }
if (changedContact.chatType === ChatType.temp) {
for (const contact of recentContact.changedList) {
if (activatedPeerUids.includes(contact.id)) continue
activatedPeerUids.push(contact.id)
const peer = { peerUid: contact.id, chatType: contact.chatType }
if (contact.chatType === ChatType.temp) {
this.ctx.ntMsgApi.activateChatAndGetHistory(peer).then(() => {
this.ctx.ntMsgApi.getMsgHistory(peer, '', 20).then(({ msgList }) => {
const lastTempMsg = msgList.at(-1)
if (Date.now() / 1000 - parseInt(lastTempMsg?.msgTime!) < 5) {
if (Date.now() / 1000 - Number(lastTempMsg?.msgTime) < 5) {
this.ctx.parallel('nt/message-created', [lastTempMsg!])
}
})

View File

@@ -99,7 +99,7 @@ export namespace SendElementEntities {
}
}
export async function file(ctx: Context, filePath: string, fileName: string = '', folderId: string = ''): Promise<SendFileElement> {
export async function file(ctx: Context, filePath: string, fileName = '', folderId = ''): Promise<SendFileElement> {
const { fileName: _fileName, path, fileSize } = await ctx.ntFileApi.uploadFile(filePath, ElementType.FILE)
if (fileSize === 0) {
throw '文件异常,大小为 0'
@@ -117,14 +117,14 @@ export namespace SendElementEntities {
return element
}
export async function video(ctx: Context, filePath: string, fileName: string = '', diyThumbPath: string = ''): Promise<SendVideoElement> {
export async function video(ctx: Context, filePath: string, fileName = '', diyThumbPath = ''): Promise<SendVideoElement> {
try {
await stat(filePath)
} catch (e) {
throw `文件${filePath}异常,不存在`
}
ctx.logger.info('复制视频到QQ目录', filePath)
let { fileName: _fileName, path, fileSize, md5 } = await ctx.ntFileApi.uploadFile(filePath, ElementType.VIDEO)
const { fileName: _fileName, path, fileSize, md5 } = await ctx.ntFileApi.uploadFile(filePath, ElementType.VIDEO)
ctx.logger.info('复制视频到QQ目录完成', path)
if (fileSize === 0) {
@@ -170,7 +170,7 @@ export namespace SendElementEntities {
setTimeout(useDefaultThumb, 5000)
ffmpeg(filePath)
.on('error', (err) => {
.on('error', () => {
if (diyThumbPath) {
copyFile(diyThumbPath, thumbPath)
.then(() => {
@@ -194,7 +194,7 @@ export namespace SendElementEntities {
resolve(thumbPath)
})
})
let thumbPath = new Map()
const thumbPath = new Map()
const _thumbPath = await createThumb
ctx.logger.info('生成视频缩略图', _thumbPath)
const thumbSize = (await stat(_thumbPath)).size

View File

@@ -271,284 +271,4 @@ export interface IKernelMsgListener {
export interface NodeIKernelMsgListener extends IKernelMsgListener {
// eslint-disable-next-line @typescript-eslint/no-misused-new
new(listener: IKernelMsgListener): NodeIKernelMsgListener
}
export class MsgListener implements IKernelMsgListener {
onAddSendMsg(msgRecord: RawMessage) {
}
onBroadcastHelperDownloadComplete(broadcastHelperTransNotifyInfo: unknown) {
}
onBroadcastHelperProgressUpdate(broadcastHelperTransNotifyInfo: unknown) {
}
onChannelFreqLimitInfoUpdate(contact: unknown, z: unknown, freqLimitInfo: unknown) {
}
onContactUnreadCntUpdate(hashMap: unknown) {
}
onCustomWithdrawConfigUpdate(customWithdrawConfig: unknown) {
}
onDraftUpdate(contact: unknown, arrayList: unknown, j2: unknown) {
}
onEmojiDownloadComplete(emojiNotifyInfo: unknown) {
}
onEmojiResourceUpdate(emojiResourceInfo: unknown) {
}
onFeedEventUpdate(firstViewDirectMsgNotifyInfo: unknown) {
}
onFileMsgCome(arrayList: unknown) {
}
onFirstViewDirectMsgUpdate(firstViewDirectMsgNotifyInfo: unknown) {
}
onFirstViewGroupGuildMapping(arrayList: unknown) {
}
onGrabPasswordRedBag(i2: unknown, str: unknown, i3: unknown, recvdOrder: unknown, msgRecord: unknown) {
}
onGroupFileInfoAdd(groupItem: unknown) {
}
onGroupFileInfoUpdate(groupFileListResult: OnGroupFileInfoUpdateParams) {
}
onGroupGuildUpdate(groupGuildNotifyInfo: unknown) {
}
onGroupTransferInfoAdd(groupItem: unknown) {
}
onGroupTransferInfoUpdate(groupFileListResult: unknown) {
}
onGuildInteractiveUpdate(guildInteractiveNotificationItem: unknown) {
}
onGuildMsgAbFlagChanged(guildMsgAbFlag: unknown) {
}
onGuildNotificationAbstractUpdate(guildNotificationAbstractInfo: unknown) {
}
onHitCsRelatedEmojiResult(downloadRelateEmojiResultInfo: unknown) {
}
onHitEmojiKeywordResult(hitRelatedEmojiWordsResult: unknown) {
}
onHitRelatedEmojiResult(relatedWordEmojiInfo: unknown) {
}
onImportOldDbProgressUpdate(importOldDbMsgNotifyInfo: unknown) {
}
onInputStatusPush(inputStatusInfo: unknown) {
}
onKickedOffLine(kickedInfo: unknown) {
}
onLineDev(arrayList: unknown) {
}
onLogLevelChanged(j2: unknown) {
}
onMsgAbstractUpdate(arrayList: unknown) {
}
onMsgBoxChanged(arrayList: unknown) {
}
onMsgDelete(contact: unknown, arrayList: unknown) {
}
onMsgEventListUpdate(hashMap: unknown) {
}
onMsgInfoListAdd(arrayList: unknown) {
}
onMsgInfoListUpdate(msgList: RawMessage[]) {
}
onMsgQRCodeStatusChanged(i2: unknown) {
}
onMsgRecall(i2: unknown, str: unknown, j2: unknown) {
}
onMsgSecurityNotify(msgRecord: unknown) {
}
onMsgSettingUpdate(msgSetting: unknown) {
}
onNtFirstViewMsgSyncEnd() {
}
onNtMsgSyncEnd() {
}
onNtMsgSyncStart() {
}
onReadFeedEventUpdate(firstViewDirectMsgNotifyInfo: unknown) {
}
onRecvGroupGuildFlag(i2: unknown) {
}
onRecvMsg(arrayList: RawMessage[]) {
}
onRecvMsgSvrRspTransInfo(j2: unknown, contact: unknown, i2: unknown, i3: unknown, str: unknown, bArr: unknown) {
}
onRecvOnlineFileMsg(arrayList: unknown) {
}
onRecvS2CMsg(arrayList: unknown) {
}
onRecvSysMsg(arrayList: unknown) {
}
onRecvUDCFlag(i2: unknown) {
}
onRichMediaDownloadComplete(fileTransNotifyInfo: OnRichMediaDownloadCompleteParams) {
}
onRichMediaProgerssUpdate(fileTransNotifyInfo: unknown) {
}
onRichMediaUploadComplete(fileTransNotifyInfo: unknown) {
}
onSearchGroupFileInfoUpdate(searchGroupFileResult: unknown) {
}
onSendMsgError(j2: unknown, contact: unknown, i2: unknown, str: unknown) {
}
onSysMsgNotification(i2: unknown, j2: unknown, j3: unknown, arrayList: unknown) {
}
onTempChatInfoUpdate(tempChatInfo: TempOnRecvParams) {
}
onUnreadCntAfterFirstView(hashMap: unknown) {
}
onUnreadCntUpdate(hashMap: unknown) {
}
onUserChannelTabStatusChanged(z: unknown) {
}
onUserOnlineStatusChanged(z: unknown) {
}
onUserTabStatusChanged(arrayList: unknown) {
}
onlineStatusBigIconDownloadPush(i2: unknown, j2: unknown, str: unknown) {
}
onlineStatusSmallIconDownloadPush(i2: unknown, j2: unknown, str: unknown) {
}
// 第一次发现于Linux
onUserSecQualityChanged(...args: unknown[]) {
}
onMsgWithRichLinkInfoUpdate(...args: unknown[]) {
}
onRedTouchChanged(...args: unknown[]) {
}
// 第一次发现于Win 9.9.9-23159
onBroadcastHelperProgerssUpdate(...args: unknown[]) {
}
}

View File

@@ -108,7 +108,7 @@ interface InvokeOptions<ReturnType> {
}
export function invoke<
R extends Awaited<ReturnType<Extract<NTService[S][M], (...args: any) => any>>>,
R extends Awaited<ReturnType<Extract<NTService[S][M], (...args: any) => unknown>>>,
S extends keyof NTService = any,
M extends keyof NTService[S] & string = any
>(method: Extract<unknown, `${S}/${M}`> | string, args: unknown[], options: InvokeOptions<R> = {}) {
@@ -137,7 +137,7 @@ export function invoke<
const secondCallback = () => {
const hookId = registerReceiveHook<R>(options.cbCmd!, (payload) => {
// log(methodName, "second callback", cbCmd, payload, cmdCB);
if (!!options.cmdCB) {
if (options.cmdCB) {
if (options.cmdCB(payload, result)) {
removeReceiveHook(hookId)
success = true
@@ -174,7 +174,7 @@ export function invoke<
channel,
{
sender: {
send: (..._args: unknown[]) => {
send: () => {
},
},
},

View File

@@ -1,6 +1,7 @@
import { ElementType, MessageElement, Peer, RawMessage, SendMessageElement } from '@/ntqqapi/types'
import { NodeIKernelMsgListener } from '@/ntqqapi/listeners/NodeIKernelMsgListener'
import { GeneralCallResult } from './common'
import { Dict } from 'cosmokit'
export interface QueryMsgsParams {
chatInfo: Peer,
@@ -34,11 +35,11 @@ export interface NodeIKernelMsgService {
addKernelMsgListener(nodeIKernelMsgListener: NodeIKernelMsgListener): number
sendMsg(msgId: string, peer: Peer, msgElements: SendMessageElement[], map: Map<any, any>): Promise<GeneralCallResult>
sendMsg(msgId: string, peer: Peer, msgElements: SendMessageElement[], map: Map<unknown, unknown>): Promise<GeneralCallResult>
recallMsg(peer: Peer, msgIds: string[]): Promise<GeneralCallResult>
addKernelMsgImportToolListener(arg: Object): unknown
addKernelMsgImportToolListener(arg: Dict): unknown
removeKernelMsgListener(args: unknown): unknown
@@ -52,7 +53,7 @@ export interface NodeIKernelMsgService {
getOnLineDev(): void
kickOffLine(DevInfo: Object): unknown
kickOffLine(DevInfo: Dict): unknown
setStatus(args: { status: number, extStatus: number, batteryStatus: number }): Promise<GeneralCallResult>
@@ -81,11 +82,11 @@ export interface NodeIKernelMsgService {
// this.voipToken = bArr2
// this.profileId = str
setToken(arg: Object): unknown
setToken(arg: Dict): unknown
switchForeGround(): unknown
switchBackGround(arg: Object): unknown
switchBackGround(arg: Dict): unknown
//hex
setTokenForMqq(token: string): unknown
@@ -142,9 +143,9 @@ export interface NodeIKernelMsgService {
addLocalTofuRecordMsg(...args: unknown[]): unknown
addLocalRecordMsg(Peer: Peer, msgId: string, ele: MessageElement, attr: Array<any> | number, front: boolean): Promise<unknown>
addLocalRecordMsg(Peer: Peer, msgId: string, ele: MessageElement, attr: Array<unknown> | number, front: boolean): Promise<unknown>
deleteMsg(Peer: Peer, msgIds: Array<string>): Promise<any>
deleteMsg(Peer: Peer, msgIds: Array<string>): Promise<unknown>
updateElementExtBufForUI(...args: unknown[]): unknown
@@ -370,8 +371,9 @@ export interface NodeIKernelMsgService {
getFileThumbSavePathForSend(...args: unknown[]): unknown
getFileThumbSavePath(...args: unknown[]): unknown
//猜测居多
translatePtt2Text(MsgId: string, Peer: {}, MsgElement: {}): unknown
translatePtt2Text(MsgId: string, Peer: Dict, MsgElement: Dict): unknown
setPttPlayedState(...args: unknown[]): unknown
// NodeIQQNTWrapperSession fetchFavEmojiList [
@@ -448,7 +450,7 @@ export interface NodeIKernelMsgService {
getEmojiResourcePath(...args: unknown[]): unknown
JoinDragonGroupEmoji(JoinDragonGroupEmojiReq: any/*joinDragonGroupEmojiReq*/): unknown
JoinDragonGroupEmoji(JoinDragonGroupEmojiReq: unknown): unknown
getMsgAbstracts(...args: unknown[]): unknown
@@ -623,7 +625,6 @@ export interface NodeIKernelMsgService {
sendSsoCmdReqByContend(cmd: string, param: string): Promise<unknown>
//chattype,uid->Promise<any>
getTempChatInfo(ChatType: number, Uid: string): Promise<TmpChatInfoApi>
setContactLocalTop(...args: unknown[]): unknown
@@ -654,7 +655,7 @@ export interface NodeIKernelMsgService {
recordEmoji(...args: unknown[]): unknown
fetchGetHitEmotionsByWord(args: Object): Promise<unknown>//表情推荐?
fetchGetHitEmotionsByWord(args: Dict): Promise<unknown>//表情推荐?
deleteAllRoamMsgs(...args: unknown[]): unknown//漫游消息?

View File

@@ -124,7 +124,7 @@ interface VideoInfo {
interface ExtOnlineBusinessInfo {
buf: string
customStatus: any
customStatus: unknown
videoBizInfo: VideoBizInfo
videoInfo: VideoInfo
}
@@ -142,7 +142,7 @@ interface UserStatus {
termType: number
netType: number
iconType: number
customStatus: any
customStatus: unknown
setTime: string
specialFlag: number
abiFlag: number
@@ -156,8 +156,8 @@ interface UserStatus {
interface PrivilegeIcon {
jumpUrl: string
openIconList: any[]
closeIconList: any[]
openIconList: unknown[]
closeIconList: unknown[]
}
interface VasInfo {
@@ -180,7 +180,7 @@ interface VasInfo {
fontEffect: number
newLoverDiamondFlag: number
extendNameplateId: number
diyNameplateIDs: any[]
diyNameplateIDs: unknown[]
vipStartFlag: number
vipDataFlag: number
gameNameplateId: string
@@ -200,8 +200,8 @@ export interface SimpleInfo {
status: UserStatus | null
vasInfo: VasInfo | null
relationFlags: RelationFlags | null
otherFlags: any | null
intimate: any | null
otherFlags: unknown | null
intimate: unknown | null
}
interface RelationFlags {
@@ -241,7 +241,7 @@ interface CommonExt {
address: string
regTime: number
interest: string
labels: any[]
labels: unknown[]
qqLevel: QQLevel
}
@@ -323,12 +323,12 @@ export interface UserDetailInfoByUin {
regTime: number
interest: string
termType: number
labels: any[]
labels: unknown[]
qqLevel: { crownNum: number, sunNum: number, moonNum: number, starNum: number }
isHideQQLevel: number
privilegeIcon: { jumpUrl: string, openIconList: any[], closeIconList: any[] }
privilegeIcon: { jumpUrl: string, openIconList: unknown[], closeIconList: unknown[] }
isHidePrivilegeIcon: number
photoWall: { picList: any[] }
photoWall: { picList: unknown[] }
vipFlag: boolean
yearVipFlag: boolean
svipFlag: boolean

View File

@@ -132,7 +132,7 @@ export function initActionMap(adapter: Adapter) {
new GetGroupRootFiles(adapter),
new SendGroupNotice(adapter)
]
const actionMap = new Map<string, BaseAction<any, any>>()
const actionMap = new Map<string, BaseAction<unknown, unknown>>()
for (const action of actionHandlers) {
actionMap.set(action.actionName, action)
actionMap.set(action.actionName + '_async', action)

View File

@@ -2,15 +2,11 @@ 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
}
export enum ActionName {

View File

@@ -172,14 +172,14 @@ class OneBot11Adapter extends Service {
)
this.dispatch(event)
}
} catch (e: any) {
this.ctx.logger.error('解析群通知失败', e.stack)
} catch (e) {
this.ctx.logger.error('解析群通知失败', (e as Error).stack)
}
}
}
private handleMsg(msgList: RawMessage[]) {
for (let message of msgList) {
for (const message of msgList) {
// 过滤启动之前的消息
if (parseInt(message.msgTime) < this.startTime / 1000) {
continue

View File

@@ -12,7 +12,7 @@ import { handleQuickOperation, QuickOperationEvent } from '../helper/quickOperat
import { OB11HeartbeatEvent } from '../event/meta/OB11HeartbeatEvent'
import { Dict } from 'cosmokit'
type RegisterHandler = (res: Response, payload: any) => Promise<any>
type RegisterHandler = (res: Response, payload: unknown) => Promise<unknown>
class OB11Http {
private readonly expressAPP: Express
@@ -56,9 +56,9 @@ class OB11Http {
this.ctx.logger.info(`HTTP server started ${host}:${this.config.port}`)
})
llonebotError.httpServerError = ''
} catch (e: any) {
this.ctx.logger.error('HTTP服务启动失败', e.toString())
llonebotError.httpServerError = 'HTTP服务启动失败, ' + e.toString()
} catch (e) {
this.ctx.logger.error('HTTP服务启动失败', e)
llonebotError.httpServerError = 'HTTP服务启动失败, ' + e
}
}
@@ -84,7 +84,7 @@ class OB11Http {
}
private authorize(req: Request, res: Response, next: () => void) {
let serverToken = this.config.token
const serverToken = this.config.token
let clientToken = ''
const authHeader = req.get('authorization')
if (authHeader) {
@@ -99,7 +99,7 @@ class OB11Http {
this.ctx.logger.info('receive http url token', clientToken)
}
if (serverToken && clientToken != serverToken) {
if (serverToken && clientToken !== serverToken) {
return res.status(403).send(JSON.stringify({ message: 'token verify failed!' }))
}
next()
@@ -125,8 +125,8 @@ class OB11Http {
this.ctx.logger.info('收到 HTTP 请求', url, payload)
try {
res.send(await handler(res, payload))
} catch (e: any) {
res.send(OB11Response.error(e.stack.toString(), 200))
} catch (e) {
res.send(OB11Response.error((e as Error).stack!.toString(), 200))
}
})
}
@@ -136,7 +136,7 @@ namespace OB11Http {
export interface Config {
port: number
token?: string
actionMap: Map<string, BaseAction<any, any>>
actionMap: Map<string, BaseAction<unknown, unknown>>
listenLocalhost: boolean
}
}
@@ -190,7 +190,7 @@ class OB11HttpPost {
//log(`新消息事件HTTP上报没有返回快速操作不需要处理`)
}
},
(err: any) => {
(err) => {
this.ctx.logger.error(`HTTP 事件上报失败: ${host}`, err, event)
},
).catch(e => this.ctx.logger.error(e))

View File

@@ -30,8 +30,8 @@ class OB11WebSocket {
maxPayload: 1024 * 1024 * 1024
})
llonebotError.wsServerError = ''
} catch (e: any) {
llonebotError.wsServerError = '正向 WebSocket 服务启动失败, ' + e.toString()
} catch (e) {
llonebotError.wsServerError = '正向 WebSocket 服务启动失败, ' + e
return
}
this.wsServer?.on('connection', (socket, req) => {
@@ -70,7 +70,7 @@ class OB11WebSocket {
Object.assign(this.config, config)
}
private reply(socket: WebSocket, data: OB11Return<any> | OB11BaseEvent | OB11Message) {
private reply(socket: WebSocket, data: OB11Return<unknown> | OB11BaseEvent | OB11Message) {
if (socket.readyState !== WebSocket.OPEN) {
return
}
@@ -107,14 +107,14 @@ class OB11WebSocket {
}
private async handleAction(socket: WebSocket, msg: string) {
let receive: { action: ActionName | null; params: any; echo?: any } = { action: null, params: {} }
let receive: { action: ActionName | null; params: unknown; echo?: unknown } = { action: null, params: {} }
try {
receive = JSON.parse(msg.toString())
this.ctx.logger.info('收到正向 Websocket 消息', receive)
} catch (e) {
return this.reply(socket, OB11Response.error('json解析失败请检查数据格式', 1400))
}
const action: BaseAction<any, any> = this.config.actionMap.get(receive.action!)!
const action = this.config.actionMap.get(receive.action!)!
if (!action) {
return this.reply(socket, OB11Response.error('不支持的api ' + receive.action, 1404, receive.echo))
}
@@ -122,8 +122,8 @@ class OB11WebSocket {
const handleResult = await action.websocketHandle(receive.params, receive.echo)
handleResult.echo = receive.echo
this.reply(socket, handleResult)
} catch (e: any) {
this.reply(socket, OB11Response.error(`api处理出错:${e.stack}`, 1200, receive.echo))
} catch (e) {
this.reply(socket, OB11Response.error(`api处理出错:${(e as Error).stack}`, 1200, receive.echo))
}
}
@@ -169,7 +169,7 @@ namespace OB11WebSocket {
port: number
heartInterval: number
token?: string
actionMap: Map<string, BaseAction<any, any>>
actionMap: Map<string, BaseAction<unknown, unknown>>
listenLocalhost: boolean
}
}
@@ -200,7 +200,7 @@ class OB11WebSocketReverse {
}
}
private reply(socket: WebSocket, data: OB11Return<any> | OB11BaseEvent | OB11Message) {
private reply(socket: WebSocket, data: OB11Return<unknown> | OB11BaseEvent | OB11Message) {
if (socket.readyState !== WebSocket.OPEN) {
return
}
@@ -211,19 +211,19 @@ class OB11WebSocketReverse {
}
private async handleAction(msg: string) {
let receive: { action: ActionName | null; params: any; echo?: any } = { action: null, params: {} }
let receive: { action: ActionName | null; params: unknown; echo?: unknown } = { action: null, params: {} }
try {
receive = JSON.parse(msg.toString())
this.ctx.logger.info('收到反向Websocket消息', receive)
} catch (e) {
return this.reply(this.wsClient!, OB11Response.error('json解析失败请检查数据格式', 1400, receive.echo))
}
const action: BaseAction<any, any> = this.config.actionMap.get(receive.action!)!
const action = this.config.actionMap.get(receive.action!)!
if (!action) {
return this.reply(this.wsClient!, OB11Response.error('不支持的api ' + receive.action, 1404, receive.echo))
}
try {
let handleResult = await action.websocketHandle(receive.params, receive.echo)
const handleResult = await action.websocketHandle(receive.params, receive.echo)
this.reply(this.wsClient!, handleResult)
} catch (e) {
this.reply(this.wsClient!, OB11Response.error(`api处理出错:${e}`, 1200, receive.echo))
@@ -287,7 +287,7 @@ namespace OB11WebSocketReverse {
url: string
heartInterval: number
token?: string
actionMap: Map<string, BaseAction<any, any>>
actionMap: Map<string, BaseAction<unknown, unknown>>
}
}
@@ -312,8 +312,8 @@ class OB11WebSocketReverseManager {
for (const ws of this.list) {
try {
ws.stop()
} catch (e: any) {
this.ctx.logger.error('反向 WebSocket 关闭:', e.stack)
} catch (e) {
this.ctx.logger.error('反向 WebSocket 关闭:', (e as Error).stack)
}
}
this.list.length = 0
@@ -335,7 +335,7 @@ namespace OB11WebSocketReverseManager {
hosts: string[]
heartInterval: number
token?: string
actionMap: Map<string, BaseAction<any, any>>
actionMap: Map<string, BaseAction<unknown, unknown>>
}
}

View File

@@ -27,9 +27,9 @@ export async function createSendElements(
peer: Peer,
ignoreTypes: OB11MessageDataType[] = [],
) {
let sendElements: SendMessageElement[] = []
let deleteAfterSentFiles: string[] = []
for (let sendMsg of messageData) {
const sendElements: SendMessageElement[] = []
const deleteAfterSentFiles: string[] = []
for (const sendMsg of messageData) {
if (ignoreTypes.includes(sendMsg.type)) {
continue
}
@@ -164,10 +164,6 @@ export async function createSendElements(
sendElements.push(SendElementEntities.ark(sendMsg.data.data))
}
break
case OB11MessageDataType.poke: {
let qq = sendMsg.data?.qq || sendMsg.data?.id
}
break
case OB11MessageDataType.dice: {
const resultId = sendMsg.data?.result
sendElements.push(SendElementEntities.dice(resultId))
@@ -269,7 +265,7 @@ export async function sendMsg(
//log('发送消息总大小', totalSize, 'bytes')
const timeout = 10000 + (totalSize / 1024 / 256 * 1000) // 10s Basic Timeout + PredictTime( For File 512kb/s )
//log('设置消息超时时间', timeout)
const returnMsg = await ctx.ntMsgApi.sendMsg(peer, sendElements, waitComplete, timeout)
const returnMsg = await ctx.ntMsgApi.sendMsg(peer, sendElements, timeout)
if (returnMsg) {
returnMsg.msgShortId = MessageUnique.createMsg(peer, returnMsg.msgId)
ctx.logger.info('消息发送', returnMsg.msgShortId)

View File

@@ -105,7 +105,7 @@ export interface OB11Return<DataType> {
retcode: number
data: DataType
message: string
echo?: any // ws调用api才有此字段
echo?: unknown // ws调用api才有此字段
wording?: string // go-cqhttp字段错误信息
}

View File

@@ -87,8 +87,7 @@ async function onSettingWindowCreated(view: Element) {
<setting-text>HTTP 事件上报密钥</setting-text>
</div>
<div class="q-input">
<input id="config-ob11-httpSecret" class="q-input__inner" data-config-key="ob11.httpSecret" type="text" value="${config.ob11.httpSecret
}" placeholder="未设置" />
<input id="config-ob11-httpSecret" class="q-input__inner" data-config-key="ob11.httpSecret" type="text" value="${config.ob11.httpSecret}" placeholder="未设置" />
</div>
</setting-item>
<setting-item data-direction="row">