koishi-plugin-chat-analyse 0.4.4 → 0.4.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/Data.d.ts ADDED
@@ -0,0 +1,19 @@
1
+ import { Context, Command } from 'koishi';
2
+ /**
3
+ * @class Data
4
+ * @description
5
+ * 提供数据备份、恢复和清理的管理功能,恢复逻辑采用分批处理以优化性能。
6
+ * 清理功能支持按表、时间范围和用户范围进行精确操作。
7
+ */
8
+ export declare class Data {
9
+ private ctx;
10
+ private dataDir;
11
+ constructor(ctx: Context);
12
+ /**
13
+ * @public
14
+ * @method registerCommands
15
+ * @description 在 'analyse.admin' 命令下注册所有数据管理相关的子命令。
16
+ * @param {Command} analyse - '.admin' 命令实例。
17
+ */
18
+ registerCommands(analyse: Command): void;
19
+ }
package/lib/index.d.ts CHANGED
@@ -17,6 +17,7 @@ export interface Config {
17
17
  enableRankStat: boolean;
18
18
  enableOriRecord: boolean;
19
19
  enableWhoAt: boolean;
20
+ enableData: boolean;
20
21
  atRetentionDays: number;
21
22
  rankRetentionDays: number;
22
23
  }
package/lib/index.js CHANGED
@@ -1,6 +1,8 @@
1
+ var __create = Object.create;
1
2
  var __defProp = Object.defineProperty;
2
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
3
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
4
6
  var __hasOwnProp = Object.prototype.hasOwnProperty;
5
7
  var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
6
8
  var __export = (target, all) => {
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
15
17
  }
16
18
  return to;
17
19
  };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
18
28
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
29
 
20
30
  // src/index.ts
@@ -27,7 +37,7 @@ __export(src_exports, {
27
37
  using: () => using
28
38
  });
29
39
  module.exports = __toCommonJS(src_exports);
30
- var import_koishi5 = require("koishi");
40
+ var import_koishi6 = require("koishi");
31
41
 
32
42
  // src/Collector.ts
33
43
  var import_koishi = require("koishi");
@@ -900,6 +910,165 @@ var WhoAt = class {
900
910
  }
901
911
  };
902
912
 
