-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
241 lines (164 loc) · 6.19 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
'''
Provide API endpoints for the MVS backend.
'''
import sys
import os
# Flask server stuff.
from flask import Flask, request, abort, send_from_directory
from flask_restful import abort, Api, Resource, reqparse
from flask_cors import *
# But let's use WSGIServer for actually putting the host up.
import eventlet
from eventlet import wsgi
from pdb import set_trace as debug
import os
from werkzeug.utils import secure_filename
from subprocess import Popen
from database import MongoDatabase
from pymongo import MongoClient
from processing import Processor
from ipdb import set_trace as debug
from config import *
# -------------------------------------------------------------
# Is this production or development?
DEV = True
# Specify the port number.
PORT = 1496
# Directory to save videos to.
ROOT_DIR = os.getcwd()
SAVE_DIR = f'{os.getcwd()}/videos'
# Create the server.
app = Flask(__name__)
api = Api(app)
valid_headers = ['Content-Type', 'Access-Control-Allow-Origin', '*']
cors = CORS(app, allow_headers=valid_headers)
# Connect to the database.
mongo = MongoDatabase()
# Video processing.
processor = Processor()
# Do a little server-side checking.
ALLOWED_EXTENSIONS = set(['webm', 'mp4', 'mp3', 'wav', 'jpeg', 'gif', 'png'])
# -------------------------------------------------------------
# Global functions.
def allowed_file(filename):
'''Ensure we want to keep this file.'''
return True
def validate_filepath(func):
'''Decorator to validate a filepath from the frontend.'''
def wrapper(obj, video_filename: str = ''):
'''
:obj - the class object. Have to have it for the decoration.
:video_filename - the path to be validated.
'''
# Disallow anything but pure filenames - no messing with other directories.
if video_filename.find('/'):
old_filename = video_filename
split = video_filename.split('/')
video_filename = split[-1]
print(f'Modified filename from {old_filename} to {video_filename}.')
if not os.path.exists(os.path.join(SAVE_DIR, video_filename)):
print(f'Filename: {video_filename} does not exist in directory {SAVE_DIR}. Aborting request.')
abort(404)
func(obj, video_filename)
return wrapper
# --------------------------------------------------------------
class Video(Resource):
@validate_filepath
def get(self, video_filename: str = ''):
'''Return the video for the user to download.'''
print(f'Sending file {video_filename} from {SAVE_DIR}')
response = send_from_directory(directory=SAVE_DIR, filename=video_filename)
return response
@validate_filepath
def delete(self, video_filename: str = ''):
'''Delete a video from the database and the server.'''
print(f'Deleting file {video_filename} from {SAVE_DIR} and from the database.')
os.remove(os.path.join(SAVE_DIR, video_filename))
mongo.delete_video(video_filename)
class Videos(Resource):
def get(self):
'''Return a list of the avilable videos in the database.'''
return mongo.list_videos()
def post(self):
'''Add video files to the database.'''
posts = dict(request.files)
if 'videos' not in posts:
print('No videos in the request...')
return self.get()
for video in posts['videos']:
if video.filename and allowed_file(video.filename):
filename = secure_filename(video.filename)
print(f'Saving {filename} to {SAVE_DIR}...')
video.save(os.path.join(SAVE_DIR, filename))
mongo.add_video(filename, SAVE_DIR)
return self.get()
class VideoServer(Resource):
def get(self):
'''Return the URL of the video server.'''
return 'http://localhost:2007'
class VideoProcessing(Resource):
def get(self):
'''Get the status of all video processing.'''
return processor.get_status()
def post(self):
'''Specify a video and options to process.'''
data = request.data
print('Put processing code here....')
return self.get()
class Experiments(Resource):
def get(self):
return 'Maiden rules.'
def post(self):
'''Add a new experiment'''
experiment = request.json
mongo.add_experiment(experiment)
class Dishes(Resource):
def get(self):
return get_list_of_dishes()
'''
class GroundTruths(Resource):
"""Handle creation of ground truth, etc."""
def post(self):
"""Create a new post-field ground truth point."""
data = request.json
new_truth = create_machine_truth(data)
db.add_ground_truth(new_truth)
'''
# ----------------------------------------------------------------
api.add_resource(Videos, '/videos', methods=['GET', 'POST'])
api.add_resource(Video, '/video/<video_filename>', methods=['GET', 'DELETE'])
api.add_resource(VideoServer, '/video_server', methods=['GET'])
api.add_resource(Dishes, '/dishes', methods=['GET'])
api.add_resource(Experiments, '/experiments', methods=['POST', 'GET'])
# -----------------------------------------------------------------
def start_video_server():
'''Start a simple HTTP video server for dealing with downloads.'''
os.chdir(SAVE_DIR)
print('> Launching simple HTTP server for video downloads.')
video_server = Popen(['http-server', '-p', '2007'])
# Now go back to the original root.
os.chdir(ROOT_DIR)
return video_server
def start_mongo():
'''Start mongo if it isn't running.'''
client = MongoClient(serverSelectionTimeoutMS=50)
try:
client.server_info()
return None
except:
db_server = Popen(['mongo'])
return db_server
if __name__ == '__main__':
# Launch the server.
if DEV:
app.run(port=PORT, debug=True)
else:
try:
video_server = start_video_server()
db_server = start_mongo()
wsgi.server(eventlet.listen(('localhost', PORT)), app)
except:
print('> Shutting down the servers!')
if db_server:
db_server.kill()
video_server.kill()