Skip to content

Commit 419336c

Browse files
committed
Add images upload to backend
1 parent efc936c commit 419336c

File tree

3 files changed

+40
-0
lines changed

3 files changed

+40
-0
lines changed

mystbin/backend/routers/pastes.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,9 @@
5353
del __p, __f # micro-opt, don't keep unneeded variables in-ram
5454

5555

56+
CF_DLURL = f"https://api.cloudflare.com/client/v4/accounts/{__config['cf_images_account']}/images/v2/direct_upload?requireSignedURLs=true"
57+
58+
5659
def generate_paste_id():
5760
"""Generate three random words."""
5861
word_samples = sample(word_list, 3)
@@ -177,6 +180,26 @@ async def put_pastes(
177180
return UJSONResponse(paste, status_code=201)
178181

179182

183+
@router.get(
184+
"/images/upload",
185+
tags=["pastes"],
186+
status_code=201,
187+
include_in_schema=False,
188+
)
189+
async def get_image_upload_link(request: MystbinRequest, auth: Optional[str] = ''):
190+
if auth != __config['cf_images_frontend_secret']:
191+
return UJSONResponse({'error': 'Unauthorized.'}, status_code=401)
192+
193+
headers = {
194+
'Authorization': f'Bearer {__config["cf_images_token"]}'}
195+
196+
async with request.app.state.client.post(CF_DLURL, headers=headers) as resp:
197+
data = await resp.json()
198+
199+
result = data['result']['uploadURL']
200+
return UJSONResponse({'url': result}, status_code=201)
201+
202+
180203
desc = f"""Get a paste by ID.
181204
182205
This endpoint falls under the `getpaste` ratelimit bucket.

mystbin/backend/utils/db.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -968,3 +968,12 @@ async def put_log(self, request: Request, response: Response) -> None:
968968
response.status_code,
969969
resp,
970970
)
971+
972+
async def put_paste_images(self, parent_id, tab_id) -> None:
973+
query = """INSERT INTO images VALUES($1, $2)"""
974+
975+
await self._do_query(
976+
query,
977+
parent_id,
978+
tab_id
979+
)

mystbin/database/schema.sql

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,14 @@ CREATE TABLE IF NOT EXISTS files (
3535
PRIMARY KEY (parent_id, index)
3636
);
3737

38+
CREATE TABLE IF NOT EXISTS images (
39+
parent_id TEXT REFERENCES pastes(id) ON DELETE CASCADE,
40+
tab_id BIGINT,
41+
index SERIAL NOT NULL,
42+
PRIMARY KEY (parent_id, index)
43+
44+
);
45+
3846
CREATE TABLE IF NOT EXISTS bookmarks (
3947
userid bigint not null references users(id) ON DELETE CASCADE,
4048
paste text not null references pastes(id) ON DELETE CASCADE,

0 commit comments

Comments
 (0)