veltrixcode commited on
Commit
cb6f208
·
verified ·
1 Parent(s): b6eb1b6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +96 -396
app.py CHANGED
@@ -1,410 +1,110 @@
1
- from flask import Flask, request, jsonify, render_template_string
2
- import os
3
- from datetime import datetime
4
- from werkzeug.utils import secure_filename
5
  import uuid
6
- import io
7
- from internetarchive import get_item
8
 
9
- app = Flask(__name__)
10
 
11
- # Allow all hosts
12
- app.config['SERVER_NAME'] = None
13
-
14
- # Internet Archive S3 Configuration
15
- IA_ACCESS_KEY = "YXzY5OrREXLL6XBh"
16
- IA_SECRET_KEY = "m2XnL3X7xCB1pNGE"
 
 
17
 
18
- ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg'}
19
- MAX_FILE_SIZE = 50 * 1024 * 1024 # 50MB
 
 
20
 
21
- def allowed_file(filename):
22
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
23
 
24
- HTML_TEMPLATE = """
25
- <!DOCTYPE html>
26
- <html lang="en">
27
- <head>
28
- <meta charset="UTF-8">
29
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
30
- <title>Image Upload - Archive.org CDN</title>
31
- <style>
32
- * {
33
- margin: 0;
34
- padding: 0;
35
- box-sizing: border-box;
36
- }
37
- body {
38
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, sans-serif;
39
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
40
- min-height: 100vh;
41
- display: flex;
42
- justify-content: center;
43
- align-items: center;
44
- padding: 20px;
45
- }
46
- .container {
47
- background: rgba(255, 255, 255, 0.95);
48
- backdrop-filter: blur(10px);
49
- border-radius: 24px;
50
- padding: 40px;
51
- max-width: 600px;
52
- width: 100%;
53
- box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
54
- }
55
- h1 {
56
- color: #2d3748;
57
- margin-bottom: 10px;
58
- font-size: 32px;
59
- text-align: center;
60
- }
61
- .subtitle {
62
- color: #718096;
63
- text-align: center;
64
- margin-bottom: 30px;
65
- font-size: 14px;
66
- }
67
- .upload-area {
68
- border: 3px dashed #cbd5e0;
69
- border-radius: 16px;
70
- padding: 60px 20px;
71
- text-align: center;
72
- cursor: pointer;
73
- transition: all 0.3s ease;
74
- background: #f7fafc;
75
- margin-bottom: 20px;
76
- }
77
- .upload-area:hover {
78
- border-color: #667eea;
79
- background: #edf2f7;
80
- transform: translateY(-2px);
81
- }
82
- .upload-area.dragover {
83
- border-color: #667eea;
84
- background: #e6fffa;
85
- }
86
- .upload-icon {
87
- font-size: 48px;
88
- margin-bottom: 16px;
89
- }
90
- .upload-text {
91
- color: #4a5568;
92
- font-size: 18px;
93
- margin-bottom: 8px;
94
- }
95
- .upload-hint {
96
- color: #a0aec0;
97
- font-size: 14px;
98
- }
99
- input[type="file"] {
100
- display: none;
101
- }
102
- .btn {
103
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
104
- color: white;
105
- border: none;
106
- padding: 14px 32px;
107
- border-radius: 12px;
108
- font-size: 16px;
109
- font-weight: 600;
110
- cursor: pointer;
111
- width: 100%;
112
- transition: all 0.3s ease;
113
- box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
114
- }
115
- .btn:hover {
116
- transform: translateY(-2px);
117
- box-shadow: 0 6px 20px rgba(102, 126, 234, 0.6);
118
- }
119
- .btn:disabled {
120
- background: #cbd5e0;
121
- cursor: not-allowed;
122
- box-shadow: none;
123
- }
124
- .preview-container {
125
- margin: 20px 0;
126
- display: none;
127
- }
128
- .preview-image {
129
- max-width: 100%;
130
- border-radius: 12px;
131
- box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
132
- }
133
- .result-container {
134
- margin-top: 20px;
135
- padding: 20px;
136
- background: #f0fff4;
137
- border-radius: 12px;
138
- border: 2px solid #9ae6b4;
139
- display: none;
140
- }
141
- .result-container.error {
142
- background: #fff5f5;
143
- border-color: #fc8181;
144
- }
145
- .url-box {
146
- display: flex;
147
- gap: 10px;
148
- margin-top: 10px;
149
- }
150
- .url-input {
151
- flex: 1;
152
- padding: 12px;
153
- border: 2px solid #e2e8f0;
154
- border-radius: 8px;
155
- font-size: 14px;
156
- font-family: monospace;
157
- }
158
- .copy-btn {
159
- padding: 12px 24px;
160
- background: #667eea;
161
- color: white;
162
- border: none;
163
- border-radius: 8px;
164
- cursor: pointer;
165
- font-weight: 600;
166
- transition: all 0.3s ease;
167
- }
168
- .copy-btn:hover {
169
- background: #5568d3;
170
- }
171
- .loading {
172
- display: none;
173
- text-align: center;
174
- margin: 20px 0;
175
- }
176
- .spinner {
177
- border: 4px solid #f3f4f6;
178
- border-top: 4px solid #667eea;
179
- border-radius: 50%;
180
- width: 40px;
181
- height: 40px;
182
- animation: spin 1s linear infinite;
183
- margin: 0 auto;
184
- }
185
- @keyframes spin {
186
- 0% { transform: rotate(0deg); }
187
- 100% { transform: rotate(360deg); }
188
- }
189
- .file-info {
190
- margin: 15px 0;
191
- padding: 12px;
192
- background: #edf2f7;
193
- border-radius: 8px;
194
- display: none;
195
- }
196
- .file-info-text {
197
- color: #4a5568;
198
- font-size: 14px;
199
- }
200
- </style>
201
- </head>
202
- <body>
203
- <div class="container">
204
- <h1>📸 Image Upload</h1>
205
- <p class="subtitle">Upload to Archive.org CDN</p>
206
- <div class="upload-area" id="uploadArea">
207
- <div class="upload-icon">☁️</div>
208
- <div class="upload-text">Click or drag image here</div>
209
- <div class="upload-hint">PNG, JPG, GIF, WEBP up to 50MB</div>
210
- <input type="file" id="fileInput" accept="image/*">
211
- </div>
212
- <div class="file-info" id="fileInfo">
213
- <div class="file-info-text" id="fileInfoText"></div>
214
- </div>
215
- <div class="preview-container" id="previewContainer">
216
- <img id="previewImage" class="preview-image" alt="Preview">
217
- </div>
218
- <button class="btn" id="uploadBtn" disabled>Upload Image</button>
219
- <div class="loading" id="loading">
220
- <div class="spinner"></div>
221
- <p style="margin-top: 10px; color: #4a5568;">Uploading...</p>
222
- </div>
223
- <div class="result-container" id="resultContainer">
224
- <div style="font-weight: 600; margin-bottom: 10px; color: #2d3748;" id="resultTitle">✅ Upload Successful!</div>
225
- <div class="url-box">
226
- <input type="text" class="url-input" id="urlInput" readonly>
227
- <button class="copy-btn" id="copyBtn">Copy</button>
228
- </div>
229
- </div>
230
- </div>
231
- <script>
232
- const uploadArea = document.getElementById('uploadArea');
233
- const fileInput = document.getElementById('fileInput');
234
- const uploadBtn = document.getElementById('uploadBtn');
235
- const previewContainer = document.getElementById('previewContainer');
236
- const previewImage = document.getElementById('previewImage');
237
- const loading = document.getElementById('loading');
238
- const resultContainer = document.getElementById('resultContainer');
239
- const urlInput = document.getElementById('urlInput');
240
- const copyBtn = document.getElementById('copyBtn');
241
- const fileInfo = document.getElementById('fileInfo');
242
- const fileInfoText = document.getElementById('fileInfoText');
243
- const resultTitle = document.getElementById('resultTitle');
244
- let selectedFile = null;
245
- uploadArea.addEventListener('click', () => fileInput.click());
246
- uploadArea.addEventListener('dragover', (e) => {
247
- e.preventDefault();
248
- uploadArea.classList.add('dragover');
249
- });
250
- uploadArea.addEventListener('dragleave', () => {
251
- uploadArea.classList.remove('dragover');
252
- });
253
- uploadArea.addEventListener('drop', (e) => {
254
- e.preventDefault();
255
- uploadArea.classList.remove('dragover');
256
- const files = e.dataTransfer.files;
257
- if (files.length > 0) {
258
- handleFile(files[0]);
259
- }
260
- });
261
- fileInput.addEventListener('change', (e) => {
262
- if (e.target.files.length > 0) {
263
- handleFile(e.target.files[0]);
264
- }
265
- });
266
- function handleFile(file) {
267
- if (!file.type.startsWith('image/')) {
268
- alert('Please select an image file');
269
- return;
270
- }
271
- if (file.size > 50 * 1024 * 1024) {
272
- alert('File size must be less than 50MB');
273
- return;
274
- }
275
- selectedFile = file;
276
-
277
- const reader = new FileReader();
278
- reader.onload = (e) => {
279
- previewImage.src = e.target.result;
280
- previewContainer.style.display = 'block';
281
- };
282
- reader.readAsDataURL(file);
283
- fileInfoText.textContent = `${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)`;
284
- fileInfo.style.display = 'block';
285
- uploadBtn.disabled = false;
286
- resultContainer.style.display = 'none';
287
- }
288
- uploadBtn.addEventListener('click', async () => {
289
- if (!selectedFile) return;
290
- const formData = new FormData();
291
- formData.append('file', selectedFile);
292
- uploadBtn.disabled = true;
293
- loading.style.display = 'block';
294
- resultContainer.style.display = 'none';
295
- try {
296
- const response = await fetch('/upload', {
297
- method: 'POST',
298
- body: formData
299
- });
300
- const data = await response.json();
301
- if (data.success) {
302
- urlInput.value = data.url;
303
- resultContainer.className = 'result-container';
304
- resultTitle.textContent = '✅ Upload Successful!';
305
- resultContainer.style.display = 'block';
306
- } else {
307
- resultContainer.className = 'result-container error';
308
- resultTitle.textContent = '❌ Upload Failed';
309
- urlInput.value = data.error || 'Unknown error occurred';
310
- resultContainer.style.display = 'block';
311
- }
312
- } catch (error) {
313
- resultContainer.className = 'result-container error';
314
- resultTitle.textContent = '❌ Upload Failed';
315
- urlInput.value = error.message;
316
- resultContainer.style.display = 'block';
317
- } finally {
318
- loading.style.display = 'none';
319
- uploadBtn.disabled = false;
320
- }
321
- });
322
- copyBtn.addEventListener('click', () => {
323
- urlInput.select();
324
- document.execCommand('copy');
325
- copyBtn.textContent = 'Copied!';
326
- setTimeout(() => {
327
- copyBtn.textContent = 'Copy';
328
- }, 2000);
329
- });
330
- </script>
331
  </body>
332
  </html>
333
  """
