@alemonjs/qq-bot 2.1.0-alpha.2 → 2.1.0-alpha.21

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.
Files changed (109) hide show
  1. package/README.md +7 -30
  2. package/lib/config.d.ts +8 -0
  3. package/lib/config.js +20 -0
  4. package/lib/desktop.d.ts +1 -3
  5. package/lib/desktop.js +3 -12
  6. package/lib/hook.d.ts +30 -9
  7. package/lib/hook.js +19 -17
  8. package/lib/index.d.ts +5 -6
  9. package/lib/index.js +37 -19
  10. package/lib/index.webhook.d.ts +1 -0
  11. package/lib/index.webhook.js +5 -4
  12. package/lib/index.websoket.d.ts +1 -0
  13. package/lib/index.websoket.js +41 -22
  14. package/lib/message/AT_MESSAGE_CREATE.d.ts +35 -0
  15. package/lib/message/AT_MESSAGE_CREATE.js +1 -0
  16. package/lib/message/CHANNEL_CREATE.d.ts +15 -0
  17. package/lib/message/CHANNEL_CREATE.js +1 -0
  18. package/lib/message/CHANNEL_DELETE.d.ts +15 -0
  19. package/lib/message/CHANNEL_DELETE.js +1 -0
  20. package/lib/message/CHANNEL_UPDATE.d.ts +15 -0
  21. package/lib/message/CHANNEL_UPDATE.js +1 -0
  22. package/lib/message/DIRECT_MESSAGE_CREATE.d.ts +29 -0
  23. package/lib/message/DIRECT_MESSAGE_CREATE.js +1 -0
  24. package/lib/message/DIRECT_MESSAGE_DELETE.d.ts +17 -0
  25. package/lib/message/DIRECT_MESSAGE_DELETE.js +1 -0
  26. package/lib/message/ERROR.d.ts +1 -0
  27. package/lib/message/ERROR.js +1 -0
  28. package/lib/message/GUILD_CREATE.d.ts +15 -0
  29. package/lib/message/GUILD_CREATE.js +1 -0
  30. package/lib/message/GUILD_DELETE.d.ts +15 -0
  31. package/lib/message/GUILD_DELETE.js +1 -0
  32. package/lib/message/GUILD_MEMBER_ADD.d.ts +14 -0
  33. package/lib/message/GUILD_MEMBER_ADD.js +1 -0
  34. package/lib/message/GUILD_MEMBER_REMOVE.d.ts +14 -0
  35. package/lib/message/GUILD_MEMBER_REMOVE.js +1 -0
  36. package/lib/message/GUILD_MEMBER_UPDATE.d.ts +14 -0
  37. package/lib/message/GUILD_MEMBER_UPDATE.js +1 -0
  38. package/lib/message/GUILD_UPDATE.d.ts +15 -0
  39. package/lib/message/GUILD_UPDATE.js +1 -0
  40. package/lib/message/INTERACTION_CREATE.d.ts +53 -0
  41. package/lib/message/INTERACTION_CREATE.js +1 -0
  42. package/lib/message/MESSAGE_CREATE.d.ts +1 -0
  43. package/lib/message/MESSAGE_CREATE.js +1 -0
  44. package/lib/message/MESSAGE_DELETE.d.ts +1 -0
  45. package/lib/message/MESSAGE_DELETE.js +1 -0
  46. package/lib/message/MESSAGE_REACTION_ADD.d.ts +13 -0
  47. package/lib/message/MESSAGE_REACTION_ADD.js +1 -0
  48. package/lib/message/MESSAGE_REACTION_REMOVE.d.ts +13 -0
  49. package/lib/message/MESSAGE_REACTION_REMOVE.js +1 -0
  50. package/lib/message/PUBLIC_MESSAGE_DELETE.d.ts +15 -0
  51. package/lib/message/PUBLIC_MESSAGE_DELETE.js +1 -0
  52. package/lib/message/READY.d.ts +6 -0
  53. package/lib/message/READY.js +1 -0
  54. package/lib/message/group/C2C_MESSAGE_CREATE.d.ts +9 -0
  55. package/lib/message/group/C2C_MESSAGE_CREATE.js +1 -0
  56. package/lib/message/group/C2C_MSG_RECEIVE.d.ts +4 -0
  57. package/lib/message/group/C2C_MSG_RECEIVE.js +1 -0
  58. package/lib/message/group/C2C_MSG_REJECT.d.ts +4 -0
  59. package/lib/message/group/C2C_MSG_REJECT.js +1 -0
  60. package/lib/message/group/FRIEND_ADD.d.ts +4 -0
  61. package/lib/message/group/FRIEND_ADD.js +1 -0
  62. package/lib/message/group/FRIEND_DEL.d.ts +4 -0
  63. package/lib/message/group/FRIEND_DEL.js +1 -0
  64. package/lib/message/group/GROUP_ADD_ROBOT.d.ts +5 -0
  65. package/lib/message/group/GROUP_ADD_ROBOT.js +1 -0
  66. package/lib/message/group/GROUP_AT_MESSAGE_CREATE.d.ts +11 -0
  67. package/lib/message/group/GROUP_AT_MESSAGE_CREATE.js +1 -0
  68. package/lib/message/group/GROUP_DEL_ROBOT.d.ts +5 -0
  69. package/lib/message/group/GROUP_DEL_ROBOT.js +1 -0
  70. package/lib/message/group/GROUP_MSG_RECEIVE.d.ts +5 -0
  71. package/lib/message/group/GROUP_MSG_RECEIVE.js +1 -0
  72. package/lib/message/group/GROUP_MSG_REJECT.d.ts +5 -0
  73. package/lib/message/group/GROUP_MSG_REJECT.js +1 -0
  74. package/lib/register.d.ts +2 -3
  75. package/lib/register.js +270 -176
  76. package/lib/sdk/api.d.ts +196 -969
  77. package/lib/sdk/api.js +267 -916
  78. package/lib/sdk/client.webhook.d.ts +9 -0
  79. package/lib/sdk/{client.js → client.webhook.js} +19 -53
  80. package/lib/sdk/client.websoket.d.ts +9 -0
  81. package/lib/sdk/client.websoket.js +43 -96
  82. package/lib/sdk/config.d.ts +1 -0
  83. package/lib/sdk/instance.d.ts +3 -0
  84. package/lib/sdk/instance.js +93 -0
  85. package/lib/sdk/intents.d.ts +3 -0
  86. package/lib/sdk/intents.js +25 -90
  87. package/lib/sdk/message.d.ts +4 -0
  88. package/lib/sdk/message.group.d.ts +24 -0
  89. package/lib/sdk/message.group.js +1 -0
  90. package/lib/sdk/message.guild.d.ts +38 -0
  91. package/lib/sdk/message.guild.js +1 -0
  92. package/lib/sdk/message.js +1 -0
  93. package/lib/sdk/message.public.d.ts +6 -0
  94. package/lib/sdk/message.public.js +1 -0
  95. package/lib/sdk/typing.d.ts +67 -59
  96. package/lib/sdk/typing.js +1 -0
  97. package/lib/sdk/webhook.secret.d.ts +14 -0
  98. package/lib/sdk/webhook.secret.js +6 -21
  99. package/lib/sends.d.ts +29 -0
  100. package/lib/sends.js +546 -477
  101. package/lib/utils.d.ts +1 -0
  102. package/lib/utils.js +7 -12
  103. package/package.json +9 -5
  104. package/lib/index.group.js +0 -19
  105. package/lib/index.guild.js +0 -36
  106. package/lib/sdk/client.websoket.group.js +0 -221
  107. package/lib/sdk/client.websoket.guild.js +0 -205
  108. package/lib/sdk/counter.js +0 -19
  109. package/lib/sdk/from.js +0 -44
