forked from lokedhs/keybase-chat
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathkeybase-chat.el
More file actions
1427 lines (1273 loc) · 62.5 KB
/
Copy pathkeybase-chat.el
File metadata and controls
1427 lines (1273 loc) · 62.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
;;; keybase-chat --- Keybase chat implementation in Emacs -*- lexical-binding: t -*-
(require 'url)
(require 'subr-x)
(require 'notifications)
(require 'cl)
(require 'keybase-markup)
(defgroup keybase nil
"Keybase chat implementation"
:prefix 'keybase
:group 'applications)
(defcustom keybase--program "keybase"
"The name of the keybase binary"
:type 'string
:group 'keybase)
(defcustom keybase-attribution 'keybase-default-attribution
"A function that prints the attribution before each Keybase message.
It will be given two arguments, the timestamp of the message in seconds since
the epoch and the sender's keybase name."
:type 'function
:group 'keybase)
(defcustom keybase--datetime-format "%H:%M:%S"
"The datetime format used to convert timestamps"
:type 'string
:group 'keybase)
(defcustom keybase-channel-mode-hook nil
"Hook called by `keybase-channel-mode'"
:type 'hook
:group 'keybase)
(defface keybase-default
()
"Default face for chat buffers."
:group 'keybase)
(defface keybase-message-text-content
'((t
:inherit keybase-default))
"Face used to display the text content of messages."
:group 'keybase)
(defface keybase-message-text-content-bold
'((t
:weight bold
:inherit keybase-default))
"Face used to display bold text."
:group 'keybase)
(defface keybase-message-text-content-italics
'((t
:slant italic
:foreground "#00ff00"
:inherit keybase-default))
"Face used to display italics text."
:group 'keybase)
(defface keybase-message-text-content-in-progress
'((((class color))
:foreground "#505050"
:inherit keybase-default)
(t
:inherit keybase-default))
"Face used to display the text content of a message that has
not been confirmed from the server yet.")
(defface keybase-message-from
'((((class color))
:foreground "#00b000"
:inherit keybase-default)
(t
:inherit keybase-default))
"Face used to display the 'from' part of a message."
:group 'keybase)
(defface keybase-reply
'((((class color))
;; :foreground "#00b000"
:inherit keybase-default)
(t
:inherit keybase-default))
"Face used to display the 'from' part of a message."
:group 'keybase)
(defface keybase-channel-summary-title
'((t
:weight bold
:inherit keybase-default))
"Face used to display the headlines in the channel list."
:group 'keybase)
(defface keybase-channel-summary-team
'((t
:weight bold
:inherit keybase-default))
"Face used to display the team name in the channel list"
:group 'keybase)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Utilities
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defun keybase-message-text-content-code-face ()
"Return a face with a verbatim look, using the current foreground and background colors."
(let ((fg (face-attribute 'default :foreground))
(bg (face-attribute 'default :background)))
;; adjust the colors slightly to give the face a verbatim look
(setq fg (color-darken-name fg 10))
(setq bg (color-lighten-name bg 10))
`((((class color))
:foreground ,fg
:background ,bg
:family "DejaVu Sans Mono" ; use a font that is commonly used for code
:inherit keybase-default)
(t
:inherit keybase-default))))
(cl-defun keybase--json-find (obj path &key (error-if-missing t))
;; (print path)
;; (print obj)
(let ((curr obj))
(loop for path-entry in path
for node = (assoc path-entry curr)
unless node
do (if error-if-missing
(error "Node not found in json: %S" path-entry)
(return nil))
do (setq curr (cdr node))
finally (return curr))))
(cl-defmacro keybase--with-json-bind ((&rest defs) json &body body)
(declare (indent 2))
(let ((json-sym (gensym "json")))
`(let ((,json-sym ,json))
(let ,(loop for (sym path) in defs
collect `(,sym (keybase--json-find ,json-sym ',path)))
,@body))))
(cl-defmacro keybase--ensure-hash-value (key hash &body body)
(let ((hash-sym (gensym))
(key-sym (gensym))
(val-sym (gensym))
(default-value-sym (gensym)))
`(let* ((,hash-sym ,hash)
(,key-sym ,key)
(,val-sym (gethash ,key-sym ,hash-sym ',default-value-sym)))
(if (eq ,val-sym ',default-value-sym)
(let ((,val-sym (progn ,@body)))
(setf (gethash ,key-sym ,hash-sym) ,val-sym)
,val-sym)
;; ELSE: The value was found in the hash table
,val-sym))))
(defun keybase--json-parse-result-buffer ()
(let* ((content (buffer-substring (point) (point-max)))
(decoded-content (decode-coding-string content 'utf-8)))
(json-read-from-string decoded-content)))
(defun keybase--url-handler (status buffer callback as-json-p)
(let ((error-status (getf status :error)))
(if error-status
(progn
(message "Got error: %S" status)
(let ((kill-buffer-query-functions nil))
(kill-buffer (current-buffer)))
(signal (car error-status) (cdr error-status)))
;; ELSE: No error
(progn
(goto-char (point-min))
(search-forward "\n\n")
(let ((data (if as-json-p
(potato--keybase-parse-result-buffer)
(buffer-substring (point) (point-max)))))
(with-current-buffer buffer
(funcall callback data))
(let ((kill-buffer-query-functions nil))
(kill-buffer (current-buffer))))))))
(cl-defun keybase--url-retrieve (url method callback &key (as-json-p t) ignore-response)
(let ((buffer (current-buffer)))
(let ((url-request-method method))
(url-retrieve url
(lambda (status)
(unless ignore-response
(keybase--url-handler status buffer callback as-json-p)))
nil t))))
(defun keybase--insert-image-handler (overlay data)
(let ((image (create-image data nil t))
(start (overlay-start overlay))
(end (overlay-end overlay)))
(delete-overlay overlay)
(save-excursion
(let ((inhibit-read-only t))
(goto-char start)
(delete-region start end)
(let ((start (point)))
(insert-image image "[image]"))))))
(defun keybase--insert-image-url-async (url)
"Downloads and insert the image specified by URL at point.
The download is performed in the background, and while
downloading the image, a temporary message is displayed. This
message is then replaced by the image once the download has
finished."
(let ((start (point)))
(insert "[loading-image]")
(let ((overlay (make-overlay start (point))))
(keybase--url-retrieve url "GET"
(lambda (data)
(keybase--insert-image-handler overlay data))
:as-json-p nil))))
(defun keybase--find-or-make-empty-buffer (name initialiser)
(let ((buffer (get-buffer name)))
(if buffer
(with-current-buffer buffer
(let ((inhibit-read-only t))
(delete-region (point-min) (point-max))
buffer))
(let ((buffer (generate-new-buffer name)))
(with-current-buffer buffer
(funcall initialiser))
buffer))))
(defvar keybase-button-keymap
(let ((map (make-sparse-keymap)))
(define-key map [mouse-2] 'keybase-open-selected-button)
(define-key map (kbd "RET") 'keybase-open-selected-button)
map))
(defun keybase-open-selected-button ()
(interactive)
(let ((callback (get-char-property (point)
'button-function))
(data (get-char-property (point)
'button-data)))
(funcall callback data)))
(cl-defun keybase--make-clickable-button (message function data)
(propertize message
'font-lock-face 'link
'keymap keybase-button-keymap
'mouse-face 'highlight
'button-function function
'button-data data))
(defun keybase--get-message (msgid)
"get message corresponding to msgid in context of current channel"
(let ((response (keybase--request-chat-api `((method . "get")
(params . ((options . ((channel . ,(keybase--channel-info-as-json keybase--channel-info))
(message_ids . ,(list msgid))))))))))
(seq-elt (keybase--json-find response
'(result messages))
0)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Channel tools
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar keybase-channel-link-keymap
(let ((map (make-sparse-keymap)))
(define-key map [mouse-2] 'keybase-open-selected-channel)
(define-key map (kbd "RET") 'keybase-open-selected-channel)
map))
(defun keybase--make-channel-button (name channel)
(propertize name
'font-lock-face 'link
'mouse-face 'highlight
'help-echo (format "mouse-2: open channel buffer")
'keybase-channel-name channel
'keymap keybase-channel-link-keymap))
(defun keybase-open-selected-channel ()
(interactive)
(when-let ((channel (get-char-property (point) 'keybase-channel-name)))
(keybase-join-channel channel)))
(defvar keybase-username-link-keymap
(let ((map (make-sparse-keymap)))
(define-key map [mouse-2] 'keybase-open-selected-username)
(define-key map (kbd "RET") 'keybase-open-selected-username)
map))
(defun keybase-open-selected-username ()
(interactive)
(when-let ((user (get-char-property (point) 'keybase-user)))
(keybase-user-info user)))
(cl-defun keybase--make-clickable-username (name &key include-prefix highlight)
(apply #'propertize (format "%s%s" (if include-prefix "@" "") name)
'font-lock-face 'link
'help-echo (format "mouse-2: open user info for %s" name)
'keybase-user name
'keymap keybase-username-link-keymap
(if highlight
(list 'mouse-face 'highlight)
nil)))
(defun keybase--private-conversation-channel-name (user)
(let ((current-name (with-current-buffer keybase--proc-buf keybase--username)))
(list "impteamnative" (if (string< current-name user)
(format "%s,%s" current-name user)
(format "%s,%s" user current-name))
nil)))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; Channel mode
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defvar keybase--proc-buf nil)
(defvar keybase--active-buffers nil
"List of active channels.
Each entry is of the form (CHANNEL-INFO . BUFFER)")
(defvar keybase--channels nil
"List of channels.
Each entry is of the form (CHANNEL-INFO UNREAD")
(defvar keybase-channel-mode-map
(let ((map (make-sparse-keymap)))
(define-key map (kbd "<S-return>") 'keybase-insert-nl)
(define-key map (kbd "RET") 'keybase-send-input-line)
;;(define-key map (kbd "@") 'keybase-insert-user)
(define-key map (kbd "C-c C-d") 'keybase-delete-message)
(define-key map (kbd "C-c C-r") 'keybase-reply-to-message)
(define-key map (kbd "C-c C-e") 'keybase-edit-message)
(define-key map (kbd "C-c C-a") 'keybase-send-file)
(define-key map [menu-bar keybase] (cons "Keybase" (make-sparse-keymap "Keybase")))
(define-key map [menu-bar keybase join-channel] '("Join channel" . keybase-join-channel))
(define-key map [menu-bar keybase create-private-conversation] '("Private conversation" . keybase-create-private-converstion))
(define-key map [menu-bar keybase show-user-info] '("User info" . keybase-user-info))
(define-key map [menu-bar keybase delete-message] '("Delete message" . keybase-delete-message))
map))
(defun keybase-reply-to-message ()
(interactive)
(let ((reply-to-msgid (keybase--find-message-at-point (point))))
(if reply-to-msgid
(keybase--input (read-from-minibuffer "Reply: " ) reply-to-msgid)
(message "No message at point"))))
(defun keybase--edit-message (msgid new-message)
"given msgid and new-content, sends api call to edit the message accordingly"
(keybase--request-chat-api `((method . "edit")
(params . ((options . ((channel . ,(keybase--channel-info-as-json keybase--channel-info))
(message_id . ,msgid)
("message" . ((body . ,new-message))))))))))
(defun keybase-edit-message ()
(interactive)
(let ((msgid (keybase--find-message-at-point (point)))
(sender (get-char-property (point)
'keybase-sender)))
(cond
((null msgid)
(error "No message at point"))
((not (string-equal sender (with-current-buffer keybase--proc-buf keybase--username)))
(error "You cannot edit messages that aren't yours"))
(t (let* ((current-message (keybase--json-find (keybase--get-message msgid)
'(msg content text body)))
(new-message (read-from-minibuffer "Edit text: " current-message)))
(when (yes-or-no-p (format "Really change to '%s'? " new-message))
(keybase--edit-message msgid new-message)))))))
(defun keybase--temp-copy-remote (file-path)
(let ((tmp-file-path (keybase--make-temp-file (file-name-nondirectory file-path))))
(tramp-do-copy-or-rename-file 'copy file-path
tmp-file-path)
tmp-file-path))
(defun keybase--send-file (file-path title)
"sends given file with title"
(let* ((remote-flag (string-prefix-p "/ssh" file-path))
(file-path (if remote-flag
(keybase--temp-copy-remote file-path)
file-path)))
(keybase--request-api-async keybase--program
(list "chat" "api")
`((method . "attach")
(params . ((options . ((channel . ,(keybase--channel-info-as-json keybase--channel-info))
(filename . ,file-path)
(title . ,title))))))
(lambda (json)
(if remote-flag
(delete-file file-path))))))
(defun keybase-send-file ()
(interactive)
(let* ((file-path (read-file-name "Choose file to send: "))
(default-title (first (last (split-string file-path "/"))))
(title (read-from-minibuffer "Message along attachment: ")))
(keybase--send-file file-path title)))
(defun keybase--load-more-messages-handler (data)
(keybase-load-messages))
(define-derived-mode keybase-channel-mode nil "Keybase"
"Mode for Keybase channel content"
(use-local-map keybase-channel-mode-map)
(insert (keybase--make-clickable-button "[Load more messages]" #'keybase--load-more-messages-handler nil))
(insert "\n\n")
(setq-local keybase--start-of-messages-marker (make-marker))
(set-marker keybase--start-of-messages-marker (point))
(setq-local keybase--output-marker (make-marker))
(setq-local keybase--input-marker (make-marker))
(set-marker keybase--output-marker (point-max))
(insert "channel> ")
(add-text-properties (point-at-bol) (point)
(list 'read-only t
'rear-nonsticky t
'front-sticky '(read-only)
'inhibit-line-move-field-capture t
'field 'output))
(set-marker-insertion-type keybase--output-marker t)
(set-marker keybase--input-marker (point-max)))
(defun keybase--read-input-line (start end)
(let ((uid-refs (loop for overlay in (overlays-in start end)
for uid = (overlay-get overlay 'keybase-user-ref)
when uid
collect (list (overlay-start overlay) (overlay-end overlay) uid overlay))))
(with-output-to-string
(loop with p = start
for uid-ref in (sort uid-refs (lambda (a b) (< (first a) (first b))))
if (< p (first uid-ref))
do (princ (buffer-substring p (first uid-ref)))
do (progn
(error "uid-refs not implemented")
(princ (format "\U000f0001user:%s:%s\U000f0001"
(third uid-ref) (buffer-substring (first uid-ref) (second uid-ref))))
(setq p (second uid-ref))
(delete-overlay (fourth uid-ref)))
finally (when (< p end)
(princ (buffer-substring p end)))))))
(defun keybase-insert-nl ()
"Insert a newline into the message."
(interactive)
(insert "\n"))
(defun keybase-insert-user ()
"Select a username to be inserted into the new message."
(interactive)
(error "can't insert user"))
(defun keybase-delete-message ()
(interactive)
(let ((msgid (keybase--find-message-at-point (point))))
(if msgid
(when (yes-or-no-p "Really delete message? ")
(keybase--request-chat-api `((method . "delete")
(params . ((options . ((channel . ,(keybase--channel-info-as-json keybase--channel-info))
(message_id . ,msgid))))))))
;; ELSE: No message at point
(message "No message at point"))))
(defun keybase--buffer-closed ()
(setq keybase--active-buffers (cl-remove (current-buffer) keybase--active-buffers :key #'cdr :test #'eq)))
(defun keybase--generate-channel-name (channel-info)
(if (third channel-info)
(format "*keybase %s - %s*" (second channel-info) (third channel-info))
(format "*keybase %s*" (second channel-info))))
(defun keybase--window-config-updated ()
"Hook function that is locally installed for window-configuration-change-hook in all channel buffers."
(let ((recompute nil))
(when (get-buffer-window)
;; Clear unread count
(when (plusp keybase--unread-in-channel)
(setq recompute t)))
(when recompute
(keybase--recompute-modeline))))
(defvar keybase--mark-unread-in-progress nil)
(defvar keybase--mark-unread-pending nil)
(defun keybase--find-most-recent-message ()
(let ((pos (previous-single-char-property-change (point-max) 'keybase-remote-message-id)))
(if pos
(get-char-property (1- pos) 'keybase-remote-message-id)
nil)))
(defun keybase--mark-unread-start-process ()
(when keybase--mark-unread-in-progress
(error "Mark unread already in progress"))
(if-let ((msgid (keybase--find-most-recent-message)))
(let ((proc (keybase--request-api-async keybase--program
'("chat" "api")
`((method . "mark")
(params . ((options . ((channel . ,(keybase--channel-info-as-json keybase--channel-info)))))))
(lambda (json)
(setq keybase--mark-unread-in-progress nil)
(keybase--mark-pending-unread)))))
(setq keybase--mark-unread-in-progress proc)
t)
;; ELSE: Return nil to indicate that a process was not started
nil))
(defun keybase--mark-pending-unread ()
(loop while keybase--mark-unread-pending
until (let ((req (car keybase--mark-unread-pending)))
(setq keybase--mark-unread-pending (cdr keybase--mark-unread-pending))
(with-current-buffer req
(keybase--mark-unread-start-process)))))
(defun keybase--mark-unread ()
(when (plusp keybase--unread-in-channel)
(setq keybase--unread-in-channel 0)
(if keybase--mark-unread-in-progress
(cl-pushnew (current-buffer) keybase--mark-unread-pending)
(keybase--mark-unread-start-process))))
(defun keybase--process-buffer-list-update ()
(unless (eq major-mode 'keybase-channel-mode)
(error "This function should only be called with channel buffers"))
(when (eq (current-buffer) (car (buffer-list)))
(keybase--mark-unread)))
(defun keybase--create-buffer (channel-info)
;; First ensure that the listener is running
(keybase--find-process-buffer)
;; Create the buffer
(let ((buffer (generate-new-buffer (keybase--generate-channel-name channel-info))))
(with-current-buffer buffer
(keybase-channel-mode)
(setq-local keybase--channel-info channel-info)
(setq-local keybase--unread-in-channel 0)
(add-hook 'kill-buffer-hook 'keybase--buffer-closed nil t)
(add-hook 'buffer-list-update-hook 'keybase--process-buffer-list-update nil t)
(push (cons channel-info buffer) keybase--active-buffers)
(setq-local keybase--next-tag nil)
(keybase-load-messages 10))
(unless (member 'keybase-display-notifications-string global-mode-string)
(if global-mode-string
(setq global-mode-string (append global-mode-string '(keybase-display-notifications-string)))
(setq global-mode-string '("" keybase-display-notifications-string)))
(keybase--recompute-modeline))
buffer))
(cl-defun keybase--find-channel-buffer (channel-info &key (if-missing :error))
(unless (member if-missing '(:error :create :ignore))
(error "Illegal argument to if-missing: %S" if-missing))
(let ((e (find channel-info keybase--active-buffers :key #'car :test #'equal)))
(cond (e
(cdr e))
((eq if-missing :create)
(keybase--create-buffer channel-info))
((eq if-missing :error)
(error "No buffer for channel %S" channel-info)))))
(cl-defun keybase-load-messages (&optional (num 10))
"Load NUM messages from the message history."
(interactive)
(let* ((messages-json (keybase--request-chat-api `((method . "read")
(params . ((options . ((channel . ,(keybase--channel-info-as-json keybase--channel-info))
(pagination . (,@(if keybase--next-tag
`((next . ,keybase--next-tag))
nil)
(num . ,num))))))))))
(next-tag (keybase--json-find messages-json '(result pagination next)))
(messages (keybase--json-find messages-json '(result messages))))
(setq keybase--next-tag next-tag)
(loop for msg-entry across messages
for msg = (keybase--json-find msg-entry '(msg))
for msg-text = (keybase--get-message-text msg-entry)
for id = (keybase--json-find msg '(id))
for sender = (keybase--json-find msg '(sender username))
for timestamp = (keybase--json-find msg '(sent_at_ms))
for content = (keybase--json-find msg '(content))
for type = (keybase--json-find content '(type))
for reply-to-msgid = (keybase--json-find content '(text replyTo) :error-if-missing nil)
for attachment = (keybase--json-find content '(attachment) :error-if-missing nil)
when (or (equal type "text") (equal type "attachment"))
do (keybase--insert-message id timestamp sender msg-text attachment reply-to-msgid))))
(defun keybase--format-custom-date (timestamp)
(let ((time (seconds-to-time (/ timestamp 1000))))
(format-time-string keybase--datetime-format time)))
(defun keybase--recompute-modeline ()
(setq keybase-display-notifications-string (keybase--make-unread-notification-string))
(force-mode-line-update t))
(defun keybase--make-unread-notification-string ()
(with-output-to-string
(princ "Unread: ")
(let ((unread-channels (loop with first = t
for channel in keybase--active-buffers
for (name unread) = (with-current-buffer (cdr channel)
(list keybase--channel-info keybase--unread-in-channel))
when (plusp unread)
collect name)))
(if unread-channels
(loop for first = t then nil
for name in unread-channels
unless first
do (princ ", ")
do (princ (keybase--generate-channel-name name)))
;; ELSE: Just return the empty string
""))))
(defun keybase-default-attribution (sender timestamp)
(format "[%s] %s "
(keybase--make-clickable-username sender :highlight nil)
(keybase--format-custom-date timestamp)))
(defvar keybase--first-paragraph nil)
(defun keybase--render-markup-element (element)
(etypecase element
(string (insert element))
(list (if (stringp (car element))
(insert (car element))
(ecase (car element)
(:paragraph
(let ((col (current-column))
(wrapcol fill-column))
(let ((content (with-temp-buffer
(keybase--insert-markup-inner (cdr element))
(let ((sentence-end-double-space nil)
(fill-column (- wrapcol col)))
(fill-region (point-min) (point-max))
(buffer-string)))))
(loop for v in (keybase--split-with-regexp "\n" content :empty t)
for first = t then nil
unless first
do (loop repeat col
do (insert " "))
do (progn
(insert v)
(insert "\n"))))))
(:newline
(insert "\n"))
(:bold
(let ((start (point)))
(keybase--insert-markup-inner (cdr element))
(add-text-properties start (point) (list 'face 'keybase-message-text-content-bold))))
(:italics
(let ((start (point)))
(keybase--insert-markup-inner (cdr element))
(add-text-properties start (point) (list 'face 'keybase-message-text-content-italics))))
(:code
(insert (propertize (cdr element) 'face (keybase-message-text-content-code-face))))
(:code-block
(insert "\n")
(insert (propertize (third element) 'face (keybase-message-text-content-code-face)))
(insert "\n"))
(:user
(insert (keybase--make-clickable-username (cdr element) :include-prefix t :highlight t))))))))
(defun keybase--insert-markup-inner (content)
(loop for v in content
do (keybase--render-markup-element v)))
(defun keybase--parse-user (string fn)
(let ((pos 0)
(length (length string))
(result nil))
(cl-labels ((append-res (elems) (setq result (append result elems)))
(collect-part (v) (when (< pos v) (setq result (append result (funcall fn (subseq string pos v)))))))
(loop while (< pos length)
do (let ((result (string-match "@\\([a-z0-9_]+\\)\\(?:$\\|\\W\\)" string pos)))
(if result
(let ((user (match-string 1 string))
(end-pos (match-end 1)))
(collect-part result)
(append-res `((:user . ,user)))
(setq pos end-pos))
;; ELSE: No more results
(collect-part length)
(setq pos length))))
result)))
(defun keybase--insert-markup-string (message)
(let ((content (let ((keybase--custom-parser-3 #'keybase--parse-user))
(keybase--markup-paragraphs message :allow-nl t))))
(let ((keybase--first-paragraph t))
(keybase--insert-markup-inner content))))
(defvar keybase--current-id 0)
(defun keybase--make-in-progress-id ()
(format "temp-%d" (incf keybase--current-id)))
(defun keybase--get-message-path (msg-json)
"gets the path to use to get message text (differs based on
presence of attachment or not"
(let ((type (keybase--json-find msg-json
'(msg content type))))
(cond
((string= type "attachment") '(msg content attachment object title))
((string= type "text") '(msg content text body)))))
(defun keybase--get-message-text (msg-json)
"gets the text to display for given msg-json (differs based on
presence of attachment or not"
(keybase--json-find msg-json
(keybase--get-message-path msg-json)))
(defun keybase--insert-reply (msgid)
"inserts message corresponding to message id in reply format"
;; (print "keybase--insert-reply")
(let* ((msg-json (aref
(keybase--json-find
(keybase--request-chat-api `((method . "get")
(params . ((options .
((channel . ,(keybase--channel-info-as-json keybase--channel-info))
(message_ids . ,(list msgid))))))))
'(result messages))
0))
(msg (keybase--get-message-text msg-json)))
(keybase--with-json-bind ((id (msg id))
(sender (msg sender username))
(timestamp (msg sent_at_ms)))
msg-json
(insert (propertize (string-join (list "\n> "
(funcall keybase-attribution sender timestamp)
"\n> "
(dired-replace-in-string "\n" "\n> " msg)))
'face 'keybase-reply)))))
(defun keybase--insert-message-content (id timestamp sender message attachment &optional
reply-to-msgid)
"Insert message content at the current cursor position.
ID may be nil, in which case this message represents an
in-progress message which is inserted while a new message is
being inserted. It will later be replaced with the real content
once it is received from the server."
(let ((inhibit-read-only t)
(start (point)))
(insert (propertize (funcall keybase-attribution sender timestamp)
'face
'keybase-message-from))
(when reply-to-msgid
(keybase--insert-reply reply-to-msgid))
(insert "\n") ;; start message content on newline after attribution
(keybase--insert-markup-string message)
(when attachment
(keybase--insert-attachment id attachment)
(insert "\n"))
(insert "\n")
(let ((gen-id (or id
(keybase--make-in-progress-id))))
(add-text-properties start
(point)
(append (list 'read-only
t
'keybase-message-id
gen-id
'keybase-timestamp
timestamp
'keybase-reply-to-msgid
reply-to-msgid
'keybase-sender
sender
'front-sticky
'(read-only))
(if (null id)
(list 'keybase-in-progress gen-id 'keybase-content
message 'face 'keybase-message-text-content-in-progress)
(list 'keybase-remote-message-id id)))))))
(defun keybase--insert-attachment (msgid attachment)
"given attachment object and message id, downloads the
attachment and inserts reference to file"
(let ((fpath (keybase--download-file msgid attachment))
(fname (keybase--json-find attachment
'(object filename))))
;; (print "CALLED")
(insert (keybase--make-clickable-button fname 'find-file
fpath))))
(defun keybase--insert-message (id timestamp sender message attachment &optional reply-to-msgid)
(save-excursion
(goto-char keybase--output-marker)
(let ((new-pos (loop with prev-pos = (point)
for pos = (previous-single-char-property-change prev-pos 'keybase-timestamp)
do (let ((prop (get-char-property pos 'keybase-timestamp)))
(when (and prop (< prop timestamp))
(return prev-pos)))
do (when (<= pos (marker-position keybase--start-of-messages-marker))
(return (marker-position keybase--start-of-messages-marker)))
do (setq prev-pos pos)
finally (return prev-pos))))
(goto-char new-pos)
(keybase--insert-message-content id timestamp sender message attachment reply-to-msgid))))
(defun keybase--find-message-in-log (id)
(loop with curr = (point-min)
for pos = (next-single-property-change curr 'keybase-message-id)
while pos
for value = (get-char-property pos 'keybase-message-id)
when (equal value id)
return (list pos (next-single-property-change pos 'keybase-message-id))
do (setq curr pos)
finally (return nil)))
(defun keybase--find-message-at-point (pos)
(get-char-property pos 'keybase-message-id))
(defun keybase--handle-post-message (json)
(let ((id (keybase--json-find json '(id)))
(message (keybase--get-message-text `((msg . ,json))))
(sender (keybase--json-find json '(sender username)))
(timestamp (keybase--json-find json '(sent_at_ms)))
(reply-to-msgid (keybase--json-find json '(content text replyTo) :error-if-missing nil))
(attachment (keybase--json-find json '(content attachment) :error-if-missing nil)))
;; If this message is sent by us, we need to check if there is an
;; in-progress message inserted in the buffer. If so, it beeds to
;; be removed before the real one is sent.
(when (equal sender (with-current-buffer keybase--proc-buf keybase--username))
(save-excursion
(loop with curr = (point-min)
for pos = (next-single-property-change curr 'keybase-in-progress)
while pos
when (and (get-char-property pos 'keybase-in-progress)
(equal (get-char-property pos 'keybase-content) message))
do (let ((end (next-single-property-change pos 'keybase-message-id))
(inhibit-read-only t))
(delete-region pos end)
(return nil))
do (setq curr pos))))
(keybase--insert-message id timestamp sender message attachment reply-to-msgid)
(let ((old keybase--unread-in-channel))
(incf keybase--unread-in-channel)
(when (zerop old)
(keybase--recompute-modeline)))))
(defun keybase--delete-message (id)
(message "deleting message %S" id)
(let ((old-message-pos (keybase--find-message-in-log id)))
(when old-message-pos
(let ((inhibit-read-only t))
(delete-region (first old-message-pos) (second old-message-pos))))))
(defun keybase--handle-delete (json)
(let ((message-list (keybase--json-find json '(content delete messageIDs))))
(loop for id across message-list
do (keybase--delete-message id))))
(defun keybase--handle-edit (json)
(let* ((old-msgid (keybase--json-find json
'(content edit messageID)))
(old-message-pos (keybase--find-message-in-log old-msgid)))
;; If the message isn't already displayed, we don't need to do
;; anything (we don't want old messages added just because someone
;; edited them)
(when old-message-pos
(destructuring-bind (old-message-start old-message-end)
old-message-pos
(save-excursion
(let* ((msg old-message-start)
(old-timestamp (get-char-property msg 'keybase-timestamp))
(reply-to-msgid (get-char-property msg 'keybase-reply-to-msgid)))
(unless old-timestamp
(error "no timestamp for previous message"))
(let ((inhibit-read-only t))
(delete-region old-message-start old-message-end))
;; An UPDATE message contains the same fields as a TEXT message.
(let ((message (keybase--json-find json
'(content edit body)))
(sender (keybase--json-find json
'(sender username)))
(attachment (keybase--json-find json
'(content attachment)
:error-if-missing nil)))
(goto-char old-message-start)
(keybase--insert-message-content old-msgid
old-timestamp sender message attachment reply-to-msgid))))))))
(defvar *keybase--attachment-type-none* 0)
(defvar *keybase--attachment-type-image* 1)
(defvar *keybase--attachment-type-video* 2)
(defvar *keybase--attachment-type-audio* 3)
(defun keybase--file-to-extension (file)
"Returns the extension for the given FILE, or null if the file does not have an extension."
(let ((result (string-match "^.*\\.\\([^.]+\\)$" file)))
(if result
(match-string 1 file)
nil)))
(defun keybase--insert-image (title filename)
(let ((image-data (with-temp-buffer
(insert-file-contents-literally filename)
(decode-coding-string (buffer-string) 'no-conversion))))
(let ((image (create-image image-data nil t)))
(insert-image image "[image]"))))
(defun keybase--make-temp-file (fname)
(let ((temp-dir (make-temp-file "emacs-keybase" t)))
(concat temp-dir "/" fname)))
(defun keybase--download-file (message-id attachment)
"downloads file and returns filepath given message"
(let* ((filename (keybase--json-find attachment
'(object filename)))
(out-filepath (keybase--make-temp-file filename)))
(keybase--request-chat-api `((method . "download")
(params . ((options . ((channel . ,(keybase--channel-info-as-json keybase--channel-info))
(message_id . ,message-id)
(output . ,out-filepath)))))))
out-filepath))
(defun keybase--handle-attachment-message (json)
(let* ((message-id (keybase--json-find json
'(id)))
(sender (keybase--json-find json
'(sender username)))
(timestamp (keybase--json-find json
'(sent_at)))
(attachment (keybase--json-find json
'(content attachment))))
;; (out-file (make-temp-file "emacs-keybase-"
;; nil
;; (format ".%s" filename)))
(progn
;; (keybase--request-chat-api `((method . "download")
;; (params . ((options . ((channel . ,(keybase--channel-info-as-json keybase--channel-info))
;; (message_id . ,message-id)
;; (output . ,out-file)))))))
(keybase--insert-message message-id timestamp
sender nil attachment))))
(defun keybase--handle-image-message (json)
(let* ((id (keybase--json-find json '(id)))
(sender (keybase--json-find json '(sender username)))
(timestamp (keybase--json-find json '(sent_at)))
(attachment (keybase--json-find json '(content attachment)))
(asset-type (keybase--json-find attachment '(object metadata assetType))))
(when (eql asset-type *keybase--attachment-type-image*)
(let* ((filename (keybase--json-find attachment '(object filename)))
(content-type (keybase--json-find attachment '(object mimeType)))
(title (keybase--json-find attachment '(object title)))
(file (make-temp-file "emacs-keybase" nil (format ".%s" (keybase--file-to-extension filename)))))
(unwind-protect
(progn
(keybase--request-chat-api `((method . "download")
(params . ((options . ((channel . ,(keybase--channel-info-as-json keybase--channel-info))
(message_id . ,id)
(output . ,file)))))))
(keybase--insert-message id timestamp sender "Uploaded file" (list title file)))
(delete-file file))))))
(cl-defun keybase--handle-incoming-chat-message (json)
;; (setq check json)
;; (message (format "%s" json))
(let ((msg (keybase--json-find json '(msg) :error-if-missing nil)))
(when msg
(let* ((channel-info (keybase--parse-channel-name (keybase--json-find msg '(channel))))
(buffer (keybase--find-channel-buffer channel-info :if-missing :ignore)))
(when buffer
(with-current-buffer buffer
(let ((type (keybase--json-find msg '(content type))))
(cond ((or (equal type "text") (equal type "attachment"))
(keybase--handle-post-message msg))
((equal type "delete")
(keybase--handle-delete msg))
((equal type "edit")
(keybase--handle-edit msg))
((equal type "attachment")
(keybase--handle-attachment-message msg))))))
;; We need to check mentions for all channels, not just the ones the user have opened
(let ((at-mention-usernames (keybase--json-find msg '(at_mention_usernames) :error-if-missing nil))
(username (with-current-buffer keybase--proc-buf keybase--username)))
(when (loop for v across at-mention-usernames
when (equal v username)
return t)
(message "mention in channel: %S" channel-info)))))))
(defun keybase--request-api (command command-args arg)
(let ((output-buf (generate-new-buffer " *keybase api*")))
(unwind-protect
(progn
(if arg
(with-temp-buffer
(insert (json-encode arg))
(apply #'call-process-region (point-min) (point-max) command nil (list output-buf nil) nil command-args))