913
+ // src/Data.ts
914
+ var import_koishi5 = require("koishi");
915
+ var fs = __toESM(require("fs/promises"));
916
+ var path = __toESM(require("path"));
917
+ var ALL_TABLES = [
918
+ "analyse_user",
919
+ "analyse_cmd",
920
+ "analyse_msg",
921
+ "analyse_rank",
922
+ "analyse_at",
923
+ "analyse_cache"
924
+ ];
925
+ var Data = class {
926
+ constructor(ctx) {
927
+ this.ctx = ctx;
928
+ this.dataDir = path.join(this.ctx.baseDir, "data", "chat-analyse");
929
+ }
930
+ static {
931
+ __name(this, "Data");
932
+ }
933
+ dataDir;
934
+ /**
935
+ * @public
936
+ * @method registerCommands
937
+ * @description 在 'analyse.admin' 命令下注册所有数据管理相关的子命令。
938
+ * @param {Command} analyse - '.admin' 命令实例。
939
+ */
940
+ registerCommands(analyse) {
941
+ analyse.subcommand(".backup", "备份统计数据", { authority: 4 }).action(async () => {
942
+ try {
943
+ await fs.mkdir(this.dataDir, { recursive: true });
944
+ const allUsers = await this.ctx.database.get("analyse_user", {});
945
+ const uidToUserInfoMap = new Map(allUsers.map((u) => [u.uid, u]));
946
+ for (const tableName of ALL_TABLES) {
947
+ const filepath = path.join(this.dataDir, `${tableName}.json`);
948
+ let dataToExport;
949
+ if (tableName === "analyse_user") {
950
+ dataToExport = allUsers.map(({ uid, ...rest }) => rest);
951
+ } else {
952
+ const records = await this.ctx.database.get(tableName, {});
953
+ dataToExport = records.map((record) => {
954
+ const userInfo = uidToUserInfoMap.get(record.uid);
955
+ if (!userInfo) return null;
956
+ const { uid, ...restOfRecord } = record;
957
+ return {
958
+ userId: userInfo.userId,
959
+ channelId: userInfo.channelId,
960
+ ...restOfRecord
961
+ };
962
+ }).filter(Boolean);
963
+ }
964
+ await fs.writeFile(filepath, JSON.stringify(dataToExport, null, 2));
965
+ }
966
+ return `数据备份成功`;
967
+ } catch (error) {
968
+ this.ctx.logger.error("数据备份失败:", error);
969
+ return "数据备份失败";
970
+ }
971
+ });
972
+ analyse.subcommand(".restore", "恢复统计数据", { authority: 4 }).action(async () => {
973
+ const BATCH_SIZE = 100;
974
+ try {
975
+ const userTablePath = path.join(this.dataDir, "analyse_user.json");
976
+ try {
977
+ const usersToImport = JSON.parse(await fs.readFile(userTablePath, "utf-8"));
978
+ if (Array.isArray(usersToImport) && usersToImport.length > 0) {
979
+ for (let i = 0; i < usersToImport.length; i += BATCH_SIZE) {
980
+ const batch = usersToImport.slice(i, i + BATCH_SIZE);
981
+ await this.ctx.database.upsert("analyse_user", batch);
982
+ }
983
+ }
984
+ } catch (e) {
985
+ if (e.code !== "ENOENT") throw e;
986
+ this.ctx.logger.warn("无用户数据可恢复");
987
+ }
988
+ const allUsers = await this.ctx.database.get("analyse_user", {});
989
+ const userToUidMap = new Map(allUsers.map((u) => [`${u.channelId}:${u.userId}`, u.uid]));
990
+ for (const tableName of ALL_TABLES.filter((t) => t !== "analyse_user")) {
991
+ const filepath = path.join(this.dataDir, `${tableName}.json`);
992
+ try {
993
+ const recordsToImport = JSON.parse(await fs.readFile(filepath, "utf-8"));
994
+ if (Array.isArray(recordsToImport) && recordsToImport.length > 0) {
995
+ const recordsWithUid = recordsToImport.map((r) => {
996
+ const uid = userToUidMap.get(`${r.channelId}:${r.userId}`);
997
+ if (!uid) return null;
998
+ const { userId, channelId, ...rest } = r;
999
+ return { uid, ...rest };
1000
+ }).filter(Boolean);
1001
+ if (recordsWithUid.length > 0) {
1002
+ for (let i = 0; i < recordsWithUid.length; i += BATCH_SIZE) {
1003
+ const batch = recordsWithUid.slice(i, i + BATCH_SIZE);
1004
+ await this.ctx.database.upsert(tableName, batch);
1005
+ }
1006
+ }
1007
+ }
1008
+ } catch (e) {
1009
+ if (e.code !== "ENOENT") throw e;
1010
+ }
1011
+ }
1012
+ return `数据恢复成功`;
1013
+ } catch (error) {
1014
+ this.ctx.logger.error("数据恢复失败:", error);
1015
+ return "数据恢复失败";
1016
+ }
1017
+ });
1018
+ analyse.subcommand(".clear", "清理统计数据", { authority: 4 }).option("table", "-t <table:string> 指定表").option("guild", "-g <guildId:string> 指定群组").option("user", "-u <user:string> 指定用户").option("days", "-d <days:number> 指定天数").option("all", "-a 清理全部数据").action(async ({ options }) => {
1019
+ if (!options.table && !options.guild && !options.user && !options.all && !options.days) return "请提供清理条件";
1020
+ try {
1021
+ if (options.all) {
1022
+ for (const tableName of ALL_TABLES) await this.ctx.database.remove(tableName, {});
1023
+ return "已清除所有聊天分析数据";
1024
+ }
1025
+ let tablesToClear;
1026
+ if (options.table) {
1027
+ if (!ALL_TABLES.includes(options.table)) return `无效表名: ${options.table}`;
1028
+ tablesToClear = [options.table];
1029
+ } else {
1030
+ tablesToClear = ALL_TABLES.filter((t) => t !== "analyse_user");
1031
+ }
1032
+ const queryParts = { query: {}, desc: "" };
1033
+ const descParts = [];
1034
+ if (options.guild || options.user) {
1035
+ const uidsToClear = [];
1036
+ const scopeDesc = [];
1037
+ if (options.guild) {
1038
+ uidsToClear.push(...(await this.ctx.database.get("analyse_user", { channelId: options.guild })).map((u) => u.uid));
1039
+ scopeDesc.push(`群组 ${options.guild} `);
1040
+ }
1041
+ if (options.user) {
1042
+ const userId = import_koishi5.Element.select(options.user, "at")[0]?.attrs.id || options.user;
1043
+ uidsToClear.push(...(await this.ctx.database.get("analyse_user", { userId })).map((u) => u.uid));
1044
+ scopeDesc.push(`用户 ${userId} `);
1045
+ }
1046
+ const uniqueUids = [...new Set(uidsToClear)];
1047
+ if (uniqueUids.length === 0) return "未找到该用户";
1048
+ queryParts.query.uid = { $in: uniqueUids };
1049
+ descParts.push(scopeDesc.join("、"));
1050
+ }
1051
+ if (options.days && options.days > 0) {
1052
+ queryParts.query.timestamp = { $lt: new Date(Date.now() - options.days * import_koishi5.Time.day) };
1053
+ descParts.push(`超过 ${options.days} 天`);
1054
+ }
1055
+ for (const tableName of tablesToClear) {
1056
+ const finalQuery = { ...queryParts.query };
1057
+ if (tableName === "analyse_user" && finalQuery.timestamp) delete finalQuery.timestamp;
1058
+ await this.ctx.database.remove(tableName, finalQuery);
1059
+ }
1060
+ const targetStr = options.table ? `表 ${options.table} ` : "所有表";
1061
+ const conditionStr = descParts.join(" 且 ");
1062
+ const finalDescription = conditionStr ? `${targetStr} 中${conditionStr}的数据` : `${targetStr}的全部统计数据`;
1063
+ return `已成功清理${finalDescription}`;
1064
+ } catch (error) {
1065
+ this.ctx.logger.error("数据清理失败:", error);
1066
+ return "数据清理失败";
1067
+ }
1068
+ });
1069
+ }
1070
+ };
1071
+
903
1072
  // src/index.ts
