Cleaner connection code.
[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        (lirc-display-notice "Left channel " lirc-current-channel)
383        (setq lirc-current-channel nil)
384        (lirc-del-channel (car (lirc-msg-params msg)))
385        (lirc-render-prompt))
386
387       ("PART"
388        (let ((channel (car (lirc-msg-params msg)))
389              (nick (lirc-msg-src msg)))
390          (lirc-del-channel-users channel nick)
391          (lirc-display-notice nick " left channel " channel)))
392
393       ("QUIT"
394        (let ((nick (lirc-msg-src msg))
395              (reason (mapconcat 'identity (lirc-msg-params msg) " ")))
396          (lirc-del-users nick)
397          (lirc-display-notice nick " quit: " reason)))
398
399       ((and "NICK"
400             (guard (equal lirc-nick (lirc-msg-src msg))))
401        (setq lirc-nick (car (lirc-msg-params msg)))
402        (lirc-display-notice "Set nick to " lirc-nick))
403
404       ("NICK"
405        (let ((old-nick (lirc-msg-src msg))
406              (new-nick (car (lirc-msg-params msg))))
407          (lirc-display-notice nick " is now known as " new-nick)
408          (lirc-rename-user nick new-nick)))
409
410       ("NOTICE"
411        (let ((nick (lirc-msg-src msg))
412              (channel (car (lirc-msg-params msg)))
413              (text (cadr (lirc-msg-params msg))))
414          (pcase text
415            ((rx (: "\01VERSION "
416                    (let version (* (not "\01")))
417                    "\01"))
418             (lirc-display-notice "CTCP version reply from " nick ": " version))
419            (_
420             (lirc-display-notice text)))))
421
422       ("PRIVMSG"
423        (let ((nick (lirc-msg-src msg))
424              (channel (car (lirc-msg-params msg)))
425              (text (cadr (lirc-msg-params msg))))
426          (pcase text
427            ((rx (: "\01ACTION "
428                    (let action (* (not "\01")))
429                    "\01"))
430             (lirc-display-action nick action))
431
432            ("\01VERSION\01"
433             (let ((version-string (concat lirc-version " - running on GNU Emacs " emacs-version)))
434               (lirc-send-msg (lirc-msg nil nil "NOTICE"
435                                        (list nick (concat "\01VERSION "
436                                                           version-string
437                                                           "\01")))))
438             (lirc-display-notice "CTCP version request received from " nick))
439
440            ((rx (let ping (: "\01PING " (* (not "\01")) "\01")))
441             (lirc-send-msg (lirc-msg nil nil "NOTICE" (list nick ping)))
442             (lirc-display-notice "CTCP ping received from " nick))
443
444            ("\01USERINFO\01"
445             (lirc-display-notice "CTCP userinfo request from " nick " (no response sent)"))
446
447            (_
448             (lirc-display-message channel nick text)))))
449       (_
450        (lirc-display-string (lirc-msg->string msg))))))
451
452
453 ;;; Command entering
454 ;;
455
456 (defun lirc-enter-string (string)
457   (if (string-prefix-p "/" string)
458       (pcase (substring string 1)
459         ((rx (: "TOPIC" " " (let new-topic (* not-newline))))
460          (lirc-send-msg (lirc-msg nil nil "TOPIC" lirc-current-channel new-topic)))
461
462         ((rx (: "me" " " (let action (* not-newline))))
463          (lirc-send-msg (lirc-msg nil nil "PRIVMSG"
464                                   (list lirc-current-channel
465                                         (concat "\01ACTION " action "\01"))))
466          (lirc-display-action lirc-nick action))
467
468         ((rx (: "VERSION" " " (let nick (* (not whitespace)))))
469          (lirc-send-msg (lirc-msg nil nil "PRIVMSG"
470                                   (list nick "\01VERSION\01")))
471          (lirc-display-notice "CTCP version request sent to " nick))
472
473         ((rx "PART")
474          (lirc-send-msg (lirc-msg nil nil "PART" lirc-current-channel)))
475
476         ((rx "MSG "
477              (let target (* (not whitespace)))
478              " "
479              (let text (* not-newline)))
480          (lirc-send-msg (lirc-msg nil nil "PRIVMSG" target text))
481          (lirc-display-message target lirc-nick text))
482
483         ((rx (: (let cmd-str (+ (not whitespace)))
484                 (opt (: " " (let params-str (* not-newline))))))
485          (lirc-send-msg (lirc-msg nil nil (upcase cmd-str)
486                                   (if params-str
487                                       (split-string params-str)
488                                     nil)))))
489
490     (unless (string-empty-p string)
491       (lirc-send-msg (lirc-msg nil nil "PRIVMSG" lirc-current-channel string))
492       (lirc-display-message lirc-current-channel lirc-nick string))))
493
494 (defun lirc-enter ()
495   "Enter current contents of line after prompt."
496   (interactive)
497   (with-current-buffer "*lirc*"
498     (lirc-enter-string
499      (buffer-substring lirc-input-marker (point-max)))
500     (let ((inhibit-read-only t))
501       (delete-region lirc-input-marker (point-max)))))
502
503
504
505 ;;; Mode
506 ;;
507
508 (defvar lirc-mode-map
509   (let ((map (make-sparse-keymap)))
510     (define-key map (kbd "RET") 'lirc-enter)
511     map))
512
513 (define-derived-mode lirc-mode text-mode "lirc"
514   "Major mode for LIRC.")
515
516 (when (fboundp 'evil-set-initial-state)
517   (evil-set-initial-state 'lirc-mode 'insert))
518
519 ;;; Main start procedure
520 ;;
521
522 (defun lirc ()
523   "Switch to *lirc* buffer."
524   (interactive)
525   (if (get-buffer "*lirc*")
526       (switch-to-buffer "*lirc*")
527     (switch-to-buffer "*lirc*"))
528   (lirc-mode)
529   (lirc-setup-buffer)
530   (lirc-connect)
531   "Started LIRC.")
532
533
534
535 ;;; lirc.el ends here