package/lib/utils.d.ts ADDED
@@ -0,0 +1 @@
1
+ export declare const isGuild: (str: string) => boolean;
package/lib/utils.js CHANGED
@@ -1,13 +1,8 @@
1
- /**
2
- *
3
- * @param str
4
- * @returns
5
- */
6
- const isGuild = str => {
7
- // guild ID 纯数字,例如:11586990140073229091
8
- // 转换失败,是群id。return false
9
- if (isNaN(Number(str.substring(0, 6)))) return false
10
- return true
11
- }
1
+ const isGuild = (str) => {
2
+ if (isNaN(Number(str.substring(0, 6)))) {
3
+ return false;
4
+ }
5
+ return true;
6
+ };
12
7
 
13
- export { isGuild }
8
+ export { isGuild };
package/package.json CHANGED
@@ -1,13 +1,13 @@
1
1
  {
2
2
  "name": "@alemonjs/qq-bot",
3
- "version": "2.1.0-alpha.2",
4
- "description": "阿柠檬qqbot平台连接",
3
+ "version": "2.1.0-alpha.21",
4
+ "description": "阿柠檬qq-bot平台连接",
5
5
  "author": "lemonade",
6
6
  "license": "MIT",
7
7
  "type": "module",
8
8
  "main": "lib/index.js",
9
9
  "scripts": {
10
- "build": "node bundle.js"
10
+ "build": "lvy build"
11
11
  },
12
12
  "dependencies": {
13
13
  "axios": "^1.4.0",
@@ -25,11 +25,15 @@
25
25
  "uuid": "^11.0.3",
26
26
  "@noble/curves": "^1.7.0"
27
27
  },
28
+ "peerDependencies": {
29
+ "alemonjs": "^2.1.0-alpha.15"
30
+ },
28
31
  "types": "lib",
29
32
  "exports": {
30
33
  ".": {
31
34
  "import": "./lib/index.js",
32
- "types": "./lib/index.d.ts"
35
+ "types": "./lib/index.d.ts",
36
+ "require": "./lib/index.js"
33
37
  },
34
38
  "./package": "./package.json",
35
39
  "./desktop": "./lib/desktop.js"
@@ -70,4 +74,4 @@
70
74
  "type": "git",
71
75
  "url": "https://github.com/lemonade-lab/alemonjs.git"
72
76
  }
73
- }
77
+ }
@@ -1,19 +0,0 @@
1
- import { QQBotGroupClient } from './sdk/client.websoket.group.js';
2
- import { getQQBotConfig, register } from './register.js';
3
-
4
- const start = () => {
5
- const config = getQQBotConfig();
6
- // intents 需要默认值
7
- const client = new QQBotGroupClient({
8
- ...config,
9
- intents: config?.intents ?? ['GROUP_AND_C2C_EVENT'],
10
- is_private: config?.is_private ?? false,
11
- sandbox: config?.sandbox ?? false,
12
- shard: config?.shard ?? [0, 1]
13
- });
14
- // 连接
15
- client.connect(config?.gatewayURL);
16
- register(client);
17
- };
18
-
19
- export { start };
@@ -1,36 +0,0 @@
1
- import { getQQBotConfig, register } from './register.js';
2
- import { QQBotGuildClient } from './sdk/client.websoket.guild.js';
3
-
4
- const start = () => {
5
- const config = getQQBotConfig();
6
- // intents 需要默认值
7
- const client = new QQBotGuildClient({
8
- ...config,
9
- intents: config?.intents ?? config?.is_private
10
- ? [
11
- 'GUILDS', // base
12
- 'GUILD_MEMBERS', // base
13
- 'GUILD_MESSAGES',
14
- 'GUILD_MESSAGE_REACTIONS',
15
- 'DIRECT_MESSAGE',
16
- 'INTERACTION',
17
- 'FORUMS_EVENT'
18
- ]
19
- : [
20
- 'GUILDS', // base
21
- 'GUILD_MEMBERS', // base
22
- 'GUILD_MESSAGE_REACTIONS',
23
- 'DIRECT_MESSAGE',
24
- 'INTERACTION',
25
- 'PUBLIC_GUILD_MESSAGES'
26
- ],
27
- is_private: config?.is_private ?? false,
28
- sandbox: config?.sandbox ?? false,
29
- shard: config?.shard ?? [0, 1]
30
- });
31
- // 连接
32
- client.connect(config?.gatewayURL);
33
- register(client);
34
- };
35
-
36
- export { start };
@@ -1,221 +0,0 @@
1
- import WebSocket from 'ws';
2
- import { QQBotAPI } from './api.js';
3
- import { config } from './config.js';
4
- import { getIntentsMask } from './intents.js';
5
- import { Counter } from './counter.js';
6
-
7
- /**
8
- * 连接
9
- */
10
- class QQBotGroupClient extends QQBotAPI {
11
- //
12
- #counter = new Counter(1); // 初始值为1
13
- // 标记是否已连接
14
- #isConnected = false;
15
- // 存储最新的消息序号
16
- #heartbeat_interval = 30000;
17
- // 鉴权
18
- #IntervalId = null;
19
- // url
20
- #gatewayUrl = null;
21
- /**
22
- * 设置配置
23
- * @param opstion
24
- */
25
- constructor(opstion) {
26
- super();
27
- for (const key in opstion) {
28
- config.set(key, opstion[key]);
29
- }
30
- }
31
- /**
32
- * 定时鉴权
33
- * @param cfg
34
- * @returns
35
- */
36
- async #setTimeoutBotConfig() {
37
- const accessToken = async () => {
38
- const app_id = config.get('app_id');
39
- const secret = config.get('secret');
40
- if (!app_id || !secret)
41
- return;
42
- // 发送请求
43
- const data = await this.getAuthentication(app_id, secret).then(res => res.data);
44
- config.set('access_token', data.access_token);
45
- console.info('refresh', data.expires_in, 's');
46
- setTimeout(accessToken, data.expires_in * 1000);
47
- };
48
- await accessToken();
49
- return;
50
- }
51
- /**
52
- * 鉴权数据
53
- * @returns
54
- */
55
- #aut() {
56
- const token = config.get('access_token');
57
- const intents = config.get('intents');
58
- const shard = config.get('shard');
59
- return {
60
- op: 2, // op = 2
61
- d: {
62
- token: `QQBot ${token}`,
63
- intents: getIntentsMask(intents),
64
- shard: shard,
65
- properties: {
66
- $os: process.platform,
67
- $browser: 'alemonjs',
68
- $device: 'alemonjs'
69
- }
70
- }
71
- };
72
- }
73
- #ws = null;
74
- #events = {};
75
- /**
76
- * 注册事件处理程序
77
- * @param key 事件名称
78
- * @param val 事件处理函数
79
- */
80
- on(key, val) {
81
- if (!this.#events[key])
82
- this.#events[key] = [];
83
- this.#events[key].push(val);
84
- return this;
85
- }
86
- /**
87
- *
88
- * @param cfg
89
- * @param conversation
90
- */
91
- async connect(gatewayURL) {
92
- // 定时模式
93
- await this.#setTimeoutBotConfig();
94
- // 请求url
95
- if (!this.#gatewayUrl) {
96
- this.#gatewayUrl = gatewayURL ?? (await this.gateway().then(res => res?.url));
97
- }
98
- if (!this.#gatewayUrl)
99
- return;
100
- // 重新连接的逻辑
101
- const reconnect = async () => {
102
- if (this.#counter.get() >= 5) {
103
- console.info('The maximum number of reconnections has been reached, cancel reconnection');
104
- return;
105
- }
106
- setTimeout(() => {
107
- console.info('[ws] reconnecting...');
108
- // 重新starrt
109
- start();
110
- // 记录
111
- this.#counter.getNextId();
112
- }, 5000);
113
- };
114
- const start = () => {
115
- if (this.#gatewayUrl) {
116
- const map = {
117
- 0: async ({ t, d }) => {
118
- if (this.#events[t]) {
119
- try {
120
- for (const event of this.#events[t]) {
121
- // 是否是函数
122
- if (typeof event != 'function')
123
- continue;
124
- event(d);
125
- }
126
- }
127
- catch (err) {
128
- if (this.#events['ERROR']) {
129
- for (const event of this.#events['ERROR']) {
130
- // 是否是函数
131
- if (typeof event != 'function')
132
- continue;
133
- event(err);
134
- }
135
- }
136
- }
137
- }
138
- // Ready Event,鉴权成功
139
- if (t === 'READY') {
140
- this.#IntervalId = setInterval(() => {
141
- if (this.#isConnected) {
142
- this.#ws &&
143
- this.#ws.send(JSON.stringify({
144
- op: 1, // op = 1
145
- d: null // 如果是第一次连接,传null
146
- }));
147
- }
148
- }, this.#heartbeat_interval);
149
- }
150
- // Resumed Event,恢复连接成功
151
- if (t === 'RESUMED') {
152
- console.info('[ws] restore connection');
153
- // 重制次数
154
- this.#counter.reStart();
155
- }
156
- return;
157
- },
158
- 6: ({ d }) => {
159
- console.info('[ws] connection attempt', d);
160
- return;
161
- },
162
- 7: async ({ d }) => {
163
- // 执行重新连接
164
- console.info('[ws] reconnect', d);
165
- // 取消鉴权发送
166
- if (this.#IntervalId)
167
- clearInterval(this.#IntervalId);
168
- return;
169
- },
170
- 9: ({ d }) => {
171
- console.info('[ws] parameter error', d);
172
- return;
173
- },
174
- 10: ({ d }) => {
175
- // 重制次数
176
- this.#isConnected = true;
177
- // 记录新循环
178
- this.#heartbeat_interval = d.heartbeat_interval;
179
- // 发送鉴权
180
- this.#ws && this.#ws.send(JSON.stringify(this.#aut()));
181
- return;
182
- },
183
- 11: () => {
184
- // OpCode 11 Heartbeat ACK 消息,心跳发送成功
185
- console.info('[ws] heartbeat transmission');
186
- // 重制次数
187
- this.#counter.reStart();
188
- return;
189
- },
190
- 12: ({ d }) => {
191
- console.info('[ws] platform data', d);
192
- return;
193
- }
194
- };
195
- // 连接
196
- this.#ws = new WebSocket(this.#gatewayUrl);
197
- this.#ws.on('open', () => {
198
- console.info('[ws] open');
199
- });
200
- // 监听消息
201
- this.#ws.on('message', async (msg) => {
202
- const message = JSON.parse(msg.toString('utf8'));
203
- if (process.env.NTQQ_WS == 'dev')
204
- console.info('message', message);
205
- // 根据 opcode 进行处理
206
- if (map[message.op]) {
207
- map[message.op](message);
208
- }
209
- });
210
- // 关闭
211
- this.#ws.on('close', async (err) => {
212
- await reconnect();
213
- console.info('[ws] close', err);
214
- });
215
- }
216
- };
217
- start();
218
- }
219
- }
220
-
221
- export { QQBotGroupClient };
@@ -1,205 +0,0 @@
1
- import WebSocket from 'ws';
2
- import { config } from './config.js';
3
- import { getIntentsMask } from './intents.js';
4
- import { QQBotAPI } from './api.js';
5
- import { Counter } from './counter.js';
6
-
7
- /**
8
- * 连接
9
- */
10
- class QQBotGuildClient extends QQBotAPI {
11
- //
12
- #counter = new Counter(1); // 初始值为1
13
- // 标记是否已连接
14
- #isConnected = false;
15
- // 存储最新的消息序号
16
- #heartbeat_interval = 30000;
17
- // 鉴权
18
- #IntervalId = null;
19
- // url
20
- #gatewayUrl = null;
21
- #ws;
22
- /**
23
- *
24
- * @param opstion
25
- */
26
- constructor(opstion) {
27
- super();
28
- for (const key in opstion) {
29
- config.set(key, opstion[key]);
30
- }
31
- }
32
- /**
33
- * 鉴权数据
34
- * @returns
35
- */
36
- #aut() {
37
- const app_id = config.get('app_id');
38
- const token = config.get('token');
39
- const intents = config.get('intents');
40
- const shard = config.get('shard');
41
- return {
42
- op: 2, // op = 2
43
- d: {
44
- token: `Bot ${app_id}.${token}`,
45
- intents: getIntentsMask(intents),
46
- shard,
47
- properties: {
48
- $os: process.platform,
49
- $browser: 'alemonjs',
50
- $device: 'alemonjs'
51
- }
52
- }
53
- };
54
- }
55
- #events = {};
56
- /**
57
- * 注册事件处理程序
58
- * @param key 事件名称
59
- * @param val 事件处理函数
60
- */
61
- on(key, val) {
62
- if (!this.#events[key])
63
- this.#events[key] = [];
64
- this.#events[key].push(val);
65
- return this;
66
- }
67
- /**
68
- *
69
- * @param cfg
70
- */
71
- async connect(gatewayURL) {
72
- //
73
- this.#gatewayUrl =
74
- gatewayURL ??
75
- (await this.gateway()
76
- .then(res => res.url)
77
- .catch(err => {
78
- if (this.#events['ERROR']) {
79
- for (const item of this.#events['ERROR']) {
80
- item(err);
81
- }
82
- }
83
- }));
84
- // 请求url
85
- if (!this.#gatewayUrl)
86
- return this;
87
- // 重新连接的逻辑
88
- const reconnect = async () => {
89
- if (this.#counter.get() >= 5) {
90
- console.info('The maximum number of reconnections has been reached, cancel reconnection');
91
- return;
92
- }
93
- setTimeout(() => {
94
- console.info('[ws] reconnecting...');
95
- // 重新starrt
96
- start();
97
- // 记录
98
- this.#counter.getNextId();
99
- }, 5000);
100
- };
101
- const start = () => {
102
- if (this.#gatewayUrl) {
103
- const map = {
104
- 0: async ({ t, d }) => {
105
- // 执行
106
- if (this.#events[t]) {
107
- try {
108
- for (const event of this.#events[t]) {
109
- // 是否是函数
110
- if (typeof event != 'function')
111
- continue;
112
- event(d);
113
- }
114
- }
115
- catch (err) {
116
- if (this.#events['ERROR']) {
117
- for (const item of this.#events['ERROR']) {
118
- item(err);
119
- }
120
- }
121
- }
122
- }
123
- // Ready Event,鉴权成功
124
- if (t === 'READY') {
125
- this.#IntervalId = setInterval(() => {
126
- if (this.#isConnected) {
127
- this.#ws.send(JSON.stringify({
128
- op: 1, // op = 1
129
- d: null // 如果是第一次连接,传null
130
- }));
131
- }
132
- }, this.#heartbeat_interval);
133
- }
134
- // Resumed Event,恢复连接成功
135
- if (t === 'RESUMED') {
136
- console.info('[ws] restore connection');
137
- // 重制次数
138
- this.#counter.reStart();
139
- }
140
- return;
141
- },
142
- 6: ({ d }) => {
143
- console.info('[ws] connection attempt', d);
144
- return;
145
- },
146
- 7: async ({ d }) => {
147
- // 执行重新连接
148
- console.info('[ws] reconnect', d);
149
- // 取消鉴权发送
150
- if (this.#IntervalId)
151
- clearInterval(this.#IntervalId);
152
- return;
153
- },
154
- 9: ({ d }) => {
155
- console.info('[ws] parameter error', d);
156
- return;
157
- },
158
- 10: ({ d }) => {
159
- // 重制次数
160
- this.#isConnected = true;
161
- // 记录新循环
162
- this.#heartbeat_interval = d.heartbeat_interval;
163
- // 发送鉴权
164
- this.#ws.send(JSON.stringify(this.#aut()));
165
- return;
166
- },
167
- 11: () => {
168
- // OpCode 11 Heartbeat ACK 消息,心跳发送成功
169
- console.info('[ws] heartbeat transmission');
170
- // 重制次数
171
- this.#counter.reStart();
172
- return;
173
- },
174
- 12: ({ d }) => {
175
- console.info('[ws] platform data', d);
176
- return;
177
- }
178
- };
179
- // 连接
180
- this.#ws = new WebSocket(this.#gatewayUrl);
181
- this.#ws.on('open', () => {
182
- console.info('[ws] open');
183
- });
184
- // 监听消息
185
- this.#ws.on('message', async (msg) => {
186
- const message = JSON.parse(msg.toString('utf8'));
187
- if (process.env.QQ_WS == 'dev')
188
- console.info('message', message);
189
- if (map[message.op]) {
190
- map[message.op](message);
191
- }
192
- });
193
- // 关闭
194
- this.#ws.on('close', async (err) => {
195
- await reconnect();
196
- console.info('[ws] close', err);
197
- });
198
- }
199
- };
200
- start();
201
- return this;
202
- }
203
- }
204
-
205
- export { QQBotGuildClient };
@@ -1,19 +0,0 @@
1
- class Counter {
2
- #counter = 1;
3
- #val = 0;
4
- constructor(initialValue) {
5
- this.#counter = initialValue;
6
- this.#val = initialValue;
7
- }
8
- getNextId() {
9
- return ++this.#counter;
10
- }
11
- get() {
12
- return this.#counter;
13
- }
14
- reStart() {
15
- this.#counter = this.#val;
16
- }
17
- }
18
-
19
- export { Counter };
package/lib/sdk/from.js DELETED
@@ -1,44 +0,0 @@
1
- import { existsSync, createReadStream } from 'fs';
2
- import { Readable, isReadable } from 'stream';
3
- import { basename } from 'path';
4
- import { fileTypeFromBuffer, fileTypeFromStream } from 'file-type';
5
-
6
- /**
7
- * 创建form
8
- * @param image
9
- * @param name
10
- * @returns
11
- */
12
- async function createPicFrom(image, name = 'image.jpg') {
13
- let picData;
14
- // 是 string
15
- if (typeof image === 'string') {
16
- if (!existsSync(image))
17
- return false;
18
- if (!name)
19
- name = basename(image);
20
- picData = createReadStream(image);
21
- // 是 buffer
22
- }
23
- else if (Buffer.isBuffer(image)) {
24
- const file = await fileTypeFromBuffer(image);
25
- if (!name)
26
- name = 'file.' + file?.ext;
27
- picData = new Readable();
28
- picData.push(image);
29
- picData.push(null);
30
- // 是 文件流
31
- }
32
- else if (isReadable(image)) {
33
- const file = await fileTypeFromStream(image);
34
- if (!name)
35
- name = 'file.' + file?.ext;
36
- picData = image;
37
- }
38
- else {
39
- return false;
40
- }
41
- return { picData, image, name };
42
- }
43
-
44
- export { createPicFrom };