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.

1519 lines
79KB

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