@perk-net/perk-pushplus-sdk 1.2.0 → 1.2.1

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@perk-net/perk-pushplus-sdk",
3
- "version": "1.2.0",
3
+ "version": "1.2.1",
4
4
  "description": "pushplus(推送加) 官方接口 JavaScript/TypeScript SDK,可在 Node.js 与浏览器中使用",
5
5
  "keywords": [
6
6
  "pushplus",
package/src/api/base.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { ResolvedPushPlusConfig } from '../config';
2
2
  import { PushPlusError } from '../exception';
3
- import { HttpRequester, HttpResponse, isSuccessfulHttpStatus } from '../http';
3
+ import { HttpRequester, HttpResponse, callExecuteRaw, isSuccessfulHttpStatus } from '../http';
4
4
  import { ApiResponse } from '../models';
5
5
 
6
6
  /**
@@ -62,6 +62,32 @@ export abstract class AbstractApi {
62
62
  return parseApiResponse<T>(resp);
63
63
  }
64
64
 
65
+ /**
66
+ * 执行带二进制请求体的请求并返回原始 ApiResponse(不进行 code 校验)。
67
+ * 用于 multipart 上传等场景。
68
+ */
69
+ protected async executeRaw<T>(
70
+ method: string,
71
+ path: string,
72
+ headers: Record<string, string> | undefined | null,
73
+ body: Uint8Array,
74
+ ): Promise<ApiResponse<T>> {
75
+ const url = this.resolveUrl(path);
76
+ const resp = await callExecuteRaw(this.http, {
77
+ method,
78
+ url,
79
+ headers: headers ?? undefined,
80
+ body,
81
+ });
82
+ if (!isSuccessfulHttpStatus(resp.statusCode)) {
83
+ throw new PushPlusError(
84
+ `PushPlus 接口 HTTP 调用失败: status=${resp.statusCode}, body=${resp.body}`,
85
+ resp.statusCode,
86
+ );
87
+ }
88
+ return parseApiResponse<T>(resp);
89
+ }
90
+
65
91
  /** 执行请求并直接返回 data;非 200 抛出异常。 */
66
92
  protected async executeForData<T>(
67
93
  method: string,
@@ -1,6 +1,7 @@
1
1
  import { AccessKeyManager } from '../access-key-manager';
2
2
  import { ResolvedPushPlusConfig } from '../config';
3
3
  import { HttpRequester } from '../http';
4
+ import { FileInput, buildFileMultipart, toFileBytes } from '../multipart';
4
5
  import { DocContent, DocListItem, DocListQuery, DocVo, PageResult } from '../models';
5
6
  import { OpenAbstractApi } from './open-base';
6
7
 
@@ -9,6 +10,9 @@ import { OpenAbstractApi } from './open-base';
9
10
  *
10
11
  * 文档:https://www.pushplus.plus/doc/ecosystem/doc/
11
12
  * 基础路径:`/push/api/open/doc`
13
+ *
14
+ * 文档开放接口不单独提供推送接口。发布后请通过 `client.send` 推送分享页:
15
+ * `template=doc`,`pushId=docCode`。
12
16
  */
13
17
  export class DocApi extends OpenAbstractApi {
14
18
  constructor(config: ResolvedPushPlusConfig, http: HttpRequester, mgr: AccessKeyManager) {
@@ -29,6 +33,20 @@ export class DocApi extends OpenAbstractApi {
29
33
  return this.executeOpen<DocVo>('POST', '/push/api/open/doc/create', { title });
30
34
  }
31
35
 
36
+ /**
37
+ * 导入 Word(.docx)创建文档。
38
+ *
39
+ * 标题默认取文件名;创建后默认关闭分享,需再调用 publish 才会同步到分享页。
40
+ */
41
+ async importWord(file: FileInput, fileName = 'document.docx'): Promise<DocVo> {
42
+ const bytes = await toFileBytes(file);
43
+ const name = fileName && fileName.trim() ? fileName : 'document.docx';
44
+ return this.executeOpenMultipart<DocVo>(
45
+ '/push/api/open/doc/import',
46
+ buildFileMultipart(name, guessDocxContentType(name), bytes),
47
+ );
48
+ }
49
+
32
50
  /** 获取文档元信息与 HTML 草稿正文。 */
33
51
  content(docCode: string): Promise<DocContent> {
34
52
  return this.executeOpen<DocContent>(
@@ -75,3 +93,9 @@ export class DocApi extends OpenAbstractApi {
75
93
  return this.executeOpen<DocVo>('POST', '/push/api/open/doc/updateShare', body);
76
94
  }
77
95
  }
96
+
97
+ function guessDocxContentType(name: string): string {
98
+ return name.toLowerCase().endsWith('.docx')
99
+ ? 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
100
+ : 'application/octet-stream';
101
+ }
@@ -2,6 +2,7 @@ import { AccessKeyManager } from '../access-key-manager';
2
2
  import { ResolvedPushPlusConfig } from '../config';
3
3
  import { PushPlusError } from '../exception';
4
4
  import { HttpRequester } from '../http';
5
+ import { FileInput, buildFileMultipart, toFileBytes } from '../multipart';
5
6
  import { DocListItem, DocListQuery, ExcelContent, ExcelVo, PageResult } from '../models';
6
7
  import { OpenAbstractApi } from './open-base';
7
8
 
@@ -10,6 +11,9 @@ import { OpenAbstractApi } from './open-base';
10
11
  *
11
12
  * 文档:https://www.pushplus.plus/doc/ecosystem/sheet/
12
13
  * 基础路径:`/push/api/open/excel`
14
+ *
15
+ * 表格开放接口不单独提供推送接口。发布后请通过 `client.send` 推送分享页:
16
+ * `template=excel`,`pushId=docCode`。
13
17
  */
14
18
  export class ExcelApi extends OpenAbstractApi {
15
19
  constructor(config: ResolvedPushPlusConfig, http: HttpRequester, mgr: AccessKeyManager) {
@@ -30,6 +34,20 @@ export class ExcelApi extends OpenAbstractApi {
30
34
  return this.executeOpen<ExcelVo>('POST', '/push/api/open/excel/create', { title });
31
35
  }
32
36
 
37
+ /**
38
+ * 导入 Excel(.xlsx / .xls)创建表格。
39
+ *
40
+ * 标题默认取文件名;创建后默认关闭分享,需再调用 publish 才会同步到分享页。
41
+ */
42
+ async importExcel(file: FileInput, fileName = 'workbook.xlsx'): Promise<ExcelVo> {
43
+ const bytes = await toFileBytes(file);
44
+ const name = fileName && fileName.trim() ? fileName : 'workbook.xlsx';
45
+ return this.executeOpenMultipart<ExcelVo>(
46
+ '/push/api/open/excel/import',
47
+ buildFileMultipart(name, guessExcelContentType(name), bytes),
48
+ );
49
+ }
50
+
33
51
  /** 获取表格元信息与整表 JSON 草稿。 */
34
52
  content(docCode: string): Promise<ExcelContent> {
35
53
  return this.executeOpen<ExcelContent>(
@@ -112,3 +130,14 @@ function stringifyJsonContent(content: string | object): string {
112
130
  throw new PushPlusError(`序列化表格内容失败: ${(e as Error).message}`, -1, { cause: e });
113
131
  }
114
132
  }
133
+
134
+ function guessExcelContentType(name: string): string {
135
+ const lower = name.toLowerCase();
136
+ if (lower.endsWith('.xlsx')) {
137
+ return 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
138
+ }
139
+ if (lower.endsWith('.xls')) {
140
+ return 'application/vnd.ms-excel';
141
+ }
142
+ return 'application/octet-stream';
143
+ }
@@ -17,6 +17,9 @@ import { OpenAbstractApi } from './open-base';
17
17
  *
18
18
  * 文档:https://www.pushplus.plus/doc/ecosystem/form/
19
19
  * 基础路径:`/push/api/open/form`
20
+ *
21
+ * 表单开放接口不单独提供推送接口。发布后请通过 `client.send` 推送填写页:
22
+ * `template=form`,`pushId=formCode`。
20
23
  */
21
24
  export class FormApi extends OpenAbstractApi {
22
25
  constructor(config: ResolvedPushPlusConfig, http: HttpRequester, mgr: AccessKeyManager) {
@@ -1,7 +1,7 @@
1
1
  import { AccessKeyManager } from '../access-key-manager';
2
2
  import { ResolvedPushPlusConfig } from '../config';
3
3
  import { HttpRequester } from '../http';
4
- import { FriendItem, FriendQrCode, PageQuery, PageResult } from '../models';
4
+ import { FriendBlacklistItem, FriendItem, FriendQrCode, PageQuery, PageResult } from '../models';
5
5
  import { OpenAbstractApi } from './open-base';
6
6
 
7
7
  /**
@@ -44,4 +44,41 @@ export class FriendApi extends OpenAbstractApi {
44
44
  async editRemark(id: number, remark: string): Promise<void> {
45
45
  await this.executeOpen<unknown>('POST', '/api/open/friend/editRemark', { id, remark });
46
46
  }
47
+
48
+ /**
49
+ * 5. 将好友加入黑名单。
50
+ *
51
+ * 加入后将解除双方好友关系,对方无法再添加你。不能将自己加入黑名单,仅可将已有好友加入黑名单。
52
+ *
53
+ * @param friendId 好友 id(好友列表中的 friendId 字段)
54
+ */
55
+ async addBlacklist(friendId: number): Promise<void> {
56
+ await this.executeOpen<unknown>(
57
+ 'POST',
58
+ this.appendQuery('/api/open/friend/addBlacklist', { friendId }),
59
+ );
60
+ }
61
+
62
+ /** 6. 好友黑名单列表。 */
63
+ blacklistList(query?: PageQuery): Promise<PageResult<FriendBlacklistItem>> {
64
+ return this.executeOpen<PageResult<FriendBlacklistItem>>(
65
+ 'POST',
66
+ '/api/open/friend/blacklistList',
67
+ query ?? {},
68
+ );
69
+ }
70
+
71
+ /**
72
+ * 7. 解除好友黑名单。
73
+ *
74
+ * 解除后不会自动恢复好友关系,需重新扫码添加。
75
+ *
76
+ * @param id 黑名单记录 ID(黑名单列表中的 id 字段)
77
+ */
78
+ async removeBlacklist(id: number): Promise<void> {
79
+ await this.executeOpen<unknown>(
80
+ 'POST',
81
+ this.appendQuery('/api/open/friend/removeBlacklist', { id }),
82
+ );
83
+ }
47
84
  }
@@ -2,6 +2,7 @@ import { AccessKeyManager } from '../access-key-manager';
2
2
  import { ResolvedPushPlusConfig } from '../config';
3
3
  import { PushPlusError } from '../exception';
4
4
  import { HttpRequester } from '../http';
5
+ import { FileMultipart } from '../multipart';
5
6
  import { AbstractApi, isApiSuccess } from './base';
6
7
 
7
8
  /**
@@ -51,4 +52,43 @@ export abstract class OpenAbstractApi extends AbstractApi {
51
52
  resp.code ?? -1,
52
53
  );
53
54
  }
55
+
56
+ /** 以 multipart 上传文件(自动携带 access-key;code=401 时刷新后重试一次)。 */
57
+ protected executeOpenMultipart<T>(path: string, multipart: FileMultipart): Promise<T> {
58
+ return this.executeOpenRaw<T>('POST', path, multipart.body, {
59
+ 'Content-Type': multipart.contentType,
60
+ });
61
+ }
62
+
63
+ /**
64
+ * 执行带二进制 body 的开放接口请求;当返回 code=401 时自动刷新 key 并重试一次。
65
+ */
66
+ protected async executeOpenRaw<T>(
67
+ method: string,
68
+ path: string,
69
+ body: Uint8Array,
70
+ extraHeaders?: Record<string, string>,
71
+ ): Promise<T> {
72
+ const headers = { ...(await this.headersWithAccessKey()), ...(extraHeaders ?? {}) };
73
+ const resp = await this.executeRaw<T>(method, path, headers, body);
74
+ if (isApiSuccess(resp)) {
75
+ return resp.data as T;
76
+ }
77
+ if (resp.code === OpenAbstractApi.CODE_ACCESS_KEY_INVALID) {
78
+ this.accessKeyManager.invalidate();
79
+ const retryHeaders = { ...(await this.headersWithAccessKey()), ...(extraHeaders ?? {}) };
80
+ const retry = await this.executeRaw<T>(method, path, retryHeaders, body);
81
+ if (isApiSuccess(retry)) {
82
+ return retry.data as T;
83
+ }
84
+ throw new PushPlusError(
85
+ `PushPlus 开放接口业务失败(重试后): code=${retry.code}, msg=${retry.msg}`,
86
+ retry.code ?? -1,
87
+ );
88
+ }
89
+ throw new PushPlusError(
90
+ `PushPlus 开放接口业务失败: code=${resp.code}, msg=${resp.msg}`,
91
+ resp.code ?? -1,
92
+ );
93
+ }
54
94
  }
@@ -1,7 +1,7 @@
1
1
  import { AccessKeyManager } from '../access-key-manager';
2
2
  import { ResolvedPushPlusConfig } from '../config';
3
3
  import { HttpRequester } from '../http';
4
- import { PageResult, TopicUserItem, TopicUserListQuery } from '../models';
4
+ import { PageResult, TopicUserBlacklistItem, TopicUserItem, TopicUserListQuery } from '../models';
5
5
  import { OpenAbstractApi } from './open-base';
6
6
 
7
7
  /**
@@ -27,4 +27,43 @@ export class TopicUserApi extends OpenAbstractApi {
27
27
  async editRemark(id: number, remark: string): Promise<void> {
28
28
  await this.executeOpen<unknown>('POST', '/api/open/topicUser/editRemark', { id, remark });
29
29
  }
30
+
31
+ /**
32
+ * 4. 将订阅人加入黑名单。
33
+ *
34
+ * 加入后将移出群组,对方无法再加入该群组。积分群组不支持黑名单。不能将自己加入黑名单。
35
+ *
36
+ * @param topicRelationId 用户编号(订阅人列表中的 id 字段)
37
+ */
38
+ async addBlacklist(topicRelationId: number): Promise<void> {
39
+ const path = this.appendQuery('/api/open/topicUser/addBlacklist', { topicRelationId });
40
+ await this.executeOpen<unknown>('POST', path);
41
+ }
42
+
43
+ /**
44
+ * 5. 订阅人黑名单列表。
45
+ *
46
+ * `query.params.topicId` 必填。
47
+ */
48
+ blacklistList(query: TopicUserListQuery): Promise<PageResult<TopicUserBlacklistItem>> {
49
+ return this.executeOpen<PageResult<TopicUserBlacklistItem>>(
50
+ 'POST',
51
+ '/api/open/topicUser/blacklistList',
52
+ query,
53
+ );
54
+ }
55
+
56
+ /**
57
+ * 6. 解除订阅人黑名单。
58
+ *
59
+ * 解除后不会自动恢复群组订阅,对方可重新加入该群组。
60
+ *
61
+ * @param id 黑名单记录 ID(黑名单列表中的 id 字段)
62
+ */
63
+ async removeBlacklist(id: number): Promise<void> {
64
+ await this.executeOpen<unknown>(
65
+ 'POST',
66
+ this.appendQuery('/api/open/topicUser/removeBlacklist', { id }),
67
+ );
68
+ }
30
69
  }
package/src/config.ts CHANGED
@@ -87,6 +87,6 @@ export function resolveConfig(input: PushPlusConfig | undefined | null): Resolve
87
87
  logRequest: cfg.logRequest ?? false,
88
88
  rateLimitGuardEnabled: cfg.rateLimitGuardEnabled ?? true,
89
89
  rateLimitCooldownMs: cfg.rateLimitCooldownMs ?? 0,
90
- userAgent: cfg.userAgent ?? `@perk-net/perk-pushplus-sdk/1.2.0`,
90
+ userAgent: cfg.userAgent ?? `@perk-net/perk-pushplus-sdk/1.2.1`,
91
91
  };
92
92
  }
package/src/index.ts CHANGED
@@ -79,10 +79,12 @@ export type {
79
79
  TopicItem,
80
80
  TopicUserItem,
81
81
  TopicUserListQuery,
82
+ TopicUserBlacklistItem,
82
83
  WebhookItem,
83
84
  WebhookSaveRequest,
84
85
  FriendItem,
85
86
  FriendQrCode,
87
+ FriendBlacklistItem,
86
88
  ClawBotInfo,
87
89
  ClawBotMessage,
88
90
  ClawBotQrCode,
@@ -150,3 +152,4 @@ export {
150
152
  export { FormApi } from './api/form-api';
151
153
  export { DocApi } from './api/doc-api';
152
154
  export { ExcelApi } from './api/excel-api';
155
+ export { type FileInput } from './multipart';
package/src/models.ts CHANGED
@@ -426,6 +426,19 @@ export interface TopicUserListQuery {
426
426
  params?: Record<string, unknown>;
427
427
  }
428
428
 
429
+ /** 群组订阅人黑名单列表项。 */
430
+ export interface TopicUserBlacklistItem {
431
+ /** 黑名单记录 ID;解除黑名单时使用。 */
432
+ id?: number;
433
+ /** 被拉黑用户 ID。 */
434
+ userId?: number;
435
+ nickName?: string;
436
+ openId?: string;
437
+ headImgUrl?: string;
438
+ /** 拉黑时间。 */
439
+ createTime?: string;
440
+ }
441
+
429
442
  /* ============================== 开放接口 - webhook ============================== */
430
443
 
431
444
  export interface WebhookItem {
@@ -474,6 +487,18 @@ export interface FriendQrCode {
474
487
  qrCodeImgUrl?: string;
475
488
  }
476
489
 
490
+ /** 好友黑名单列表项。 */
491
+ export interface FriendBlacklistItem {
492
+ /** 黑名单记录 ID;解除黑名单时使用。 */
493
+ id?: number;
494
+ /** 被拉黑好友 ID。 */
495
+ friendId?: number;
496
+ nickName?: string;
497
+ headImgUrl?: string;
498
+ /** 拉黑时间。 */
499
+ createTime?: string;
500
+ }
501
+
477
502
  /* ============================== 开放接口 - clawbot ============================== */
478
503
 
479
504
  export interface ClawBotInfo {
@@ -661,16 +686,19 @@ export interface ImageItem {
661
686
 
662
687
  /* ============================== 开放接口 - form(push 表单) ============================== */
663
688
 
664
- /** 我的表单分页查询。 */
689
+ /** 我的表单分页查询。官方结构为 `{current, pageSize, params:{keyword, status}}`。 */
665
690
  export interface FormListQuery {
666
- /** 页码,从 1 开始。 */
667
- pageNum?: number;
668
- /** 每页条数。 */
691
+ /** 当前所在分页数,默认 1 */
692
+ current?: number;
693
+ /** 每页大小,默认 20,最大 50。 */
669
694
  pageSize?: number;
670
- /** 按标题关键词搜索。 */
671
- keyword?: string;
672
- /** 表单状态:0草稿 / 1收集中 / 2已停止。 */
673
- status?: number;
695
+ params?: {
696
+ /** 按标题关键词搜索。 */
697
+ keyword?: string;
698
+ /** 表单状态:0草稿 / 1收集中 / 2已停止。 */
699
+ status?: number;
700
+ [key: string]: unknown;
701
+ };
674
702
  }
675
703
 
676
704
  /** 表单封面页配置。 */
@@ -786,13 +814,18 @@ export interface FormPublishResult {
786
814
 
787
815
  /* ============================== 开放接口 - doc / excel 共用查询 ============================== */
788
816
 
789
- /** 文档 / 表格分页查询。 */
817
+ /** 文档 / 表格分页查询。官方结构为 `{current, pageSize, params:{keyword, shareEnabled}}`。 */
790
818
  export interface DocListQuery {
791
- pageNum?: number;
819
+ /** 当前所在分页数,默认 1。 */
820
+ current?: number;
821
+ /** 每页大小,默认 20,最大 50。 */
792
822
  pageSize?: number;
793
- keyword?: string;
794
- /** true 时仅返回已开启分享的记录。 */
795
- shareEnabled?: boolean;
823
+ params?: {
824
+ keyword?: string;
825
+ /** true 时仅返回已开启分享的记录。 */
826
+ shareEnabled?: boolean;
827
+ [key: string]: unknown;
828
+ };
796
829
  }
797
830
 
798
831
  /** 文档 / 表格列表项。 */
@@ -0,0 +1,62 @@
1
+ import { PushPlusError } from './exception';
2
+
3
+ /** 二进制文件输入。 */
4
+ export type FileInput = Uint8Array | ArrayBuffer | Blob;
5
+
6
+ export interface FileMultipart {
7
+ contentType: string;
8
+ body: Uint8Array;
9
+ }
10
+
11
+ /** 构造仅含一个 file 字段的 multipart/form-data 请求体。 */
12
+ export function buildFileMultipart(
13
+ fileName: string,
14
+ contentType: string | undefined,
15
+ fileBytes: Uint8Array,
16
+ ): FileMultipart {
17
+ if (fileBytes == null || fileBytes.byteLength === 0) {
18
+ throw new PushPlusError('上传文件内容不能为空');
19
+ }
20
+ const safeName = fileName && fileName.trim() ? fileName : 'file';
21
+ const mime = contentType && contentType.trim() ? contentType : 'application/octet-stream';
22
+ const boundary = '----PushPlusBoundary' + randomBoundarySuffix();
23
+ const crlf = '\r\n';
24
+ const enc = new TextEncoder();
25
+ const head = enc.encode(
26
+ `--${boundary}${crlf}` +
27
+ `Content-Disposition: form-data; name="file"; filename="${escapeFileName(safeName)}"${crlf}` +
28
+ `Content-Type: ${mime}${crlf}${crlf}`,
29
+ );
30
+ const tail = enc.encode(`${crlf}--${boundary}--${crlf}`);
31
+ const body = new Uint8Array(head.byteLength + fileBytes.byteLength + tail.byteLength);
32
+ body.set(head, 0);
33
+ body.set(fileBytes, head.byteLength);
34
+ body.set(tail, head.byteLength + fileBytes.byteLength);
35
+ return { contentType: `multipart/form-data; boundary=${boundary}`, body };
36
+ }
37
+
38
+ export async function toFileBytes(file: FileInput): Promise<Uint8Array> {
39
+ if (file instanceof Uint8Array) {
40
+ return file;
41
+ }
42
+ if (file instanceof ArrayBuffer) {
43
+ return new Uint8Array(file);
44
+ }
45
+ if (typeof Blob !== 'undefined' && file instanceof Blob) {
46
+ const ab = await file.arrayBuffer();
47
+ return new Uint8Array(ab);
48
+ }
49
+ throw new PushPlusError(`不支持的上传文件类型: ${Object.prototype.toString.call(file)}`);
50
+ }
51
+
52
+ function escapeFileName(name: string): string {
53
+ return name.replace(/"/g, '_').replace(/\r/g, ' ').replace(/\n/g, ' ');
54
+ }
55
+
56
+ function randomBoundarySuffix(): string {
57
+ let s = '';
58
+ for (let i = 0; i < 32; i++) {
59
+ s += Math.floor(Math.random() * 16).toString(16);
60
+ }
61
+ return s;
62
+ }