]> code.delx.au - gnu-emacs-elpa/blob - packages/web-server/examples/018-web-shell.el
Merge commit '0cda39255827f283e7578cd469ae42daad9556a2' from js2-mode
[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-2014 Free Software Foundation, Inc.
4
5 ;; This software is free software: you can redistribute it and/or modify
6 ;; it under the terms of the GNU General Public License as published by
7 ;; the Free Software Foundation, either version 3 of the License, or
8 ;; (at your option) any later version.
9
10 ;; This software is distributed in the hope that it will be useful,
11 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
12 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 ;; GNU General Public License for more details.
14
15 ;; You should have received a copy of the GNU General Public License
16 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
17
18 ;;; Commentary:
19
20 ;; DO NOT RUN THIS EXAMPLE!
21
22 ;; At least not if anyone has network access to your computer.
23
24 ;; This example starts a local shell using the `shell' function. The
25 ;; resulting comint buffer is then exported using web sockets.
26 ;; Clients can run local shell commands and see their results through
27 ;; their browser.
28
29 ;; This example is included because it should be easily generalizable
30 ;; to build web interfaces to other comint buffers using web sockets.
31
32 ;;; Code:
33 (defvar web-shell-port 9018)
34
35 (defun web-shell-f-to-s (f)
36 (with-temp-buffer
37 (insert-file-contents-literally
38 (expand-file-name f
39 (file-name-directory
40 (or load-file-name buffer-file-name default-directory))))
41 (buffer-string)))
42
43 (defvar web-shell-js (web-shell-f-to-s "018-web-shell.js"))
44
45 (defvar web-shell-html (web-shell-f-to-s "018-web-shell.html"))
46
47 (defvar web-shell-socket nil)
48
49 (defun web-shell-socket-respond (string)
50 (when web-shell-socket
51 (process-send-string web-shell-socket (ws-web-socket-frame string))))
52
53 (defun web-shell-socket-handler (process string)
54 (message "recieved %S" string)
55 (with-current-buffer "*shell*"
56 (goto-char (process-mark (get-buffer-process (current-buffer))))
57 (insert string)
58 (comint-send-input)))
59
60 (defun web-shell-handler (request)
61 (with-slots (process headers) request
62 ;; if a web-socket request
63 (if (ws-web-socket-connect request 'web-shell-socket-handler)
64 ;; then connect and keep open
65 (prog1 :keep-alive
66 (setq web-shell-socket process)
67 (add-hook 'comint-output-filter-functions 'web-shell-socket-respond))
68 ;; otherwise send the html and javascript
69 (save-window-excursion (shell))
70 (ws-response-header process 200 '("Content-type" . "text/html"))
71 (process-send-string process
72 (format web-shell-html (format web-shell-js web-shell-port))))))
73
74 (ws-start 'web-shell-handler 9018)