forked from patrickfuller/camp
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathserver.py
144 lines (115 loc) · 4.38 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python
"""
Creates an HTTP server with basic auth and websocket communication.
"""
import argparse
import base64
import hashlib
import os
import time
import threading
import webbrowser
try:
import cStringIO as io
except ImportError:
import io
import tornado.web
import tornado.websocket
from tornado.ioloop import PeriodicCallback
# Hashed password for comparison and a cookie for login cache
ROOT = os.path.normpath(os.path.dirname(__file__))
with open(os.path.join(ROOT, "password.txt")) as in_file:
PASSWORD = in_file.read().strip()
COOKIE_NAME = "camp"
class IndexHandler(tornado.web.RequestHandler):
def get(self):
if args.require_login and not self.get_secure_cookie(COOKIE_NAME):
self.redirect("/login")
else:
self.render("index.html", port=args.port, returnssh=">")
class LoginHandler(tornado.web.RequestHandler):
def get(self):
self.render("login.html")
def post(self):
user = self.get_argument("user", "")
password = self.get_argument("password", "")
if hashlib.sha512(password).hexdigest() == PASSWORD and user == "diogo":
self.set_secure_cookie(COOKIE_NAME, str(time.time()))
self.redirect("/")
else:
time.sleep(1)
self.redirect(u"/login?error")
class PlayHandler(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
def post(self):
song = self.get_argument("musica", "")
os.system('mpg321 song/' + song + ' &')
self.redirect("/")
class SSHCommand(tornado.web.RequestHandler):
def get(self):
self.render("index.html")
def post(self):
ssh = self.get_argument("ssh", "")
p = os.popen(ssh,"r").readlines()
retorno = "".join(p)
self.render("index.html", port=args.port, returnssh=retorno)
class WebSocket(tornado.websocket.WebSocketHandler):
def on_message(self, message):
"""Evaluates the function pointed to by json-rpc."""
# Start an infinite loop when this is called
if message == "read_camera":
self.camera_loop = PeriodicCallback(self.loop, 10)
self.camera_loop.start()
# Extensibility for other methods
else:
print("Unsupported function: " + message)
def loop(self):
"""Sends camera images in an infinite loop."""
sio = io.StringIO()
if args.use_usb:
_, frame = camera.read()
img = Image.fromarray(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
img.save(sio, "JPEG")
else:
camera.capture(sio, "jpeg", use_video_port=True)
try:
self.write_message(base64.b64encode(sio.getvalue()))
except tornado.websocket.WebSocketClosedError:
self.camera_loop.stop()
parser = argparse.ArgumentParser(description="Starts a webserver that "
"connects to a webcam.")
parser.add_argument("--port", type=int, default=8000, help="The "
"port on which to serve the website.")
parser.add_argument("--resolution", type=str, default="low", help="The "
"video resolution. Can be high, medium, or low.")
parser.add_argument("--require-login", action="store_true", help="Require "
"a password to log in to webserver.")
parser.add_argument("--use-usb", action="store_true", help="Use a USB "
"webcam instead of the standard Pi camera.")
args = parser.parse_args()
if args.use_usb:
import cv2
from PIL import Image
camera = cv2.VideoCapture(0)
else:
import picamera
camera = picamera.PiCamera()
camera.start_preview()
resolutions = {"high": (1280, 720), "medium": (640, 480), "low": (320, 240)}
if args.resolution in resolutions:
if args.use_usb:
w, h = resolutions[args.resolution]
camera.set(3, w)
camera.set(4, h)
else:
camera.resolution = resolutions[args.resolution]
else:
raise Exception("%s not in resolution options." % args.resolution)
handlers = [(r"/", IndexHandler), (r"/login", LoginHandler), (r"/ssh",SSHCommand),
(r"/play",PlayHandler),
(r"/websocket", WebSocket),
(r'/static/(.*)', tornado.web.StaticFileHandler, {'path': ROOT})]
application = tornado.web.Application(handlers, cookie_secret=PASSWORD)
application.listen(args.port)
tornado.ioloop.IOLoop.instance().start()