Add internal user plist and use it to print usernames

This commit is contained in:
Miguel de la Cruz 2022-05-22 20:09:12 +02:00
parent c72317202f
commit a0a752d6bd

View file

@ -19,6 +19,15 @@
:group 'mattermost
:type 'string)
(defvar mattermost-users-plist '()
"A plist with the server users by id")
(defvar mattermost-token nil
"The user token to access the server")
(defvar mattermost-user-id nil
"The ID of the authenticated user")
(setq mattermost-server-url "https://chat.ctrlz.es")
;; ToDo: probably not the best way to get a keyword from a string
@ -34,6 +43,25 @@
(goto-char url-http-end-of-headers)
(json-read)))
(defun mattermost-print-post (post)
"Prints the post in the current buffer"
(let* ((msg (plist-get post :message))
;; ToDo: convert to a readable date
;; (update-at (plist-get post :update_at))
(user-id (plist-get post :user_id))
(user (mattermost--get-user user-id))
(username (plist-get user :username)))
(insert (format "[%s] %s\n" username msg))))
(defun mattermost--get-user (user-id)
"Returns the user from the internal cache or fetches it first"
(let* ((user-id-keyword (mattermost-string->keyword user-id))
(user (plist-get mattermost-users-plist user-id-keyword)))
(if (not user)
(let ((user (mattermost-get-user user-id)))
(setq mattermost-users-plist (plist-put mattermost-users-plist user-id-keyword user)))
user)))
;; ToDo: once mattermost-request parses headers, use it to fetch both
;; the user (set the id to a local var) and the headers (set the
;; token)
@ -47,7 +75,6 @@
(search-forward "Token: ")
(let ((token (word-at-point))
(response (mattermost-parse-json)))
;; ToDo: define these as local vars somehow
(setq mattermost-token token)
(setq mattermost-user-id (plist-get response :id))
token))))
@ -63,6 +90,10 @@
(with-current-buffer (url-retrieve-synchronously (concat mattermost-server-url "/api/v4" url) t)
(mattermost-parse-json))))
(defun mattermost-get-user (user-id)
"Returns the user information"
(mattermost-request "GET" (format "/users/%s" user-id)))
(defun mattermost-get-teams ()
"Returns the user's team list"
(mattermost-request "GET" "/teams"))
@ -94,19 +125,18 @@
channel-name
channel-display-name)))))))))
;; ToDo: remove
(setq msgs (mattermost-get-channel-messages "68w17u1da7yg7enayudjjqqwse"))
(car (plist-get msgs :posts))
(with-current-buffer (get-buffer-create "*Town Square*")
(erase-buffer)
(dolist (msgid (plist-get msgs :order))
(let* ((posts (plist-get msgs :posts))
(post (plist-get posts (mattermost-string->keyword msgid)))
(user-id (plist-get post :user_id))
(message (plist-get post :message))
(update-at (plist-get post :update_at)))
(insert (format "[%s %s] %s\n" user-id update-at message)))))
(let ((posts (plist-get msgs :posts))
(order (plist-get msgs :order)))
(dolist (msgid order)
(let* ((msgid-keyword (mattermost-string->keyword msgid))
(post (plist-get posts msgid-keyword)))
(mattermost-print-post post)))))
(provide 'mattermost)
;;; mattermost.el ends here