904
1073
  var usage = `
905
1074
  <div style="border-radius: 10px; border: 1px solid #ddd; padding: 16px; margin-bottom: 20px; box-shadow: 0 2px 5px rgba(0,0,0,0.1);">
@@ -915,22 +1084,23 @@ var usage = `
915
1084
  `;
916
1085
  var name = "chat-analyse";
917
1086
  var using = ["database", "puppeteer", "cron"];
918
- var Config = import_koishi5.Schema.intersect([
919
- import_koishi5.Schema.object({
920
- enableListener: import_koishi5.Schema.boolean().default(true).description("启用消息监听"),
921
- enableOriRecord: import_koishi5.Schema.boolean().default(true).description("启用原始记录")
1087
+ var Config = import_koishi6.Schema.intersect([
1088
+ import_koishi6.Schema.object({
1089
+ enableListener: import_koishi6.Schema.boolean().default(true).description("启用消息监听"),
1090
+ enableOriRecord: import_koishi6.Schema.boolean().default(true).description("启用原始记录")
922
1091
  }).description("监听配置"),
923
- import_koishi5.Schema.object({
924
- enableCmdStat: import_koishi5.Schema.boolean().default(true).description("启用命令统计"),
925
- enableMsgStat: import_koishi5.Schema.boolean().default(true).description("启用消息统计")
926
- }).description("统计配置"),
927
- import_koishi5.Schema.object({
928
- enableRankStat: import_koishi5.Schema.boolean().default(true).description("启用发言排行"),
929
- rankRetentionDays: import_koishi5.Schema.number().min(0).default(31).description("记录保留天数")
1092
+ import_koishi6.Schema.object({
1093
+ enableCmdStat: import_koishi6.Schema.boolean().default(true).description("启用命令统计"),
1094
+ enableMsgStat: import_koishi6.Schema.boolean().default(true).description("启用消息统计"),
1095
+ enableData: import_koishi6.Schema.boolean().default(false).description("启用数据管理")
1096
+ }).description("功能配置"),
1097
+ import_koishi6.Schema.object({
1098
+ enableRankStat: import_koishi6.Schema.boolean().default(true).description("启用发言排行"),
1099
+ rankRetentionDays: import_koishi6.Schema.number().min(0).default(31).description("记录保留天数")
930
1100
  }).description("发言排行配置"),
931
- import_koishi5.Schema.object({
932
- enableWhoAt: import_koishi5.Schema.boolean().default(true).description("启用 @ 记录"),
933
- atRetentionDays: import_koishi5.Schema.number().min(0).default(7).description("记录保留天数")
1101
+ import_koishi6.Schema.object({
1102
+ enableWhoAt: import_koishi6.Schema.boolean().default(true).description("启用 @ 记录"),
1103
+ atRetentionDays: import_koishi6.Schema.number().min(0).default(7).description("记录保留天数")
934
1104
  }).description("@ 记录配置")
935
1105
  ]);
936
1106
  function apply(ctx, config) {
@@ -938,6 +1108,7 @@ function apply(ctx, config) {
938
1108
  const analyse = ctx.command("analyse", "聊天记录分析");
939
1109
  new Stat(ctx, config).registerCommands(analyse);
940
1110
  if (config.enableWhoAt) new WhoAt(ctx, config).registerCommand(analyse);
1111
+ if (config.enableData) new Data(ctx).registerCommands(analyse);
941
1112
  }
942
1113
  __name(apply, "apply");
943
1114
  // Annotate the CommonJS export names for ESM import in node:
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-chat-analyse",
3
3
  "description": "聊天记录分析",
4
- "version": "0.4.4",
4
+ "version": "0.4.5",
5
5
  "contributors": [
6
6
  "Yis_Rime <yis_rime@outlook.com>"
7
7
  ],