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
|
import os
import base64
import io
import binascii
import zipfile
from uuid import uuid4
from flask import after_this_request, send_from_directory, Blueprint, current_app
from flask_restful import Resource, reqparse, abort, request, url_for, Api
from cerberus import Validator
from werkzeug.datastructures import FileStorage
from flasgger import swag_from
from matweb import file_removal_scheduler, utils
api_bp = Blueprint('api_bp', __name__)
api = Api(api_bp, prefix='/api')
class APIUpload(Resource):
@swag_from('./oas/upload.yml')
def post(self):
utils.check_upload_folder(current_app.config['UPLOAD_FOLDER'])
req_parser = reqparse.RequestParser()
req_parser.add_argument('file_name', type=str, required=True, help='Post parameter is not specified: file_name')
req_parser.add_argument('file', type=str, required=True, help='Post parameter is not specified: file')
args = req_parser.parse_args()
try:
file_data = base64.b64decode(args['file'])
except (binascii.Error, ValueError):
abort(400, message='Failed decoding file')
file = FileStorage(stream=io.BytesIO(file_data), filename=args['file_name'])
try:
filename, filepath = utils.save_file(file, current_app.config['UPLOAD_FOLDER'])
except ValueError:
abort(400, message='Invalid Filename')
parser, mime = utils.get_file_parser(filepath)
if parser is None:
abort(415, message='The type %s is not supported' % mime)
meta = parser.get_meta()
if not parser.remove_all():
abort(500, message='Unable to clean %s' % mime)
key, secret, meta_after, output_filename = utils.cleanup(parser, filepath, current_app.config['UPLOAD_FOLDER'])
return utils.return_file_created_response(
utils.get_file_removal_max_age_sec(),
output_filename,
mime,
key,
secret,
meta,
meta_after,
url_for(
'api_bp.apidownload',
key=key,
secret=secret,
filename=output_filename,
_external=True
)
), 201
class APIDownload(Resource):
@swag_from('./oas/download.yml')
def get(self, key: str, secret: str, filename: str):
complete_path, filepath = utils.is_valid_api_download_file(filename, key, secret, current_app.config['UPLOAD_FOLDER'])
# Make sure the file is NOT deleted on HEAD requests
if request.method == 'GET':
file_removal_scheduler.run_file_removal_job(current_app.config['UPLOAD_FOLDER'])
@after_this_request
def remove_file(response):
if os.path.exists(complete_path):
os.remove(complete_path)
return response
return send_from_directory(current_app.config['UPLOAD_FOLDER'], filepath, as_attachment=True)
class APIClean(Resource):
@swag_from('./oas/remove_metadata.yml')
def post(self):
if 'file' not in request.files:
abort(400, message='No file part')
uploaded_file = request.files['file']
if not uploaded_file.filename:
abort(400, message='No selected `file`')
try:
filename, filepath = utils.save_file(uploaded_file, current_app.config['UPLOAD_FOLDER'])
except ValueError:
abort(400, message='Invalid Filename')
parser, mime = utils.get_file_parser(filepath)
if parser is None:
abort(415, message='The type %s is not supported' % mime)
if parser.remove_all() is not True:
abort(500, message='Unable to clean %s' % mime)
_, _, _, output_filename = utils.cleanup(parser, filepath, current_app.config['UPLOAD_FOLDER'])
@after_this_request
def remove_file(response):
os.remove(os.path.join(current_app.config['UPLOAD_FOLDER'], output_filename))
return response
return send_from_directory(current_app.config['UPLOAD_FOLDER'], output_filename, as_attachment=True)
class APIBulkDownloadCreator(Resource):
schema = {
'download_list': {
'type': 'list',
'minlength': 2,
'maxlength': int(os.environ.get('MAT2_MAX_FILES_BULK_DOWNLOAD', 10)),
'schema': {
'type': 'dict',
'schema': {
'key': {'type': 'string', 'required': True},
'secret': {'type': 'string', 'required': True},
'file_name': {'type': 'string', 'required': True}
}
}
}
}
v = Validator(schema)
@swag_from('./oas/bulk.yml')
def post(self):
utils.check_upload_folder(current_app.config['UPLOAD_FOLDER'])
data = request.json
if not data:
abort(400, message="Post Body Required")
if not self.v.validate(data):
abort(400, message=self.v.errors)
# prevent the zip file from being overwritten
zip_filename = 'files.' + str(uuid4()) + '.zip'
zip_path = os.path.join(current_app.config['UPLOAD_FOLDER'], zip_filename)
cleaned_files_zip = zipfile.ZipFile(zip_path, 'w')
with cleaned_files_zip:
for file_candidate in data['download_list']:
complete_path, file_path = utils.is_valid_api_download_file(
file_candidate['file_name'],
file_candidate['key'],
file_candidate['secret'],
current_app.config['UPLOAD_FOLDER']
)
try:
cleaned_files_zip.write(complete_path)
os.remove(complete_path)
except ValueError:
abort(400, message='Creating the archive failed')
try:
cleaned_files_zip.testzip()
except ValueError as e:
abort(400, message=str(e))
parser, mime = utils.get_file_parser(zip_path)
if not parser.remove_all():
abort(500, message='Unable to clean %s' % mime)
key, secret, meta_after, output_filename = utils.cleanup(parser, zip_path, current_app.config['UPLOAD_FOLDER'])
return {
'inactive_after_sec': utils.get_file_removal_max_age_sec(),
'output_filename': output_filename,
'mime': mime,
'key': key,
'secret': secret,
'meta_after': meta_after,
'download_link': url_for(
'api_bp.apidownload',
key=key,
secret=secret,
filename=output_filename,
_external=True
)
}, 201
class APISupportedExtensions(Resource):
@swag_from('./oas/extension.yml')
def get(self):
return utils.get_supported_extensions()
api.add_resource(
APIUpload,
'/upload'
)
api.add_resource(
APIDownload,
'/download/<string:key>/<string:secret>/<string:filename>'
)
api.add_resource(
APIClean,
'/remove_metadata'
)
api.add_resource(
APIBulkDownloadCreator,
'/download/bulk'
)
api.add_resource(APISupportedExtensions, '/extension')
|