/
cdn_provider.py
295 lines (212 loc) · 6.79 KB
/
cdn_provider.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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
"""
CDN manager for the app
Change to switch to an actual CDN upload if pushing to prod
"""
import io
import os
import re
import uuid
from cloudinary import uploader, api
from pypdf import PdfReader, PdfWriter
from typing import Literal, Optional, overload
from werkzeug.datastructures import FileStorage
# Setup
ENV = os.getenv('ENV', '')
Cloudinary_Folders = {
'Image': 'image-uploads',
'Textbook': 'textbook-uploads',
'Submission': 'submission-uploads',
}
UploadBaseLocation = os.path.join(os.getcwd(), 'src', 'uploads')
CopyrightNoticeLocation = os.path.join(UploadBaseLocation, 'copyright.pdf')
SubmissionUpload = os.path.join(UploadBaseLocation, 'SubmissionUpload')
TextbookLocation = os.path.join(UploadBaseLocation, 'textbooks')
ImageLocation = os.path.join(UploadBaseLocation, 'images')
TextbookFileEXT = ['pdf']
ImageFileEXT = ['png', 'jpg', 'jpeg']
SubmissionFileEXT = ['pdf', 'txt', 'docx', 'doc', 'odt']
class BadFileEXT(Exception):
"""Raised when file extension is not supported"""
def __init__(self, message: str = 'File extension is not supported', *args, **kwargs):
super().__init__(message, *args, **kwargs)
class FileDoesNotExistError(Exception):
"""Raised when file does not exist"""
def __init__(self, message: str = 'File does not exist', *args, **kwargs):
super().__init__(message, *args, **kwargs)
def _dirCheck():
"""Ensure that the upload directories exist"""
if ENV == 'production':
return
if not os.path.isdir(UploadBaseLocation):
os.mkdir(UploadBaseLocation)
if not os.path.isdir(SubmissionUpload):
os.mkdir(SubmissionUpload)
if not os.path.isdir(TextbookLocation):
os.mkdir(TextbookLocation)
if not os.path.isdir(ImageLocation):
os.mkdir(ImageLocation)
def _injectCopyright(file: PdfReader) -> PdfWriter:
"""Injects copyright notice"""
writer = PdfWriter()
writer.add_page(PdfReader(CopyrightNoticeLocation).pages[0])
writer.append_pages_from_reader(file)
return writer
@overload
def _get_unique_filename() -> str:
"""For production"""
...
@overload
def _get_unique_filename(dir: str, filename: str, extension: str) -> str:
"""Ensure edge case where file already exists (although unliekly as filename would be uuid, but doesn't hurt to be sure)"""
...
def _get_unique_filename(
dir: Optional[str] = None,
filename: Optional[str] = None,
extension: Optional[str] = None,
) -> str:
if ENV == 'production':
return uuid.uuid4().hex
if not dir or not filename or not extension:
raise ValueError('dir, filename, and extension are required for development upload')
regex = re.compile(r'[^a-zA-Z0-9-]')
filename = regex.sub('', filename)
while True:
filename = f'{regex.sub("", filename)}.{extension}'
if os.path.exists(os.path.join(dir, filename)):
filename = uuid.uuid4().hex
else:
return filename
def _development_upload(
fileType: Literal['Image', 'Textbook', 'Submission'], file: FileStorage, filename: str
):
_dirCheck()
if not file.filename:
raise BadFileEXT('File does not have a name')
ext = file.filename.split('.')[-1]
# Upload the file
match fileType:
case 'Image':
if ext not in ImageFileEXT:
raise BadFileEXT(f'{ext} is not supported')
filename = _get_unique_filename(ImageLocation, filename, ext)
# Save the file
location = os.path.join(ImageLocation, filename)
file.save(location)
file.close()
return location
case 'Textbook':
if ext not in TextbookFileEXT:
raise BadFileEXT()
filename = _get_unique_filename(TextbookLocation, filename, ext)
# Inject copyright notice
writer = _injectCopyright(PdfReader(file.stream))
location = os.path.join(TextbookLocation, filename)
with open(location, 'wb') as out:
writer.write(out)
return location
case 'Submission':
if ext not in SubmissionFileEXT:
raise BadFileEXT()
filename = _get_unique_filename(SubmissionUpload, filename, ext)
location = os.path.join(SubmissionUpload, filename)
file.save(location)
file.close()
return location
def _production_upload(
fileType: Literal['Image', 'Textbook', 'Submission'], file: FileStorage
):
updatedFile = None
file.filename = _get_unique_filename()
if fileType == 'Textbook':
updatedFile = io.BytesIO(file.stream.read())
_injectCopyright(PdfReader(file.stream)).write_stream(updatedFile)
res = uploader.upload(
updatedFile.getvalue() if updatedFile else file, folder=Cloudinary_Folders[fileType]
)
return res['public_id']
def uploadTextbook(file: FileStorage, filename: str) -> str:
"""
Upload a textbook file to CDN
Parameters
----------
`file: FileStorage`, required
The file data to upload
`filename: str`, required
The filename of the uploaded, will overwrite if invalid
Returns
-------
`Interalpath: str`
The internal path to access the uploaded content
Raises
------
`BadFileEXT`
Raised when the file extension is not valid for a textbook
"""
return (
_production_upload('Textbook', file)
if ENV == 'production'
else _development_upload('Textbook', file, filename)
)
def uploadImage(file: FileStorage, filename: str) -> str:
"""
Upload image to CDN
Parameters
----------
`file: FileStorage`, required
The file data to upload
`filename: str`, required
The filename of the uploaded, will overwrite if invalid
Returns
-------
`Interalpath: str`
The internal path to access the uploaded content
Raises
------
`BadFileEXT`
Raised when the file extension is not valid for an image
"""
return (
_production_upload('Image', file)
if ENV == 'production'
else _development_upload('Image', file, filename)
)
def uploadSubmission(file: FileStorage, filename: str) -> str:
"""
Upload submission to CDN
Parameters
----------
`file: FileStorage`, required
The file data to upload
`filename: str`, required
The filename of the uploaded, will overwrite if invalid
Returns
-------
`Interalpath: str`
The internal path to access the uploaded content
Raises
------
`BadFileEXT`
Raised when the file extension is not valid for an image
"""
return (
_production_upload('Submission', file)
if ENV == 'production'
else _development_upload('Submission', file, filename)
)
def deleteFile(fileLocation: str) -> None:
"""
Delete file
Parameters
----------
`fileLocation: str`, required
The iuri of the file to delete
"""
_dirCheck()
if ENV == 'production':
res = api.delete_resources(public_ids=[fileLocation], type='upload')
if res['deleted'][fileLocation] != 'deleted':
raise Exception('Failed to delete file from CDN')
return
if not os.path.exists(fileLocation):
raise FileDoesNotExistError()
os.remove(fileLocation)