Files
emacs-mattermost/lisp/mattermost-protocol.el
T
Ivan I. Ovchinnikov 612456334f feat(ui): working vertical slice — dashboard, channel view, send
- mattermost-dashboard-mode: list channels from bridge
- mattermost-channel-mode: view history and send messages
- Interactive connection prompt (password in memory only)
- Fix JSON array parsing (vectors → lists) in protocol layer
- Add mattermost-reset-state for clean reconnects
- Add dev-check.sh for quick Rust validation
- Verified end-to-end: Emacs → Bridge → Mattermost → back
2026-11-21 09:03:19 +03:00

93 lines
4.0 KiB
EmacsLisp

;;; mattermost-protocol.el --- TCP JSONL protocol handler -*- lexical-binding: t; -*-
(require 'json)
(require 'mattermost-custom)
(defvar mattermost--process nil
"The process object for the bridge connection.")
(defvar mattermost--pending-requests (make-hash-table :test 'equal)
"Hash table of pending requests indexed by ID.")
(defvar mattermost--input-buffer ""
"Accumulator for incomplete TCP chunks.")
(defun mattermost-connect-to-bridge ()
"Connect to the running Rust bridge."
(interactive)
(when (and (boundp 'mattermost--process) mattermost--process (process-live-p mattermost--process))
(delete-process mattermost--process))
(setq mattermost--process
(open-network-stream
"mattermost-bridge"
"*mattermost-log*"
mattermost-bridge-host
mattermost-bridge-port))
;; Очищаем буфер при новом подключении
(setq mattermost--input-buffer "")
(set-process-filter mattermost--process #'mattermost--process-filter)
(message "[MM-PROTOCOL] Connected to Mattermost bridge."))
(defun mattermost--process-filter (_proc output)
"Handle OUTPUT from the bridge process with proper chunk buffering."
;; Добавляем новые данные к накопителю
(setq mattermost--input-buffer (concat mattermost--input-buffer output))
;; Разбиваем по переносам строк
(let ((lines (split-string mattermost--input-buffer "\n" t)))
;; Последняя строка может быть неполной — сохраняем её на следующий вызов
(if (string-suffix-p "\n" output)
(setq mattermost--input-buffer "")
(setq mattermost--input-buffer (car (last lines)))
;; Убираем последний (неполный) элемент из списка для обработки
(setq lines (butlast lines)))
(dolist (line lines)
;; ДОБАВЛЕНО: :array-type 'list чтобы JSON-массивы становились списками, а не векторами
(let ((msg (ignore-errors (json-parse-string line :object-type 'plist :array-type 'list))))
(if msg
(let ((id (plist-get msg :id))
(type (plist-get msg :type)))
(cond
((string= type "response")
(let ((cb (gethash id mattermost--pending-requests)))
(if cb
(progn
(funcall cb msg)
(remhash id mattermost--pending-requests))
(message "[MM-PROTOCOL] WARNING: No callback for id=%s" id))))
((string= type "event")
(mattermost--handle-event msg))))
(message "[MM-PROTOCOL] Failed to parse JSON: %S"
(substring line 0 (min 100 (length line)))))))))
(defun mattermost--send-request (method params callback)
"Send a request with METHOD and PARAMS, calling CALLBACK on response."
(let* ((id (format "req-%d" (random 100000)))
;; 1. Создаем реальный payload для отправки
(payload (list :id id :type "request" :method method :params params))
(json-str (concat (json-encode payload) "\n"))
;; 2. Создаем копию ТОЛЬКО для логирования
(safe-params (copy-tree params)))
;; Маскируем пароль в копии для лога
(when (plist-get safe-params :password)
(plist-put safe-params :password "***MASKED***"))
(let ((safe-payload (list :id id :type "request" :method method :params safe-params)))
(message "[MM-PROTOCOL] Sending request id=%s method=%s" id method))
(puthash id callback mattermost--pending-requests)
;; Отправляем реальный json-str с настоящим паролем!
(process-send-string mattermost--process json-str)))
(defun mattermost--handle-event (_msg)
"Handle an asynchronous event MSG from the bridge."
;; TODO: Fan out events to buffers
)
(provide 'mattermost-protocol)