A WhatsApp (Web) transport for XMPP.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1534 lines
80 KiB

  1. (in-package :whatsxmpp)
  2. (defparameter +version+ "0.0.1")
  3. (defvar *archiving-enabled* nil
  4. "T if archiving user messages is enabled, NIL otherwise")
  5. (defvar *history-fetches-enabled* nil
  6. "T if full history fetches are enabled, NIL otherwise")
  7. (defclass whatsxmpp-component (xmpp-component)
  8. ((whatsapps
  9. :initform (make-hash-table :test 'equal)
  10. :accessor component-whatsapps)
  11. (presence-timers
  12. :initform (make-hash-table :test 'equal)
  13. :accessor component-presence-timers)
  14. (reconnect-timer
  15. :initform nil
  16. :accessor component-reconnect-timer)
  17. (upload-component-name
  18. :initarg :upload-component-name
  19. :accessor component-upload-component-name)))
  20. (defun send-text-message (comp to-jid text &optional from)
  21. "Send a simple text message to TO-JID, containing TEXT."
  22. (with-message (comp to-jid :from from)
  23. (cxml:with-element "body"
  24. (cxml:text text))))
  25. (defun handle-connection-complete (comp)
  26. (format *debug-io* "Connection complete! \\o/")
  27. (emit :connected comp))
  28. (defparameter +whatsapp-user-disco-info-list+
  29. `((disco-identity "whatsxmpp" "phone" "client")
  30. ;; FIXME: The features here must be lexicographically sorted!
  31. (disco-feature ,+entity-caps-ns+)
  32. (disco-feature ,+chat-states-ns+)
  33. (disco-feature ,+disco-info-ns+))
  34. "List of calls to DISCO-IDENTITY and DISCO-FEATURE for WhatsApp users bridged through to XMPP.")
  35. (defparameter +whatsapp-user-entity-caps+
  36. (generate-entity-caps +whatsapp-user-disco-info-list+)
  37. "Entity caps string for a bridged WhatsApp user.")
  38. (defun disco-info-handler (comp &key to from &allow-other-keys)
  39. "Handles XEP-0030 disco#info requests."
  40. (format *debug-io* "~&disco#info: ~A~%" to)
  41. (with-component-data-lock (comp)
  42. `((cxml:with-element "query"
  43. (cxml:attribute "xmlns" ,+disco-info-ns+)
  44. ,@(multiple-value-bind
  45. (to-hostname to-localpart to-resource)
  46. (parse-jid to)
  47. (declare (ignore to-hostname to-resource))
  48. (let* ((uid (get-user-id from))
  49. (user-name (get-contact-name uid to-localpart))
  50. (chat-subject (get-user-chat-subject uid to-localpart)))
  51. (cond
  52. ((equal to (component-name comp))
  53. `((disco-identity "whatsxmpp bridge" "xmpp" "gateway")
  54. (disco-feature ,+disco-info-ns+)
  55. (disco-feature ,+disco-items-ns+)
  56. (disco-feature ,+muc-ns+)))
  57. (user-name
  58. +whatsapp-user-disco-info-list+)
  59. (chat-subject
  60. `((disco-identity ,chat-subject "text" "conference")
  61. (disco-feature ,+disco-info-ns+)
  62. (disco-feature ,+muc-ns+)
  63. (disco-feature ,+mam-ns+)
  64. (disco-feature ,+muc-stable-id-ns+)
  65. (disco-feature ,+unique-stanzas-ns+)
  66. (disco-feature "muc_hidden")
  67. (disco-feature "muc_persistent")
  68. (disco-feature "muc_membersonly")
  69. (disco-feature "muc_nonanonymous")))
  70. (t nil))))))))
  71. (defun disco-items-handler (comp &key to from &allow-other-keys)
  72. "Handles XEP-0030 disco#items requests."
  73. (format *debug-io* "~&disco#items: ~A from ~A~%" to from)
  74. (with-component-data-lock (comp)
  75. `((cxml:with-element "query"
  76. (cxml:attribute "xmlns" ,+disco-items-ns+)
  77. ,@(when (equal to (component-name comp))
  78. (let ((uid (get-user-id (strip-resource from))))
  79. (format *debug-io* "~&muc list disco#items for ~A~%" (strip-resource from))
  80. (loop
  81. for (localpart . subject) in (get-user-groupchats uid)
  82. collect `(cxml:with-element "item"
  83. (cxml:attribute "jid" ,(concatenate 'string
  84. localpart "@"
  85. (component-name comp)))
  86. (cxml:attribute "name" ,subject)))))))))
  87. (defun admin-jid (comp)
  88. "Get the admin JID for COMP. You need the lock to be taken out for this one."
  89. (concatenate 'string "admin@" (component-name comp) "/adminbot"))
  90. (defparameter *admin-help-text*
  91. (format nil
  92. "** whatsxmpp, version ~A, a theta.eu.org project **
  93. Commands:
  94. - register: set up the bridge
  95. - unregister: log out of the bridge and wipe all bridge data (!)
  96. - connect: manually connect to WhatsApp
  97. - stop: disconnect from WhatsApp, and disable automatic reconnections
  98. - status: get your current status
  99. - getroster: trigger an XEP-0144 roster item exchange (in some clients, this'll pop up a window asking to add contacts to your roster)
  100. - help: view this help text
  101. - refresh-chats: force the bridge to update member lists + subject for all of your group chats
  102. - enable-archiving: enable storage of *unencrypted* WhatsApp messages by the bridge
  103. - disable-archiving: disable the above archiving setting
  104. - full-history-fetch: fetch ALL historic messages from WhatsApp and store them in the bridge's archive"
  105. +version+))
  106. (defparameter *admin-privileged-help-text*
  107. "You may execute the following additional administrator commands:
  108. - force-unregister USER: forcibly remove USER from the bridge")
  109. (defparameter *reconnect-every-secs* 5
  110. "Interval between calls to WA-RESETUP-USERS.")
  111. (defun admin-msg (comp jid text)
  112. "Send an admin message from the admin on COMP to JID."
  113. (send-text-message comp jid text (admin-jid comp)))
  114. (defun admin-presence (comp jid status &optional show)
  115. "Send presence from the admin on COMP to JID."
  116. (with-presence (comp jid
  117. :from (admin-jid comp))
  118. (when show
  119. (cxml:with-element "show"
  120. (cxml:text show)))
  121. (cxml:with-element "status"
  122. (cxml:text status))))
  123. (defun wa-resetup-users (comp)
  124. "Go through the list of WhatsApp users and reconnect those whose connections have dropped."
  125. (with-component-data-lock (comp)
  126. (let* ((users-to-reconnect
  127. (loop
  128. for jid being the hash-keys in (component-whatsapps comp)
  129. using (hash-value conn)
  130. do (when conn
  131. (symbol-macrolet
  132. ((ticks (gethash jid (component-presence-timers comp))))
  133. (unless ticks
  134. (setf ticks 0))
  135. (when (> (incf ticks) #.(/ (* 60 60) 5))
  136. (format *debug-io* "~&periodic presence available for ~A~%" jid)
  137. (whatscl::send-presence conn :available))))
  138. append (unless conn
  139. (list jid))))
  140. (num-users (length users-to-reconnect)))
  141. (when (> num-users 0)
  142. (format *debug-io* "~&resetup-users: ~A users to reconnect~%" num-users))
  143. (loop
  144. for user in users-to-reconnect
  145. do (handle-setup-user comp user))
  146. (trivial-timers:schedule-timer (component-reconnect-timer comp) *reconnect-every-secs*))))
  147. (defparameter *user-jid-scanner*
  148. (cl-ppcre:create-scanner "u([0-9]+)"))
  149. (defparameter *group-jid-scanner*
  150. (cl-ppcre:create-scanner "g([0-9]+)-([0-9]+)"))
  151. (defun wa-jid-to-whatsxmpp-localpart (waj)
  152. "Convert a whatscl JID object to a WhatsXMPP localpart."
  153. (unless waj
  154. (format *error-output* "WA-JID-TO-WHATSXMPP-LOCALPART called with NIL!")
  155. (return-from wa-jid-to-whatsxmpp-localpart "unknown"))
  156. (with-accessors ((localpart whatscl::jid-localpart) (hostname whatscl::jid-hostname)) waj
  157. (cond
  158. ((or (equal hostname "s.whatsapp.net") (equal hostname "c.us"))
  159. (concatenate 'string "u" localpart))
  160. ((equal hostname "g.us")
  161. (concatenate 'string "g" localpart))
  162. (t
  163. (concatenate 'string "other-" localpart "-" hostname)))))
  164. (defun whatsxmpp-localpart-to-wa-jid (localpart)
  165. "Parses a WhatsXMPP localpart, returning a whatscl JID object if parsing is successful.
  166. WhatsXMPP represents users as u440123456789 and groups as g1234-5678."
  167. (cl-ppcre:register-groups-bind (digits)
  168. (*user-jid-scanner* localpart)
  169. (return-from whatsxmpp-localpart-to-wa-jid
  170. (whatscl::make-jid digits "s.whatsapp.net")))
  171. (cl-ppcre:register-groups-bind (creator ts)
  172. (*group-jid-scanner* localpart)
  173. (return-from whatsxmpp-localpart-to-wa-jid
  174. (whatscl::make-jid (concatenate 'string creator "-" ts) "g.us"))))
  175. (defun wa-conn-recent-p (comp conn jid)
  176. (let ((current (gethash jid (component-whatsapps comp))))
  177. (eql current conn)))
  178. (defmacro with-wa-handler-context ((comp conn jid) &body body)
  179. "Takes the component data lock, checks that CONN is the most up-to-date connection for JID, and then executes BODY."
  180. `(with-component-data-lock (,comp)
  181. (if (wa-conn-recent-p ,comp ,conn ,jid)
  182. (progn ,@body)
  183. (warn "WA handler called with out of date connection, ignoring"))))
  184. (defun wa-handle-ws-error (comp conn jid err)
  185. (with-wa-handler-context (comp conn jid)
  186. (format *debug-io* "~&ws-error ~A: ~A~%" jid err)
  187. (admin-msg comp jid
  188. (format nil "WhatsApp websocket error: ~A~%Will automatically reconnect, but if issues persist, try a re-connect or re-register." err))
  189. (admin-presence comp jid "WebSocket error" "away")
  190. (setf (gethash jid (component-whatsapps comp)) nil)))
  191. (defun wa-handle-ws-close (comp conn jid)
  192. (with-wa-handler-context (comp conn jid)
  193. (format *debug-io* "~&ws-close: ~A~%" jid)
  194. (when (nth-value 1 (gethash jid (component-whatsapps comp)))
  195. ;; If true, we're still doing automatic reconnections.
  196. ;; Otherwise, we will have already yelled at the user for
  197. ;; whatever caused them to disconnect, so don't do anything here.
  198. (admin-msg comp jid
  199. "WhatsApp websocket closed (will reconnect soon).")
  200. (admin-presence comp jid "WebSocket closed" "away")
  201. (setf (gethash jid (component-whatsapps comp)) nil))))
  202. (defun wa-handle-ws-qrcode (comp conn jid qrcode)
  203. (with-wa-handler-context (comp conn jid)
  204. (format *debug-io* "~&qrcode: ~A~%" jid)
  205. (admin-presence comp jid "Waiting for QR code" "away")
  206. (send-qrcode comp jid qrcode)))
  207. (defun update-session-data (jid sessdata)
  208. (with-prepared-statement
  209. (update-sessdata-stmt "UPDATE users SET session_data = ? WHERE jid = ?")
  210. (format *debug-io* "~&update sessdata for ~A~%" jid)
  211. (bind-parameters update-sessdata-stmt sessdata jid)
  212. (sqlite:step-statement update-sessdata-stmt)))
  213. (defun wa-handle-ws-connected (comp conn jid wa-jid)
  214. (with-wa-handler-context (comp conn jid)
  215. (let ((sessdata (whatscl::serialize-persistent-session (whatscl::wac-session conn)))
  216. (status (format nil "Logged in to WhatsApp as ~A." wa-jid)))
  217. (update-session-data jid sessdata)
  218. (admin-msg comp jid status)
  219. (admin-presence comp jid status)
  220. (whatscl::send-presence conn :available)
  221. (format *debug-io* "~&ws-connected: ~A (as ~A)~%" jid wa-jid))))
  222. (defun wa-handle-disconnect (comp conn jid kind)
  223. (with-wa-handler-context (comp conn jid)
  224. (format *debug-io* "~&disconnect for ~A: ~A" jid kind)
  225. (let ((reason
  226. (case kind
  227. (:replaced "Connection replaced by other WhatsApp Web session")
  228. (:removed "Connection removed in mobile app"))))
  229. (admin-msg comp jid (format nil "Error: ~A." reason))
  230. (admin-presence comp jid reason "xa"))
  231. (admin-msg comp jid "(Disabling automatic reconnections.)")
  232. (remhash jid (component-whatsapps comp))))
  233. (defun wa-handle-error-status-code (comp conn jid err)
  234. (with-wa-handler-context (comp conn jid)
  235. (format *debug-io* "~&error-status-code for ~A: ~A~%" jid err)
  236. (if (typep err 'whatscl::login-error)
  237. (progn
  238. (let ((status-code (whatscl::scerror-status-code err)))
  239. (cond
  240. ((equal status-code 401)
  241. (progn
  242. (admin-msg comp jid "Error: The WhatsApp Web connection was removed from your device! You'll need to scan the QR code again.")
  243. (admin-presence comp jid "Connection removed" "xa")
  244. (update-session-data jid "")))
  245. ((equal status-code 403)
  246. (progn
  247. (admin-msg comp jid "Error: WhatsApp Web denied access. You may have violated the Terms of Service.")
  248. (admin-presence comp jid "Access denied" "xa")
  249. (update-session-data jid "")))
  250. ((equal status-code 419)
  251. (progn
  252. (admin-msg comp jid "Error: WhatsApp Web have invalidated this connection for some reason. You'll need to scan the QR code again. (It's unclear why this happens.)")
  253. (admin-presence comp jid "Connection invalidated" "xa")
  254. (update-session-data jid "")))
  255. (t
  256. (progn
  257. (admin-presence comp jid "Login failure" "xa")
  258. (admin-msg comp jid (format nil "Login failure: ~A" err))))))
  259. (admin-msg comp jid "(Disabling automatic reconnections.)")
  260. (remhash jid (component-whatsapps comp)))
  261. (admin-msg comp jid (format nil "Warning: A non-fatal WhatsApp error has occurred.~%You should be fine to continue, but if problems persist, consider re-connecting or re-registering.~%Details: ~A" err)))))
  262. (defun wa-handle-error (comp conn jid err bt)
  263. (with-wa-handler-context (comp conn jid)
  264. (format *debug-io* "~&whatscl error for ~A: ~A~%Backtrace:~A~%" jid err bt)
  265. (admin-msg comp jid
  266. (format nil "A programming error has been detected and your connection has been aborted unexpectedly.~%Report the following error to the bridge admin: ~A" err))
  267. (admin-msg comp jid "(Disabling automatic reconnections.)")
  268. (admin-presence comp jid "Programming error" "xa")
  269. (remhash jid (component-whatsapps comp))))
  270. (defun whatsxmpp-ping-handler (comp &key to from &allow-other-keys)
  271. (declare (ignore comp to from))
  272. ;; This is a stub!
  273. nil)
  274. (defun whatsxmpp-mam-query-handler (comp &key to from stanza &allow-other-keys)
  275. "Handles Message Archive Management (MAM) queries."
  276. (with-component-data-lock (comp)
  277. (let* ((stripped (strip-resource from))
  278. (local-time:*default-timezone* local-time:+utc-zone+)
  279. (uid (or
  280. (get-user-id stripped)
  281. (error 'stanza-error
  282. :defined-condition "registration-required"
  283. :text "You must be a bridge user to run MAM queries."
  284. :type "auth")))
  285. (chat-id (or
  286. (get-user-chat-id uid (nth-value 1 (parse-jid to)))
  287. (error 'stanza-error
  288. :defined-condition "item-not-found"
  289. :text "Couldn't find a WhatsApp chat with that JID."
  290. :type "modify")))
  291. (query-params (alist-from-mam-query (elt (child-elements stanza) 0))))
  292. (format *debug-io* "~&MAM query for ~A from ~A:~% params ~A~%" from to query-params)
  293. (labels ((unix-from-mam (time-input)
  294. (alexandria:when-let ((time time-input))
  295. (local-time:timestamp-to-unix (local-time:parse-timestring time))))
  296. (unix-from-mam-params (keyword params)
  297. (unix-from-mam (whatscl::cassoc keyword params))))
  298. (multiple-value-bind (messages completep)
  299. (query-archive uid chat-id
  300. :start (unix-from-mam-params :start query-params)
  301. :end (unix-from-mam-params :end query-params)
  302. :limit (alexandria:when-let
  303. ((limit (whatscl::cassoc :max query-params)))
  304. (parse-integer limit))
  305. :reference-stanza-id (or
  306. (whatscl::cassoc :after query-params)
  307. (whatscl::cassoc :before query-params))
  308. :forward-page (assoc :after query-params))
  309. (format *debug-io* "~&MAM query for ~A returned ~A messages (complete: ~A)" from (length messages) completep)
  310. (loop
  311. for msg in messages
  312. do (deliver-mam-history-message comp msg from (whatscl::cassoc :query-id query-params)))
  313. `((cxml:with-element "fin"
  314. (cxml:attribute "xmlns" ,+mam-ns+)
  315. (cxml:attribute "complete" ,(if completep "true" "false"))
  316. (cxml:with-element "set"
  317. (cxml:attribute "xmlns" ,+rsm-ns+)
  318. ,@(when (> (length messages) 0)
  319. `((cxml:with-element "first"
  320. (cxml:text ,(xmpp-id (first messages))))
  321. (cxml:with-element "last"
  322. (cxml:text ,(xmpp-id (car (last messages)))))))))))))))
  323. (defun do-chat-history-request (comp conn jid uid requested-jid)
  324. "Retrieves full chat history for the REQUESTED-JID, and inserts it into the database."
  325. (whatscl::get-full-chat-history
  326. conn requested-jid
  327. (lambda (conn chat-history)
  328. (with-wa-handler-context (comp conn jid)
  329. (bt:make-thread
  330. (lambda ()
  331. (let ((num-inserted 0))
  332. (loop
  333. for msg in chat-history
  334. do (unless (lookup-wa-msgid-in-history uid (whatscl::message-id msg))
  335. (incf num-inserted)
  336. (catcher
  337. (attach (with-component-data-lock (comp)
  338. (make-xmpp-messages-for-wa-message comp conn jid msg))
  339. (lambda (messages)
  340. (with-component-data-lock (comp)
  341. (loop
  342. for x-msg in messages
  343. do (progn
  344. (insert-xmpp-message x-msg)
  345. (incf num-inserted))))))
  346. (error (e)
  347. (warn "Couldn't insert chat history message: ~A" e)))))
  348. (with-component-data-lock (comp)
  349. (admin-msg comp jid (format nil "Inserted ~A (of ~A) chat history messages for ~A." num-inserted (length chat-history) requested-jid)))))
  350. :name (format nil "chat history insertion thread for ~A / ~A" jid requested-jid))
  351. (if (eql (length chat-history) 0)
  352. (admin-msg comp jid (format nil "Warning: chat history request for ~A errored, or returned no results." requested-jid))
  353. (admin-msg comp jid (format nil "Inserting ~A chat history messages for ~A..." (length chat-history) requested-jid)))))
  354. :sleep-secs 0.2
  355. :chunk-size 100))
  356. (defun wa-handle-message (comp conn jid msg delivery-type)
  357. (declare (ignore delivery-type))
  358. (with-wa-handler-context (comp conn jid)
  359. (let ((uid (get-user-id jid)))
  360. (when (lookup-wa-msgid uid (whatscl::message-id msg))
  361. ;; Don't process the same WhatsApp message twice.
  362. (return-from wa-handle-message))
  363. (catcher
  364. (attach (make-xmpp-messages-for-wa-message comp conn jid msg)
  365. (lambda (messages)
  366. (with-component-data-lock (comp)
  367. (loop
  368. for x-msg in messages
  369. do (progn
  370. (deliver-xmpp-message comp x-msg)
  371. (when (and *archiving-enabled* (user-archiving-enabled-p uid) (uiop:string-prefix-p "g" (conversation x-msg)))
  372. (insert-xmpp-message x-msg))
  373. (when (orig-id x-msg)
  374. (insert-user-message uid (xmpp-id x-msg) (orig-id x-msg))))))))
  375. (error (e)
  376. (with-component-data-lock (comp)
  377. (format *error-output* "~&processing of message ~A for ~A failed! error: ~A~%" (whatscl::message-id msg) jid e)
  378. (insert-user-message uid (concatenate 'string "error-" (whatscl::message-id msg)) (whatscl::message-id msg))
  379. (admin-msg comp jid
  380. (format nil "Warning: The bridge missed a message (whatsapp id ~A). The error was:~%~A"
  381. (whatscl::message-id msg) e))))))))
  382. (defun get-avatar-data (avatar-url)
  383. "Fetches AVATAR-URL, using the database as a cache. Returns the SHA1 hash (lowercase) of the avatar data as first argument, and the actual octets as second."
  384. (with-prepared-statements
  385. ((get-stmt "SELECT sha1, image FROM avatar_data WHERE avatar_url = ?")
  386. (insert-stmt "INSERT INTO avatar_data (avatar_url, sha1, image) VALUES (?, ?, ?)"))
  387. (bind-parameters get-stmt avatar-url)
  388. (if (sqlite:step-statement get-stmt)
  389. (with-bound-columns (sha1 image) get-stmt
  390. (values sha1 image))
  391. (progn
  392. (format *debug-io* "~&fetching avatar url: ~A~%" avatar-url)
  393. (multiple-value-bind (data status-code)
  394. (drakma:http-request avatar-url)
  395. (format *debug-io* "~&fetch resulted in status ~A~%" status-code)
  396. (when (eql status-code 200)
  397. (let ((sha1 (sha1-octets data)))
  398. (bind-parameters insert-stmt avatar-url sha1 data)
  399. (sqlite:step-statement insert-stmt)
  400. (values sha1 data))))))))
  401. (defun get-contact-avatar-data (uid localpart)
  402. "Get a set of avatar data (returned by GET-AVATAR-DATA) for LOCALPART, a possible contact for the user with ID UID.
  403. Returns three values: avatar data (as two values), and a generalized boolean specifying whether the user had an avatar (i.e. for no avatar users, returns (VALUES NIL NIL T))"
  404. (with-prepared-statements
  405. ((get-stmt "SELECT avatar_url FROM user_contacts WHERE user_id = ? AND wa_jid = ?"))
  406. (bind-parameters get-stmt uid localpart)
  407. (when (sqlite:step-statement get-stmt)
  408. (with-bound-columns (avatar-url) get-stmt
  409. (values-list (append
  410. (if (and avatar-url (> (length avatar-url) 0) (not (equal avatar-url "NO-AVATAR")))
  411. (multiple-value-list (get-avatar-data avatar-url))
  412. `(nil nil))
  413. (cons (> (length avatar-url) 0) nil)))))))
  414. (defun wa-request-avatar (comp conn jid wa-jid localpart)
  415. (format *debug-io* "~&requesting avatar for ~A from ~A~%" localpart jid)
  416. (whatscl::get-profile-picture conn wa-jid
  417. (lambda (conn result)
  418. (wa-handle-avatar-result comp conn jid localpart result))))
  419. (defun handle-wa-contact-presence (comp conn jid localpart &key noretry destination)
  420. "Send out a presence stanza for LOCALPART to JID, or queue requests for that user's status or avatar if they're lacking."
  421. (unless (uiop:string-prefix-p "u" localpart)
  422. (return-from handle-wa-contact-presence))
  423. (let* ((uid (get-user-id jid))
  424. (status (get-contact-status uid localpart))
  425. (wa-jid (whatsxmpp-localpart-to-wa-jid localpart)))
  426. (multiple-value-bind (avatar-sha1 avatar-data has-avatar-p)
  427. (get-contact-avatar-data uid localpart)
  428. (declare (ignore avatar-data))
  429. (if (and has-avatar-p status)
  430. (with-presence (comp (or destination jid)
  431. :from (concatenate 'string
  432. localpart
  433. "@"
  434. (component-name comp)))
  435. (cxml:with-element "status"
  436. (cxml:text status))
  437. (cxml:with-element "c"
  438. (cxml:attribute "xmlns" +entity-caps-ns+)
  439. (cxml:attribute "hash" "sha-1")
  440. (cxml:attribute "node" "https://git.theta.eu.org/eta/whatsxmpp")
  441. (cxml:attribute "ver" +whatsapp-user-entity-caps+))
  442. (cxml:with-element "x"
  443. (cxml:attribute "xmlns" +vcard-avatar-ns+)
  444. (if avatar-sha1
  445. (cxml:with-element "photo"
  446. (cxml:text avatar-sha1))
  447. (cxml:with-element "photo"))))
  448. (progn
  449. (unless noretry
  450. (unless avatar-sha1
  451. (wa-request-avatar comp conn jid wa-jid localpart))
  452. (unless status
  453. (format *debug-io* "~&requesting status for ~A from ~A~%" localpart jid)
  454. (whatscl::get-profile-status conn wa-jid
  455. (lambda (conn result)
  456. (wa-handle-status-result comp conn jid localpart result))))))))))
  457. (defun handle-wa-contact-presence-subscriptions (comp jid localpart)
  458. "Check if we need to send out presence subscriptions for LOCALPART."
  459. (unless (uiop:string-prefix-p "u" localpart)
  460. (return-from handle-wa-contact-presence-subscriptions))
  461. (let ((uid (get-user-id jid)))
  462. (assert uid () "No user ID for ~A!" jid)
  463. (with-prepared-statements
  464. ((get-stmt "SELECT subscription_state, name, notify, id FROM user_contacts WHERE user_id = ? AND wa_jid = ?")
  465. (update-stmt "UPDATE user_contacts SET subscription_state = ? WHERE id = ?"))
  466. (bind-parameters get-stmt uid localpart)
  467. (unless (sqlite:step-statement get-stmt)
  468. (error "No contact with localpart ~A exists!" localpart))
  469. (with-bound-columns (subscription-state name notify ctid) get-stmt
  470. (let ((name-to-use (or name
  471. (when notify (concatenate 'string "~" notify))))
  472. (from (concatenate 'string localpart "@" (component-name comp))))
  473. (when (and (equal subscription-state "none") name-to-use)
  474. (with-presence (comp jid
  475. :type "subscribe"
  476. :from from)
  477. (cxml:with-element "nick"
  478. (cxml:attribute "xmlns" +nick-ns+)
  479. (cxml:text name-to-use)))
  480. (bind-parameters update-stmt "asked" ctid)
  481. (sqlite:step-statement update-stmt)))))))
  482. (defun add-wa-contact (comp conn jid contact)
  483. "Adds the WHATSCL:CONTACT to the list of JID's contacts, or updates it if it already exists. Returns the contact's localpart."
  484. (with-accessors ((ct-jid whatscl::contact-jid)
  485. (ct-notify whatscl::contact-notify)
  486. (ct-name whatscl::contact-name))
  487. contact
  488. (let ((uid (get-user-id jid))
  489. (wx-localpart (wa-jid-to-whatsxmpp-localpart ct-jid)))
  490. (unless (uiop:string-prefix-p "u" wx-localpart)
  491. (return-from add-wa-contact))
  492. (assert uid () "No user ID for ~A!" jid)
  493. (with-prepared-statements
  494. ((get-stmt "SELECT id, name, notify FROM user_contacts WHERE user_id = ? AND wa_jid = ?")
  495. (update-stmt "UPDATE user_contacts SET name = ?, notify = ? WHERE id = ?")
  496. (update-chat-names "UPDATE user_chat_members SET resource = ? WHERE wa_jid = ?")
  497. (insert-stmt "INSERT INTO user_contacts (user_id, wa_jid, name, notify) VALUES (?, ?, ?, ?)"))
  498. (bind-parameters get-stmt uid wx-localpart)
  499. (if (sqlite:step-statement get-stmt)
  500. (with-bound-columns (id name notify) get-stmt
  501. (let ((notify (or ct-notify notify))
  502. (name (or ct-name name)))
  503. (bind-parameters update-stmt name notify id)
  504. (sqlite:step-statement update-stmt)))
  505. (progn
  506. (bind-parameters insert-stmt uid wx-localpart ct-name ct-notify)
  507. (sqlite:step-statement insert-stmt)))
  508. ;; Update the resource in all chats the user is joined to, so we can use the user's actual name instead of a phone number if possible
  509. (let ((newname (get-contact-name uid wx-localpart)))
  510. (bind-parameters update-chat-names newname wx-localpart))
  511. wx-localpart))))
  512. (defun wa-handle-contacts (comp conn jid contacts)
  513. (with-wa-handler-context (comp conn jid)
  514. (format *debug-io* "~&got ~A contacts for ~A~%" (length contacts) jid)
  515. (loop
  516. for contact in contacts
  517. do (add-wa-contact comp conn jid contact))))
  518. (defun wa-handle-contact (comp conn jid contact)
  519. (with-wa-handler-context (comp conn jid)
  520. (format *debug-io* "~&got contact ~A for ~A~%" contact jid)
  521. (add-wa-contact comp conn jid contact)))
  522. (defun request-wa-chat-metadata (comp conn jid wx-localpart)
  523. "Request chat metadata for WX-LOCALPART (a MUC localpart) for the user with JID."
  524. (format *debug-io* "~&requesting chat metadata for ~A from ~A~%" wx-localpart jid)
  525. (whatscl::get-group-metadata conn (whatsxmpp-localpart-to-wa-jid wx-localpart)
  526. (lambda (conn meta)
  527. (wa-handle-group-metadata comp conn jid wx-localpart meta))))
  528. (defun handle-wa-chat-invitation (comp conn jid uid localpart &key noretry)
  529. "Checks to see whether the group chat LOCALPART has any metadata; if not, requests some. If it does, and the user hasn't been invited to that group chat yet, send them an invitation."
  530. (unless (uiop:string-prefix-p "g" localpart)
  531. (return-from handle-wa-chat-invitation))
  532. (with-prepared-statements
  533. ((get-stmt "SELECT id, invitation_state FROM user_chats WHERE user_id = ? AND wa_jid = ?")
  534. (count-stmt "SELECT COUNT(*) FROM user_chat_members WHERE chat_id = ?")
  535. (update-stmt "UPDATE user_chats SET invitation_state = ? WHERE id = ?"))
  536. (bind-parameters get-stmt uid localpart)
  537. (assert (sqlite:step-statement get-stmt) ()
  538. "Chat ~A doesn't exist in database!" localpart)
  539. (with-bound-columns (chat-id invitation-state) get-stmt
  540. (bind-parameters count-stmt chat-id)
  541. (assert (sqlite:step-statement count-stmt))
  542. (with-bound-columns (n-members) count-stmt
  543. (if (> n-members 0)
  544. (when (equal invitation-state "none")
  545. (with-message (comp jid)
  546. (cxml:with-element "x"
  547. (cxml:attribute "xmlns" +muc-invite-ns+)
  548. (cxml:attribute "jid" (concatenate 'string
  549. localpart
  550. "@"
  551. (component-name comp)))))
  552. (bind-parameters update-stmt "invited" chat-id)
  553. (sqlite:step-statement update-stmt))
  554. (unless noretry
  555. (request-wa-chat-metadata comp conn jid localpart)))))))
  556. (defun add-wa-chat (comp conn jid ct-jid)
  557. "Adds the JID CT-JID to the list of the user's groupchats, if it is a groupchat. If it's a user JID, sends a presence subscription request if necessary."
  558. (let ((uid (get-user-id jid))
  559. (wx-localpart (wa-jid-to-whatsxmpp-localpart ct-jid)))
  560. (when (uiop:string-prefix-p "u" wx-localpart)
  561. ;; The user has an open chat with this other user, so they probably want a presence subscription.
  562. (when (get-contact-name uid wx-localpart) ;; FIXME
  563. (handle-wa-contact-presence-subscriptions comp jid wx-localpart))
  564. (return-from add-wa-chat))
  565. (unless (uiop:string-prefix-p "g" wx-localpart)
  566. (warn "Interesting localpart passed to ADD-WA-CHAT: ~A" wx-localpart)
  567. (return-from add-wa-chat))
  568. (assert uid () "No user ID for ~A!" jid)
  569. (unless (get-user-chat-id uid wx-localpart)
  570. (insert-user-chat uid wx-localpart))
  571. (handle-wa-chat-invitation comp conn jid uid wx-localpart)))
  572. (defun wa-handle-chats (comp conn jid chats)
  573. (with-wa-handler-context (comp conn jid)
  574. (format *debug-io* "~&got ~A chats for ~A~%" (length chats) jid)
  575. (loop
  576. for chat in chats
  577. do (add-wa-chat comp conn jid (whatscl::chat-jid chat)))))
  578. (defun wa-handle-message-ack (comp conn jid &key id ack from to participant &allow-other-keys)
  579. (with-wa-handler-context (comp conn jid)
  580. (format *debug-io* "~&message ack: ~A is ~A (from ~A, to ~A, participant ~A)~%" id ack from to participant)
  581. (when (equal (whatscl::jid-to-string from) (whatscl::wac-jid conn))
  582. ;; (someone else acked this message)
  583. (let* ((uid (get-user-id jid))
  584. (xmpp-id (lookup-wa-msgid uid id)))
  585. (if xmpp-id
  586. (let ((marker-name
  587. (cond
  588. ((eql ack :received) "received")
  589. ((eql ack :read) "displayed")
  590. ((eql ack :played) "displayed")
  591. (t (return-from wa-handle-message-ack)))))
  592. (if participant
  593. (let* ((participant-localpart (wa-jid-to-whatsxmpp-localpart participant))
  594. (group-localpart (wa-jid-to-whatsxmpp-localpart to))
  595. (chat-id (get-user-chat-id uid group-localpart)))
  596. (if chat-id
  597. (let ((from-resource (or (get-participant-resource chat-id participant-localpart)
  598. participant-localpart))
  599. (recipients (get-user-chat-joined uid group-localpart)))
  600. (loop
  601. for recip in recipients
  602. do (with-message (comp recip
  603. :from (concatenate 'string
  604. group-localpart
  605. "@"
  606. (component-name comp)
  607. "/"
  608. from-resource)
  609. :type "groupchat")
  610. (cxml:with-element marker-name
  611. (cxml:attribute "xmlns" +chat-markers-ns+)
  612. (cxml:attribute "id" xmpp-id)))))
  613. (warn "Ack for message ID ~A: couldn't find chat id?" id)))
  614. (let ((from-jid (concatenate 'string
  615. (wa-jid-to-whatsxmpp-localpart to)
  616. "@"
  617. (component-name comp))))
  618. (with-message (comp jid
  619. :from from-jid)
  620. (cxml:with-element marker-name
  621. (cxml:attribute "xmlns" +chat-markers-ns+)
  622. (cxml:attribute "id" xmpp-id))))))
  623. (warn "Got ack for unknown message id ~A" id))))))
  624. (defun wa-handle-message-send-result (comp conn jid &key orig-from orig-to orig-id orig-body result muc-resource)
  625. (with-wa-handler-context (comp conn jid)
  626. (format *debug-io* "~&message send result for ~A from ~A: ~A~%" orig-id orig-from result)
  627. (handler-case
  628. (let ((status (cdr (assoc :status result))))
  629. (unless status
  630. (error "No status response provided by WhatsApp"))
  631. (unless (eql status 200)
  632. (error "Message sending failed with code ~A" status))
  633. (if muc-resource
  634. ;; Do a MUC echo
  635. (let* ((new-from (concatenate 'string orig-to "/" muc-resource))
  636. (group-localpart (nth-value 1 (parse-jid orig-to)))
  637. (recipients (get-user-chat-joined (get-user-id jid) group-localpart)))
  638. (when (and *archiving-enabled* (user-archiving-enabled-p (get-user-id jid)))
  639. ;; FIXME: You can break the database's UNIQUE constraint here.
  640. (insert-xmpp-message (make-instance 'xmpp-message
  641. :conversation group-localpart
  642. :uid (get-user-id jid)
  643. :from muc-resource
  644. :timestamp (local-time:now)
  645. :xmpp-id orig-id
  646. :body orig-body)))
  647. (loop
  648. for recip in recipients
  649. do (with-message (comp recip :from new-from :id orig-id :type "groupchat")
  650. (cxml:with-element "body"
  651. (cxml:text orig-body))
  652. (cxml:with-element "stanza-id"
  653. (cxml:attribute "xmlns" +unique-stanzas-ns+)
  654. ;; XXX: This isn't actually compliant; we're supposed to generate
  655. ;; our own IDs here. However, the worst you can do is confuse
  656. ;; your own clients...
  657. (cxml:attribute "id" orig-id)
  658. (cxml:attribute "by" orig-to))
  659. (cxml:with-element "markable"
  660. (cxml:attribute "xmlns" +chat-markers-ns+)))))
  661. (with-message (comp orig-from :from orig-to)
  662. (cxml:with-element "received"
  663. (cxml:attribute "xmlns" +delivery-receipts-ns+)
  664. (cxml:attribute "id" orig-id)))))
  665. (error (e)
  666. (send-stanza-error comp
  667. :id orig-id :to orig-from :from orig-to
  668. :stanza-type "message"
  669. :e (make-condition 'stanza-error
  670. :defined-condition "recipient-unavailable"
  671. :type "modify"
  672. :text (format nil "~A" e)))))))
  673. (defun wa-handle-avatar-result (comp conn jid for-localpart result)
  674. (with-wa-handler-context (comp conn jid)
  675. (format *debug-io* "~&avatar result for ~A from ~A: ~A~%" for-localpart jid result)
  676. (let ((avatar-url (or result "NO-AVATAR"))
  677. (uid (get-user-id jid)))
  678. (with-prepared-statements
  679. ((update-stmt "UPDATE user_contacts SET avatar_url = ? WHERE user_id = ? AND wa_jid = ?"))
  680. (bind-parameters update-stmt avatar-url uid for-localpart)
  681. (sqlite:step-statement update-stmt)
  682. (handle-wa-contact-presence comp conn jid for-localpart :noretry t)))))
  683. (defun wa-handle-status-result (comp conn jid for-localpart result)
  684. (with-wa-handler-context (comp conn jid)
  685. (format *debug-io* "~&status result for ~A from ~A: ~A~%" for-localpart jid result)
  686. (let ((avatar-url (or result "Status unknown or hidden"))
  687. (uid (get-user-id jid)))
  688. (with-prepared-statements
  689. ((update-stmt "UPDATE user_contacts SET status = ? WHERE user_id = ? AND wa_jid = ?"))
  690. (bind-parameters update-stmt avatar-url uid for-localpart)
  691. (sqlite:step-statement update-stmt)
  692. (handle-wa-contact-presence comp conn jid for-localpart :noretry t)))))
  693. (defun wa-handle-picture-change (comp conn jid for-jid was-removed)
  694. (with-wa-handler-context (comp conn jid)
  695. (let* ((localpart (wa-jid-to-whatsxmpp-localpart for-jid))
  696. (uid (get-user-id jid))
  697. (contact-name (get-contact-name uid localpart)))
  698. (when contact-name
  699. (format *debug-io* "~&picture change notification for ~A from ~A (removed: ~A)~%" localpart jid was-removed)
  700. (if was-removed
  701. (with-prepared-statements
  702. ((update-stmt "UPDATE user_contacts SET avatar_url = ? WHERE user_id = ? AND wa_jid = ?"))
  703. (bind-parameters update-stmt "NO-AVATAR" uid localpart)
  704. (sqlite:step-statement update-stmt)
  705. (handle-wa-contact-presence comp conn jid localpart :noretry t))
  706. (wa-request-avatar comp conn jid for-jid localpart))))))
  707. (defun wa-handle-status-change (comp conn jid for-jid status)
  708. (with-wa-handler-context (comp conn jid)
  709. (let* ((localpart (wa-jid-to-whatsxmpp-localpart for-jid))
  710. (uid (get-user-id jid))
  711. (contact-name (get-contact-name uid localpart)))
  712. (when contact-name
  713. (format *debug-io* "~&status change notification for ~A from ~A~%" localpart jid)
  714. (with-prepared-statements
  715. ((update-stmt "UPDATE user_contacts SET status = ? WHERE user_id = ? AND wa_jid = ?"))
  716. (bind-parameters update-stmt status uid localpart)
  717. (sqlite:step-statement update-stmt)
  718. (handle-wa-contact-presence comp conn jid localpart :noretry t))))))
  719. (defun wa-handle-group-metadata (comp conn jid localpart data)
  720. (with-wa-handler-context (comp conn jid)
  721. (let* ((uid (get-user-id jid))
  722. (cid (get-user-chat-id uid localpart))
  723. (subject (whatscl::cassoc :subject data)))
  724. (unless cid
  725. (setf cid (insert-user-chat uid localpart)))
  726. (format *debug-io* "~&got group metadata for ~A from ~A~%" localpart jid)
  727. (unless subject
  728. (admin-msg comp jid (format nil "Warning: Failed to update group ~A: received ~A~%This warning usually appears when trying to get information for a group you're no longer in, and can be safely ignored." localpart data))
  729. (warn "Received incomplete group metadata for ~A from ~A: ~A" localpart jid data)
  730. (return-from wa-handle-group-metadata))
  731. (when cid
  732. (with-prepared-statements
  733. ((update-subject-stmt "UPDATE user_chats SET subject = ? WHERE id = ?")
  734. (delete-members-stmt "DELETE FROM user_chat_members WHERE chat_id = ?")
  735. (insert-member-stmt "INSERT INTO user_chat_members (chat_id, wa_jid, resource, affiliation) VALUES (?, ?, ?, ?)"))
  736. (with-transaction
  737. (bind-parameters update-subject-stmt subject cid)
  738. (bind-parameters delete-members-stmt cid)
  739. (sqlite:step-statement update-subject-stmt)
  740. (sqlite:step-statement delete-members-stmt)
  741. (loop
  742. for part in (whatscl::aval :participants data)
  743. do (let ((localpart (wa-jid-to-whatsxmpp-localpart
  744. (whatscl::parse-jid
  745. (whatscl::aval :id part)))))
  746. (bind-parameters insert-member-stmt
  747. cid localpart ; chat_id, wa_jid
  748. (3 ; resource
  749. (or
  750. (get-contact-name uid localpart)
  751. (substitute #\+ #\u localpart)))
  752. (4 ; affiliation
  753. (if (whatscl::cassoc :is-admin part)
  754. "admin"
  755. "member"))))
  756. (sqlite:step-statement insert-member-stmt)
  757. (sqlite:reset-statement insert-member-stmt)))
  758. (handle-wa-chat-invitation comp conn jid uid localpart :noretry t))))))
  759. (defun wa-handle-presence (comp conn jid &key for-jid type participant &allow-other-keys)
  760. (with-wa-handler-context (comp conn jid)
  761. (let* ((localpart (wa-jid-to-whatsxmpp-localpart for-jid))
  762. (chat-state
  763. (cond
  764. ((eql type :composing) "composing")
  765. ((eql type :paused) "paused")
  766. ((eql type :available) "active")
  767. ((eql type :unavailable) "gone")
  768. (t (return-from wa-handle-presence)))))
  769. (unless participant ; Groups hard
  770. (let ((from-jid (concatenate 'string
  771. localpart
  772. "@"
  773. (component-name comp))))
  774. (with-message (comp jid
  775. :from from-jid)
  776. (cxml:with-element chat-state
  777. (cxml:attribute "xmlns" +chat-states-ns+))))))))
  778. (defun wa-handle-chat-modified (comp conn jid chat-jid)
  779. (with-wa-handler-context (comp conn jid)
  780. (let ((wx-localpart (wa-jid-to-whatsxmpp-localpart chat-jid)))
  781. (format *debug-io* "~&chat-modified: ~A for ~A~&" wx-localpart jid)
  782. (request-wa-chat-metadata comp conn jid wx-localpart))))
  783. (defun bind-wa-handlers (comp conn jid)
  784. (on :ws-close conn (lambda (&rest args)
  785. (declare (ignore args))
  786. (wa-handle-ws-close comp conn jid)))
  787. (on :ws-error conn (lambda (e) (wa-handle-ws-error comp conn jid e)))
  788. (on :disconnect conn (lambda (k) (wa-handle-disconnect comp conn jid k)))
  789. (on :chat-modified conn (lambda (k) (wa-handle-chat-modified comp conn jid k)))
  790. (on :error conn (lambda (e backtrace) (wa-handle-error comp conn jid e backtrace)))
  791. (on :error-status-code conn (lambda (e) (wa-handle-error-status-code comp conn jid e)))
  792. (on :qrcode conn (lambda (text) (wa-handle-ws-qrcode comp conn jid text)))
  793. (on :message conn (lambda (msg dt) (wa-handle-message comp conn jid msg dt)))
  794. (on :contacts conn (lambda (contacts) (wa-handle-contacts comp conn jid contacts)))
  795. (on :chats conn (lambda (chats) (wa-handle-chats comp conn jid chats)))
  796. (on :contact conn (lambda (contact) (wa-handle-contact comp conn jid contact)))
  797. (on :message-ack conn (lambda (&key id ack from to participant &allow-other-keys)
  798. (wa-handle-message-ack comp conn jid
  799. :id id :ack ack :from from :to to
  800. :participant participant)))
  801. (on :picture-change conn (lambda (for-jid removed)
  802. (wa-handle-picture-change comp conn jid for-jid removed)))
  803. (on :status-change conn (lambda (for-jid status)
  804. (wa-handle-status-change comp conn jid for-jid status)))
  805. (on :presence conn (lambda (&key of type participant &allow-other-keys)
  806. (wa-handle-presence comp conn jid
  807. :for-jid of :type type
  808. :participant participant)))
  809. (on :connected conn (lambda (waj) (wa-handle-ws-connected comp conn jid waj))))
  810. (defun handle-setup-user (comp jid)
  811. "Set up a WhatsApp connection for JID on COMP."
  812. (with-component-data-lock (comp)
  813. (format *debug-io* "~&setup user: ~A~%" jid)
  814. (with-prepared-statement
  815. (get-session-data-stmt "SELECT session_data FROM users WHERE jid = ?")
  816. (bind-parameters get-session-data-stmt jid)
  817. (assert (sqlite:step-statement get-session-data-stmt) ()
  818. "HANDLE-SETUP-USER called for invalid JID ~A" jid)
  819. (let* ((sessdata (sqlite:statement-column-value get-session-data-stmt 0))
  820. (sess (when (and sessdata (> (length sessdata) 0))
  821. (format *debug-io* "~&reusing old session data for ~A~%" jid)
  822. (whatscl::deserialize-persistent-session sessdata)))
  823. (conn (whatscl::make-connection sess)))
  824. (admin-msg comp jid "Connecting to WhatsApp...")
  825. (admin-presence comp jid "Connection in progress..." "away")
  826. (symbol-macrolet
  827. ((stored-conn (gethash jid (component-whatsapps comp))))
  828. (let ((old-conn))
  829. (when stored-conn
  830. (setf old-conn stored-conn))
  831. (setf stored-conn conn)
  832. (bind-wa-handlers comp conn jid)
  833. (when old-conn
  834. (admin-msg comp jid "(destroying your old connection)")
  835. (whatscl::close-connection old-conn))
  836. (handler-case
  837. (whatscl::start-connection conn)
  838. (error (e)
  839. (admin-msg comp jid (format nil "Connection failed:~% ~A" e))
  840. (admin-msg comp jid "(will retry)")
  841. (setf stored-conn nil)))))))))
  842. (defun unregister-user (comp uid)
  843. "Unregister the user with id UID from the bridge."
  844. (with-component-data-lock (comp)
  845. (let* ((user-jid (get-user-jid uid))
  846. (current-conn (gethash user-jid (component-whatsapps comp))))
  847. (db-unregister-user uid)
  848. (when current-conn
  849. (ignore-errors
  850. (whatscl::close-connection current-conn)))
  851. (remhash user-jid (component-whatsapps comp))
  852. (admin-msg comp user-jid "You have been unregistered from the bridge, and all data has been deleted. Have a nice day!"))))
  853. (defun start-user-registration (comp jid)
  854. "Register the JID as wanting to use the bridge COMP."
  855. (with-component-data-lock (comp)
  856. (let ((stripped (strip-resource jid)))
  857. (admin-msg comp jid "Starting registration!")
  858. (format *debug-io* "~&register: ~A~%" stripped)
  859. (with-prepared-statement
  860. (insert-stmt "INSERT INTO users (jid) VALUES (?) ON CONFLICT (jid) DO UPDATE SET session_data = ''")
  861. (bind-parameters insert-stmt stripped)
  862. (sqlite:step-statement insert-stmt))
  863. (with-presence (comp stripped
  864. :type "subscribe"
  865. :from (admin-jid comp))
  866. (cxml:with-element "status"
  867. (cxml:text "Please add the whatsxmpp admin user to your roster; if you don't, things will probably break in various fun ways."))
  868. (cxml:with-element "nick"
  869. (cxml:attribute "xmlns" +nick-ns+)
  870. (cxml:text "whatsxmpp admin")))
  871. (admin-msg comp jid "WhatsApp connection should begin shortly...")
  872. (handle-setup-user comp stripped))))
  873. (defun get-admin-status (comp jid)
  874. "Get the status text of the admin user for the user with ID JID. Returns a <show/> value as second value."
  875. (multiple-value-bind (conn exists-p)
  876. (gethash jid (component-whatsapps comp))
  877. (cond
  878. ((and conn (whatscl::wac-jid conn))
  879. (format nil "Connected and logged in as ~A."
  880. (whatscl::wac-jid conn)))
  881. (conn (values "Connected, but not logged in." "away"))
  882. (exists-p (values "Temporarily disconnected." "away"))
  883. (t (values "Disconnected (automatic reconnections disabled)." "xa")))))
  884. (defun do-roster-exchange (comp jid uid)
  885. "Initiate an XEP-0144 Roster Item Exchange for JID (with user ID UID)."
  886. (let ((localparts (get-user-contact-localparts uid)))
  887. (with-message (comp jid)
  888. (cxml:with-element "x"
  889. (cxml:attribute "xmlns" +roster-exchange-ns+)
  890. (loop
  891. for ct-localpart in localparts
  892. do (when ct-localpart
  893. (let* ((ct-jid (concatenate 'string
  894. ct-localpart
  895. "@"
  896. (component-name comp)))
  897. (ct-name (get-contact-name uid ct-localpart
  898. :no-phone-number t)))
  899. (when ct-name
  900. (cxml:with-element "item"
  901. (cxml:attribute "action" "add")
  902. (cxml:attribute "jid" ct-jid)
  903. (cxml:attribute "name" ct-name)
  904. (cxml:with-element "group"
  905. (cxml:text "WhatsApp")))))))))))
  906. (defun handle-admin-command (comp from body uid)
  907. "Handles an admin command sent to COMP."
  908. (labels ((reply (text)
  909. (send-text-message comp from text (admin-jid comp))))
  910. (let ((body (string-downcase body))
  911. (stripped (strip-resource from)))
  912. (cond
  913. ((and uid (equal body "register"))
  914. (reply (format nil "You're already registered!~%Try `connect`. If you really want to re-register, use the `register -force` command.")))
  915. ((or
  916. (and (not uid) (equal body "register"))
  917. (and uid (equal body "register -force")))
  918. (start-user-registration comp stripped))
  919. ((equal body "unregister")
  920. (reply "Are you sure? Unregistering will delete ALL information the bridge has about you, and is not reversible. If you still want to continue, execute the `unregister -force` command."))
  921. ((equal body "unregister -force")
  922. (if uid
  923. (unregister-user comp uid)
  924. (reply "You're not registered with the bridge.")))
  925. ((equal body "help")
  926. (progn
  927. (reply *admin-help-text*)
  928. (when (jid-admin-p stripped)
  929. (reply *admin-privileged-help-text*))))
  930. ((not uid)
  931. (reply "You're not registered with this bridge. Try `register` or `help`."))
  932. ((equal body "enable-archiving")
  933. (reply "Are you sure you want to enable archiving? Doing this will store your WhatsApp messages, *unencrypted*, on the server of the bridge operator, where they can be easily read! If you still want to continue, execute the `enable-archiving -force` command."))
  934. ((equal body "enable-archiving -force")
  935. (if *archiving-enabled*
  936. (progn
  937. (user-set-archiving-state uid t)
  938. (reply "Archiving enabled."))
  939. (reply "Archiving cannot be enabled on this bridge. Please contact the bridge administrator.")))
  940. ((equal body "disable-archiving")
  941. (progn
  942. (user-set-archiving-state uid nil)
  943. (reply "Archiving disabled. WARNING: Message history is not cleared. To do that, unregister from the bridge entirely (deleting all data), and re-register.")))
  944. ((equal body "getroster")
  945. (progn
  946. (do-roster-exchange comp stripped uid)
  947. (reply "Roster exchange request sent.")))
  948. ((equal body "status")
  949. (reply (get-admin-status comp stripped)))
  950. ((equal body "connect")
  951. (handle-setup-user comp stripped))
  952. ((equal body "stop")
  953. (let ((conn (gethash stripped (component-whatsapps comp))))
  954. (when (remhash stripped (component-whatsapps comp))
  955. (reply "WhatsApp connections disabled."))
  956. (when conn
  957. (whatscl::close-connection conn))))
  958. ((equal body "full-history-fetch")
  959. (if *history-fetches-enabled*
  960. (let ((conn (gethash stripped (component-whatsapps comp))))
  961. (if conn
  962. (let ((chats (get-user-groupchats uid)))
  963. (reply (format nil "Fetching full chat history for ~A groupchats. This will probably take a long time.~%Note that even after completion is reported, some background media uploading may be in progress.~%If the WhatsApp connection is interrupted midway through the fetch, you will need to retry the fetch."
  964. (length chats)))
  965. (bt:make-thread
  966. (lambda ()
  967. (loop
  968. for (localpart . subject) in chats
  969. do (progn
  970. (with-wa-handler-context (comp conn stripped)
  971. (do-chat-history-request comp conn stripped uid (whatsxmpp-localpart-to-wa-jid localpart)))
  972. (sleep 0.1))))
  973. :name "whatsxmpp chat history fetcher"))
  974. (reply "You're not connected to WhatsApp.")))
  975. (reply "Full history fetching is not enabled for this bridge. Please contact the bridge administrator.")))
  976. ((equal body "refresh-chats")
  977. (let ((conn (gethash stripped (component-whatsapps comp))))
  978. (if conn
  979. (let ((chats (get-user-groupchats uid)))
  980. (reply (format nil "Refreshing metadata for ~A groupchats...~%When the metadata refresh is complete, you'll need to rejoin all of your groupchats (most easily accomplished by reconnecting yourself to XMPP)."
  981. (length chats)))
  982. (loop
  983. for (localpart . subject) in chats
  984. do (request-wa-chat-metadata comp conn stripped localpart)))
  985. (reply "You're not connected to WhatsApp."))))
  986. ((uiop:string-prefix-p "refresh-chat " body)
  987. (let ((conn (gethash stripped (component-whatsapps comp)))
  988. (localpart-to-use (subseq body #.(length "refresh-chat "))))
  989. (if conn
  990. (progn
  991. (reply (format nil "Refreshing metadata for ~A..." localpart-to-use))
  992. (request-wa-chat-metadata comp conn stripped localpart-to-use))
  993. (reply "You're not connected to WhatsApp."))))
  994. ((uiop:string-prefix-p "force-unregister " body)
  995. (let ((jid-to-use (subseq body #.(length "force-unregister "))))
  996. (if (jid-admin-p stripped)
  997. (let ((uid-to-use (get-user-id jid-to-use)))
  998. (if uid-to-use
  999. (progn
  1000. (unregister-user comp uid-to-use)
  1001. (reply "User unregistered and data deleted."))
  1002. (reply "That user couldn't be found.")))
  1003. (reply "You are not a bridge administrator."))))
  1004. (t
  1005. (reply "Unknown command. Try `help` for a list of supported commands."))))))
  1006. (defun whatsxmpp-vcard-temp-handler (comp &key to from &allow-other-keys)
  1007. "Handles a vcard-temp IQ request."
  1008. (format *debug-io* "~&vcard-temp: ~A (from ~A)~%" to from)
  1009. (with-component-data-lock (comp)
  1010. (let* ((uid (get-user-id from))
  1011. (to-localpart (nth-value 1 (parse-jid to))))
  1012. (multiple-value-bind (name avatar-data)
  1013. (cond
  1014. ((equal to-localpart "admin")
  1015. "whatsxmpp admin")
  1016. ((not uid)
  1017. (error 'stanza-error
  1018. :defined-condition "registration-required"
  1019. :text "You must register with the bridge admin to view contact details."
  1020. :type "auth"))
  1021. (t
  1022. (let ((name (get-contact-name uid to-localpart)))
  1023. (unless name
  1024. (error 'stanza-error
  1025. :defined-condition "item-not-found"
  1026. :text "No vCard for that JID is available at this time."
  1027. :type "modify"))
  1028. (values name
  1029. (nth-value 1 (get-contact-avatar-data uid to-localpart))))))
  1030. `((cxml:with-element "vCard"
  1031. (cxml:attribute "xmlns" +vcard-temp-ns+)
  1032. (cxml:with-element "FN"
  1033. (cxml:text ,name))
  1034. (cxml:with-element "NICKNAME"
  1035. (cxml:text ,name))
  1036. ,(when avatar-data
  1037. `(cxml:with-element "PHOTO"
  1038. (cxml:with-element "TYPE"
  1039. (cxml:text "image/jpeg"))
  1040. (cxml:with-element "BINVAL"
  1041. (cxml:text ,(qbase64:encode-bytes avatar-data)))))))))))
  1042. (defun handle-muc-join (comp jid muc-localpart muc-chatid roomnick)
  1043. "Handles JID joining MUC-LOCALPART."
  1044. (format *debug-io* "~&~A joining MUC ~A with roomnick ~A~%" jid muc-localpart roomnick)
  1045. (let ((muc-jid (concatenate 'string muc-localpart "@" (component-name comp))))
  1046. (with-prepared-statements
  1047. ((get-subject-stmt "SELECT subject FROM user_chats WHERE id = ?")
  1048. (get-resource-stmt "SELECT user_resource FROM user_chats WHERE id = ?")
  1049. (update-resource-stmt "UPDATE user_chats SET user_resource = ? WHERE id = ?")
  1050. (get-members-stmt "SELECT id, wa_jid, resource, affiliation FROM user_chat_members WHERE chat_id = ?")
  1051. (update-member-resource-stmt "UPDATE user_chat_members SET resource = ? WHERE id = ?")
  1052. (insert-joined-stmt "INSERT INTO user_chat_joined (chat_id, jid) VALUES (?, ?) ON CONFLICT DO NOTHING"))
  1053. (labels
  1054. ((send-presence (from-resource from-jid affiliation role &rest stati)
  1055. (with-presence (comp jid :from (concatenate 'string muc-jid "/" from-resource))
  1056. (cxml:with-element "x"
  1057. (cxml:attribute "xmlns" +muc-user-ns+)
  1058. (cxml:with-element "item"
  1059. (cxml:attribute "jid" from-jid)
  1060. (cxml:attribute "affiliation" affiliation)
  1061. (cxml:attribute "role" role))
  1062. (loop
  1063. for status in stati
  1064. do (cxml:with-element "status"
  1065. (cxml:attribute "code" status)))))))
  1066. ;; step 0: if there's already a roomnick set, we gotta use that one to avoid confusion
  1067. ;; (this restriction will be relaxed in later versions)
  1068. (bind-parameters get-resource-stmt muc-chatid)
  1069. (assert (sqlite:step-statement get-resource-stmt))
  1070. (let* ((old-roomnick (first (column-values get-resource-stmt)))
  1071. (new-roomnick roomnick)
  1072. (roomnick (if (and old-roomnick (> (length old-roomnick) 0))
  1073. old-roomnick new-roomnick)))
  1074. ;; step 1: send in-room presence from other occupants
  1075. (bind-parameters get-members-stmt muc-chatid)
  1076. (loop
  1077. while (sqlite:step-statement get-members-stmt)
  1078. do (with-bound-columns (memid mem-localpart resource affiliation) get-members-stmt
  1079. (let ((resource-to-use (if (equal resource roomnick)
  1080. (concatenate 'string resource " [WA]")
  1081. resource)))
  1082. (unless (equal resource-to-use resource)
  1083. ;; prevent conflicts with the user's chosen roomnick
  1084. (bind-parameters update-member-resource-stmt resource-to-use memid)
  1085. (sqlite:step-statement update-member-resource-stmt)
  1086. (sqlite:reset-statement update-member-resource-stmt))
  1087. (send-presence resource-to-use
  1088. (concatenate 'string
  1089. mem-localpart
  1090. "@"
  1091. (component-name comp))
  1092. affiliation
  1093. (if (equal affiliation "member") "participant" "moderator")))))
  1094. ;; step 2: send self-presence
  1095. (if (equal old-roomnick new-roomnick)
  1096. (send-presence roomnick jid "member" "participant" "100" "110")
  1097. ;; 210 means "we forced what your nick was for you"
  1098. (send-presence roomnick jid "member" "participant" "100" "110" "210"))
  1099. ;; step 3: send subject
  1100. (bind-parameters get-subject-stmt muc-chatid)
  1101. (assert (sqlite:step-statement get-subject-stmt))
  1102. (with-bound-columns (subject) get-subject-stmt
  1103. (with-message (comp jid
  1104. :from muc-jid
  1105. :type "groupchat")
  1106. (cxml:with-element "subject"
  1107. (cxml:text subject))))
  1108. ;; step 4: update resource & joined information if required
  1109. (bind-parameters update-resource-stmt roomnick muc-chatid)
  1110. (sqlite:step-statement update-resource-stmt)
  1111. (bind-parameters insert-joined-stmt muc-chatid jid)
  1112. (sqlite:step-statement insert-joined-stmt))))))
  1113. (defun whatsxmpp-presence-unavailable-handler (comp &key from to &allow-other-keys)
  1114. "Handles a presence unavailable broadcast."
  1115. (with-component-data-lock (comp)
  1116. (multiple-value-bind (to-hostname to-localpart)
  1117. (parse-jid to)
  1118. (declare (ignore to-hostname))
  1119. (let* ((stripped (strip-resource from))
  1120. (uid (get-user-id stripped))
  1121. (chat-id (get-user-chat-id uid to-localpart)))
  1122. (when (and uid (uiop:string-prefix-p "g" to-localpart))
  1123. (format *debug-io* "~&~A muc-presence-unavailable: ~A~%" from to)
  1124. (when chat-id
  1125. (with-prepared-statements
  1126. ((remove-joined-stmt "DELETE FROM user_chat_joined WHERE chat_id = ? AND jid = ?"))
  1127. (bind-parameters remove-joined-stmt chat-id from)
  1128. (sqlite:step-statement remove-joined-stmt))))))))
  1129. (defun whatsxmpp-presence-handler (comp &key from to type id stanza &allow-other-keys)
  1130. "Handles a presence broadcast."
  1131. (unless (or (not type) (eql (length type) 0))
  1132. (return-from whatsxmpp-presence-handler))
  1133. (with-component-data-lock (comp)
  1134. (multiple-value-bind (to-hostname to-localpart to-resource)
  1135. (parse-jid to)
  1136. (declare (ignore to-hostname))
  1137. (let* ((stripped (strip-resource from))
  1138. (uid (get-user-id stripped))
  1139. (x-element (get-node-with-xmlns (child-elements stanza) +muc-ns+)))
  1140. (cond
  1141. (x-element
  1142. (handler-case
  1143. (progn
  1144. (format *debug-io* "~&~A muc-presence: ~A~%" from to)
  1145. (unless uid
  1146. (error 'stanza-error
  1147. :defined-condition "registration-required"
  1148. :text "You must register to join MUCs via this bridge."
  1149. :type "auth"))
  1150. (let ((chat-id (get-user-chat-id uid to-localpart)))
  1151. (unless chat-id
  1152. (error 'stanza-error
  1153. :defined-condition "item-not-found"
  1154. :text "Couldn't find a WhatsApp chat with that JID."
  1155. :type "modify"))
  1156. (unless to-resource
  1157. (error 'stanza-error
  1158. :defined-condition "jid-malformed"
  1159. :text "Please specify a room nickname."
  1160. :type "modify"))
  1161. (handle-muc-join comp from to-localpart chat-id to-resource)))
  1162. (stanza-error (e)
  1163. (send-stanza-error comp
  1164. :stanza-type "presence"
  1165. :id id :to from :from to
  1166. :e e))))
  1167. ((and uid (string-equal type "available"))
  1168. (let ((conn (gethash stripped (component-whatsapps comp))))
  1169. (when conn
  1170. (format *debug-io* "~&sending available presence for ~A~%" stripped)
  1171. (whatscl::send-presence conn :available))))
  1172. (t nil))))))
  1173. (defun whatsxmpp-presence-probe-handler (comp &key from to id &allow-other-keys)
  1174. "Handles presence probe requests."
  1175. (with-component-data-lock (comp)
  1176. (multiple-value-bind (to-hostname to-localpart)
  1177. (parse-jid to)
  1178. (declare (ignore to-hostname))
  1179. (format *debug-io* "~&presence probe to: ~A from: ~A~%" to from)
  1180. (let* ((stripped (strip-resource from))
  1181. (uid (get-user-id stripped))
  1182. (conn (gethash stripped (component-whatsapps comp))))
  1183. (flet ((respond-with-unavailable ()
  1184. (with-presence (comp from
  1185. :from to
  1186. :type "unavailable"
  1187. :id id))))
  1188. (cond
  1189. ((equal to-localpart "admin")
  1190. (multiple-value-bind (admin-status admin-show)
  1191. (get-admin-status comp stripped)
  1192. (admin-presence comp from admin-status admin-show)))
  1193. ((or (not uid) (not conn)) (respond-with-unavailable))
  1194. ((get-contact-name uid to-localpart)
  1195. (handle-wa-contact-presence comp conn stripped to-localpart
  1196. :destination from))
  1197. (t (respond-with-unavailable))))))))
  1198. (defun whatsxmpp-presence-subscribe-handler (comp &key from to id &allow-other-keys)
  1199. "Handles a presence subscription request."
  1200. (with-component-data-lock (comp)
  1201. (multiple-value-bind (to-hostname to-localpart)
  1202. (parse-jid to)
  1203. (declare (ignore to-hostname))
  1204. (format *debug-io* "~&presence subscribe from: ~A~%" from)
  1205. (if (or (equal to-localpart "admin") (whatsxmpp-localpart-to-wa-jid to-localpart))
  1206. (with-presence (comp (strip-resource from)
  1207. :from to
  1208. :type "subscribed"))
  1209. (send-stanza-error comp
  1210. :stanza-type "presence"
  1211. :id id :to from :from to
  1212. :e (make-condition 'stanza-error
  1213. :defined-condition "item-not-found"
  1214. :text "That user's JID isn't in a recognizable format."
  1215. :type "modify"))))))
  1216. (defun whatsxmpp-chat-state-handler (comp &key from to type &allow-other-keys)
  1217. "Handles a chat state sent to the whatsxmpp bridge."
  1218. (with-component-data-lock (comp)
  1219. (multiple-value-bind (to-hostname to-localpart)
  1220. (parse-jid to)
  1221. (declare (ignore to-hostname))
  1222. (format *debug-io* "~&chat state: ~A is ~A to ~A~%" from type to)
  1223. (let* ((stripped (strip-resource from))
  1224. (uid (get-user-id stripped))
  1225. (conn (gethash stripped (component-whatsapps comp)))
  1226. (wa-jid (whatsxmpp-localpart-to-wa-jid to-localpart))
  1227. (presence-type
  1228. (cond
  1229. ((string= type "composing") :composing)
  1230. ((string= type "paused") :paused)
  1231. ((string= type "active") :available)
  1232. ((string= type "gone") :unavailable)
  1233. (t (return-from whatsxmpp-chat-state-handler)))))
  1234. (unless uid
  1235. (warn "Got chat state for user that isn't registered")
  1236. (return-from whatsxmpp-chat-state-handler))
  1237. (unless wa-jid
  1238. (return-from whatsxmpp-chat-state-handler))
  1239. (unless conn
  1240. (warn "Can't send chat state, since user connection is offline")
  1241. (return-from whatsxmpp-chat-state-handler))
  1242. (whatscl::send-presence conn presence-type
  1243. (unless (or (eql presence-type :available)
  1244. (eql presence-type :unavailable))
  1245. wa-jid))))))
  1246. (defun whatsxmpp-marker-handler (comp &key from to type marker-id id &allow-other-keys)
  1247. "Handles a message marker sent to the whatsxmpp bridge."
  1248. (with-component-data-lock (comp)
  1249. (multiple-value-bind (to-hostname to-localpart)
  1250. (parse-jid to)
  1251. (declare (ignore to-hostname))
  1252. (format *debug-io* "~&marker: ~A on ~A from ~A~%" type marker-id from)
  1253. (unless (equal type "displayed")
  1254. (return-from whatsxmpp-marker-handler))
  1255. (let* ((stripped (strip-resource from))
  1256. (uid (get-user-id stripped))
  1257. (conn (gethash stripped (component-whatsapps comp)))
  1258. (wa-jid (whatsxmpp-localpart-to-wa-jid to-localpart)))
  1259. (unless uid
  1260. (warn "Got marker for user that isn't registered")
  1261. (return-from whatsxmpp-marker-handler))
  1262. (unless wa-jid
  1263. (return-from whatsxmpp-marker-handler))
  1264. (unless conn
  1265. (warn "Can't send marker, since user connection is offline")
  1266. (send-stanza-error comp
  1267. :id id :from to :to from
  1268. :stanza-type "message"
  1269. :e (make-condition 'stanza-error
  1270. :defined-condition "recipient-unavailable"
  1271. :text "Can't process chat marker: you're currently not connected to WhatsApp."
  1272. :type "wait"))
  1273. (return-from whatsxmpp-marker-handler))
  1274. (let ((wa-msgid (lookup-xmpp-msgid uid marker-id)))
  1275. (if wa-msgid
  1276. (progn
  1277. (format *debug-io* "~&marking read for ~A: ~A from ~A~%" stripped wa-msgid wa-jid)
  1278. (whatscl::send-message-read conn wa-jid wa-msgid))
  1279. (warn "Got marker for unknown XMPP message ID ~A" marker-id)))))))
  1280. (defun whatsxmpp-message-handler (comp &key from to body id oob-url &allow-other-keys)
  1281. "Handles a message sent to the whatsxmpp bridge."
  1282. (with-component-data-lock (comp)
  1283. (multiple-value-bind (to-hostname to-localpart to-resource)
  1284. (parse-jid to)
  1285. (declare (ignore to-hostname))
  1286. (format *debug-io* "~&message from: ~A~%" from)
  1287. (let* ((stripped (strip-resource from))
  1288. (uid (get-user-id stripped))
  1289. (conn (gethash stripped (component-whatsapps comp)))
  1290. (wa-jid (whatsxmpp-localpart-to-wa-jid to-localpart))
  1291. (user-resource (get-user-chat-resource uid to-localpart)))
  1292. (labels
  1293. ((send-error (e)
  1294. (send-stanza-error comp
  1295. :stanza-type "message"
  1296. :id id :to from :from to
  1297. :e e)))
  1298. (cond
  1299. ((equal to-localpart "admin")
  1300. (handle-admin-command comp from body uid))
  1301. ((not uid)
  1302. (send-error (make-condition 'stanza-error
  1303. :defined-condition "registration-required"
  1304. :text "You must register to use this bridge."
  1305. :type "auth")))
  1306. ((not wa-jid)
  1307. (send-error (make-condition 'stanza-error
  1308. :defined-condition "item-not-found"
  1309. :text "That user's JID isn't in a recognizable format."
  1310. :type "modify")))
  1311. ((or (not conn) (not (whatscl::wac-jid conn)))
  1312. (send-error (make-condition 'stanza-error
  1313. :defined-condition "recipient-unavailable"
  1314. :text "You're currently not connected to WhatsApp."
  1315. :type "wait")))
  1316. ((and to-resource (uiop:string-prefix-p "g" to-localpart))
  1317. (send-error (make-condition 'stanza-error
  1318. :defined-condition "feature-not-implemented"
  1319. :text "MUC PMs are (deliberately) not implemented. Message the user directly instead."
  1320. :type "cancel")))
  1321. (t
  1322. (let* ((content-to-send (if oob-url
  1323. (maybe-upload-whatsapp-media conn oob-url)
  1324. (promisify body)))
  1325. (callback (lambda (conn result)
  1326. (wa-handle-message-send-result comp conn stripped
  1327. :orig-from from
  1328. :orig-to to
  1329. :orig-id id
  1330. :orig-body body
  1331. :muc-resource user-resource
  1332. :result result))))
  1333. (catcher
  1334. (attach
  1335. content-to-send
  1336. (lambda (content)
  1337. (let ((msgid
  1338. (etypecase content
  1339. (whatscl::message-contents-image (whatscl::send-simple-image-message conn wa-jid content callback))
  1340. (string (whatscl::send-simple-text-message conn wa-jid content callback)))))
  1341. (whatscl::send-presence conn :available)
  1342. (insert-user-message uid id msgid))))
  1343. (t (e)
  1344. (format *error-output* "~&failed to send message! ~A~%" e)
  1345. (send-error (make-condition 'stanza-error
  1346. :defined-condition "internal-server-error"
  1347. :text (princ-to-string e)
  1348. :type "wait"))))))))))))
  1349. (defun whatsxmpp-load-users (comp)
  1350. (with-component-data-lock (comp)
  1351. (with-prepared-statement
  1352. (stmt "SELECT jid FROM users;")
  1353. (loop
  1354. while (sqlite:step-statement stmt)
  1355. do (with-bound-columns (jid) stmt
  1356. (setf (gethash jid (component-whatsapps comp)) nil))))))
  1357. (defun register-whatsxmpp-handlers (comp)
  1358. (register-component-iq-handler comp :disco-info #'disco-info-handler)
  1359. (register-component-iq-handler comp :vcard-temp-get #'whatsxmpp-vcard-temp-handler)
  1360. (register-component-iq-handler comp :disco-items #'disco-items-handler)
  1361. (register-component-iq-handler comp :mam-query #'whatsxmpp-mam-query-handler)
  1362. (register-component-iq-handler comp :ping #'whatsxmpp-ping-handler))
  1363. (defun whatsxmpp-init ()
  1364. "Initialise the whatsxmpp bridge."
  1365. (connect-database)
  1366. (with-prepared-statement
  1367. (config "SELECT server, port, component_name, shared_secret, upload_component_name, allow_archiving, allow_history_fetches FROM configuration WHERE rev = 1")
  1368. (assert (sqlite:step-statement config) () "No configuration in database!")
  1369. (destructuring-bind (server port component-name shared-secret upload-name allow-archiving allow-history-fetches)
  1370. (column-values config)
  1371. (let* ((comp (make-component server port shared-secret component-name))
  1372. (ret (change-class comp 'whatsxmpp-component
  1373. :upload-component-name upload-name)))
  1374. (setf *archiving-enabled* (not (eql allow-archiving 0)))
  1375. (when *archiving-enabled*
  1376. (format *debug-io* "~&[!] WARNING: Archiving of user messages is enabled. If you're running a public bridge, this has potential privacy implications!~%"))
  1377. (setf *history-fetches-enabled* (not (eql allow-history-fetches 0)))
  1378. (when *history-fetches-enabled*
  1379. (format *debug-io* "~&[!] WARNING: Full history fetches are enabled. Letting any user initiate a full history fetch is a potential Denial of Service vector!~%"))
  1380. (on :text-message ret (lambda (&rest args)
  1381. (apply #'whatsxmpp-message-handler ret args)))
  1382. (on :message-marker ret (lambda (&rest args)
  1383. (apply #'whatsxmpp-marker-handler ret args)))
  1384. (on :presence-subscribe ret (lambda (&rest args)
  1385. (apply #'whatsxmpp-presence-subscribe-handler ret args)))
  1386. (on :presence-probe ret (lambda (&rest args)
  1387. (apply #'whatsxmpp-presence-probe-handler ret args)))
  1388. (on :presence-unavailable ret (lambda (&rest args)
  1389. (apply #'whatsxmpp-presence-unavailable-handler ret args)))
  1390. (on :presence ret (lambda (&rest args)
  1391. (apply #'whatsxmpp-presence-handler ret args)))
  1392. (on :chat-state ret (lambda (&rest args)
  1393. (apply #'whatsxmpp-chat-state-handler ret args)))
  1394. (register-whatsxmpp-handlers ret)
  1395. (whatsxmpp-load-users ret)
  1396. (setf (component-reconnect-timer ret) (trivial-timers:make-timer
  1397. (lambda () (wa-resetup-users ret))
  1398. :name "reconnection timer"))
  1399. (on :connected ret (lambda () (wa-resetup-users ret)))
  1400. ret))))
  1401. #+sbcl
  1402. (defparameter *comp* nil)
  1403. #+sbcl
  1404. (defun report-error-and-die (err)
  1405. (format *error-output* "[!] Fatal error, bridge aborting!~%")
  1406. (trivial-backtrace:print-backtrace err
  1407. :output *error-output*)
  1408. (loop
  1409. for thr in (bt:all-threads)
  1410. do (progn
  1411. (format *error-output* "[!] State of thread ~A:~%" thr)
  1412. (sb-thread:interrupt-thread thr (lambda ()
  1413. (sb-debug:print-backtrace
  1414. :stream *error-output*)))))
  1415. (sb-ext:exit :code 1 :abort t))
  1416. #+sbcl
  1417. (defun main ()
  1418. "Hacky main() function for running this in 'the real world' (outside emacs)"
  1419. (setf *debugger-hook* (lambda (condition hook)
  1420. (declare (ignore hook))
  1421. (report-error-and-die condition)))
  1422. (when (< (length sb-ext:*posix-argv*) 2)
  1423. (format *error-output* "fatal: a path to the database must be provided~%")
  1424. (format *error-output* "usage: ~A DATABASE_PATH~%" (elt sb-ext:*posix-argv* 0))
  1425. (sb-ext:exit :code 2 :abort t))
  1426. (let ((*default-database-path* (elt sb-ext:*posix-argv* 1)))
  1427. (format t "[*] whatsxmpp version ~A / an eta project <https://theta.eu.org>~%" +version+)
  1428. (format t "[+] Using database at ~A~%" *default-database-path*)
  1429. #+use-swank
  1430. (block nil
  1431. (format t "[+] Starting SWANK server~%")
  1432. (setf swank:*configure-emacs-indentation* nil)
  1433. (swank:create-server :dont-close t))
  1434. (format t "[+] Initializing bridge~%")
  1435. (setf *comp* (whatsxmpp-init))
  1436. (on :error *comp* (lambda (e)
  1437. (report-error-and-die e)))
  1438. ;; don't pretty-print stuff with newlines
  1439. (setf *print-right-margin* most-positive-fixnum)
  1440. ;; We don't have anything better to do, so let's wait on a condition
  1441. ;; variable that'll never wake up.
  1442. (let ((lock (bt:make-lock))
  1443. (condvar (bt:make-condition-variable)))
  1444. (loop
  1445. (bt:with-lock-held (lock)
  1446. (bt:condition-wait condvar lock))))))
  1447. #+use-swank
  1448. (uiop:register-image-dump-hook
  1449. (lambda ()
  1450. (swank-loader:init
  1451. :load-contribs t
  1452. :reload t)
  1453. (swank:swank-require '("SWANK-FANCY-INSPECTOR" "SWANK-FUZZY" "SWANK-MACROSTEP" "SWANK-PRESENTATIONS"
  1454. "SWANK-REPL" "SWANK-PACKAGE-FU" "SWANK-TRACE-DIALOG" "SWANK-INDENTATION"
  1455. "SWANK-SBCL-EXTS" "SWANK-ARGLISTS" "SWANK-C-P-C" "SWANK-UTIL" "SB-CLTL2"
  1456. "SB-INTROSPECT" "SB-BSD-SOCKETS" "SB-POSIX" "ASDF" "asdf" "UIOP" "uiop"))))