@stacksjs/chat 0.75.58 → 0.75.59
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/dist/inbox/types.d.ts +1 -0
- package/dist/index.js +1 -1
- package/package.json +6 -6
package/dist/inbox/types.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -36,7 +36,7 @@ var Ke=Object.defineProperty;var qe=(e)=>e;function Xe(e,t){this[e]=qe.bind(null
|
|
|
36
36
|
`).all(...s);for(let i of n){let a=t.get(i.message_id)??[],o=he(i.filename);a.push({guid:i.guid,path:o,name:i.transfer_name||(o?o.split("/").pop():i.guid),mimeType:i.mime_type,uti:i.uti,bytes:i.total_bytes??0,isSticker:i.is_sticker===1}),t.set(i.message_id,a)}}return t}}import{Database as je}from"bun:sqlite";import{existsSync as We,readdirSync as bt,readFileSync as yt}from"fs";import{homedir as vt}from"os";import{dirname as At,join as U}from"path";var be=U(vt(),"Library","Application Support","AddressBook");function Be(e,t){if(!t||t.length<2)return null;if(t[0]===1)return t.subarray(1);if(t[0]===2){let r=new TextDecoder().decode(t.subarray(1)).replace(/\0+$/,"").trim();if(!/^[\w-]+$/.test(r))return null;let s=U(At(e),".AddressBook-v22_SUPPORT","_EXTERNAL_DATA",r);try{return new Uint8Array(yt(s))}catch{return null}}return null}function xt(e){let t=[],r=U(e,"AddressBook-v22.abcddb");if(We(r))t.push(r);let s=U(e,"Sources");try{for(let n of bt(s)){let i=U(s,n,"AddressBook-v22.abcddb");if(We(i))t.push(i)}}catch{}return t}function Ze(e){let t=e.replace(/[^\p{L}\p{N}\s]/gu," ").trim().split(/\s+/).filter(Boolean);if(t.length===0)return"?";let r=t[0][0],s=t.length>1?t[t.length-1][0]:"";return(r+s).toUpperCase()}class j{byHandle=new Map;static load(e=be){let t=new j;for(let r of xt(e))try{t.read(r)}catch{}return t}get size(){return this.byHandle.size}read(e){let t=new je(e,{readonly:!0});try{let r=new Set(t.query("PRAGMA table_info(ZABCDRECORD)").all().map((c)=>c.name)),s=["ZTHUMBNAILIMAGEDATA","ZIMAGEDATA"].filter((c)=>r.has(c)),n=s.length>0?`(${s.map((c)=>`${c} IS NOT NULL`).join(" OR ")})`:"0",i=t.query(`
|
|
37
37
|
SELECT Z_PK AS id, ZFIRSTNAME AS first, ZLASTNAME AS last, ZNICKNAME AS nick, ZORGANIZATION AS org, ${n} AS hasPhoto
|
|
38
38
|
FROM ZABCDRECORD
|
|
39
|
-
`).all(),a=new Map,o=new Set;for(let c of i){let f=[c.first,c.last].filter(Boolean).join(" ").trim()||c.nick?.trim()||c.org?.trim();if(f)a.set(c.id,f);if(c.hasPhoto)o.add(c.id)}let l=t.query("SELECT ZOWNER AS owner, ZFULLNUMBER AS value FROM ZABCDPHONENUMBER").all(),g=t.query("SELECT ZOWNER AS owner, ZADDRESS AS value FROM ZABCDEMAILADDRESS").all();for(let c of[...l,...g]){let m=a.get(c.owner);if(!m||!c.value)continue;let f=x(c.value),v=o.has(c.owner)?{file:e,record:c.owner}:null,u=this.byHandle.get(f);if(!u)this.byHandle.set(f,{name:m,initials:Ze(m),photo:v});else if(!u.photo&&v)u.photo=v}}finally{t.close()}}set(e,t){this.byHandle.set(x(e),{name:t,initials:Ze(t)})}lookup(e){return this.byHandle.get(x(e))??null}nameFor(e){return this.lookup(e)?.name??null}hasPhoto(e){return!!this.lookup(e)?.photo}photo(e){let t=this.lookup(e)?.photo;if(!t)return null;try{let r=new je(t.file,{readonly:!0});try{let s=r.query("SELECT ZTHUMBNAILIMAGEDATA AS thumb, ZIMAGEDATA AS full FROM ZABCDRECORD WHERE Z_PK = ?").get(t.record);return Be(t.file,s?.thumb??null)??Be(t.file,s?.full??null)}finally{r.close()}}catch{return null}}}function Mt(e){if(e.style===L)return`group:${e.groupId||e.guid}`;return`direct:${e.identifier}`}function He(e){let t=new Map;for(let r of e){let s=Mt(r),n=t.get(s);if(!n){t.set(s,{key:s,kind:r.style===L?"group":"direct",chatGuids:[r.guid],displayName:r.displayName,groupId:r.groupId,groupPhotoGuid:r.style===L?r.groupPhotoGuid:null,participants:r.style===L?[...r.participants]:[r.identifier],messageCount:r.messageCount,recoverableCount:r.recoverableCount,unreadCount:r.unreadCount,lastMessageAt:r.lastMessageAt,lastMessageRowId:r.lastMessageRowId,lastMessageText:r.lastMessageText,lastMessageFromMe:r.lastMessageFromMe,services:[r.service]});continue}if(n.chatGuids.push(r.guid),n.kind==="group"&&!n.groupPhotoGuid)n.groupPhotoGuid=r.groupPhotoGuid;if(n.messageCount+=r.messageCount,n.recoverableCount+=r.recoverableCount,n.unreadCount+=r.unreadCount,!n.services.includes(r.service))n.services.push(r.service);for(let i of r.participants)if(n.kind==="group"&&!n.participants.includes(i))n.participants.push(i);if((r.lastMessageAt??0)>(n.lastMessageAt??0))n.lastMessageAt=r.lastMessageAt,n.lastMessageRowId=r.lastMessageRowId,n.lastMessageText=r.lastMessageText,n.lastMessageFromMe=r.lastMessageFromMe,n.displayName=r.displayName??n.displayName}return[...t.values()].sort((r,s)=>(s.lastMessageAt??0)-(r.lastMessageAt??0))}function ye(e){if(e.kind==="group")return e.groupId?`sms://open?groupid=${encodeURIComponent(e.groupId)}`:null;let t=e.participants[0];if(!t||!Oe(t))return null;return`sms:${t}`}var kt={2000:"\u2764\uFE0F",2001:"\uD83D\uDC4D",2002:"\uD83D\uDC4E",2003:"\uD83D\uDE02",2004:"\u203C\uFE0F",2005:"\u2753",2006:"\uD83D\uDE00",2007:"\uD83D\uDD16"};function _t(e){Bun.spawn(["/usr/bin/open",e],{stdio:["ignore","ignore","ignore"]})}class W{provider="imessage";label="iMessage";databasePath;addressBookDir;openUrl;controller;confirmDeletes;platform;contacts=null;contactsLoadedAt=0;constructor(e={}){this.databasePath=e.databasePath??ge,this.addressBookDir=e.addressBookDir??be,this.openUrl=e.openUrl??_t,this.controller=e.controller,this.confirmDeletes=e.confirmDeletes??!1,this.platform=e.platform??Et.platform}rowNames(e){let t=[];if(e.kind==="group")t.push(e.displayName);else if(e.participants[0])t.push(this.names().nameFor(e.participants[0]),ee(e.participants[0]),e.participants[0]);return[...new Set(t.filter((r)=>!!r))]}open(e){let t=new fe(this.databasePath);try{return e(t)}finally{t.close()}}names(){if(this.addressBookDir===!1)return this.contacts??=new j;if(!this.contacts||Date.now()-this.contactsLoadedAt>600000)this.contacts=j.load(this.addressBookDir),this.contactsLoadedAt=Date.now();return this.contacts}person(e){if(!e)return null;let t=this.names();return{id:e,name:t.nameFor(e),avatar:t.hasPhoto(e)?e:null}}async avatar(e){if(e.startsWith("group:")){let t=this.open((r)=>r.attachmentFile(e.slice(6)));return N(t&&se(t)?new Uint8Array(St(t)):null)}return N(this.names().photo(e))}grouped=null;chats(e){let t=[this.databasePath,`${this.databasePath}-wal`].map((r)=>{try{let s=Ct(r);return`${s.mtimeMs}:${s.size}`}catch{return"-"}}).join("|");if(this.grouped?.stamp!==t)this.grouped={stamp:t,chats:He(e.chats())};return this.grouped.chats}find(e,t){return this.chats(e).find((r)=>r.key===t)}async status(){if(this.platform!=="darwin")return{connected:!1,detail:"iMessage is only available on a Mac.",needs:"unsupported-platform"};try{return this.open(()=>{return}),{connected:!0,detail:"Reading Messages on this Mac."}}catch(e){if(e instanceof re&&e.needsFullDiskAccess&&se(wt(this.databasePath)))return{connected:!1,detail:"Grant Full Disk Access in System Settings > Privacy & Security.",needs:"full-disk-access"};return{connected:!1,detail:"Sign in to Messages on this Mac.",needs:"messages-signed-out"}}}async conversations(){return this.open((e)=>this.chats(e).map((t)=>this.toConversation(t)))}toConversation(e){let t=ye(e);return{provider:"imessage",id:e.key,kind:e.kind,title:e.kind==="group"?e.displayName:null,participants:e.participants.map((r)=>this.person(r)),workspace:null,lastMessageAt:e.lastMessageAt,preview:e.messageCount>0?e.lastMessageText:null,previewFromMe:e.lastMessageFromMe,unread:e.unreadCount,cursor:String(e.lastMessageRowId),visible:e.messageCount>0,deleted:e.recoverableCount,archive:t?{mode:"confirm",detail:"Opens it in Messages at Delete Conversation for you to confirm. Messages keeps it in Recently Deleted for 30 days."}:{mode:"unsupported",detail:"Messages cannot open this conversation by address, so delete it there yourself."},url:t,avatar:e.kind==="group"&&e.groupPhotoGuid?`group:${e.groupPhotoGuid}`:null}}async messages(e,t={}){return this.open((r)=>{let s=this.find(r,e);if(!s)return[];let n=t.includeDeleted;return(t.after||!t.limit?r.messages(s.chatGuids,{afterRowId:Number(t.after)||0,byRowId:!0,limit:t.limit,includeDeleted:n}):r.messages(s.chatGuids,{newestFirst:!0,limit:t.limit,includeDeleted:n}).reverse()).map((a)=>this.toMessage(e,a))})}toMessage(e,t){let r=t.reactionType>=3000;return{id:t.guid,conversationId:e,kind:t.kind,text:t.kind==="event"&&t.groupTitle?`Named the conversation \u201C${t.groupTitle}\u201D`:t.text,fromMe:t.isFromMe,sentAt:t.sentAt,sender:t.isFromMe?null:this.person(t.sender),targetId:t.targetGuid,reaction:t.kind==="reaction"?kt[r?t.reactionType-1000:t.reactionType]??"\u2022":null,reactionRemoved:r,replyToId:t.replyToGuid,editedAt:t.editedAt,unsent:t.unsent,attachments:t.attachments.map((s)=>({id:s.guid,name:s.name,mimeType:s.mimeType,bytes:s.bytes,path:s.path&&se(s.path)?s.path:null,url:null})),cursor:String(t.rowid)}}async archive(e){let t=this.open((n)=>this.find(n,e)),r=t?ye(t):null;if(!t||!r)return{mode:"unsupported",removed:!1,detail:"Messages cannot open this conversation by address, so delete it there yourself."};if(t.messageCount===0)return{mode:"confirm",removed:!0,detail:"Already gone from Messages."};let s=this.rowNames(t);if(this.controller&&s.length>0){let n=await this.controller.remove(s,r,this.confirmDeletes);return{mode:"confirm",removed:!1,detail:n.ok?this.confirmDeletes?"Deleted in Messages.":"Messages is asking you to confirm the delete.":n.detail}}return this.openUrl(r),{mode:"confirm",removed:!1,detail:"Messages is open on the conversation: choose Conversation > Delete Conversation to finish."}}async unarchive(e){if(!this.controller)return;let t=this.open((s)=>this.find(s,e));if(!t||t.messageCount>0)return;let r=this.rowNames(t);if(r.length>0)await this.controller.recover(r)}async attachment(e){if(!e.path||!se(e.path))return new Response("Not found",{status:404});return new Response(Bun.file(e.path),{headers:{"content-type":e.mimeType??"application/octet-stream"}})}}var Tt="im,mpim,public_channel,private_channel",Rt={"+1":"\uD83D\uDC4D",thumbsup:"\uD83D\uDC4D","-1":"\uD83D\uDC4E",heart:"\u2764\uFE0F",joy:"\uD83D\uDE02",laughing:"\uD83D\uDE06",tada:"\uD83C\uDF89",eyes:"\uD83D\uDC40",fire:"\uD83D\uDD25",white_check_mark:"\u2705",pray:"\uD83D\uDE4F",raised_hands:"\uD83D\uDE4C",rocket:"\uD83D\uDE80"},ne=(e)=>Math.round(Number(e)*1000);class ie extends Error{method;code;constructor(e,t){super(`Slack ${e} failed: ${t}`);this.method=e;this.code=t;this.name="SlackApiError"}}class B{provider="slack";label="Slack";token;fetch;apiBase;concurrency;self=null;users=new Map;avatars=new Map;channels=new Map;constructor(e){this.token=e.token,this.fetch=e.fetch??((t,r)=>fetch(t,r)),this.apiBase=(e.apiBase??"https://slack.com/api").replace(/\/$/,""),this.concurrency=e.concurrency??4}async api(e,t={},r=!1){for(let s=0;;s++){let n=new URLSearchParams(Object.entries(t).map(([o,l])=>[o,String(l)])),i=r?await this.fetch(`${this.apiBase}/${e}`,{method:"POST",headers:{authorization:`Bearer ${this.token}`,"content-type":"application/x-www-form-urlencoded"},body:n.toString()}):await this.fetch(`${this.apiBase}/${e}?${n}`,{headers:{authorization:`Bearer ${this.token}`}});if(i.status===429&&s<3){await Bun.sleep(Math.min(30,Number(i.headers.get("retry-after"))||1)*1000);continue}let a=await i.json();if(!a.ok)throw new ie(e,a.error??`http_${i.status}`);return a}}async whoami(){if(!this.self){let e=await this.api("auth.test");this.self={userId:e.user_id,team:e.team,teamId:e.team_id}}return this.self}async userName(e){if(!e)return null;if(!this.users.has(e))try{let{user:t}=await this.api("users.info",{user:e});this.users.set(e,t.profile?.display_name||t.profile?.real_name||t.real_name||t.name||null),this.avatars.set(e,t.profile?.image_72??null)}catch{this.users.set(e,null)}return this.users.get(e)??null}async person(e){if(!e)return null;let t=await this.userName(e);return{id:e,name:t,avatar:this.avatars.get(e)??null}}async avatar(e){if(!Q(e,["slack-edge.com","slack.com","gravatar.com"]))return new Response("Not found",{status:404});return this.fetch(e)}async status(){if(!this.token)return{connected:!1,detail:"Add a Slack user token.",needs:"token"};try{return{connected:!0,detail:`Signed in to ${(await this.whoami()).team}.`}}catch(e){return{connected:!1,detail:e instanceof Error?e.message:String(e),needs:"token"}}}archiveSupport(e){if(e.is_im||e.is_mpim)return{mode:"native",detail:"Closes the conversation in Slack. Slack reopens it when someone writes."};if(!e.is_private)return{mode:"native",detail:"Leaves the channel in Slack, and rejoins it if you unarchive."};return{mode:"unsupported",detail:"Leaving a private channel would need someone to invite you back, so it stays in Slack."}}async list(){let e=[],t="";do{let r=await this.api("users.conversations",{types:Tt,exclude_archived:!0,limit:200,...t?{cursor:t}:{}});e.push(...r.channels),t=r.response_metadata?.next_cursor??""}while(t);return e}async conversations(){let e=await this.whoami(),t=await this.list(),r=[];for(let s=0;s<t.length;s+=this.concurrency){let n=t.slice(s,s+this.concurrency);r.push(...await Promise.all(n.map((i)=>this.describe(i,e))))}return r.sort((s,n)=>(n.lastMessageAt??0)-(s.lastMessageAt??0))}async describe(e,t){let[{channel:r},s]=await Promise.all([this.api("conversations.info",{channel:e.id}).catch(()=>({channel:e})),this.api("conversations.history",{channel:e.id,limit:1}).catch(()=>({messages:[]}))]),n={...e,...r};this.channels.set(n.id,n);let i=s.messages[0],a=[];if(n.is_im)a=[await this.person(n.user)];else if(n.is_mpim){let o=await this.api("conversations.members",{channel:n.id,limit:50}).catch(()=>({members:[]}));a=await Promise.all(o.members.filter((l)=>l!==t.userId).map(async(l)=>await this.person(l)))}return{provider:"slack",id:n.id,kind:n.is_im?"direct":n.is_mpim?"group":"channel",title:n.is_im||n.is_mpim?null:`#${n.name}`,participants:a,workspace:t.team,lastMessageAt:i?ne(i.ts):null,preview:i?.text||(i?.files?.length?"Attachment":null),previewFromMe:i?.user===t.userId,unread:n.unread_count_display??0,cursor:i?.ts??"0",visible:n.is_im||n.is_mpim?n.is_open!==!1:!0,archive:this.archiveSupport(n),url:`slack://channel?team=${t.teamId}&id=${n.id}`}}async messages(e,t={}){let r=await this.whoami(),s=[],n="",i=t.limit??1000;do{let o=await this.api("conversations.history",{channel:e,limit:Math.min(200,i),...t.after?{oldest:t.after,inclusive:!1}:{},...n?{cursor:n}:{}});s.push(...o.messages),n=o.has_more?o.response_metadata?.next_cursor??"":""}while(n&&s.length<i);s.sort((o,l)=>Number(o.ts)-Number(l.ts));let a=[];for(let o of s.slice(-i)){let l=await this.person(o.user),g=!!o.subtype&&!["file_share","thread_broadcast","me_message"].includes(o.subtype);a.push({id:o.ts,conversationId:e,kind:g?"event":"message",text:o.text??null,fromMe:o.user===r.userId,sentAt:ne(o.ts),sender:o.user===r.userId?null:l??(o.username?{id:o.bot_id??o.username,name:o.username}:null),targetId:null,reaction:null,reactionRemoved:!1,replyToId:o.thread_ts&&o.thread_ts!==o.ts?o.thread_ts:null,editedAt:o.edited?ne(o.edited.ts):null,unsent:!1,attachments:(o.files??[]).map((c)=>({id:c.id,name:c.name??c.title??c.id,mimeType:c.mimetype??null,bytes:c.size??0,path:null,url:c.url_private??null})),cursor:o.ts});for(let c of o.reactions??[])for(let m of c.users??[])a.push({id:`${o.ts}:${c.name}:${m}`,conversationId:e,kind:"reaction",text:null,fromMe:m===r.userId,sentAt:ne(o.ts),sender:m===r.userId?null:await this.person(m),targetId:o.ts,reaction:Rt[c.name]??`:${c.name}:`,reactionRemoved:!1,replyToId:null,editedAt:null,unsent:!1,attachments:[],cursor:o.ts})}return a}async channel(e){let t=this.channels.get(e);if(t)return t;let{channel:r}=await this.api("conversations.info",{channel:e});return this.channels.set(e,r),r}async archive(e){let t=await this.channel(e),r=this.archiveSupport(t);if(r.mode!=="native")return{mode:r.mode,removed:!1,detail:r.detail};if(t.is_im||t.is_mpim)await this.api("conversations.close",{channel:e},!0);else await this.api("conversations.leave",{channel:e},!0);return this.channels.set(e,{...t,is_open:!1}),{mode:"native",removed:!0,detail:r.detail}}async unarchive(e){let t=await this.channel(e);if(t.is_im||t.is_mpim)await this.api("conversations.open",{channel:e},!0);else if(!t.is_private)await this.api("conversations.join",{channel:e},!0);this.channels.set(e,{...t,is_open:!0})}async attachment(e){if(!e.url)return new Response("Not found",{status:404});return this.fetch(e.url,{headers:{authorization:`Bearer ${this.token}`}})}}import{existsSync as oe,readFileSync as Lt}from"fs";import{basename as $t,dirname as we,extname as Ut,join as Ee}from"path";import jt from"process";function ve(e,t){let r=0n,s=0n;for(let n=t;n<e.length&&n<t+10;n++){let i=e[n];if(r|=BigInt(i&127)<<s,(i&128)===0)return{value:r,next:n+1};s+=7n}throw Error("Truncated varint")}function It(e){let t=[],r=0;while(r<e.length){let s=ve(e,r);r=s.next;let n=Number(s.value>>3n),i=Number(s.value&7n);if(n===0)throw Error("Field number 0");if(i===0){let a=ve(e,r);t.push({field:n,wire:i,value:a.value}),r=a.next}else if(i===1||i===5){let a=i===1?8:4;if(r+a>e.length)throw Error("Truncated fixed field");let o=0n;for(let l=a-1;l>=0;l--)o=o<<8n|BigInt(e[r+l]);t.push({field:n,wire:i,value:o}),r+=a}else if(i===2){let a=ve(e,r),o=a.next,l=o+Number(a.value);if(l>e.length)throw Error("Truncated length-delimited field");t.push({field:n,wire:i,value:e.subarray(o,l)}),r=l}else throw Error(`Unsupported wire type ${i}`)}return t}function Z(e){if(!e||e.length===0)return null;try{return It(e)}catch{return null}}function Dt(e,t){let r=e?.find((s)=>s.field===t&&s.wire===2);return r?r.value:null}function Ae(e,t){return(e??[]).filter((r)=>r.field===t&&r.wire===2).map((r)=>r.value)}function H(e,t){let r=Dt(e,t);if(!r)return null;let s=new TextDecoder("utf-8",{fatal:!0});try{return s.decode(r)}catch{return null}}function xe(e,t){let r=e?.find((s)=>s.field===t&&s.wire!==2);return r?r.value:null}import{Database as Pt}from"bun:sqlite";import{homedir as Ot}from"os";import{join as Me}from"path";var Ge=Me(Ot(),"Library","Group Containers","group.net.whatsapp.WhatsApp.shared"),Se=Me(Ge,"ChatStorage.sqlite"),Je=Me(Ge,"Message"),G=0,Nt=1,Ft=4,d={Text:0,Image:1,Video:2,Audio:3,Contact:4,Location:5,GroupEvent:6,Link:7,Document:8,Call:10,Gif:11,Deleted:14,Sticker:15};class ae extends Error{path;needsFullDiskAccess;constructor(e,t){let r=t instanceof Error?t.message:String(t);super(`Cannot read ${e}: ${r}`);this.path=e;this.name="WhatsAppAccessError",this.needsFullDiskAccess=/authorization denied|not permitted|unable to open/i.test(r)}}function h(e){let t=e?.replace(/\uFFFC/g,"").trim();return t?t:null}class Ce{path;db;constructor(e=Se){this.path=e;try{this.db=new Pt(e,{readonly:!0}),this.db.query("SELECT 1 FROM ZWACHATSESSION LIMIT 1").all()}catch(t){throw new ae(e,t)}}close(){this.db.close()}columns(e){try{return new Set(this.db.query(`PRAGMA table_info(${e})`).all().map((t)=>t.name))}catch{return new Set}}get hasMetadata(){return this.columns("ZWAMEDIAITEM").has("ZMETADATA")}get hasReceipts(){return this.columns("ZWAMESSAGE").has("ZMESSAGEINFO")&&this.columns("ZWAMESSAGEINFO").has("ZRECEIPTINFO")}sessions(e){return this.db.query(`
|
|
39
|
+
`).all(),a=new Map,o=new Set;for(let c of i){let f=[c.first,c.last].filter(Boolean).join(" ").trim()||c.nick?.trim()||c.org?.trim();if(f)a.set(c.id,f);if(c.hasPhoto)o.add(c.id)}let l=t.query("SELECT ZOWNER AS owner, ZFULLNUMBER AS value FROM ZABCDPHONENUMBER").all(),g=t.query("SELECT ZOWNER AS owner, ZADDRESS AS value FROM ZABCDEMAILADDRESS").all();for(let c of[...l,...g]){let m=a.get(c.owner);if(!m||!c.value)continue;let f=x(c.value),v=o.has(c.owner)?{file:e,record:c.owner}:null,u=this.byHandle.get(f);if(!u)this.byHandle.set(f,{name:m,initials:Ze(m),photo:v});else if(!u.photo&&v)u.photo=v}}finally{t.close()}}set(e,t){this.byHandle.set(x(e),{name:t,initials:Ze(t)})}lookup(e){return this.byHandle.get(x(e))??null}nameFor(e){return this.lookup(e)?.name??null}hasPhoto(e){return!!this.lookup(e)?.photo}photo(e){let t=this.lookup(e)?.photo;if(!t)return null;try{let r=new je(t.file,{readonly:!0});try{let s=r.query("SELECT ZTHUMBNAILIMAGEDATA AS thumb, ZIMAGEDATA AS full FROM ZABCDRECORD WHERE Z_PK = ?").get(t.record);return Be(t.file,s?.thumb??null)??Be(t.file,s?.full??null)}finally{r.close()}}catch{return null}}}function Mt(e){if(e.style===L)return`group:${e.groupId||e.guid}`;return`direct:${e.identifier}`}function He(e){let t=new Map;for(let r of e){let s=Mt(r),n=t.get(s);if(!n){t.set(s,{key:s,kind:r.style===L?"group":"direct",chatGuids:[r.guid],displayName:r.displayName,groupId:r.groupId,groupPhotoGuid:r.style===L?r.groupPhotoGuid:null,participants:r.style===L?[...r.participants]:[r.identifier],messageCount:r.messageCount,recoverableCount:r.recoverableCount,unreadCount:r.unreadCount,lastMessageAt:r.lastMessageAt,lastMessageRowId:r.lastMessageRowId,lastMessageText:r.lastMessageText,lastMessageFromMe:r.lastMessageFromMe,services:[r.service]});continue}if(n.chatGuids.push(r.guid),n.kind==="group"&&!n.groupPhotoGuid)n.groupPhotoGuid=r.groupPhotoGuid;if(n.messageCount+=r.messageCount,n.recoverableCount+=r.recoverableCount,n.unreadCount+=r.unreadCount,!n.services.includes(r.service))n.services.push(r.service);for(let i of r.participants)if(n.kind==="group"&&!n.participants.includes(i))n.participants.push(i);if((r.lastMessageAt??0)>(n.lastMessageAt??0))n.lastMessageAt=r.lastMessageAt,n.lastMessageRowId=r.lastMessageRowId,n.lastMessageText=r.lastMessageText,n.lastMessageFromMe=r.lastMessageFromMe,n.displayName=r.displayName??n.displayName}return[...t.values()].sort((r,s)=>(s.lastMessageAt??0)-(r.lastMessageAt??0))}function ye(e){if(e.kind==="group")return e.groupId?`sms://open?groupid=${encodeURIComponent(e.groupId)}`:null;let t=e.participants[0];if(!t||!Oe(t))return null;return`sms:${t}`}var kt={2000:"\u2764\uFE0F",2001:"\uD83D\uDC4D",2002:"\uD83D\uDC4E",2003:"\uD83D\uDE02",2004:"\u203C\uFE0F",2005:"\u2753",2006:"\uD83D\uDE00",2007:"\uD83D\uDD16"};function _t(e){Bun.spawn(["/usr/bin/open",e],{stdio:["ignore","ignore","ignore"]})}class W{provider="imessage";label="iMessage";databasePath;addressBookDir;openUrl;controller;confirmDeletes;platform;contacts=null;contactsLoadedAt=0;constructor(e={}){this.databasePath=e.databasePath??ge,this.addressBookDir=e.addressBookDir??be,this.openUrl=e.openUrl??_t,this.controller=e.controller,this.confirmDeletes=e.confirmDeletes??!1,this.platform=e.platform??Et.platform}rowNames(e){let t=[];if(e.kind==="group")t.push(e.displayName);else if(e.participants[0])t.push(this.names().nameFor(e.participants[0]),ee(e.participants[0]),e.participants[0]);return[...new Set(t.filter((r)=>!!r))]}open(e){let t=new fe(this.databasePath);try{return e(t)}finally{t.close()}}names(){if(this.addressBookDir===!1)return this.contacts??=new j;if(!this.contacts||Date.now()-this.contactsLoadedAt>600000)this.contacts=j.load(this.addressBookDir),this.contactsLoadedAt=Date.now();return this.contacts}person(e){if(!e)return null;let t=this.names();return{id:e,name:t.nameFor(e),avatar:t.hasPhoto(e)?e:null}}async avatar(e){if(e.startsWith("group:")){let t=this.open((r)=>r.attachmentFile(e.slice(6)));return N(t&&se(t)?new Uint8Array(St(t)):null)}return N(this.names().photo(e))}grouped=null;chats(e){let t=[this.databasePath,`${this.databasePath}-wal`].map((r)=>{try{let s=Ct(r);return`${s.mtimeMs}:${s.size}`}catch{return"-"}}).join("|");if(this.grouped?.stamp!==t)this.grouped={stamp:t,chats:He(e.chats())};return this.grouped.chats}find(e,t){return this.chats(e).find((r)=>r.key===t)}async status(){if(this.platform!=="darwin")return{connected:!1,detail:"iMessage is only available on a Mac.",needs:"unsupported-platform"};try{return this.open(()=>{return}),{connected:!0,detail:"Reading Messages on this Mac."}}catch(e){if(e instanceof re&&e.needsFullDiskAccess&&se(wt(this.databasePath)))return{connected:!1,detail:"Grant Full Disk Access in System Settings > Privacy & Security.",needs:"full-disk-access"};return{connected:!1,detail:"Sign in to Messages on this Mac.",needs:"messages-signed-out"}}}async conversations(){return this.open((e)=>this.chats(e).map((t)=>this.toConversation(t)))}toConversation(e){let t=ye(e);return{provider:"imessage",id:e.key,kind:e.kind,title:e.kind==="group"?e.displayName:null,participants:e.participants.map((r)=>this.person(r)),workspace:null,lastMessageAt:e.lastMessageAt,preview:e.messageCount>0?e.lastMessageText:null,previewFromMe:e.lastMessageFromMe,unread:e.unreadCount,cursor:String(e.lastMessageRowId),visible:e.messageCount>0,deleted:e.recoverableCount,archive:t?{mode:"confirm",detail:"Opens it in Messages at Delete Conversation for you to confirm. Messages keeps it in Recently Deleted for 30 days."}:{mode:"unsupported",detail:"Messages cannot open this conversation by address, so delete it there yourself."},url:t,avatar:e.kind==="group"&&e.groupPhotoGuid?`group:${e.groupPhotoGuid}`:null}}async messages(e,t={}){return this.open((r)=>{let s=this.find(r,e);if(!s)return[];let n=t.includeDeleted;return(t.after||!t.limit?r.messages(s.chatGuids,{afterRowId:Number(t.after)||0,byRowId:!0,limit:t.limit,includeDeleted:n}):r.messages(s.chatGuids,{newestFirst:!0,limit:t.limit,includeDeleted:n}).reverse()).map((a)=>this.toMessage(e,a))})}toMessage(e,t){let r=t.reactionType>=3000;return{id:t.guid,conversationId:e,kind:t.kind,text:t.kind==="event"&&t.groupTitle?`Named the conversation \u201C${t.groupTitle}\u201D`:t.text,fromMe:t.isFromMe,sentAt:t.sentAt,sender:t.isFromMe?null:this.person(t.sender),targetId:t.targetGuid,reaction:t.kind==="reaction"?kt[r?t.reactionType-1000:t.reactionType]??"\u2022":null,reactionRemoved:r,replyToId:t.replyToGuid,service:t.service,editedAt:t.editedAt,unsent:t.unsent,attachments:t.attachments.map((s)=>({id:s.guid,name:s.name,mimeType:s.mimeType,bytes:s.bytes,path:s.path&&se(s.path)?s.path:null,url:null})),cursor:String(t.rowid)}}async archive(e){let t=this.open((n)=>this.find(n,e)),r=t?ye(t):null;if(!t||!r)return{mode:"unsupported",removed:!1,detail:"Messages cannot open this conversation by address, so delete it there yourself."};if(t.messageCount===0)return{mode:"confirm",removed:!0,detail:"Already gone from Messages."};let s=this.rowNames(t);if(this.controller&&s.length>0){let n=await this.controller.remove(s,r,this.confirmDeletes);return{mode:"confirm",removed:!1,detail:n.ok?this.confirmDeletes?"Deleted in Messages.":"Messages is asking you to confirm the delete.":n.detail}}return this.openUrl(r),{mode:"confirm",removed:!1,detail:"Messages is open on the conversation: choose Conversation > Delete Conversation to finish."}}async unarchive(e){if(!this.controller)return;let t=this.open((s)=>this.find(s,e));if(!t||t.messageCount>0)return;let r=this.rowNames(t);if(r.length>0)await this.controller.recover(r)}async attachment(e){if(!e.path||!se(e.path))return new Response("Not found",{status:404});return new Response(Bun.file(e.path),{headers:{"content-type":e.mimeType??"application/octet-stream"}})}}var Tt="im,mpim,public_channel,private_channel",Rt={"+1":"\uD83D\uDC4D",thumbsup:"\uD83D\uDC4D","-1":"\uD83D\uDC4E",heart:"\u2764\uFE0F",joy:"\uD83D\uDE02",laughing:"\uD83D\uDE06",tada:"\uD83C\uDF89",eyes:"\uD83D\uDC40",fire:"\uD83D\uDD25",white_check_mark:"\u2705",pray:"\uD83D\uDE4F",raised_hands:"\uD83D\uDE4C",rocket:"\uD83D\uDE80"},ne=(e)=>Math.round(Number(e)*1000);class ie extends Error{method;code;constructor(e,t){super(`Slack ${e} failed: ${t}`);this.method=e;this.code=t;this.name="SlackApiError"}}class B{provider="slack";label="Slack";token;fetch;apiBase;concurrency;self=null;users=new Map;avatars=new Map;channels=new Map;constructor(e){this.token=e.token,this.fetch=e.fetch??((t,r)=>fetch(t,r)),this.apiBase=(e.apiBase??"https://slack.com/api").replace(/\/$/,""),this.concurrency=e.concurrency??4}async api(e,t={},r=!1){for(let s=0;;s++){let n=new URLSearchParams(Object.entries(t).map(([o,l])=>[o,String(l)])),i=r?await this.fetch(`${this.apiBase}/${e}`,{method:"POST",headers:{authorization:`Bearer ${this.token}`,"content-type":"application/x-www-form-urlencoded"},body:n.toString()}):await this.fetch(`${this.apiBase}/${e}?${n}`,{headers:{authorization:`Bearer ${this.token}`}});if(i.status===429&&s<3){await Bun.sleep(Math.min(30,Number(i.headers.get("retry-after"))||1)*1000);continue}let a=await i.json();if(!a.ok)throw new ie(e,a.error??`http_${i.status}`);return a}}async whoami(){if(!this.self){let e=await this.api("auth.test");this.self={userId:e.user_id,team:e.team,teamId:e.team_id}}return this.self}async userName(e){if(!e)return null;if(!this.users.has(e))try{let{user:t}=await this.api("users.info",{user:e});this.users.set(e,t.profile?.display_name||t.profile?.real_name||t.real_name||t.name||null),this.avatars.set(e,t.profile?.image_72??null)}catch{this.users.set(e,null)}return this.users.get(e)??null}async person(e){if(!e)return null;let t=await this.userName(e);return{id:e,name:t,avatar:this.avatars.get(e)??null}}async avatar(e){if(!Q(e,["slack-edge.com","slack.com","gravatar.com"]))return new Response("Not found",{status:404});return this.fetch(e)}async status(){if(!this.token)return{connected:!1,detail:"Add a Slack user token.",needs:"token"};try{return{connected:!0,detail:`Signed in to ${(await this.whoami()).team}.`}}catch(e){return{connected:!1,detail:e instanceof Error?e.message:String(e),needs:"token"}}}archiveSupport(e){if(e.is_im||e.is_mpim)return{mode:"native",detail:"Closes the conversation in Slack. Slack reopens it when someone writes."};if(!e.is_private)return{mode:"native",detail:"Leaves the channel in Slack, and rejoins it if you unarchive."};return{mode:"unsupported",detail:"Leaving a private channel would need someone to invite you back, so it stays in Slack."}}async list(){let e=[],t="";do{let r=await this.api("users.conversations",{types:Tt,exclude_archived:!0,limit:200,...t?{cursor:t}:{}});e.push(...r.channels),t=r.response_metadata?.next_cursor??""}while(t);return e}async conversations(){let e=await this.whoami(),t=await this.list(),r=[];for(let s=0;s<t.length;s+=this.concurrency){let n=t.slice(s,s+this.concurrency);r.push(...await Promise.all(n.map((i)=>this.describe(i,e))))}return r.sort((s,n)=>(n.lastMessageAt??0)-(s.lastMessageAt??0))}async describe(e,t){let[{channel:r},s]=await Promise.all([this.api("conversations.info",{channel:e.id}).catch(()=>({channel:e})),this.api("conversations.history",{channel:e.id,limit:1}).catch(()=>({messages:[]}))]),n={...e,...r};this.channels.set(n.id,n);let i=s.messages[0],a=[];if(n.is_im)a=[await this.person(n.user)];else if(n.is_mpim){let o=await this.api("conversations.members",{channel:n.id,limit:50}).catch(()=>({members:[]}));a=await Promise.all(o.members.filter((l)=>l!==t.userId).map(async(l)=>await this.person(l)))}return{provider:"slack",id:n.id,kind:n.is_im?"direct":n.is_mpim?"group":"channel",title:n.is_im||n.is_mpim?null:`#${n.name}`,participants:a,workspace:t.team,lastMessageAt:i?ne(i.ts):null,preview:i?.text||(i?.files?.length?"Attachment":null),previewFromMe:i?.user===t.userId,unread:n.unread_count_display??0,cursor:i?.ts??"0",visible:n.is_im||n.is_mpim?n.is_open!==!1:!0,archive:this.archiveSupport(n),url:`slack://channel?team=${t.teamId}&id=${n.id}`}}async messages(e,t={}){let r=await this.whoami(),s=[],n="",i=t.limit??1000;do{let o=await this.api("conversations.history",{channel:e,limit:Math.min(200,i),...t.after?{oldest:t.after,inclusive:!1}:{},...n?{cursor:n}:{}});s.push(...o.messages),n=o.has_more?o.response_metadata?.next_cursor??"":""}while(n&&s.length<i);s.sort((o,l)=>Number(o.ts)-Number(l.ts));let a=[];for(let o of s.slice(-i)){let l=await this.person(o.user),g=!!o.subtype&&!["file_share","thread_broadcast","me_message"].includes(o.subtype);a.push({id:o.ts,conversationId:e,kind:g?"event":"message",text:o.text??null,fromMe:o.user===r.userId,sentAt:ne(o.ts),sender:o.user===r.userId?null:l??(o.username?{id:o.bot_id??o.username,name:o.username}:null),targetId:null,reaction:null,reactionRemoved:!1,replyToId:o.thread_ts&&o.thread_ts!==o.ts?o.thread_ts:null,editedAt:o.edited?ne(o.edited.ts):null,unsent:!1,attachments:(o.files??[]).map((c)=>({id:c.id,name:c.name??c.title??c.id,mimeType:c.mimetype??null,bytes:c.size??0,path:null,url:c.url_private??null})),cursor:o.ts});for(let c of o.reactions??[])for(let m of c.users??[])a.push({id:`${o.ts}:${c.name}:${m}`,conversationId:e,kind:"reaction",text:null,fromMe:m===r.userId,sentAt:ne(o.ts),sender:m===r.userId?null:await this.person(m),targetId:o.ts,reaction:Rt[c.name]??`:${c.name}:`,reactionRemoved:!1,replyToId:null,editedAt:null,unsent:!1,attachments:[],cursor:o.ts})}return a}async channel(e){let t=this.channels.get(e);if(t)return t;let{channel:r}=await this.api("conversations.info",{channel:e});return this.channels.set(e,r),r}async archive(e){let t=await this.channel(e),r=this.archiveSupport(t);if(r.mode!=="native")return{mode:r.mode,removed:!1,detail:r.detail};if(t.is_im||t.is_mpim)await this.api("conversations.close",{channel:e},!0);else await this.api("conversations.leave",{channel:e},!0);return this.channels.set(e,{...t,is_open:!1}),{mode:"native",removed:!0,detail:r.detail}}async unarchive(e){let t=await this.channel(e);if(t.is_im||t.is_mpim)await this.api("conversations.open",{channel:e},!0);else if(!t.is_private)await this.api("conversations.join",{channel:e},!0);this.channels.set(e,{...t,is_open:!0})}async attachment(e){if(!e.url)return new Response("Not found",{status:404});return this.fetch(e.url,{headers:{authorization:`Bearer ${this.token}`}})}}import{existsSync as oe,readFileSync as Lt}from"fs";import{basename as $t,dirname as we,extname as Ut,join as Ee}from"path";import jt from"process";function ve(e,t){let r=0n,s=0n;for(let n=t;n<e.length&&n<t+10;n++){let i=e[n];if(r|=BigInt(i&127)<<s,(i&128)===0)return{value:r,next:n+1};s+=7n}throw Error("Truncated varint")}function It(e){let t=[],r=0;while(r<e.length){let s=ve(e,r);r=s.next;let n=Number(s.value>>3n),i=Number(s.value&7n);if(n===0)throw Error("Field number 0");if(i===0){let a=ve(e,r);t.push({field:n,wire:i,value:a.value}),r=a.next}else if(i===1||i===5){let a=i===1?8:4;if(r+a>e.length)throw Error("Truncated fixed field");let o=0n;for(let l=a-1;l>=0;l--)o=o<<8n|BigInt(e[r+l]);t.push({field:n,wire:i,value:o}),r+=a}else if(i===2){let a=ve(e,r),o=a.next,l=o+Number(a.value);if(l>e.length)throw Error("Truncated length-delimited field");t.push({field:n,wire:i,value:e.subarray(o,l)}),r=l}else throw Error(`Unsupported wire type ${i}`)}return t}function Z(e){if(!e||e.length===0)return null;try{return It(e)}catch{return null}}function Dt(e,t){let r=e?.find((s)=>s.field===t&&s.wire===2);return r?r.value:null}function Ae(e,t){return(e??[]).filter((r)=>r.field===t&&r.wire===2).map((r)=>r.value)}function H(e,t){let r=Dt(e,t);if(!r)return null;let s=new TextDecoder("utf-8",{fatal:!0});try{return s.decode(r)}catch{return null}}function xe(e,t){let r=e?.find((s)=>s.field===t&&s.wire!==2);return r?r.value:null}import{Database as Pt}from"bun:sqlite";import{homedir as Ot}from"os";import{join as Me}from"path";var Ge=Me(Ot(),"Library","Group Containers","group.net.whatsapp.WhatsApp.shared"),Se=Me(Ge,"ChatStorage.sqlite"),Je=Me(Ge,"Message"),G=0,Nt=1,Ft=4,d={Text:0,Image:1,Video:2,Audio:3,Contact:4,Location:5,GroupEvent:6,Link:7,Document:8,Call:10,Gif:11,Deleted:14,Sticker:15};class ae extends Error{path;needsFullDiskAccess;constructor(e,t){let r=t instanceof Error?t.message:String(t);super(`Cannot read ${e}: ${r}`);this.path=e;this.name="WhatsAppAccessError",this.needsFullDiskAccess=/authorization denied|not permitted|unable to open/i.test(r)}}function h(e){let t=e?.replace(/\uFFFC/g,"").trim();return t?t:null}class Ce{path;db;constructor(e=Se){this.path=e;try{this.db=new Pt(e,{readonly:!0}),this.db.query("SELECT 1 FROM ZWACHATSESSION LIMIT 1").all()}catch(t){throw new ae(e,t)}}close(){this.db.close()}columns(e){try{return new Set(this.db.query(`PRAGMA table_info(${e})`).all().map((t)=>t.name))}catch{return new Set}}get hasMetadata(){return this.columns("ZWAMEDIAITEM").has("ZMETADATA")}get hasReceipts(){return this.columns("ZWAMESSAGE").has("ZMESSAGEINFO")&&this.columns("ZWAMESSAGEINFO").has("ZRECEIPTINFO")}sessions(e){return this.db.query(`
|
|
40
40
|
SELECT s.Z_PK AS pk, s.ZCONTACTJID AS jid, s.ZSESSIONTYPE AS type, s.ZPARTNERNAME AS name,
|
|
41
41
|
s.ZARCHIVED AS archived, s.ZUNREADCOUNT AS unread, s.ZLASTMESSAGEDATE AS lastDate,
|
|
42
42
|
s.ZLASTMESSAGETEXT AS lastText, COALESCE(last.ZISFROMME, 0) AS lastFromMe,
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/chat",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.75.
|
|
5
|
+
"version": "0.75.59",
|
|
6
6
|
"description": "Easily interact with chat APIs.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -58,13 +58,13 @@
|
|
|
58
58
|
"prepublishOnly": "bun run build"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@stacksjs/logging": "0.75.
|
|
61
|
+
"@stacksjs/logging": "0.75.59"
|
|
62
62
|
},
|
|
63
63
|
"devDependencies": {
|
|
64
|
-
"@stacksjs/cli": "0.75.
|
|
65
|
-
"@stacksjs/config": "0.75.
|
|
66
|
-
"@stacksjs/error-handling": "0.75.
|
|
67
|
-
"@stacksjs/types": "0.75.
|
|
64
|
+
"@stacksjs/cli": "0.75.59",
|
|
65
|
+
"@stacksjs/config": "0.75.59",
|
|
66
|
+
"@stacksjs/error-handling": "0.75.59",
|
|
67
|
+
"@stacksjs/types": "0.75.59",
|
|
68
68
|
"better-dx": "^0.2.24"
|
|
69
69
|
}
|
|
70
70
|
}
|