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