forked from elastickent/rocknsm-upload
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.py
154 lines (110 loc) · 4.89 KB
/
app.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
#!flask/bin/python
# Author: Ngo Duy Khanh
# Email: [email protected]
# Git repository: https://github.com/ngoduykhanh/flask-file-uploader
# This work based on jQuery-File-Upload which can be found at https://github.com/blueimp/jQuery-File-Upload/
import os
import PIL
from PIL import Image
import simplejson
import traceback
import datetime
import subprocess
from flask import Flask, request, render_template, redirect, url_for, send_from_directory
from flask_bootstrap import Bootstrap
from werkzeug import secure_filename
from lib.upload_file import uploadfile
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['UPLOAD_FOLDER'] = 'data/'
app.config['THUMBNAIL_FOLDER'] = 'data/thumbnail/'
app.config['MAX_CONTENT_LENGTH'] = 1500 * 1024 * 1024
ALLOWED_EXTENSIONS = set(['pcap', 'zip', 'tgz', 'gz'])
IGNORED_FILES = set(['.gitignore'])
bootstrap = Bootstrap(app)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def gen_file_name(filename):
"""
If file was exist already, rename it and return a new name
"""
i = 1
while os.path.exists(os.path.join(app.config['UPLOAD_FOLDER'], filename)):
name, extension = os.path.splitext(filename)
filename = '%s_%s%s' % (name, str(i), extension)
i += 1
return filename
def create_thumbnail(image):
try:
base_width = 80
img = Image.open(os.path.join(app.config['UPLOAD_FOLDER'], image))
w_percent = (base_width / float(img.size[0]))
h_size = int((float(img.size[1]) * float(w_percent)))
img = img.resize((base_width, h_size), PIL.Image.ANTIALIAS)
img.save(os.path.join(app.config['THUMBNAIL_FOLDER'], image))
return True
except:
print traceback.format_exc()
return False
@app.route("/upload", methods=['GET', 'POST'])
def upload():
if request.method == 'POST':
files = request.files['file']
if files:
filename = secure_filename(files.filename)
filename = gen_file_name(filename)
mime_type = files.content_type
if not allowed_file(files.filename):
result = uploadfile(name=filename, type=mime_type, size=0, not_allowed_msg="File type not allowed")
else:
# save file to disk
uploaded_file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
files.save(uploaded_file_path)
tstamp = datetime.datetime.utcnow().strftime('%Y-%m-%d-%H.%M.%S.%f')[:-3]
brolabel = 'ROCK::sensor_id=%s-%s' % (tstamp,
(os.path.splitext(filename)[0]))
result = subprocess.check_output(['bro', '-r', uploaded_file_path, 'local',
brolabel])
# create thumbnail after saving
if mime_type.startswith('image'):
create_thumbnail(filename)
# get file size after saving
size = os.path.getsize(uploaded_file_path)
# return json for js call back
result = uploadfile(name=filename, type=mime_type, size=size)
return simplejson.dumps({"files": [result.get_file()]})
if request.method == 'GET':
# get all file in ./data directory
files = [f for f in os.listdir(app.config['UPLOAD_FOLDER']) if os.path.isfile(os.path.join(app.config['UPLOAD_FOLDER'],f)) and f not in IGNORED_FILES ]
file_display = []
for f in files:
size = os.path.getsize(os.path.join(app.config['UPLOAD_FOLDER'], f))
file_saved = uploadfile(name=f, size=size)
file_display.append(file_saved.get_file())
return simplejson.dumps({"files": file_display})
return redirect(url_for('index'))
@app.route("/delete/<string:filename>", methods=['DELETE'])
def delete(filename):
file_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
file_thumb_path = os.path.join(app.config['THUMBNAIL_FOLDER'], filename)
if os.path.exists(file_path):
try:
os.remove(file_path)
if os.path.exists(file_thumb_path):
os.remove(file_thumb_path)
return simplejson.dumps({filename: 'True'})
except:
return simplejson.dumps({filename: 'False'})
# serve static files
@app.route("/thumbnail/<string:filename>", methods=['GET'])
def get_thumbnail(filename):
return send_from_directory(app.config['THUMBNAIL_FOLDER'], filename=filename)
@app.route("/data/<string:filename>", methods=['GET'])
def get_file(filename):
return send_from_directory(os.path.join(app.config['UPLOAD_FOLDER']), filename=filename)
@app.route('/', methods=['GET', 'POST'])
def index():
return render_template('index.html')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80, debug=True)