@maxhub/max-bot-api 0.2.1 → 0.2.2

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.
@@ -32,6 +32,68 @@ const node_crypto_1 = require("node:crypto");
32
32
  const node_path_1 = __importDefault(require("node:path"));
33
33
  const api_1 = require("../network/api");
34
34
  const DEFAULT_UPLOAD_TIMEOUT = 20000; // ms
35
+ /**
36
+ * Загрузить чанк данных через Content-Range запрос
37
+ */
38
+ async function uploadRangeChunk({ uploadUrl, chunk, startByte, endByte, fileSize, fileName, }, { signal } = {}) {
39
+ const uploadRes = await fetch(uploadUrl, {
40
+ method: 'POST',
41
+ body: chunk,
42
+ headers: {
43
+ 'Content-Disposition': `attachment; filename="${fileName}"`,
44
+ 'Content-Range': `bytes ${startByte}-${endByte}/${fileSize}`,
45
+ 'Content-Type': 'application/x-binary; charset=x-user-defined',
46
+ 'X-File-Name': fileName,
47
+ 'X-Uploading-Mode': 'parallel',
48
+ Connection: 'keep-alive',
49
+ },
50
+ signal,
51
+ });
52
+ if (uploadRes.status >= 400) {
53
+ const error = await uploadRes.json();
54
+ throw new api_1.MaxError(uploadRes.status, error);
55
+ }
56
+ return uploadRes.text();
57
+ }
58
+ /**
59
+ * Загрузить файл через Content-Range запрос
60
+ */
61
+ async function uploadRange({ uploadUrl, file }, options) {
62
+ const size = file.contentLength;
63
+ let startByte = 0;
64
+ let endByte = 0;
65
+ for await (const chunk of file.stream) {
66
+ endByte = startByte + chunk.length - 1;
67
+ await uploadRangeChunk({
68
+ uploadUrl,
69
+ startByte,
70
+ endByte,
71
+ chunk,
72
+ fileName: file.fileName,
73
+ fileSize: size,
74
+ }, options);
75
+ startByte = endByte + 1;
76
+ }
77
+ }
78
+ /**
79
+ * Загрузить файл через Multipart запрос
80
+ */
81
+ async function uploadMultipart({ uploadUrl, file }, { signal } = {}) {
82
+ const body = new FormData();
83
+ body.append('data', {
84
+ [Symbol.toStringTag]: 'File',
85
+ name: file.fileName,
86
+ stream: () => file.stream,
87
+ size: file.contentLength,
88
+ });
89
+ const result = await fetch(uploadUrl, {
90
+ method: 'POST',
91
+ body,
92
+ signal,
93
+ });
94
+ const response = await result.json();
95
+ return response;
96
+ }
35
97
  class Upload {
36
98
  constructor(api) {
37
99
  this.api = api;
@@ -70,7 +132,8 @@ class Upload {
70
132
  };
71
133
  };
72
134
  this.upload = async (type, file, options) => {
73
- const { url: uploadUrl } = await this.api.raw.uploads.getUploadUrl({ type });
135
+ const res = await this.api.raw.uploads.getUploadUrl({ type });
136
+ const { url: uploadUrl, token } = res;
74
137
  const uploadController = new AbortController();
75
138
  const uploadInterval = setTimeout(() => {
76
139
  uploadController.abort();
@@ -81,56 +144,31 @@ class Upload {
81
144
  file,
82
145
  uploadUrl,
83
146
  abortController: uploadController,
147
+ token,
84
148
  });
85
149
  }
86
150
  return await this.uploadFromBuffer({
87
151
  file,
88
152
  uploadUrl,
89
153
  abortController: uploadController,
154
+ token,
90
155
  });
91
156
  }
92
157
  finally {
93
158
  clearTimeout(uploadInterval);
94
159
  }
95
160
  };
