/
t0pic.py
142 lines (122 loc) · 4.25 KB
/
t0pic.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
# t0pic - pic.t0.vc
# MIT License
import random
import string
from flask import abort, Flask, request, redirect
from pathlib import Path
from PIL import Image
app = Flask(__name__)
DATA_FOLDER = Path('data')
MAX_SIZE = 1920
PORT = 5003
URL = 'https://pic.t0.vc'
POST_PARAM = 'pic'
MAX_FILE_SIZE = 16 * 1024 * 1024 # 16 MB
def help():
form = (
f'<form action="{URL}" method="POST" accept-charset="UTF-8" enctype="multipart/form-data">'
'<input name="web" type="hidden" value="true">'
f'<input name="{POST_PARAM}" type="file" accept="image/*" />'
'<br><br><button type="submit">Submit</button></form>'
)
return f"""
<meta name="color-scheme" content="light dark" />
<meta name="viewport" content="width=1%" />
<pre>
pic.t0.vc
NAME
t0pic: command line image host.
USAGE
<image output> | curl -F '{POST_PARAM}=@/dev/stdin' {URL}
or upload from the web:
{form}
or paste the image into this page.
DESCRIPTION
I got sick of imgur not working on mobile, so I built this
Images are resized to a max dimension of {MAX_SIZE} px
Don't use this for anything serious
EXAMPLES
~$ cat kitten.jpg | curl -F '{POST_PARAM}=@/dev/stdin' {URL}
{URL}/YXKV.jpg
~$ firefox {URL}/YXKV.jpg
Add this to your .bashrc:
alias {POST_PARAM}="curl -F '{POST_PARAM}=@/dev/stdin' {URL}"
Now you can pipe directly into {POST_PARAM}!
SOURCE CODE
https://txt.t0.vc/CQQE
nginx config: https://txt.t0.vc/ZKEH
https://github.com/tannercollin/t0pic
SEE ALSO
https://txt.t0.vc
https://url.t0.vc
</pre>"""
def paste():
return f"""
window.addEventListener('paste', e => {{
const file = e.clipboardData.items[0].getAsFile();
const url = URL.createObjectURL(file);
const image = new Image();
image.src = url;
const form = new FormData();
form.append('{POST_PARAM}', file);
fetch('/', {{
method: 'POST',
body: form
}})
.then(r => r.text())
.then(u => window.location = u)
.catch(e => alert(e.message));
}});
"""
def new_id():
return ''.join(random.choice(string.ascii_uppercase) for _ in range(4))
@app.route('/', methods=['GET'])
def index():
return f'<html><script>{paste()}</script><body>{help()}</body></html>'
@app.route('/', methods=['POST'])
def new():
try:
if 'pic' not in request.files or request.files['pic'].filename == '':
print("No file part")
abort(400) # No file was uploaded
pic = request.files['pic']
if pic.mimetype not in ['application/octet-stream', 'image/png', 'image/jpeg', 'image/gif']:
print(f"Unsupported image format: {pic.mimetype}")
abort(400) # Consider using a more specific status code or returning an error message
if pic.seek(0, 2) > MAX_ALLOWED_SIZE: # Move to end to get file size
print(f"File size exceeds maximum allowed limit: {pic.tell()} bytes")
abort(413) # Payload Too Large
pic.seek(0) # Reset file pointer
nid = new_id()
while nid in [p.stem for p in PICS.iterdir()]:
nid = new_id()
pic = Image.open(pic.stream) # Use .stream to read directly from Flask file storage
if pic.format == 'PNG':
ext = '.png'
elif pic.format == 'JPEG':
ext = '.jpg'
elif pic.format == 'GIF':
ext = '.gif'
else:
print(f"Unsupported image format: {pic.format}")
abort(400)
filename = nid + ext
if pic.format == 'GIF':
# Handle GIFs separately to preserve animation
pic.save(PICS / filename, save_all=True)
else:
pic.thumbnail([MAX_SIZE, MAX_SIZE], Image.Resampling.LANCZOS)
pic.save(PICS / filename) # Use pathlib's / operator for path concatenation
print(f'Adding pic {nid}{ext}')
url = f'{URL}/{nid}{ext}'
if 'web' in request.form:
return redirect(url)
else:
return f'{url}\n'
except Exception as e:
print(f"Error processing image upload: {e}")
abort(400)
if __name__ == '__main__':
if not DATA_FOLDER.exists():
DATA_FOLDER.mkdir(parents=True)
app.run(port=PORT, debug=False)