qiwe-api.service.ts 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. const API_BASE = process.env.QIWE_API_BASE || 'https://manager.qiweapi.com/qiwe';
  2. const TOKEN = process.env.QIWE_TOKEN || '';
  3. const GUID = process.env.QIWE_GUID || '';
  4. interface QiWeResponse<T = any> {
  5. code: number;
  6. msg: string;
  7. data: T;
  8. }
  9. interface RoomInfo {
  10. roomId: string;
  11. roomName: string;
  12. roomOwnerId: string;
  13. roomMemberCount: number;
  14. roomAvatarUrl: string;
  15. roomCreateTime: string;
  16. roomUpdateTime: string;
  17. roomFlag: number;
  18. ticket: string;
  19. }
  20. interface SessionInfo {
  21. sessionId: string;
  22. sessionType: number;
  23. }
  24. export interface InternalContactRef {
  25. userId: string;
  26. partyId: string;
  27. }
  28. export interface ContactDetail {
  29. userId: string;
  30. name: string;
  31. mobile: string;
  32. position: string;
  33. }
  34. async function callApi<T = any>(method: string, params: Record<string, any> = {}): Promise<QiWeResponse<T>> {
  35. const resp = await fetch(`${API_BASE}/api/qw/doApi`, {
  36. method: 'POST',
  37. headers: {
  38. 'Content-Type': 'application/json',
  39. 'X-QIWEI-TOKEN': TOKEN,
  40. },
  41. body: JSON.stringify({ tokenId: TOKEN, method, params }),
  42. });
  43. if (!resp.ok) {
  44. throw new Error(`QiWe API HTTP ${resp.status}: ${resp.statusText}`);
  45. }
  46. const json = await resp.json();
  47. if (json.code !== 0) {
  48. throw new Error(`QiWe API error code=${json.code}: ${json.msg}`);
  49. }
  50. return json;
  51. }
  52. /** 获取创建的群列表(含群名称、群主、人数等完整信息) */
  53. export async function getRoomList(page = 1, pageSize = 50): Promise<{
  54. rooms: RoomInfo[];
  55. hasMore: boolean;
  56. total: number;
  57. }> {
  58. const resp = await callApi<{
  59. hasMore: boolean;
  60. nextStartIndex: number;
  61. roomCount: number;
  62. roomList: RoomInfo[];
  63. }>('/room/getRoomList', { guid: GUID, page, pageSize });
  64. return {
  65. rooms: resp.data.roomList || [],
  66. hasMore: resp.data.hasMore || false,
  67. total: resp.data.roomCount || 0,
  68. };
  69. }
  70. /** 获取所有群(遍历分页) */
  71. export async function getAllRooms(): Promise<RoomInfo[]> {
  72. const all: RoomInfo[] = [];
  73. let page = 1;
  74. while (true) {
  75. const { rooms, hasMore } = await getRoomList(page, 50);
  76. all.push(...rooms);
  77. if (!hasMore) break;
  78. page++;
  79. }
  80. return all;
  81. }
  82. /** 获取会话列表(含群会话和个人会话) */
  83. export async function getSessionList(sessionType?: number): Promise<SessionInfo[]> {
  84. const resp = await callApi<{
  85. collectList: SessionInfo[];
  86. shieldList: SessionInfo[];
  87. topList: SessionInfo[];
  88. }>('/session/getSessionList', { guid: GUID });
  89. const all = [
  90. ...(resp.data.collectList || []),
  91. ...(resp.data.shieldList || []),
  92. ...(resp.data.topList || []),
  93. ];
  94. if (sessionType !== undefined) {
  95. return all.filter((s) => s.sessionType === sessionType);
  96. }
  97. return all;
  98. }
  99. /** 内部联系人分页(企微组织成员) */
  100. export async function getInternalContactList(limit = 100): Promise<InternalContactRef[]> {
  101. if (!TOKEN || !GUID) return [];
  102. const resp = await callApi<{
  103. contactList: InternalContactRef[];
  104. hasMore: boolean;
  105. currentVersion?: string;
  106. }>('/contact/getWxWorkContactList', {
  107. guid: GUID,
  108. limit,
  109. });
  110. return resp.data.contactList || [];
  111. }
  112. /** 联系人详情批量(API-18 /contact/batchGetUserinfo) */
  113. export async function getContactDetailsBatch(userIds: string[]): Promise<ContactDetail[]> {
  114. if (!TOKEN || !GUID || userIds.length === 0) return [];
  115. try {
  116. const resp = await callApi<{
  117. contactList: Array<{
  118. userId: string;
  119. nickname?: string;
  120. name?: string;
  121. mobile?: string;
  122. position?: string;
  123. }>;
  124. }>('/contact/batchGetUserinfo', { guid: GUID, userIdList: userIds });
  125. return (resp.data.contactList || []).map((c) => ({
  126. userId: c.userId,
  127. name: c.nickname || c.name || c.userId,
  128. mobile: c.mobile || '',
  129. position: c.position || '',
  130. }));
  131. } catch {
  132. return userIds.map((userId) => ({ userId, name: userId, mobile: '', position: '' }));
  133. }
  134. }
  135. export interface SyncMsgListItem {
  136. fromRoomId?: number | string;
  137. senderId?: number | string;
  138. receiverId?: number | string;
  139. senderName?: string;
  140. msgType?: number;
  141. timestamp?: number;
  142. seq?: number;
  143. msgServerId?: number;
  144. msgUniqueIdentifier?: string;
  145. msgData?: Record<string, unknown>;
  146. }
  147. /** 同步历史消息分页(API-06 /msg/syncMsg) */
  148. export async function syncMsgPage(
  149. guid: string,
  150. msgSeq: number,
  151. limit = 50,
  152. ): Promise<{
  153. hasMore: number | boolean;
  154. travelSyncKey: number;
  155. syncMsgList: SyncMsgListItem[];
  156. }> {
  157. const resp = await callApi<{
  158. hasMore: number | boolean;
  159. travelSyncKey: number;
  160. syncMsgList: SyncMsgListItem[];
  161. }>('/msg/syncMsg', { guid, msgSeq, limit });
  162. return {
  163. hasMore: resp.data.hasMore ?? 0,
  164. travelSyncKey: resp.data.travelSyncKey ?? msgSeq,
  165. syncMsgList: resp.data.syncMsgList || [],
  166. };
  167. }
  168. export interface RoomMemberRef {
  169. userId: string;
  170. nickname: string;
  171. }
  172. export interface RoomDetailDto {
  173. roomId: string;
  174. roomName: string;
  175. memberCount: number;
  176. ownerId: string;
  177. members: RoomMemberRef[];
  178. }
  179. function parseRoomMember(raw: unknown): RoomMemberRef | null {
  180. if (!raw || typeof raw !== 'object') return null;
  181. const o = raw as Record<string, unknown>;
  182. const userId = String(o.userId ?? o.memberId ?? '');
  183. if (!userId) return null;
  184. const nickname = String(o.nickname ?? o.name ?? o.memberName ?? o.displayName ?? '');
  185. return { userId, nickname };
  186. }
  187. /** 批量获取群详情(API-08) */
  188. export async function batchGetRoomDetails(
  189. guid: string,
  190. roomIdList: string[],
  191. ): Promise<RoomDetailDto[]> {
  192. const ids = roomIdList.map((id) => String(id).trim()).filter(Boolean);
  193. if (!TOKEN || !guid || ids.length === 0) return [];
  194. const resp = await callApi<{
  195. roomList: Array<{
  196. roomId: string;
  197. roomName: string;
  198. roomOwnerId?: string;
  199. memberList?: unknown[];
  200. }>;
  201. }>('/room/batchGetRoomDetail', { guid, roomIdList: ids });
  202. return (resp.data.roomList || []).map((r) => {
  203. const members = (r.memberList || [])
  204. .map(parseRoomMember)
  205. .filter((m): m is RoomMemberRef => m !== null);
  206. return {
  207. roomId: String(r.roomId),
  208. roomName: r.roomName || '',
  209. memberCount: members.length,
  210. ownerId: r.roomOwnerId ? String(r.roomOwnerId) : '',
  211. members,
  212. };
  213. });
  214. }
  215. /** 获取 Token 和 Guid 的可用性 */
  216. export function getQiWeConfig() {
  217. return { apiBase: API_BASE, token: TOKEN, guid: GUID };
  218. }