96
- this.uploadFromStream = async ({ file, uploadUrl, abortController }) => {
97
- return new Promise((resolve, reject) => {
98
- let prevChunk = -1;
99
- let uploadData = null;
100
- file.stream.on('data', async (chunk) => {
101
- file.stream.pause();
102
- const startBite = prevChunk + 1;
103
- const endBite = prevChunk + chunk.length;
104
- const uploadRes = await fetch(uploadUrl, {
105
- method: 'POST',
106
- body: chunk,
107
- headers: {
108
- 'Content-Disposition': `attachment; filename="${file.fileName}"`,
109
- 'Content-Range': `bytes ${startBite}-${endBite}/${file.contentLength}`,
110
- },
111
- signal: abortController?.signal,
112
- });
113
- if (uploadRes.status >= 400) {
114
- const error = await uploadRes.json();
115
- throw new api_1.MaxError(uploadRes.status, error);
116
- }
117
- if (!uploadData) {
118
- uploadData = await uploadRes.json();
119
- }
120
- file.stream.resume();
121
- prevChunk += chunk.length;
122
- });
123
- file.stream.on('end', async () => {
124
- if (!uploadData) {
125
- reject(new Error('Failed to upload'));
126
- return;
127
- }
128
- resolve(uploadData);
129
- });
130
- file.stream.on('error', (err) => {
131
- reject(err);
132
- });
133
- });
161
+ this.uploadFromStream = async ({ file, uploadUrl, token, abortController, }) => {
162
+ if (token) {
163
+ await uploadRange({ file, uploadUrl }, abortController);
164
+ return {
165
+ token,
166
+ file,
167
+ uploadUrl,
168
+ abortController,
169
+ };
170
+ }
171
+ return uploadMultipart({ file, uploadUrl }, abortController);
134
172
  };
135
173
  this.uploadFromBuffer = async ({ file, uploadUrl, abortController }) => {
136
174
  const formData = new FormData();
@@ -1,5 +1,5 @@
1
1
  declare const defaultOptions: {
2
- readonly baseUrl: "https://botapi.max.ru";
2
+ baseUrl: string;
3
3
  };
4
4
  export type ClientOptions = Partial<typeof defaultOptions>;
5
5
  export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
@@ -7,7 +7,7 @@ exports.createClient = void 0;
7
7
  const debug_1 = __importDefault(require("debug"));
8
8
  const debug = (0, debug_1.default)('one-me:client');
9
9
  const defaultOptions = {
10
- baseUrl: 'https://botapi.max.ru',
10
+ baseUrl: 'https://platform-api.max.ru',
11
11
  };
12
12
  const createClient = (token, options = {}) => {
13
13
  const { baseUrl } = { ...defaultOptions, ...options };
@@ -23,7 +23,7 @@ const createClient = (token, options = {}) => {
23
23
  },
24
24
  };
25
25
  }
26
- const url = new URL(buildUrl(method, token, callOptions.path), baseUrl);
26
+ const url = new URL(buildUrl(method, callOptions.path), baseUrl);
27
27
  Object.keys(callOptions.query ?? {}).forEach((param) => {
28
28
  const value = callOptions.query?.[param];
29
29
  if (!value)
@@ -31,6 +31,7 @@ const createClient = (token, options = {}) => {
31
31
  url.searchParams.set(param, value.toString());
32
32
  });
33
33
  const init = { ...getResponseInit(callOptions?.body), method: httpMethod };
34
+ init.headers = { ...init.headers, Authorization: token };
34
35
  const res = await fetch(url.href, init);
35
36
  if (res.status === 401) {
36
37
  return {
@@ -59,7 +60,7 @@ const getResponseInit = (body) => {
59
60
  },
60
61
  };
61
62
  };
62
- const buildUrl = (baseUrl, token, path) => {
63
+ const buildUrl = (baseUrl, path) => {
63
64
  let url = baseUrl;
64
65
  if (path) {
65
66
  Object.keys(path)?.forEach((key) => {
@@ -68,5 +69,5 @@ const buildUrl = (baseUrl, token, path) => {
68
69
  url = url.replace(regexp, value);
69
70
  });
70
71
  }
71
- return `${url}?access_token=${token}`;
72
+ return url;
72
73
  };
@@ -1,7 +1,7 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.MessagesApi = void 0;
4
- const utils_1 = require("../../../../../utils");
4
+ const promises_1 = require("node:timers/promises");
5
5
  const error_1 = require("../../error");
6
6
  const base_api_1 = require("../../base-api");
7
7
  class MessagesApi extends base_api_1.BaseApi {
@@ -28,7 +28,7 @@ class MessagesApi extends base_api_1.BaseApi {
28
28
  if (err instanceof error_1.MaxError) {
29
29
  if (err.code === 'attachment.not.ready') {
30
30
  console.log('Attachment not ready');
31
- await (0, utils_1.sleep)(1000);
31
+ await (0, promises_1.setTimeout)(1000);
32
32
  return this.send({
33
33
  chat_id, user_id, disable_link_preview, ...body,
34
34
  });
@@ -6,4 +6,5 @@ export type GetUploadUrlDTO = {
6
6
  };
7
7
  export type GetUploadUrlResponse = {
8
8
  url: string;
9
+ token?: string;
9
10
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@maxhub/max-bot-api",
3
- "version": "0.2.1",
3
+ "version": "0.2.2",
4
4
  "description": "Max Bot Framework",
5
5
  "repository": "https://github.com/max-messenger/max-bot-api-client-ts",
6
6
  "author": "Juice Development",
package/readme.md CHANGED
@@ -9,7 +9,7 @@
9
9
  > Если вы новичок, то можете прочитать [официальную документацию](https://dev.max.ru/), написанную разработчиками Max
10
10
 
11
11
  ### Получение токена
12
- Откройте диалог с [PrimeBot](https://max.ru/primebot), следуйте инструкциям и создайте нового бота. После создания бота PrimeBot отправит вам токен.
12
+ Откройте диалог с [Master Bot](https://max.ru/masterbot), следуйте инструкциям и создайте нового бота. После создания бота Master Bot отправит вам токен.
13
13
 
14
14
  ### Установка
15
15
  #### npm
package/dist/utils.d.ts DELETED
@@ -1,3 +0,0 @@
1
- import fs from 'node:fs';
2
- export declare const sleep: (ms: number) => Promise<void>;
3
- export declare const streamToBlob: (stream: fs.ReadStream, mimeType?: string) => Promise<Blob>;
package/dist/utils.js DELETED
@@ -1,24 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.streamToBlob = exports.sleep = void 0;
4
- const sleep = async (ms) => {
5
- await new Promise((resolve) => {
6
- setTimeout(resolve, ms);
7
- });
8
- };
9
- exports.sleep = sleep;
10
- const streamToBlob = async (stream, mimeType) => {
11
- return new Promise((resolve, reject) => {
12
- const chunks = [];
13
- stream
14
- .on('data', (chunk) => chunks.push(chunk))
15
- .once('end', () => {
16
- const blob = mimeType
17
- ? new Blob(chunks, { type: mimeType })
18
- : new Blob(chunks);
19
- resolve(blob);
20
- })
21
- .once('error', reject);
22
- });
23
- };
24
- exports.streamToBlob = streamToBlob;