334
 
335
- @app.route('/')
336
- def index():
337
- return render_template_string(HTML_TEMPLATE)
 
 
 
 
 
 
 
 
 
338
 
339
- @app.route('/upload', methods=['POST'])
340
- def upload_file():
341
- try:
342
- if 'file' not in request.files:
343
- return jsonify({'success': False, 'error': 'No file provided'}), 400
344
-
345
- file = request.files['file']
346
-
347
- if file.filename == '':
348
- return jsonify({'success': False, 'error': 'No file selected'}), 400
349
-
350
- if not allowed_file(file.filename):
351
- return jsonify({'success': False, 'error': 'Invalid file type'}), 400
352
-
353
- # Generate unique identifier for this upload batch
354
- timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
355
- unique_id = str(uuid.uuid4())[:8]
356
- identifier = f"upload_{timestamp}_{unique_id}"
357
-
358
- # Get the item (will be created if doesn't exist)
359
- item = get_item(identifier)
360
-
361
- # Generate unique filename
362
- original_filename = secure_filename(file.filename)
363
- filename = f"{timestamp}_{unique_id}_{original_filename}"
364
-
365
- # Read file into BytesIO
366
- file_data = io.BytesIO(file.read())
367
- file_data.name = filename
368
-
369
- # Upload using internetarchive library with credentials
370
- metadata = {
371
- 'mediatype': 'image',
372
- 'collection': 'opensource', # Use 'opensource' or your collection
373
- 'title': f'Image Upload {timestamp}',
374
- 'description': 'Image uploaded via API'
375
- }
376
-
377
- response = item.upload(
378
- file_data,
379
- metadata=metadata,
380
- access_key=IA_ACCESS_KEY,
381
- secret_key=IA_SECRET_KEY,
382
- verbose=False,
383
- queue_derive=False
 
 
 
384
  )
