forked from vincelwt/RaspberryCast
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
executable file
·237 lines (201 loc) · 6.97 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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#!/usr/bin/env python
import logging
import os
import sys
import json
try:
# this works in Python3
from urllib.request import urlretrieve
except ImportError:
# this works in Python2
from urllib import urlretrieve
from bottle import Bottle, SimpleTemplate, request, response, \
template, run, static_file
from process import launchvideo, queuevideo, playlist, \
setState, getState, setVolume
if len(sys.argv) > 1:
config_file = sys.argv[1]
else:
config_file = 'raspberrycast.conf'
with open(config_file) as f:
config = json.load(f)
# Setting log
logging.basicConfig(
filename='RaspberryCast.log',
format="%(asctime)s - %(levelname)s - %(message)s",
datefmt='%m-%d %H:%M:%S',
level=logging.DEBUG
)
logger = logging.getLogger("RaspberryCast")
# Creating handler to print messages on stdout
root = logging.getLogger()
root.setLevel(logging.DEBUG)
ch = logging.StreamHandler(sys.stdout)
ch.setLevel(logging.INFO)
formatter = logging.Formatter('%(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
root.addHandler(ch)
try:
os.mkfifo("/tmp/cmd")
except OSError as e:
# 17 means the file already exists.
if e.errno != 17:
raise
if config["new_log"]:
os.system("sudo fbi -T 1 --noverbose -a images/ready.jpg")
setState("0")
open('video.queue', 'w').close() # Reset queue
logger.info('Server successfully started!')
app = Bottle()
SimpleTemplate.defaults["get_url"] = app.get_url
@app.hook('after_request')
def enable_cors():
response.headers['Access-Control-Allow-Origin'] = '*'
@app.route('/static/<filename>', name='static')
def server_static(filename):
return static_file(filename, root='static')
@app.route('/')
@app.route('/remote')
def remote():
logger.debug('Remote page requested.')
return template('remote')
@app.route('/stream')
def stream():
url = request.query['url']
logger.debug('Received URL to cast: '+url)
if 'slow' in request.query:
if request.query['slow'] in ["True", "true"]:
config["slow_mode"] = True
else:
config["slow_mode"] = False
# TODO: Do we really want to write this to disk?
with open(config_file, 'w') as f:
json.dump(config, f)
try:
if ('localhost' in url) or ('127.0.0.1' in url):
ip = request.environ['REMOTE_ADDR']
logger.debug('''URL contains localhost adress. \
Replacing with remote ip : ''' + ip)
url = url.replace('localhost', ip).replace('127.0.0.1', ip)
if 'subtitles' in request.query:
subtitles = request.query['subtitles']
if ('localhost' in subtitles) or ('127.0.0.1' in subtitles):
ip = request.environ['REMOTE_ADDR']
logger.debug(
'''Subtitle path contains localhost adress.
Replacing with remote IP.''')
subtitles = subtitles\
.replace('localhost', ip)\
.replace('127.0.0.1', ip)
logger.debug('Subtitles link is '+subtitles)
urlretrieve(subtitles, "subtitle.srt")
launchvideo(url, config, sub=True)
else:
logger.debug('No subtitles for this stream')
if (
("youtu" in url and "list=" in url) or
("soundcloud" in url and "/sets/" in url)):
playlist(url, True, config)
else:
launchvideo(url, config, sub=False)
return "1"
except Exception as e:
logger.error(
'Error in launchvideo function or during downlading the subtitles')
logger.exception(e)
return "0"
@app.route('/queue')
def queue():
url = request.query['url']
if 'slow' in request.query:
if request.query['slow'] in ["True", "true"]:
config["slow_mode"] = True
else:
config["slow_mode"] = False
with open('raspberrycast.conf', 'w') as f:
json.dump(config, f)
try:
if getState() != "0":
logger.info('Adding URL to queue: '+url)
if (
("youtu" in url and "list=" in url) or
("soundcloud" in url and "/sets/" in url)):
playlist(url, False, config)
else:
queuevideo(url, config)
return "2"
else:
logger.info('No video currently playing, playing url : '+url)
if (
("youtu" in url and "list=" in url) or
("soundcloud" in url and "/sets/" in url)):
playlist(url, True, config)
else:
launchvideo(url, config, sub=False)
return "1"
except Exception as e:
logger.error('Error in launchvideo or queuevideo function !')
logger.exception(e)
return "0"
@app.route('/video')
def video():
control = request.query['control']
if control == "pause":
logger.info('Command : pause')
os.system("echo -n p > /tmp/cmd &")
return "1"
elif control in ["stop", "next"]:
logger.info('Command : stop video')
os.system("echo -n q > /tmp/cmd &")
return "1"
elif control == "right":
logger.info('Command : forward')
os.system("echo -n $'\x1b\x5b\x43' > /tmp/cmd &")
return "1"
elif control == "left":
logger.info('Command : backward')
os.system("echo -n $'\x1b\x5b\x44' > /tmp/cmd &")
return "1"
elif control == "longright":
logger.info('Command : long forward')
os.system("echo -n $'\x1b\x5b\x41' > /tmp/cmd &")
return "1"
elif control == "longleft":
logger.info('Command : long backward')
os.system("echo -n $'\x1b\x5b\x42' > /tmp/cmd &")
return "1"
@app.route('/sound')
def sound():
vol = request.query['vol']
if vol == "more":
logger.info('REMOTE: Command : Sound ++')
os.system("echo -n + > /tmp/cmd &")
elif vol == "less":
logger.info('REMOTE: Command : Sound --')
os.system("echo -n - > /tmp/cmd &")
setVolume(vol)
return "1"
@app.route('/shutdown')
def shutdown():
time = request.query['time']
if time == "cancel":
os.system("shutdown -c")
logger.info("Shutdown canceled.")
return "1"
else:
try:
time = int(time)
if (time < 400 and time >= 0):
shutdown_command = "shutdown -h +" + str(time) + " &"
os.system(shutdown_command)
logger.info("Shutdown should be successfully programmed")
return "1"
except:
logger.error("Error in shutdown command parameter")
return "0"
@app.route('/running')
def webstate():
currentState = getState()
logger.debug("Running state as been asked : "+currentState)
return currentState
run(app, reloader=False, host='0.0.0.0', debug=True, quiet=True, port=2020)