5244c2fb24a2f8d2a16037f5fd243304f077f235
[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 ;;; Customizations
34 ;;
35
36 (defgroup lirc nil
37   "Lightweight IRC client."
38   :group 'network)
39
40 (defcustom lirc-nick "plugd"
41   "Default nick.")
42 (defcustom lirc-full-name "plugd"
43   "Default full name.")
44 (defcustom lirc-user-name "plugd"
45   "Default user name.")
46 (defcustom lirc-host "irc.libera.chat"
47   "Default server.")
48 (defcustom lirc-port 6697
49   "Default port.")
50
51 (defcustom lirc-prompt-string "> "
52   "Prompt.")
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-prompt
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-prompt
100   (propertize "!!!" 'face 'lirc-error))
101
102
103 ;;; Network process
104 ;;
105
106 (defvar lirc-response "")
107
108 (defun lirc-filter (proc string)
109   (dolist (line (split-string (concat lirc-response string) "\n"))
110     (if (string-suffix-p "\r" line)
111         (lirc-eval-msg-string (string-trim line))
112       (setq lirc-response line))))
113
114 (defun lirc-get-process (&optional connect)
115   (let ((proc (get-process "lirc")))
116     (if (and proc (eq (process-status proc) 'open))
117         proc
118       (if connect
119           (make-network-process :name "lirc"
120                                 :host lirc-host
121                                 :service lirc-port
122                                 :filter #'lirc-filter
123                                 :nowait nil
124                                 :tls-parameters (cons 'gnutls-x509pki
125                                                       (gnutls-boot-parameters
126                                                        :type 'gnutls-x509pki
127                                                        :hostname lirc-host))
128                                 :buffer "*lirc*")
129         (lirc-display-error "No server connection established.")
130         (error "No server connection established")))))
131
132 ;;; Messages
133 ;;
134
135 (defun lirc-as-string (obj)
136   (if obj
137       (with-output-to-string (princ obj))
138     nil))
139
140 (defun lirc-msg (tags src cmd &rest params)
141   (list (lirc-as-string tags)
142         (lirc-as-string src)
143         (upcase (lirc-as-string cmd))
144         (mapcar #'lirc-as-string
145                 (if (and params (listp (elt params 0)))
146                     (elt params 0)
147                   params))))
148
149 (defun lirc-msg-tags (msg) (elt msg 0))
150 (defun lirc-msg-src (msg) (elt msg 1))
151 (defun lirc-msg-cmd (msg) (elt msg 2))
152 (defun lirc-msg-params (msg) (elt msg 3))
153 (defun lirc-msg-trail (msg)
154   (let ((params (lirc-msg-params msg)))
155     (if params
156         (elt params (- (length params) 1)))))
157
158 (defvar lirc-msg-regex
159   (rx
160    (opt (: "@" (group (* (not (or "\n" "\r" ";" " ")))))
161         (* whitespace))
162    (opt (: ":" (: (group (* (not (any space "!" "@"))))
163                   (* (not (any space)))))
164         (* whitespace))
165    (group (: (* (not whitespace))))
166    (* whitespace)
167    (opt (group (+ not-newline))))
168   "Regex used to parse IRC messages.
169 Note that this regex is incomplete.  Noteably, we discard the non-nick
170 portion of the source component of the message, as LIRC doesn't use this.")
171
172 (defun lirc-string->msg (string)
173   (if (string-match lirc-msg-regex string)
174       (let* ((tags (match-string 1 string))
175              (src (match-string 2 string))
176              (cmd (upcase (match-string 3 string)))
177              (params-str (match-string 4 string))
178              (params
179               (if params-str
180                   (let* ((idx (cl-search ":" params-str))
181                          (l (split-string (string-trim (substring params-str 0 idx))))
182                          (r (if idx (list (substring params-str (+ 1 idx))) nil)))
183                     (append l r))
184                 nil)))
185         (apply #'lirc-msg (append (list tags src cmd) params)))
186     (error "Failed to parse string " string)))
187
188 (defun lirc--filtered-join (&rest args)
189   (string-join (seq-filter (lambda (el) el) args) " "))
190
191 (defun lirc-msg->string (msg)
192   (let ((tags (lirc-msg-tags msg))
193         (src (lirc-msg-src msg))
194         (cmd (lirc-msg-cmd msg))
195         (params (lirc-msg-params msg)))
196     (lirc--filtered-join
197      (if tags (concat "@" tags) nil)
198      (if src (concat ":" src) nil)
199      cmd
200      (if (> (length params) 1)
201          (string-join (seq-take params (- (length params) 1)) " ")
202        nil)
203      (if (> (length params) 0)
204          (concat ":" (elt params (- (length params) 1)))
205        nil))))
206
207
208 ;;; Channels
209 ;;
210
211 (defvar lirc-current-channel nil)
212 (defvar lirc-channel-list nil)
213
214 (defun lirc-add-channel (channel-name)
215   (add-to-list 'lirc-channel-list
216                (list channel-name)))
217
218 (defun lirc-del-channel (channel-name)
219   (setq lirc-channel-list
220         (assoc-delete-all channel-name lirc-channel-list)))
221
222 (defun lirc-get-channel-users (channel-name)
223   (cdr (assoc channel-name lirc-channel-list)))
224
225 (defun lirc-set-channel-users (channel-name users)
226   (setcdr (assoc channel-name lirc-channel-list) users))
227
228 (defun lirc-add-channel-users (channel-name &rest users)
229   (let ((current-users (lirc-get-channel-users channel-name)))
230     (lirc-set-channel-users channel-name (append users current-users))))
231
232 (defun lirc-del-channel-users (channel-name &rest users)
233   (let ((current-users (lirc-get-channel-users channel-name)))
234     (lirc-set-channel-users channel-name
235                             (cl-set-difference current-users users :test #'equal))))
236
237 (defun lirc-del-users (&rest users)
238   (dolist (channel lirc-channel-list)
239     (apply #'lirc-del-channel-users (cons (car channel) users))))
240
241 (defun lirc-rename-user (old-nick new-nick)
242   (dolist (channel lirc-channel-list)
243     (let ((channel-name (car channel))
244           (channel-users (cdr channel)))
245       (when (memq old-nick channel-users)
246         (lirc-del-channel-users old-nick)
247         (lirc-add-channel-users new-nick)))))
248
249
250 ;;; Buffer
251 ;;
252
253 (defun lirc-display-string (&rest strings)
254   (with-current-buffer (get-buffer-create "*lirc*")
255     (save-excursion
256       (goto-char lirc-prompt-marker)
257       (let ((inhibit-read-only t))
258         (insert-before-markers
259          (propertize (concat (format-time-string "%H:%M") " ")
260                      'face 'lirc-text
261                      'read-only t)
262          (propertize (concat (apply #'concat strings) "\n")
263                      'read-only t))))))
264
265 (defun lirc-connect ()
266   (lirc-get-process t)
267   (lirc-send-msg (lirc-msg nil nil "USER" lirc-user-name 0 "*" lirc-full-name))
268   (lirc-send-msg (lirc-msg nil nil "NICK" lirc-nick)))
269
270 (defun lirc-send-msg (msg)
271   (let ((proc (lirc-get-process)))
272     (process-send-string proc (concat (lirc-msg->string msg) "\r\n"))))
273
274 (defun lirc-render-prompt ()
275   (with-current-buffer "*lirc*"
276     (save-excursion
277       (set-marker-insertion-type lirc-prompt-marker nil)
278       (set-marker-insertion-type lirc-input-marker t)
279       (let ((inhibit-read-only t))
280         (delete-region lirc-prompt-marker lirc-input-marker)
281         (goto-char lirc-prompt-marker)
282         (insert
283          (propertize (if lirc-current-channel
284                          lirc-current-channel
285                        "[no channel]")
286                      'face 'lirc-channel
287                      'read-only t)
288          (propertize lirc-prompt-string
289                      'face 'lirc-prompt
290                      'read-only t
291                      'rear-nonsticky t)))
292       (set-marker-insertion-type lirc-input-marker nil))))
293   
294 (defvar lirc-prompt-marker nil
295   "Marker for prompt position in LIRC buffer.")
296
297 (defvar lirc-input-marker nil
298   "Marker for prompt position in LIRC buffer.")
299
300 (defun lirc-setup-buffer ()
301   (with-current-buffer (get-buffer-create "*lirc*")
302     (if (markerp lirc-prompt-marker)
303         (set-marker lirc-prompt-marker (point-max))
304       (setq lirc-prompt-marker (point-max-marker)))
305     (if (markerp lirc-input-marker)
306         (set-marker lirc-input-marker (point-max))
307       (setq lirc-input-marker (point-max-marker)))
308     (lirc-render-prompt)
309     (goto-char (point-max))
310     (recenter -1)))
311
312
313 ;;; Output formatting
314 ;;
315
316 (defun lirc-display-action (channel nick action)
317   (lirc-display-string (concat " * "
318                                (propertize (concat nick " " action)
319                                            'face 'lirc-text))))
320
321 (defun lirc-display-message (channel nick message)
322   (lirc-display-string
323    (concat
324     (propertize (concat channel " ")
325                 'face 'lirc-text)
326     (propertize (concat "<" nick "> ")
327                 'face
328                 (if (equal nick lirc-nick)
329                     'lirc-your-nick
330                   'lirc-text))
331     (propertize message 'face 'lirc-text))))
332
333 (defun lirc-display-notice (&rest notices)
334   (lirc-display-string lirc-notice-prompt " " (apply #'concat notices)))
335
336 (defun lirc-display-error (&rest messages)
337   (lirc-display-string lirc-error-prompt " "
338                        (propertize (apply #'concat messages)
339                                    'face 'lirc-error)))
340
341 ;;; Message evaluation
342 ;;
343
344 (defun lirc-eval-msg-string (string)
345   ;; (lirc-display-string string)
346   (let* ((msg (lirc-string->msg string)))
347     (pcase (lirc-msg-cmd msg)
348       ("PING"
349        (lirc-send-msg
350         (lirc-msg nil nil "PONG" (lirc-msg-params msg))))
351
352       ("353" ; NAMEREPLY
353        (let* ((params (lirc-msg-params msg))
354               (channel (elt params 2))
355               (names (split-string (elt params 3))))
356          (apply #'lirc-add-channel-users (cons channel names))))
357
358       ("366" ; ENDOFNAMES
359        (lirc-display-notice
360         (lirc-as-string (length (lirc-get-channel-users lirc-current-channel)))
361         " users in " lirc-current-channel))
362
363       ((rx (= 3 (any digit)))
364        (lirc-display-notice (mapconcat 'identity (cdr (lirc-msg-params msg)) " ")))
365
366       ((and "JOIN"
367             (guard (equal lirc-nick (lirc-msg-src msg))))
368        (let ((channel (car (lirc-msg-params msg))))
369          (setq lirc-current-channel channel)
370          (lirc-add-channel channel)
371          (lirc-display-notice "Joining channel " channel)
372          (lirc-render-prompt)))
373
374       ("JOIN"
375        (let ((channel (car (lirc-msg-params msg)))
376              (nick (lirc-msg-src msg)))
377          (lirc-add-channel-users channel nick)
378          (lirc-display-notice nick " joined channel " channel)))
379
380       ((and "PART"
381             (guard (equal lirc-nick (lirc-msg-src msg))))
382        (let ((channel (car (lirc-msg-params msg))))
383          (lirc-display-notice "Left channel " channel)
384          (lirc-del-channel (car (lirc-msg-params msg)))
385          (when (equal lirc-current-channel channel)
386            (setq lirc-current-channel nil)
387            (lirc-render-prompt))))
388
389       ("PART"
390        (let ((channel (car (lirc-msg-params msg)))
391              (nick (lirc-msg-src msg)))
392          (lirc-del-channel-users channel nick)
393          (lirc-display-notice nick " left channel " channel)))
394
395       ("QUIT"
396        (let ((nick (lirc-msg-src msg))
397              (reason (mapconcat 'identity (lirc-msg-params msg) " ")))
398          (lirc-del-users nick)
399          (lirc-display-notice nick " quit: " reason)))
400
401       ((and "NICK"
402             (guard (equal lirc-nick (lirc-msg-src msg))))
403        (setq lirc-nick (car (lirc-msg-params msg)))
404        (lirc-display-notice "Set nick to " lirc-nick))
405
406       ("NICK"
407        (let ((old-nick (lirc-msg-src msg))
408              (new-nick (car (lirc-msg-params msg))))
409          (lirc-display-notice nick " is now known as " new-nick)
410          (lirc-rename-user nick new-nick)))
411
412       ("NOTICE"
413        (let ((nick (lirc-msg-src msg))
414              (channel (car (lirc-msg-params msg)))
415              (text (cadr (lirc-msg-params msg))))
416          (pcase text
417            ((rx (: "\01VERSION "
418                    (let version (* (not "\01")))
419                    "\01"))
420             (lirc-display-notice "CTCP version reply from " nick ": " version))
421            (_
422             (lirc-display-notice text)))))
423
424       ("PRIVMSG"
425        (let ((nick (lirc-msg-src msg))
426              (channel (car (lirc-msg-params msg)))
427              (text (cadr (lirc-msg-params msg))))
428          (pcase text
429            ((rx (: "\01ACTION "
430                    (let action (* (not "\01")))
431                    "\01"))
432             (lirc-display-action nick action))
433
434            ("\01VERSION\01"
435             (let ((version-string (concat lirc-version " - running on GNU Emacs " emacs-version)))
436               (lirc-send-msg (lirc-msg nil nil "NOTICE"
437                                        (list nick (concat "\01VERSION "
438                                                           version-string
439                                                           "\01")))))
440             (lirc-display-notice "CTCP version request received from " nick))
441
442            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
443             (lirc-send-msg (lirc-msg nil nil "NOTICE" (list nick ping)))
444             (lirc-display-notice "CTCP ping received from " nick))
445
446            ("\01USERINFO\01"
447             (lirc-display-notice "CTCP userinfo request from " nick " (no response sent)"))
448
449            (_
450             (lirc-display-message channel nick text)))))
451       (_
452        (lirc-display-string (lirc-msg->string msg))))))
453
454
455 ;;; Command entering
456 ;;
457
458 (defun lirc-enter-string (string)
459   (if (string-prefix-p "/" string)
460       (pcase (substring string 1)
461         ((rx (: "TOPIC" " " (let new-topic (* not-newline))))
462          (lirc-send-msg (lirc-msg nil nil "TOPIC" lirc-current-channel new-topic)))
463
464         ((rx (: "me" " " (let action (* not-newline))))
465          (lirc-send-msg (lirc-msg nil nil "PRIVMSG"
466                                   (list lirc-current-channel
467                                         (concat "\01ACTION " action "\01"))))
468          (lirc-display-action lirc-nick action))
469
470         ((rx (: "VERSION" " " (let nick (* (not whitespace)))))
471          (lirc-send-msg (lirc-msg nil nil "PRIVMSG"
472                                   (list nick "\01VERSION\01")))
473          (lirc-display-notice "CTCP version request sent to " nick))
474
475         ((rx "PART" (opt (: " " (let channel (* not-newline)))))
476          (if (or lirc-current-channel channel)
477              (lirc-send-msg (lirc-msg nil nil "PART" (if channel
478                                                          channel
479                                                        lirc-current-channel)))
480            (lirc-display-error "No current channel to leave.")))
481
482         ((rx "MSG "
483              (let target (* (not whitespace)))
484              " "
485              (let text (* not-newline)))
486          (lirc-send-msg (lirc-msg nil nil "PRIVMSG" target text))
487          (lirc-display-message target lirc-nick text))
488
489         ((rx (: (let cmd-str (+ (not whitespace)))
490                 (opt (: " " (let params-str (* not-newline))))))
491          (lirc-send-msg (lirc-msg nil nil (upcase cmd-str)
492                                   (if params-str
493                                       (split-string params-str)
494                                     nil)))))
495
496     (unless (string-empty-p string)
497       (if lirc-current-channel
498           (progn
499             (lirc-send-msg (lirc-msg nil nil "PRIVMSG" lirc-current-channel string))
500             (lirc-display-message lirc-current-channel lirc-nick string))
501         (lirc-display-error "No current channel.")))))
502
503 (defun lirc-enter ()
504   "Enter current contents of line after prompt."
505   (interactive)
506   (with-current-buffer "*lirc*"
507     (lirc-enter-string
508      (buffer-substring lirc-input-marker (point-max)))
509     (let ((inhibit-read-only t))
510       (delete-region lirc-input-marker (point-max)))))
511
512
513
514 ;;; Mode
515 ;;
516
517 (defvar lirc-mode-map
518   (let ((map (make-sparse-keymap)))
519     (define-key map (kbd "RET") 'lirc-enter)
520     map))
521
522 (define-derived-mode lirc-mode text-mode "lirc"
523   "Major mode for LIRC.")
524
525 (when (fboundp 'evil-set-initial-state)
526   (evil-set-initial-state 'lirc-mode 'insert))
527
528 ;;; Main start procedure
529 ;;
530
531 (defun lirc ()
532   "Switch to *lirc* buffer."
533   (interactive)
534   (if (get-buffer "*lirc*")
535       (switch-to-buffer "*lirc*")
536     (switch-to-buffer "*lirc*"))
537   (lirc-mode)
538   (lirc-setup-buffer)
539   (lirc-connect)
540   "Started LIRC.")
541
542
543
544 ;;; lirc.el ends here