385
-
386
- # Check if upload was successful
387
- if response and len(response) > 0:
388
- # Generate public URL
389
- file_url = f"https://archive.org/download/{identifier}/{filename}"
390
-
391
- return jsonify({
392
- 'success': True,
393
- 'url': file_url,
394
- 'filename': filename,
395
- 'identifier': identifier
396
- })
397
- else:
398
- return jsonify({'success': False, 'error': 'Upload failed - no response'}), 500
399
-
400
- except Exception as e:
401
- return jsonify({'success': False, 'error': str(e)}), 500
402
 
403
- @app.route('/api/upload', methods=['POST'])
404
- def api_upload():
405
- """API endpoint for programmatic uploads"""
406
- return upload_file()
 
 
 
407
 
408
- if __name__ == '__main__':
409
- # Listen on all interfaces (0.0.0.0) to allow all hosts
410
- app.run(host='0.0.0.0', port=7860, debug=False, threaded=True)
 
1
+ import http.server
2
+ import socketserver
3
+ import ssl
 
4
  import uuid
5
+ import json
6
+ import http.client
7
 
8
+ PORT = 7860
9
 
10
+ HTML = """
11
+ <!DOCTYPE html>
12
+ <html>
13
+ <body>
14
+ <h3>ImgBB Anonymous Upload (Python)</h3>
15
+ <input type="file" id="f">
16
+ <button onclick="up()">Upload</button>
17
+ <pre id="o"></pre>
18
 
19
+ <script>
20
+ async function up() {
21
+ const f = document.getElementById('f').files[0];
22
+ if (!f) return alert('Pick file');
23
 
24
+ const fd = new FormData();
25
+ fd.append('image', f);
26
 
27
+ const r = await fetch('/upload', { method: 'POST', body: fd });
28
+ const j = await r.json();
29
+ document.getElementById('o').textContent =
30
+ JSON.stringify(j, null, 2);
31
+ }
32
+ </script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  </body>
34
  </html>
35
  """
