chore: 摘除非必要文件

This commit is contained in:
zhaoyingbo 2024-11-26 01:53:34 +00:00
parent 4473c990ef
commit f0d481629b
16 changed files with 5 additions and 764 deletions

View File

@ -1,54 +0,0 @@
import { RecordModel } from "pocketbase"
import { managePb404 } from "../../utils/pbTools"
import pbClient from "../pbClient"
interface AppConfigRecordModel extends RecordModel {
value: string
}
/**
*
* @param key
* @returns
*/
const get = async (key: string) => {
const config = await managePb404<AppConfigRecordModel>(() =>
pbClient.collection("config").getFirstListItem(`key='${key}'`)
)
if (!config) return ""
return config.value
}
/**
* Deepseek的apiKey
* @returns {string} ak
*/
const getDeepseekApiKey = async () => get("deepseek_api_key")
/**
* OpenAI的key
* @returns {string} ak
*/
const getOpenAIApiKey = async () => get("openai_api_key")
/**
* Langfuse的pk
* @returns {string} pk
*/
const getLangfusePk = async () => get("langfuse_pk")
/**
* Langfuse的sk
* @returns {string} sk
*/
const getLangfuseSk = async () => get("langfuse_sk")
const appConfig = {
getOpenAIApiKey,
getDeepseekApiKey,
getLangfusePk,
getLangfuseSk,
}
export default appConfig

View File

@ -1,40 +0,0 @@
import { DB } from "../../types"
import { managePb404 } from "../../utils/pbTools"
import pbClient from "../pbClient"
/**
*
* @param appName
* @returns
*/
const get = async (appName: string) =>
managePb404<DB.AppInfo>(() =>
pbClient.collection("app_info").getFirstListItem(`name='${appName}'`)
)
/**
*
* @returns
*/
const getFullList = () =>
pbClient.collection("app_info").getFullList<DB.AppInfo>()
/**
*
* @param appName
* @param key
* @returns
*/
const getVal = async (appName: string, key: string) => {
const config = await get(appName)
if (!config) return ""
return config[key] || ""
}
const appInfo = {
get,
getVal,
getFullList,
}
export default appInfo

View File

@ -1,27 +0,0 @@
import { DB } from "../../types"
import { managePb404 } from "../../utils/pbTools"
import pbClient from "../pbClient"
const get = async (userId: string) =>
managePb404<DB.GroupAgentConfig>(() =>
pbClient
.collection("group_agent_config")
.getFirstListItem(`user_id='${userId}'`)
)
const upsert = async (data: Partial<DB.GroupAgentConfig>) => {
const { user_id } = data
const old = await get(user_id!)
if (old) {
await pbClient.collection("group_agent_config").update(old.id, data)
return old.id
}
return pbClient.collection("group_agent_config").create(data)
}
const groupAgentConfig = {
get,
upsert,
}
export default groupAgentConfig

View File

@ -1,19 +1,11 @@
import apiKey from "./apiKey"
import appConfig from "./appConfig"
import appInfo from "./appInfo"
import groupAgentConfig from "./groupAgentConfig"
import log from "./log"
import messageGroup from "./messageGroup"
import tenantAccessToken from "./tenantAccessToken"
const db = {
apiKey,
appInfo,
messageGroup,
log,
tenantAccessToken,
groupAgentConfig,
appConfig,
}
export default db

View File

@ -1,44 +0,0 @@
import logger from "@egg/logger"
import appInfo from "../appInfo"
import pbClient from "../pbClient"
const tokenCache = {} as Record<string, string>
/**
* token
* @param {string} id id
* @param {string} appName
* @param {string} value token
*/
const update = async (id: string, appName: string, value: string) => {
try {
await pbClient
.collection("app_info")
.update(id, { tenant_access_token: value })
} catch {
/* empty */
}
tokenCache[appName] = value
logger.info(`reset ${appName} access token success: ${value}`)
}
/**
* token
* @param {string} appName
* @returns {string} token
*/
const get = async (appName: string) => {
if (tokenCache[appName]) return tokenCache[appName]
const config = await appInfo.getVal(appName, "tenant_access_token")
tokenCache[appName] = config
return config
}
const tenantAccessToken = {
get,
update,
}
export default tenantAccessToken

