Things are roughly working again after refactor.
[lurk.git] / lirc.el
1 ;;; lirc.el --- Lightweight irc client  -*- lexical-binding:t -*-
2
3 ;; Copyright (C) 2021 Tim Vaughan
4
5 ;; Author: Tim Vaughan <timv@ughan.xyz>
6 ;; Created: 14 June 2021
7 ;; Version: 1.0
8 ;; Keywords: network
9 ;; Homepage: http://thelambdalab.xyz/erc
10 ;; Package-Requires: ((emacs "26"))
11
12 ;; This file is not part of GNU Emacs.
13
14 ;; This program is free software: you can redistribute it and/or modify
15 ;; it under the terms of the GNU General Public License as published by
16 ;; the Free Software Foundation, either version 3 of the License, or
17 ;; (at your option) any later version.
18
19 ;; This program is distributed in the hope that it will be useful,
20 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
21 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
22 ;; GNU General Public License for more details.
23
24 ;; You should have received a copy of the GNU General Public License
25 ;; along with this file.  If not, see <http://www.gnu.org/licenses/>.
26
27 ;;; Commentary:
28
29 ;;; Code:
30
31 (provide 'lirc)
32
33
34 ;;; Customizations
35 ;;
36
37 (defgroup lirc nil
38   "Lightweight IRC client."
39   :group 'network)
40
41 (defcustom lirc-nick "plugd"
42   "Default nick.")
43 (defcustom lirc-full-name "plugd"
44   "Default full name.")
45 (defcustom lirc-user-name "plugd"
46   "Default user name.")
47
48 (defcustom lirc-networks
49   '(("libera" "irc.libera.chat" 6697)
50     ("freenode" "chat.freenode.net" 6697)
51     ("local" "localhost" 6697))
52   "IRC networks.")
53
54 ;;; Faces
55 ;;
56
57 (defface lirc-text
58   '((t :inherit font-lock-preprocessor-face))
59   "Face used for Lirc text.")
60
61 (defface lirc-your-nick
62   '((t :inherit font-lock-constant-face))
63   "Face used for highlighting your nick.")
64
65 (defface lirc-prompt
66   '((t :inherit org-level-2))
67   "Face used for the prompt.")
68
69 (defface lirc-channel
70   '((t :inherit org-list-dt))
71   "Face used for the channel name in the prompt.")
72
73 (defface lirc-faded
74   '((t :inherit font-lock-preprocessor-face))
75   "Face used for faded Lirc text.")
76
77 (defface lirc-bold
78   '((t :inherit font-lock-function-name-face))
79   "Face used for bold Lirc text.")
80
81 (defface lirc-error
82   '((t :inherit font-lock-regexp-grouping-construct))
83   "Face used for Lirc error text.")
84
85 ;;; Global variables
86 ;;
87
88 (defvar lirc-version "Lirc v0.1")
89
90 (defvar lirc-notice-prefix
91   (concat
92    (propertize
93     "-" 'face 'lirc-faded)
94    (propertize
95     "!" 'face 'lirc-bold)
96    (propertize
97     "-" 'face 'lirc-faded)))
98
99 (defvar lirc-error-prefix
100   (propertize "!!!" 'face 'lirc-error))
101
102
103 (defvar lirc-prompt-string
104   (propertize "> " 'face 'lirc-prompt))
105
106
107 ;;; Network process
108 ;;
109
110 (defvar lirc-response "")
111
112 (defun lirc-filter (proc string)
113   (dolist (line (split-string (concat lirc-response string) "\n"))
114     (if (string-suffix-p "\r" line)
115         (lirc-eval-msg-string (string-trim line))
116       (setq lirc-response line))))
117
118
119 (defun lirc-start-process (network)
120   (let* ((row (assoc network lirc-networks))
121          (host (elt row 1))
122          (port (elt row 2)))
123     (make-network-process :name "lirc"
124                           :host host
125                           :service port
126                           :filter #'lirc-filter
127                           :nowait nil
128                           :tls-parameters (cons 'gnutls-x509pki
129                                                 (gnutls-boot-parameters
130                                                  :type 'gnutls-x509pki
131                                                  :hostname host))
132                           :buffer "*lirc*")))
133
134
135 (defun lirc-connect (network)
136   (if (get-process "lirc")
137       (lirc-display-error "Already connected.  Disconnect first.")
138     (setq lirc-current-context nil)
139     (clrhash lirc-contexts)
140     (lirc-start-process network)
141     (lirc-send-msg (lirc-msg nil nil "USER" lirc-user-name 0 "*" lirc-full-name))
142     (lirc-send-msg (lirc-msg nil nil "NICK" lirc-nick))))
143
144 (defun lirc-send-msg (msg)
145   (let ((proc (get-process "lirc")))
146     (if (and proc (eq (process-status proc) 'open))
147         (process-send-string proc (concat (lirc-msg->string msg) "\r\n"))
148       (lirc-display-error "No server connection established.")
149       (error "No server connection established"))))
150
151
152 ;;; Server messages
153 ;;
154
155 (defun lirc--as-string (obj)
156   (if obj
157       (with-output-to-string (princ obj))
158     nil))
159
160 (defun lirc-msg (tags src cmd &rest params)
161   (list (lirc--as-string tags)
162         (lirc--as-string src)
163         (upcase (lirc--as-string cmd))
164         (mapcar #'lirc--as-string
165                 (if (and params (listp (elt params 0)))
166                     (elt params 0)
167                   params))))
168
169 (defun lirc-msg-tags (msg) (elt msg 0))
170 (defun lirc-msg-src (msg) (elt msg 1))
171 (defun lirc-msg-cmd (msg) (elt msg 2))
172 (defun lirc-msg-params (msg) (elt msg 3))
173 (defun lirc-msg-trail (msg)
174   (let ((params (lirc-msg-params msg)))
175     (if params
176         (elt params (- (length params) 1)))))
177
178 (defvar lirc-msg-regex
179   (rx
180    (opt (: "@" (group (* (not (or "\n" "\r" ";" " ")))))
181         (* whitespace))
182    (opt (: ":" (: (group (* (not (any space "!" "@"))))
183                   (* (not (any space)))))
184         (* whitespace))
185    (group (: (* (not whitespace))))
186    (* whitespace)
187    (opt (group (+ not-newline))))
188   "Regex used to parse IRC messages.
189 Note that this regex is incomplete.  Noteably, we discard the non-nick
190 portion of the source component of the message, as LIRC doesn't use this.")
191
192 (defun lirc-string->msg (string)
193   (if (string-match lirc-msg-regex string)
194       (let* ((tags (match-string 1 string))
195              (src (match-string 2 string))
196              (cmd (upcase (match-string 3 string)))
197              (params-str (match-string 4 string))
198              (params
199               (if params-str
200                   (let* ((idx (cl-search ":" params-str))
201                          (l (split-string (string-trim (substring params-str 0 idx))))
202                          (r (if idx (list (substring params-str (+ 1 idx))) nil)))
203                     (append l r))
204                 nil)))
205         (apply #'lirc-msg (append (list tags src cmd) params)))
206     (error "Failed to parse string " string)))
207
208 (defun lirc--filtered-join (&rest args)
209   (string-join (seq-filter (lambda (el) el) args) " "))
210
211 (defun lirc-msg->string (msg)
212   (let ((tags (lirc-msg-tags msg))
213         (src (lirc-msg-src msg))
214         (cmd (lirc-msg-cmd msg))
215         (params (lirc-msg-params msg)))
216     (lirc--filtered-join
217      (if tags (concat "@" tags) nil)
218      (if src (concat ":" src) nil)
219      cmd
220      (if (> (length params) 1)
221          (string-join (seq-take params (- (length params) 1)) " ")
222        nil)
223      (if (> (length params) 0)
224          (concat ":" (elt params (- (length params) 1)))
225        nil))))
226
227
228 ;;; Contexts and users
229 ;;
230
231 (defvar lirc-context-table
232   '((channel lirc-display-channel-message)
233     (nick lirc-display-private-message)
234     (host lirc-diaplay-server-message)))
235
236 (defvar lirc-current-context nil)
237 (defvar lirc-contexts (make-hash-table :test #'equal))
238
239 (defun lirc-add-context (name)
240   (puthash name nil lirc-contexts))
241
242 (defun lirc-del-context (name)
243   (remhash name lirc-contexts))
244
245 (defun lirc-get-context-users (name)
246   (gethash name lirc-contexts))
247
248 (defun lirc-add-context-users (context users)
249   (puthash context
250            (append users
251                    (gethash context lirc-contexts))
252            lirc-contexts))
253
254 (defun lirc-del-context-user (context user)
255   (puthash context
256            (remove user (gethash context lirc-contexts))
257            lirc-contexts))
258
259 (defun lirc-del-user (user)
260   (dolist (context (lirc-get-context-list))
261     (lirc-del-context-user context user)))
262
263 (defun lirc-get-context-type (name)
264   (cond
265    ((string-prefix-p "#" name) 'channel)
266    ((string-match-p (rx (or "." "localhost")) name) 'host)
267    (t 'nick)))
268
269 (defun lirc-get-context-list ()
270   (let ((res nil))
271     (maphash (lambda (key val)
272                (cl-pushnew key res))
273              lirc-contexts)
274     res))
275
276 (defun lirc-get-next-context ()
277   (if lirc-current-context
278       (let* ((context-list (lirc-get-context-list))
279              (context-list* (member lirc-current-context context-list)))
280         (if (> (length context-list*) 1)
281             (cadr context-list*)
282           (car context-list)))
283     nil))
284     
285
286 (defun lirc-cycle-contexts ()
287   (interactive)
288   (if lirc-current-channel
289       (progn
290         (setq lirc-current-channel (lirc-get-channel-next lirc-current-channel))
291         (lirc-render-prompt))
292     (lirc-display-error "No channels joined.")))
293
294
295 ;;; Buffer
296 ;;
297
298 (defun lirc-display-string (&rest strings)
299   (with-current-buffer (get-buffer-create "*lirc*")
300     (save-excursion
301       (goto-char lirc-prompt-marker)
302       (let ((inhibit-read-only t)
303             (old-pos (marker-position lirc-prompt-marker))
304             (adaptive-fill-regexp (rx (= 6 anychar))))
305         (insert-before-markers
306          (propertize (concat (format-time-string "%H:%M") " ")
307                      'face 'lirc-text
308                      'read-only t)
309          (propertize (concat (apply #'concat strings) "\n")
310                      'read-only t))
311         (fill-region old-pos lirc-prompt-marker)))))
312
313 (defun lirc-render-prompt ()
314   (with-current-buffer "*lirc*"
315     (let ((update-point (= lirc-input-marker (point)))
316           (update-window-points (mapcar (lambda (w)
317                                           (list (= (window-point w) lirc-input-marker)
318                                                 w))
319                                         (get-buffer-window-list nil nil t))))
320       (save-excursion
321         (set-marker-insertion-type lirc-prompt-marker nil)
322         (set-marker-insertion-type lirc-input-marker t)
323         (let ((inhibit-read-only t))
324           (delete-region lirc-prompt-marker lirc-input-marker)
325           (goto-char lirc-prompt-marker)
326           (insert
327            (propertize (if lirc-current-context
328                            lirc-current-context
329                          "")
330                        'face 'lirc-context
331                        'read-only t)
332            (propertize lirc-prompt-string
333                        'face 'lirc-prompt
334                        'read-only t
335                        'rear-nonsticky t)))
336         (set-marker-insertion-type lirc-input-marker nil))
337       (if update-point
338           (goto-char lirc-input-marker))
339       (dolist (v update-window-points)
340         (if (car v)
341             (set-window-point (cadr v) lirc-input-marker))))))
342   
343 (defvar lirc-prompt-marker nil
344   "Marker for prompt position in LIRC buffer.")
345
346 (defvar lirc-input-marker nil
347   "Marker for prompt position in LIRC buffer.")
348
349 (defun lirc-setup-buffer ()
350   (with-current-buffer (get-buffer-create "*lirc*")
351     (if (markerp lirc-prompt-marker)
352         (set-marker lirc-prompt-marker (point-max))
353       (setq lirc-prompt-marker (point-max-marker)))
354     (if (markerp lirc-input-marker)
355         (set-marker lirc-input-marker (point-max))
356       (setq lirc-input-marker (point-max-marker)))
357     (goto-char (point-max))
358     (lirc-render-prompt)))
359
360
361 ;;; Output formatting
362 ;;
363
364 (defun lirc-display-message (from to text)
365   (let* ((to-type (lirc-get-context-type to))
366          (display-fun (cadr (assoc to-type lirc-context-table))))
367     (funcall display-fun from to text)))
368
369 (defun lirc-display-channel-message (from to text)
370   (lirc-display-string
371    (propertize (concat to
372                        " <" from "> "
373                        text)
374                'face 'lirc-text)))
375                
376
377 (defun lirc-display-action (channel-name nick action)
378   (lirc-display-string (concat channel-name
379                                " * "
380                                (propertize (concat nick " " action)
381                                            'face 'lirc-text))))
382
383 (defun lirc-display-private-message (from to text)
384   (lirc-display-string
385    (concat
386     (propertize
387      (concat "[" from " -> " to "] "
388              text)
389      'face 'lirc-text))))
390         
391
392 (defun lirc-display-notice (&rest notices)
393   (lirc-display-string lirc-notice-prefix " " (apply #'concat notices)))
394
395 (defun lirc-display-error (&rest messages)
396   (lirc-display-string lirc-error-prefix " "
397                        (propertize (apply #'concat messages)
398                                    'face 'lirc-error)))
399
400 ;;; Message evaluation
401 ;;
402
403 (defun lirc-eval-msg-string (string)
404   ;; (lirc-display-string string)
405   (let* ((msg (lirc-string->msg string)))
406     (pcase (lirc-msg-cmd msg)
407       ("PING"
408        (lirc-send-msg
409         (lirc-msg nil nil "PONG" (lirc-msg-params msg)))
410        (lirc-display-notice "ping-pong"))
411
412       ("353" ; NAMEREPLY
413        (let* ((params (lirc-msg-params msg))
414               (channel (elt params 2))
415               (names (split-string (elt params 3))))
416          (lirc-add-context-users channel names)))
417
418       ("366" ; ENDOFNAMES
419        (lirc-display-notice
420         (lirc-as-string (length (lirc-get-context-users lirc-current-context)))
421         " users in " lirc-current-context))
422
423       ((rx (= 3 (any digit)))
424        (lirc-display-notice (mapconcat 'identity (cdr (lirc-msg-params msg)) " ")))
425
426       ((and "JOIN"
427             (guard (equal lirc-nick (lirc-msg-src msg))))
428        (let ((channel-name (car (lirc-msg-params msg))))
429          (lirc-add-context channel-name)
430          (setq lirc-current-context channel-name)
431          (lirc-display-notice "Joining channel " channel-name)
432          (lirc-render-prompt)))
433
434       ("JOIN"
435        (let ((channel-name (car (lirc-msg-params msg)))
436              (nick (lirc-msg-src msg)))
437          (lirc-add-context-users channel-name (list nick))
438          (lirc-display-notice nick " joined channel " channel-name)))
439
440       ((and "PART"
441             (guard (equal lirc-nick (lirc-msg-src msg))))
442        (let ((channel-name (car (lirc-msg-params msg))))
443          (lirc-display-notice "Left channel " channel-name)
444          (lirc-del-context channel-name)
445          (if (equal channel-name lirc-current-context)
446              (setq lirc-current-context (lirc-get-next-context)))
447          (lirc-render-prompt)))
448
449       ("PART"
450        (let ((channel-name (car (lirc-msg-params msg)))
451              (nick (lirc-msg-src msg)))
452          (lirc-del-context-user channel-name nick)
453          (lirc-display-notice nick " left channel " channel-name)))
454
455       ("QUIT"
456        (let ((nick (lirc-msg-src msg))
457              (reason (mapconcat 'identity (lirc-msg-params msg) " ")))
458          (lirc-del-user nick)
459          (lirc-display-notice nick " quit: " reason)))
460
461       ((and "NICK"
462             (guard (equal lirc-nick (lirc-msg-src msg))))
463        (setq lirc-nick (car (lirc-msg-params msg)))
464        (lirc-display-notice "Set nick to " lirc-nick))
465
466       ("NICK"
467        (let ((old-nick (lirc-msg-src msg))
468              (new-nick (car (lirc-msg-params msg))))
469          (lirc-display-notice nick " is now known as " new-nick)
470          (lirc-rename-user nick new-nick)))
471
472       ("NOTICE"
473        (let ((nick (lirc-msg-src msg))
474              (channel (car (lirc-msg-params msg)))
475              (text (cadr (lirc-msg-params msg))))
476          (pcase text
477            ((rx (: "\01VERSION "
478                    (let version (* (not "\01")))
479                    "\01"))
480             (lirc-display-notice "CTCP version reply from " nick ": " version))
481            (_
482             (lirc-display-notice text)))))
483
484       ("PRIVMSG"
485        (let* ((from (lirc-msg-src msg))
486               (params (lirc-msg-params msg))
487               (to (car params))
488               (text (cadr params)))
489          (pcase text
490            ("\01VERSION\01"
491             (let ((version-string (concat lirc-version " - running on GNU Emacs " emacs-version)))
492               (lirc-send-msg (lirc-msg nil nil "NOTICE"
493                                        (list from (concat "\01VERSION "
494                                                           version-string
495                                                           "\01")))))
496             (lirc-display-notice "CTCP version request received from " from))
497
498            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
499             (lirc-send-msg (lirc-msg nil nil "NOTICE" (list from ping)))
500             (lirc-display-notice "CTCP ping received from " from))
501
502            ("\01USERINFO\01"
503             (lirc-display-notice "CTCP userinfo request from " from " (no response sent)"))
504
505            (_
506             (lirc-display-message from to text)))))
507       (_
508        (lirc-display-string (lirc-msg->string msg))))))
509
510
511 ;;; Command entering
512 ;;
513
514 (defun lirc-enter-string (string)
515   (if (string-prefix-p "/" string)
516       (pcase (substring string 1)
517         ((rx (: "CONNECT " (let network (* not-newline))))
518          (lirc-display-notice "Connecting to " network "...")
519          (lirc-connect network))
520
521         ((rx (: "TOPIC " (let new-topic (* not-newline))))
522          (lirc-send-msg (lirc-msg nil nil "TOPIC" lirc-current-context new-topic)))
523
524         ((rx (: "ME " (let action (* not-newline))))
525          (lirc-send-msg (lirc-msg nil nil "PRIVMSG"
526                                   (list lirc-current-context
527                                         (concat "\01ACTION " action "\01"))))
528          (lirc-display-action lirc-nick action))
529
530         ((rx (: "VERSION" " " (let nick (* (not whitespace)))))
531          (lirc-send-msg (lirc-msg nil nil "PRIVMSG"
532                                   (list nick "\01VERSION\01")))
533          (lirc-display-notice "CTCP version request sent to " nick))
534
535         ((rx "PART" (opt (: " " (let channel (* not-newline)))))
536          (if (or lirc-current-context channel)
537              (lirc-send-msg (lirc-msg nil nil "PART" (if channel
538                                                          channel
539                                                        lirc-current-context)))
540            (lirc-display-error "No current channel to leave.")))
541
542         ((rx "MSG "
543              (let to (* (not whitespace)))
544              " "
545              (let text (* not-newline)))
546          (lirc-send-msg (lirc-msg nil nil "PRIVMSG" target text))
547          (lirc-display-message lirc-nick target text))
548
549         ((rx (: (let cmd-str (+ (not whitespace)))
550                 (opt (: " " (let params-str (* not-newline))))))
551          (lirc-send-msg (lirc-msg nil nil (upcase cmd-str)
552                                   (if params-str
553                                       (split-string params-str)
554                                     nil)))))
555
556     (unless (string-empty-p string)
557       (if lirc-current-context
558           (progn
559             (lirc-send-msg (lirc-msg nil nil "PRIVMSG"
560                                      lirc-current-context
561                                      string))
562             (lirc-display-message lirc-nick lirc-current-context string))
563         (lirc-display-error "No current context.")))))
564
565 (defun lirc-enter ()
566   "Enter current contents of line after prompt."
567   (interactive)
568   (with-current-buffer "*lirc*"
569     (lirc-enter-string
570      (buffer-substring lirc-input-marker (point-max)))
571     (let ((inhibit-read-only t))
572       (delete-region lirc-input-marker (point-max)))))
573
574
575 ;;; Mode
576 ;;
577
578 (defvar lirc-mode-map
579   (let ((map (make-sparse-keymap)))
580     (define-key map (kbd "RET") 'lirc-enter)
581     ;; (define-key map (kbd "<C-tab>") 'lirc-cycle-channels)
582     map))
583
584 (define-derived-mode lirc-mode text-mode "lirc"
585   "Major mode for LIRC.")
586
587 (when (fboundp 'evil-set-initial-state)
588   (evil-set-initial-state 'lirc-mode 'insert))
589
590 ;;; Main start procedure
591 ;;
592
593 (defun lirc ()
594   "Switch to *lirc* buffer."
595   (interactive)
596   (if (get-buffer "*lirc*")
597       (switch-to-buffer "*lirc*")
598     (switch-to-buffer "*lirc*"))
599   (lirc-mode)
600   (lirc-setup-buffer)
601   "Started LIRC.")
602
603
604
605 ;;; lirc.el ends here