36
 
37
+ class Handler(http.server.BaseHTTPRequestHandler):
38
+
39
+ def do_GET(self):
40
+ self.send_response(200)
41
+ self.send_header("Content-Type", "text/html")
42
+ self.end_headers()
43
+ self.wfile.write(HTML.encode())
44
+
45
+ def do_POST(self):
46
+ if self.path != "/upload":
47
+ self.send_error(404)
48
+ return
49
 
50
+ content_type = self.headers.get("Content-Type")
51
+ boundary = content_type.split("boundary=")[1].encode()
52
+
53
+ length = int(self.headers.get("Content-Length"))
54
+ body = self.rfile.read(length)
55
+
56
+ parts = body.split(b"--" + boundary)
57
+ image_data = None
58
+
59
+ for p in parts:
60
+ if b"filename=" in p:
61
+ image_data = p.split(b"\r\n\r\n", 1)[1].rsplit(b"\r\n", 1)[0]
62
+ break
63
+
64
+ if not image_data:
65
+ self.send_error(400)
66
+ return
67
+
68
+ self.forward_to_imgbb(image_data)
69
+
70
+ def forward_to_imgbb(self, image_bytes):
71
+ boundary = "----WebKitFormBoundary" + uuid.uuid4().hex
72
+
73
+ head = (
74
+ f"--{boundary}\r\n"
75
+ f"Content-Disposition: form-data; name=\"type\"\r\n\r\n"
76
+ f"file\r\n"
77
+ f"--{boundary}\r\n"
78
+ f"Content-Disposition: form-data; name=\"action\"\r\n\r\n"
79
+ f"upload\r\n"
80
+ f"--{boundary}\r\n"
81
+ f"Content-Disposition: form-data; name=\"source\"; filename=\"x.jpg\"\r\n"
82
+ f"Content-Type: image/jpeg\r\n\r\n"
83
+ ).encode()
84
+
85
+ tail = f"\r\n--{boundary}--\r\n".encode()
86
+
87
+ conn = http.client.HTTPSConnection("imgbb.com")
88
+ conn.request(
89
+ "POST",
90
+ "/json",
91
+ body=head + image_bytes + tail,
92
+ headers={
93
+ "Content-Type": f"multipart/form-data; boundary={boundary}",
94
+ "Content-Length": str(len(head) + len(image_bytes) + len(tail)),
95
+ "Accept": "application/json",
96
+ "User-Agent": "Mozilla/5.0"
97
+ }
98
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
+ resp = conn.getresponse()
101
+ data = resp.read()
102
+
103
+ self.send_response(200)
104
+ self.send_header("Content-Type", "application/json")
105
+ self.end_headers()
106
+ self.wfile.write(data)
107
 
108
+ with socketserver.TCPServer(("", PORT), Handler) as httpd:
109
+ print(f"Running → http://localhost:{PORT}")
110
+ httpd.serve_forever()