feat(bridge,ui): add list_channels API and interactive dashboard

- Add Channel model to mm-core
- Implement get_my_channels in mm-client
- Add list_channels handler and routing in mm-bridge
- Create mattermost-dashboard-mode with interactive connection prompt
- Add dev-check.sh script for quick Rust validation
This commit is contained in:
Ivan I. Ovchinnikov
2026-11-20 18:53:51 +03:00
parent f08289905d
commit 8e98a68906
15 changed files with 1341 additions and 422 deletions
+45
View File
@@ -0,0 +1,45 @@
;;; mattermost-custom.el --- Customization options for mattermost.el -*- lexical-binding: t; -*-
(defgroup mattermost nil
"Mattermost client for Emacs."
:group 'applications)
(defcustom mattermost-bridge-host "127.0.0.1"
"Host where the Mattermost bridge is listening."
:type 'string
:group 'mattermost)
(defcustom mattermost-bridge-port 8765
"Port where the Mattermost bridge is listening."
:type 'integer
:group 'mattermost)
(defcustom mattermost-thread-display 'separate-buffer
"How to display threads.
If `separate-buffer', open a new buffer for each thread.
If `inline', show replies in the main buffer."
:type '(choice (const separate-buffer)
(const inline))
:group 'mattermost)
(defcustom mattermost-server-url ""
"URL of your Mattermost server (e.g. https://mattermost.local)."
:type 'string
:group 'mattermost)
(defcustom mattermost-login-id ""
"Your Mattermost login ID or email."
:type 'string
:group 'mattermost)
(defcustom mattermost-password ""
"Your Mattermost password. Consider using auth-source instead for security."
:type 'string
:group 'mattermost)
(defcustom mattermost-server-id "work"
"Internal server identifier used for token storage."
:type 'string
:group 'mattermost)
(provide 'mattermost-custom)
+116
View File
@@ -0,0 +1,116 @@
;;; mattermost-dashboard.el --- Dashboard and channel list UI -*- lexical-binding: t; -*-
(require 'mattermost-custom)
(require 'mattermost-protocol)
(defvar mattermost--current-server-id nil
"Current server ID for the dashboard buffer.")
(defvar mattermost-dashboard-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "RET") #'mattermost-dashboard-open-channel)
(define-key map (kbd "g") #'mattermost-dashboard-refresh)
map)
"Keymap for `mattermost-dashboard-mode`.")
(define-derived-mode mattermost-dashboard-mode special-mode "Mattermost-Dashboard"
"Major mode for viewing Mattermost channels list.
\\{mattermost-dashboard-mode-map}"
(setq buffer-read-only t)
(setq truncate-lines t))
(defun mattermost-ensure-connected (callback)
"Ensure connection to the bridge, prompting for missing credentials.
Calls CALLBACK with server-id on success. Password is never saved to disk."
(let* ((url (if (string= mattermost-server-url "")
(read-string "Mattermost URL (e.g., https://mattermost.local): ")
mattermost-server-url))
(login (if (string= mattermost-login-id "")
(read-string "Login ID or Email: ")
mattermost-login-id))
(password (read-passwd "Password (or PAT token): "))
(server-id mattermost-server-id))
;; Сохраняем только не-секретные настройки, если они были пустыми
(when (string= mattermost-server-url "")
(customize-save-variable 'mattermost-server-url url))
(when (string= mattermost-login-id "")
(customize-save-variable 'mattermost-login-id login))
(message "[MM-DEBUG] Connecting to %s as %s (password masked)" url login)
(mattermost--send-request
"connect"
(list :server_id server-id
:url url
:login_id login
:password password)
(lambda (response)
(if (plist-get response :ok)
(progn
(message "[MM] Connected successfully.")
(funcall callback server-id))
(message "[MM] Connect failed: %S" (plist-get response :error)))))))
(defun mattermost-dashboard ()
"Open the Mattermost dashboard showing available channels."
(interactive)
(mattermost-ensure-connected
(lambda (server-id)
(mattermost--send-request
"list_channels"
(list :server_id server-id)
(lambda (response)
(if (plist-get response :ok)
(mattermost--render-dashboard
server-id
(plist-get (plist-get response :result) :channels))
(message "[MM] Failed to list channels: %S" (plist-get response :error))))))))
(defun mattermost--render-dashboard (server-id channels)
"Render CHANNELS in a new Mattermost Dashboard buffer."
(let ((buf (get-buffer-create "*Mattermost Dashboard*")))
(with-current-buffer buf
(erase-buffer)
(mattermost-dashboard-mode)
(setq-local mattermost--current-server-id server-id)
(setq-local mattermost--channels channels)
(insert "Mattermost Channels\n")
(insert "==================\n\n")
(dolist (ch channels)
(let ((name (or (plist-get ch :display_name) "Unknown"))
(type (or (plist-get ch :channel_type) "?"))
(id (plist-get ch :id)))
(insert (format "[%s] %s (ID: %s)\n" type name id))))
(goto-char (point-min)))
(switch-to-buffer buf)))
(defun mattermost-dashboard-refresh ()
"Refresh the channel list in the current dashboard buffer."
(interactive)
(let ((server-id mattermost--current-server-id))
(unless server-id
(error "No server ID associated with this buffer"))
(message "[MM-DEBUG] Refreshing channels...")
(mattermost--send-request
"list_channels"
(list :server_id server-id)
(lambda (response)
(if (plist-get response :ok)
(mattermost--render-dashboard
server-id
(plist-get (plist-get response :result) :channels))
(message "[MM] Refresh failed: %S" (plist-get response :error)))))))
(defun mattermost-dashboard-open-channel ()
"Open the channel under point."
(interactive)
(let ((line (thing-at-point 'line t)))
(if (string-match "ID: \\([a-z0-9]+\\)" line)
(let ((channel-id (match-string 1 line)))
(message "[MM] Opening channel: %s (TODO: implement channel buffer)" channel-id))
(message "[MM] No channel ID found on this line."))))
(provide 'mattermost-dashboard)
+234
View File
@@ -0,0 +1,234 @@
;;; mattermost-dm.el --- Direct Message handling -*- lexical-binding: t; -*-
(require 'mattermost-protocol)
(defvar mattermost-self-channel-id nil
"Channel ID for the current user's self-DM.")
(defvar mattermost-self-buffer nil
"Buffer showing the self-DM history.")
(defvar mattermost--oldest-post-id nil
"ID of the oldest loaded post, used for pagination.")
(defvar mattermost--history-limit 10
"Number of posts loaded per page.")
(defun mattermost-open-self-dm ()
"Open or switch to the Self-DM buffer. Auto-connects if needed."
(interactive)
(mattermost--ensure-connected))
(defun mattermost--ensure-connected ()
"Connect to bridge and Mattermost if not already connected, then open DM."
(mattermost-connect-to-bridge)
(if mattermost-self-channel-id
(progn
(mattermost-switch-to-self-dm)
(mattermost-load-history))
(let* ((env-pass (getenv "MM_PASSWORD"))
(url (or (and (stringp mattermost-server-url)
(not (string-empty-p mattermost-server-url))
mattermost-server-url)
(read-string "Mattermost URL: ")))
(login (or (and (stringp mattermost-login-id)
(not (string-empty-p mattermost-login-id))
mattermost-login-id)
(read-string "Login ID: ")))
(password (or (and (stringp mattermost-password)
(not (string-empty-p mattermost-password))
mattermost-password)
env-pass
(read-passwd "Password: "))))
(customize-save-variable 'mattermost-server-url url)
(customize-save-variable 'mattermost-login-id login)
(setq mattermost-password password)
(message "[MM] Connecting to %s as %s..." url login)
(mattermost--send-request
"connect"
(list :server_id mattermost-server-id
:url url
:login_id login
:password password)
#'mattermost--on-connect-response))))
(defun mattermost--on-connect-response (resp)
"Handle response from connect request."
(if (equal (plist-get resp :ok) t)
(progn
(message "[MM] Connected successfully!")
(mattermost-init-self-dm))
(let ((err (plist-get resp :error)))
(message "[MM] Connection FAILED: %s"
(if (listp err) (mm--extract err "message") err)))))
(defun mattermost-init-self-dm ()
"Request Self-DM channel from bridge."
(mattermost--send-request
"open_self_dm"
(list :server_id mattermost-server-id)
#'mattermost--on-self-dm-response))
(defun mattermost--on-self-dm-response (resp)
"Handle response from open_self_dm request."
(if (equal (plist-get resp :ok) t)
(let* ((result (plist-get resp :result))
(channel (plist-get result :channel))
(id (plist-get channel :id)))
(setq mattermost-self-channel-id id)
(mattermost-switch-to-self-dm)
(mattermost-load-history))
(message "[MM] Failed to open Self-DM: %s" (plist-get resp :error))))
(defun mattermost-switch-to-self-dm ()
"Switch to the Self-DM buffer."
(let ((buf-name "*Mattermost[work]/DM:self*"))
(setq mattermost-self-buffer (get-buffer-create buf-name))
(switch-to-buffer mattermost-self-buffer)
(mattermost-mode)))
(defun mattermost-load-history ()
"Load the latest page of self-DM history."
(interactive)
(unless (and mattermost-self-channel-id
(not (string-empty-p mattermost-self-channel-id)))
(user-error "No self-DM channel yet"))
(setq mattermost--oldest-post-id nil)
(mattermost--send-request
"get_history"
(list :server_id mattermost-server-id
:channel_id mattermost-self-channel-id
:limit mattermost--history-limit)
#'mattermost--on-history-response))
(defun mattermost-load-earlier ()
"Load the previous page of history (older messages)."
(interactive)
(unless mattermost--oldest-post-id
(user-error "Nothing loaded yet, or no earlier messages"))
(mattermost--send-request
"get_history"
(list :server_id mattermost-server-id
:channel_id mattermost-self-channel-id
:limit mattermost--history-limit
:before mattermost--oldest-post-id)
#'mattermost--on-earlier-response))
(defun mattermost--on-history-response (resp)
"Handle initial get_history response."
(if (equal (plist-get resp :ok) t)
(let ((posts (mm--extract (plist-get resp :result) "posts")))
(mattermost--render-history posts t))
(message "[MM] Failed to load history: %s" (plist-get resp :error))))
(defun mattermost--on-earlier-response (resp)
"Handle paginated get_history response."
(if (equal (plist-get resp :ok) t)
(let ((posts (mm--extract (plist-get resp :result) "posts")))
(if (and posts (> (length posts) 0))
(mattermost--render-history posts nil)
(message "[MM] No earlier messages")))
(message "[MM] Failed to load earlier: %s" (plist-get resp :error))))
(defun mattermost--render-history (posts initial)
"Render POSTS into the self-DM buffer.
If INITIAL, clear the buffer and render the whole page.
Otherwise prepend older posts under the header."
(unless (buffer-live-p mattermost-self-buffer)
(error "Self-DM buffer is gone"))
(with-current-buffer mattermost-self-buffer
(let ((inhibit-read-only t))
(if initial
(progn
(erase-buffer)
(mattermost--insert-header)
(dolist (post posts)
(mattermost--insert-post post))
;; oldest = first post of the ascending page
(when posts
(setq mattermost--oldest-post-id
(mm--extract (car posts) "id"))))
;; prepend: go to end of header line
(save-excursion
(goto-char (point-min))
(forward-line 1)
(let ((start (point)))
(dolist (post posts)
(mattermost--insert-post post))
(when posts
(setq mattermost--oldest-post-id
(mm--extract (car posts) "id")))))
(message "[MM] Loaded %d earlier messages" (length posts))))))
(defun mattermost--insert-header ()
"Insert buffer header."
(insert (format "*Mattermost[work]/DM:self* — %d latest messages\n"
mattermost--history-limit))
(insert "Press 'l' to load earlier messages, C-c C-c to send.\n\n"))
(defun mattermost--insert-post (post)
"Insert a single POST at point."
(let ((msg (mm--extract post "message"))
(user-id (mm--extract post "user_id"))
(files (mm--extract post "file_ids"))
(ts (mm--extract post "create_at")))
(insert (format "[%s] %s%s\n"
(mattermost--format-time ts)
msg
(if (and (listp files) (> (length files) 0))
(format " [+%d file(s)]" (length files))
"")))))
(defun mattermost--format-time (ms)
"Format epoch milliseconds MS as HH:MM."
(if (and (numberp ms) (> ms 0))
(format-time-string "%H:%M" (seconds-to-time (/ ms 1000)))
"??:??"))
;; ============================================================
;; УНИВЕРСАЛЬНАЯ ФУНКЦИЯ ИЗВЛЕЧЕНИЯ ДАННЫХ
;; ============================================================
(defun mm--extract (obj key)
"Safely extract KEY from OBJ, handling plists, alists (string/symbol), and hash tables."
(let ((key-sym (if (stringp key) (intern key) key))
(key-str (if (stringp key) key (symbol-name key)))
(key-kw (if (stringp key) (intern (concat ":" key)) (intern (concat ":" (symbol-name key))))))
(or (plist-get obj key-kw)
(plist-get obj key-sym)
(cdr (assq key-sym obj))
(cdr (assoc key-str obj))
(and (hash-table-p obj) (gethash key-str obj))
(and (hash-table-p obj) (gethash key-sym obj))
"[NOT FOUND]")))
;; ============================================================
(define-derived-mode mattermost-mode text-mode "Mattermost"
"Major mode for Mattermost chat buffers."
(setq-local comment-start "# ")
(setq buffer-read-only nil)
(local-set-key (kbd "C-c C-c") #'mattermost-send-message)
(local-set-key (kbd "l") #'mattermost-load-earlier))
(defun mattermost-send-message ()
"Send the current line as a message."
(interactive)
(unless mattermost-self-channel-id
(user-error "Not connected"))
(let ((msg (buffer-substring (line-beginning-position) (line-end-position))))
(mattermost--send-request
"send_post"
(list :server_id mattermost-server-id
:channel_id mattermost-self-channel-id
:message msg)
#'mattermost--on-send-response)))
(defun mattermost--on-send-response (_resp)
"Handle response after sending a message."
(with-current-buffer (or mattermost-self-buffer (current-buffer))
(let ((inhibit-read-only t))
(delete-region (line-beginning-position) (line-end-position))
(insert "\n"))))
(provide 'mattermost-dm)
+91
View File
@@ -0,0 +1,91 @@
;;; 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 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)
(let ((msg (ignore-errors (json-parse-string line :object-type 'plist))))
(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)
+8
View File
@@ -0,0 +1,8 @@
;;; mattermost.el --- Emacs client for Mattermost -*- lexical-binding: t; -*-
(require 'mattermost-custom)
(require 'mattermost-protocol)
(require 'mattermost-dm)
(require 'mattermost-dashboard)
(provide 'mattermost)