]> code.delx.au - gnu-emacs-elpa/blob - packages/web-server/examples/018-web-shell.el
78814d181d5ed5863bfdfae8ce7dc07a5db409d0
[gnu-emacs-elpa] / packages / web-server / examples / 018-web-shell.el
1 ;;; web-shell.el --- interact with a SHELL through a web interface
2
3 ;; Copyright (C) 2013 Eric Schulte <schulte.eric@gmail.com>
4
5 ;;; Commentary:
6
7 ;; DO NOT RUN THIS EXAMPLE!
8
9 ;; At least not if anyone has network access to your computer.
10
11 ;; This example starts a local shell using the `shell' function. The
12 ;; resulting comint buffer is then exported using web sockets.
13 ;; Clients can run local shell commands and see their results through
14 ;; their browser.
15
16 ;; This example is included because it should be easily generalizable
17 ;; to build web interfaces to other comint buffers using web sockets.
18
19 ;;; Code:
20 (defvar web-shell-port 9018)
21
22 (defun web-shell-f-to-s (f)
23 (with-temp-buffer
24 (insert-file-contents-literally
25 (expand-file-name f
26 (file-name-directory
27 (or load-file-name buffer-file-name default-directory))))
28 (buffer-string)))
29
30 (defvar web-shell-js (web-shell-f-to-s "018-web-shell.js"))
31
32 (defvar web-shell-html (web-shell-f-to-s "018-web-shell.html"))
33
34 (defvar web-shell-socket nil)
35
36 (defun web-shell-socket-respond (string)
37 (when web-shell-socket
38 (process-send-string web-shell-socket (ws-web-socket-frame string))))
39
40 (defun web-shell-socket-handler (process string)
41 (message "recieved %S" string)
42 (with-current-buffer "*shell*"
43 (goto-char (process-mark (get-buffer-process (current-buffer))))
44 (insert string)
45 (comint-send-input)))
46
47 (defun web-shell-handler (request)
48 (with-slots (process headers) request
49 ;; if a web-socket request
50 (if (ws-web-socket-connect request 'web-shell-socket-handler)
51 ;; then connect and keep open
52 (prog1 :keep-alive
53 (setq web-shell-socket process)
54 (add-hook 'comint-output-filter-functions 'web-shell-socket-respond))
55 ;; otherwise send the html and javascript
56 (save-window-excursion (shell))
57 (ws-response-header process 200 '("Content-type" . "text/html"))
58 (process-send-string process
59 (format web-shell-html (format web-shell-js web-shell-port))))))
60
61 (ws-start 'web-shell-handler 9018)