View File

@ -1,7 +1,6 @@
import { type LarkBody } from "@egg/lark-msg-tool"
import tempMap from "../../constant/template"
import db from "../../db"
import { Context } from "../../types"
import createKVTemp from "../sheet/createKVTemp"
import groupAgent from "./groupAgent"
@ -12,14 +11,11 @@ import groupAgent from "./groupAgent"
*/
const getIsP2pOrGroupAtBot = async (
larkBody: LarkBody,
app: string
appInfo: Context.APP_INFO
): Promise<boolean> => {
const appName = (await db.appInfo.getFullList()).find(
(v) => v.name === app
)?.app_name
const isP2p = larkBody.chatType === "p2p"
const isAtBot = larkBody.mentions?.some?.(
(mention) => mention.name === appName
(mention) => mention.name === appInfo.app_name
)
return Boolean(isP2p || isAtBot)
}
@ -34,7 +30,7 @@ const filterIllegalMsg = async ({
logger,
larkService,
larkBody,
app,
appInfo,
}: Context.Data): Promise<boolean> => {
const { chatId, msgType, msgText } = larkBody
// 没有chatId的消息不处理
@ -42,7 +38,7 @@ const filterIllegalMsg = async ({
if (!chatId) return true
// 非私聊和群聊中艾特机器人的消息不处理
if (!(await getIsP2pOrGroupAtBot(larkBody, app))) {
if (!(await getIsP2pOrGroupAtBot(larkBody, appInfo))) {
return true
}
@ -66,7 +62,7 @@ const filterIllegalMsg = async ({
}
// 非表情包只在私聊或者群聊中艾特机器人时才回复
else if (await getIsP2pOrGroupAtBot(body, app)) {
else {
logger.info(`got a illegal message, chatId: ${chatId}`)
const content = JSON.stringify({
text: "哇!这是什么东东?我只懂普通文本啦![可爱]",

View File

@ -1,30 +0,0 @@
import logger from "@egg/logger"
import { LarkService } from "@egg/net-tool"
import pLimit from "p-limit"
import db from "../db"
export const resetAccessToken = async () => {
try {
const appList = await db.appInfo.getFullList()
const limit = pLimit(3)
const promiseList = appList.map((app) =>
limit(() =>
new LarkService({
appId: app.app_id,
appSecret: app.app_secret,
requestId: "schedule",
}).auth
.getAppAuth()
.then((res) => {
return db.tenantAccessToken.update(app.id, app.name, res)
})
)
)
await Promise.allSettled(promiseList)
} catch (error: any) {
logger
.child({ requestId: "schedule" })
.error(`resetAccessToken error: ${error.message}`)
}
}

View File

@ -1,15 +0,0 @@
import LarkBaseService from "./base"
class LarkAuthService extends LarkBaseService {
getAk(appId: string, appSecret: string) {
return this.post<{ tenant_access_token: string; code: number }>(
"/auth/v3/tenant_access_token/internal",
{
app_id: appId,
app_secret: appSecret,
}
)
}
}
export default LarkAuthService

View File

@ -1,30 +0,0 @@
import { NetError, NetToolBase } from "@egg/net-tool"
import db from "../../db"
class LarkBaseService extends NetToolBase {
constructor(appName: string, requestId: string) {
super({
prefix: "https://open.f.mioffice.cn/open-apis",
requestId,
getHeaders: async () => ({
Authorization: `Bearer ${await db.tenantAccessToken.get(appName)}`,
}),
})
}
protected async request<T = any>(params: any): Promise<T> {
return super.request<T>(params).catch((error: NetError) => {
const res = {
httpStatus: error.response?.status,
code: error.code,
data: error.data,
message: error.message,
} as T
this.logger.error(`larkNetTool catch error: ${JSON.stringify(res)}`)
return res
})
}
}
export default LarkBaseService

View File

@ -1,42 +0,0 @@
import { LarkServer } from "../../types"
import LarkBaseService from "./base"
class LarkChatService extends LarkBaseService {
/**
*
*/
async getInnerList() {
const path = "/im/v1/chats"
const chatList = []
let hasMore = true
let pageToken = ""
while (hasMore) {
const { data, code } = await this.get<
LarkServer.BaseListRes<LarkServer.ChatGroupData>
>(path, {
page_size: 100,
page_token: pageToken,
})
if (code !== 0) break
chatList.push(...data.items)
hasMore = data.has_more
pageToken = data.page_token
}
return {
code: 0,
data: chatList,
message: "ok",
}
}
/**
*
* @param chatId ID
*/
async getChatInfo(chatId: string) {
const path = `/im/v1/chats/${chatId}`
return this.get<LarkServer.BaseRes<LarkServer.ChatGroupData>>(path)
}
}
export default LarkChatService

View File

@ -1,141 +0,0 @@
import { LarkServer } from "../../types"
import LarkBaseService from "./base"
class LarkDriveService extends LarkBaseService {
/**
*
*
* @param docTokens -
* @param docType - "doc"
* @param userIdType - ID类型 "user_id"
* @returns
*/
async batchGetMeta(
docTokens: string[],
docType = "doc",
userIdType = "user_id"
) {
const path = "/drive/v1/metas/batch_query"
// 如果docTokens长度超出150需要分批请求
const docTokensLen = docTokens.length
const maxLen = 150
const requestMap = Array.from(
{ length: Math.ceil(docTokensLen / maxLen) },
(_, index) => {
const start = index * maxLen
const docTokensSlice = docTokens.slice(start, start + maxLen)
const data = {
request_docs: docTokensSlice.map((id) => ({
doc_token: id,
doc_type: docType,
})),
}
return this.post<LarkServer.BatchDocMetaRes>(path, data, {
user_id_type: userIdType,
})
}
)
const responses = await Promise.all(requestMap)
const metas = responses.flatMap((res) => {
return res.data?.metas || []
})
const failedList = responses.flatMap((res) => {
return res.data?.failed_list || []
})
return {
code: 0,
data: {
metas,
failedList,
},
message: "success",
}
}
/**
*
*
* @param folderToken -
* @returns
*/
async listFiles(folderToken: string) {
const path = "/drive/v1/files"
return this.get<LarkServer.BaseRes>(path, {
folder_token: folderToken,
})
}
/**
*
*
* @param folderToken -
* @param fileName -
* @param fileType -
* @returns Promise
*/
async createFile(
folderToken: string,
fileName: string,
fileType: "doc" | "sheet" | "bitable"
) {
const path = `/drive/explorer/v2/file/${folderToken}`
return this.post<LarkServer.BaseRes>(path, {
title: fileName,
type: fileType,
})
}
/**
*
*
* @param folderToken -
* @param fileToken -
* @param fileName -
* @param fileType -
* @returns Promise
*/
async copyFile(
folderToken: string,
fileToken: string,
fileName: string,
fileType: LarkServer.FileType
) {
const path = `/drive/v1/files/${fileToken}/copy`
return this.post<LarkServer.BaseRes<LarkServer.CopyFileData>>(path, {
type: fileType,
folder_token: folderToken,
name: fileName,
})
}
/**
*
*
* @param fileToken -
* @returns Promise
*/
async addCollaborator(
fileToken: string,
fileType: LarkServer.FileType,
memberType: "userid" | "openchat",
memberId: string,
perm: "view" | "edit" | "full_access"
) {
const path = `/drive/v1/permissions/${fileToken}/members`
return this.post<LarkServer.BaseRes>(
path,
{
member_type: memberType,
member_id: memberId,
perm,
},
{
type: fileType,
}
)
}
}
export default LarkDriveService

View File

@ -1,33 +0,0 @@
import LarkAuthService from "./auth"
import LarkChatService from "./chat"
import LarkDriveService from "./drive"
import LarkMessageService from "./message"
import LarkSheetService from "./sheet"
import LarkUserService from "./user"
class LarkService {
drive: LarkDriveService
message: LarkMessageService
user: LarkUserService
sheet: LarkSheetService
auth: LarkAuthService
chat: LarkChatService
requestId: string
constructor(appName: string, requestId: string) {
this.drive = new LarkDriveService(appName, requestId)
this.message = new LarkMessageService(appName, requestId)
this.user = new LarkUserService(appName, requestId)
this.sheet = new LarkSheetService(appName, requestId)
this.auth = new LarkAuthService(appName, requestId)
this.chat = new LarkChatService(appName, requestId)
this.requestId = requestId
}
child(appName?: string) {
if (!appName) return this
return new LarkService(appName, this.requestId)
}
}
export default LarkService

View File

@ -1,101 +0,0 @@
import { LarkServer } from "../../types/larkServer"
import LarkBaseService from "./base"
class LarkMessageService extends LarkBaseService {
/**
*
* @param receiveIdType id类型 open_id/user_id/union_id/email/chat_id
* @param receiveId IDID类型应与查询参数receiveIdType
* @param msgType textpostimagefileaudiomediastickerinteractiveshare_chatshare_user
* @param content JSON结构序列化后的字符串msgType对应不同内容
*/
async send(
receiveIdType: LarkServer.ReceiveIDType,
receiveId: string,
msgType: LarkServer.MsgType,
content: string | Record<string, any>
) {
const path = `/im/v1/messages?receive_id_type=${receiveIdType}`
if (typeof content === "object") {
content = JSON.stringify(content)
}
if (msgType === "text" && !content.includes('"text"')) {
content = JSON.stringify({ text: content })
}
return this.post<LarkServer.BaseRes<{ message_id: string }>>(path, {
receive_id: receiveId,
msg_type: msgType,
content,
})
}
/**
*
* @param receiveId IDID类型应与查询参数receiveIdType
* @param content
*/
async sendCard2Chat(
receiveId: string,
content: string | Record<string, any>
) {
return this.send("chat_id", receiveId, "interactive", content)
}
/**
*
* @param receiveId IDID类型应与查询参数receiveIdType
* @param content
*/
async sendText2Chat(receiveId: string, content: string) {
return this.send("chat_id", receiveId, "text", content)
}
/**
*
* @param messageId id
* @param content JSON结构序列化后的字符串msgType对应不同内容
*/
async update(messageId: string, content: string | Record<string, any>) {
const path = `/im/v1/messages/${messageId}`
if (typeof content === "object") {
content = JSON.stringify(content)
}
return this.patch<LarkServer.BaseRes>(path, { content })
}
/**
*
* @param chatId ID
* @param startTime
* @param endTime
*/
async getHistory(chatId: string, startTime: string, endTime: string) {
const path = `/im/v1/messages`
const messageList = [] as LarkServer.MessageData[]
let hasMore = true
let pageToken = ""
while (hasMore) {
const { code, data } = await this.get<
LarkServer.BaseListRes<LarkServer.MessageData>
>(path, {
container_id_type: "chat",
container_id: chatId,
start_time: startTime,
end_time: endTime,
page_size: 50,
page_token: pageToken,
})
if (code !== 0) break
messageList.push(...data.items)
hasMore = data.has_more
pageToken = data.page_token
}
return {
code: 0,
data: messageList,
message: "ok",
}
}
}
export default LarkMessageService

View File

@ -1,101 +0,0 @@
import { LarkServer } from "../../types/larkServer"
import LarkBaseService from "./base"
class LarkSheetService extends LarkBaseService {
/**
*
* @param sheetToken
* @param range
* @param values
* @returns Promise
*/
async insertRows(sheetToken: string, range: string, values: string[][]) {
const path = `/sheets/v2/spreadsheets/${sheetToken}/values_append?insertDataOption=INSERT_ROWS`
return this.post<LarkServer.BaseRes>(path, {
valueRange: {
range,
values,
},
})
}
/**
*
* @param sheetToken
* @param range
* @returns Promise
*/
async getRange(sheetToken: string, range: string) {
const path = `/sheets/v2/spreadsheets/${sheetToken}/values/${range}?valueRenderOption=ToString`
return this.get<LarkServer.SpreadsheetRes>(path)
}
/**
*
* @param appToken
* @returns Promise
*/
async getTables(appToken: string) {
const path = `/bitable/v1/apps/${appToken}/tables`
const tableList = [] as LarkServer.TableData[]
let hasMore = true
let pageToken = ""
while (hasMore) {
const { data, code } = await this.get<
LarkServer.BaseListRes<LarkServer.TableData>
>(path, {
page_size: 100,
page_token: pageToken,
})
if (code !== 0) break
tableList.push(...data.items)
hasMore = data.has_more
pageToken = data.page_token
}
return {
code: 0,
data: tableList,
message: "ok",
}
}
/**
*
* @param appToken
* @param tableId ID
* @returns Promise
*/
async getViews(appToken: string, tableId: string) {
const path = `/bitable/v1/apps/${appToken}/tables/${tableId}/views`
let has_more = true
const res = [] as LarkServer.ViewData[]
while (has_more) {
const { data, code } = await this.get<
LarkServer.BaseListRes<LarkServer.ViewData>
>(path, {
page_size: 100,
})
if (code !== 0) break
res.push(...data.items)
has_more = data.has_more
}
return {
code: 0,
data: res,
message: "ok",
}
}
/**
* ()
* @param appToken
* @param tableId ID
* @returns Promise
*/
async getRecords(appToken: string, tableId: string) {
const path = `/bitable/v1/apps/${appToken}/tables/${tableId}/records`
return this.get<LarkServer.BaseRes>(path)
}
}
export default LarkSheetService

View File

@ -1,72 +0,0 @@
import { LarkServer } from "../../types/larkServer"
import LarkBaseService from "./base"
class LarkUserService extends LarkBaseService {
/**
*
* @param code
* @returns
*/
async code2Login(code: string) {
const path = `/mina/v2/tokenLoginValidate`
return this.post<LarkServer.UserSessionRes>(path, { code })
}
/**
*
* @param userId ID
* @param userIdType ID类型
* @returns
*/
async getOne(userId: string, userIdType: "open_id" | "user_id") {
const path = `/contact/v3/users/${userId}`
return this.get<LarkServer.UserInfoRes>(path, {
user_id_type: userIdType,
})
}
/**
*
* @param userIds ID数组
* @param userIdType ID类型
* @returns
*/
async batchGet(
userIds: string[],
userIdType: "open_id" | "user_id" = "open_id"
) {
const path = `/contact/v3/users/batch`
// 如果user_id长度超出50需要分批请求,
const userCount = userIds.length
const maxLen = 50
const requestMap = Array.from(
{ length: Math.ceil(userCount / maxLen) },
(_, index) => {
const start = index * maxLen
const getParams = `${userIds
.slice(start, start + maxLen)
.map((id) => `user_ids=${id}`)
.join("&")}&user_id_type=${userIdType}`
return this.get<LarkServer.BatchUserInfoRes>(path, getParams)
}
)
const responses = await Promise.all(requestMap)
const items = responses.flatMap((res) => {
return res.data?.items || []
})
return {
code: 0,
data: {
items,
},
message: "success",
}
}
}
export default LarkUserService

View File

@ -1,23 +1,6 @@
import { RecordModel } from "pocketbase"
export namespace DB {
export interface GroupAgentConfig extends RecordModel {
user_id: string
chat_id: string
chat_name: string
pre_query?: string
}
export interface AppInfo extends RecordModel {
name: string
app_id: string
app_secret: string
app_name: string
avatar_url: string
description: string
tenant_access_token: string
}
export interface ApiKey extends RecordModel {
name: string
user: string