File size: 6,757 Bytes
a3208e0
 
 
e29ed63
a3208e0
 
 
 
 
 
0917beb
e29ed63
a3208e0
 
 
 
 
 
 
 
0a36dc6
 
8a25d70
0a36dc6
 
 
 
e29ed63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0a36dc6
 
e29ed63
 
 
0917beb
9714a9a
e29ed63
beb46f3
1168724
beb46f3
 
 
1168724
beb46f3
 
6aa377d
beb46f3
 
 
0a36dc6
beb46f3
 
 
 
 
e29ed63
 
beb46f3
e29ed63
a3208e0
 
e29ed63
 
 
a3208e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6aa377d
 
e29ed63
a3208e0
 
9714a9a
a3208e0
e29ed63
a3208e0
e29ed63
 
a3208e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e29ed63
 
 
1168724
 
 
 
 
 
 
a3208e0
 
 
1fd4e83
 
 
 
a3208e0
 
 
e29ed63
2aa2086
a3208e0
 
 
 
 
 
 
ef730ce
a3208e0
e29ed63
a3208e0
 
 
 
 
e29ed63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a3208e0
e29ed63
 
 
 
 
 
 
 
 
 
 
 
a3208e0
 
e29ed63
 
 
 
 
 
 
a3208e0
 
 
e29ed63
a3208e0
 
1fd4e83
a3208e0
 
0917beb
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
from flask import Flask, send_file, request, make_response, Response
import yt_dlp
import os
from urllib.parse import urlparse, unquote
from gallery_dl import job
import requests
from datetime import datetime
import tempfile
import shutil
import mimetypes
import uuid
import re

app = Flask(__name__)

class MediaDownloader:
    def __init__(self):
        self.temp_dir = tempfile.mkdtemp()
        self.create_directories()

    def create_directories(self):
        self.image_path = os.path.join(self.temp_dir, "images")
        self.video_path = os.path.join(self.temp_dir, "videos")
        os.makedirs(self.image_path, exist_ok=True)
        os.makedirs(self.video_path, exist_ok=True)

    def cleanup(self):
        try:
            if os.path.exists(self.temp_dir):
                shutil.rmtree(self.temp_dir)
        except Exception as e:
            print(f"Cleanup error: {str(e)}")

    def is_valid_url(self, url):
        try:
            result = urlparse(url)
            return all([result.scheme, result.netloc])
        except:
            return False

    def sanitize_filename(self, filename):
        return re.sub(r'[<>:"/\\|?*]', '_', filename)

    def download_video(self, url):
        if not self.is_valid_url(url):
            return None

        unique_id = str(uuid.uuid4())
        output_template = os.path.join(self.video_path, f'{unique_id}.%(ext)s')
        
        ydl_opts = {
            'format': 'best',
            'outtmpl': output_template,
            'ignoreerrors': True,
            'no_warnings': True,
            'quiet': True,
            'extract_flat': False,
            'http_headers': {
                'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
            }
        }

        try:
            with yt_dlp.YoutubeDL(ydl_opts) as ydl:
                info = ydl.extract_info(url, download=True)
                if info:
                    filename = ydl.prepare_filename(info)
                    return filename if os.path.exists(filename) else None
        except Exception as e:
            print(f"Video download error: {str(e)}")
            return None
        return None

    def download_images(self, url):
        if not self.is_valid_url(url):
            return None

        try:
            class UrlDl(job.Job):
                def __init__(self, url, parent=None):
                    job.Job.__init__(self, url, parent)
                    self.urls = []

                def handle_url(self, url, _):
                    self.urls.append(url)

            j = UrlDl(url)
            j.run()

            if not j.urls:
                return None

            downloaded_files = []
            for img_url in j.urls:
                try:
                    response = requests.get(img_url, headers={
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
                    }, timeout=30)
                    response.raise_for_status()

                    unique_id = str(uuid.uuid4())
                    ext = os.path.splitext(urlparse(img_url).path)[1]
                    if not ext or ext.lower() not in ['.jpg', '.jpeg', '.png', '.gif', '.webp']:
                        ext = '.jpg'
                    
                    filename = self.sanitize_filename(f"{unique_id}{ext}")
                    filepath = os.path.join(self.image_path, filename)

                    with open(filepath, 'wb') as f:
                        f.write(response.content)
                    downloaded_files.append(filepath)

                except Exception as e:
                    print(f"Error downloading image {img_url}: {str(e)}")
                    continue

            return downloaded_files if downloaded_files else None

        except Exception as e:
            print(f"Error in download_images: {str(e)}")
            return None

    def download_media(self, url):
        if not url or not self.is_valid_url(url):
            return None

        video_path = self.download_video(url)
        if video_path:
            return [video_path]

        image_paths = self.download_images(url)
        if image_paths:
            return image_paths

        return None

@app.route('/health')
def health_check():
    return 'OK', 200

@app.route('/')
def home():
    return """
    <h1>Downloader</h1>
    <p>Use: /download?url=url</p>
    """

@app.route('/download')
def download():
    try:
        url = request.args.get('url')
        if not url:
            return "No URL", 400

        url = unquote(url)
        downloader = MediaDownloader()

        try:
            files = downloader.download_media(url)

            if not files:
                downloader.cleanup()
                return "Download failed", 400

            if len(files) == 1:
                response = make_response(send_file(
                    files[0],
                    as_attachment=True,
                    download_name=os.path.basename(files[0])
                ))
                @response.call_on_close
                def cleanup():
                    downloader.cleanup()
                return response
            else:
                def generate():
                    try:
                        for file_path in files:
                            if os.path.exists(file_path):
                                with open(file_path, 'rb') as f:
                                    content = f.read()
                                    filename = os.path.basename(file_path)
                                    yield f'--boundary\n'.encode()
                                    yield f'Content-Disposition: attachment; filename="{filename}"\n'.encode()
                                    yield f'Content-Type: {mimetypes.guess_type(file_path)[0]}\n'.encode()
                                    yield f'Content-Length: {len(content)}\n\n'.encode()
                                    yield content
                                    yield b'\n'
                        yield b'--boundary--\n'
                    finally:
                        downloader.cleanup()

                response = Response(
                    generate(),
                    mimetype='multipart/x-mixed-replace; boundary=boundary',
                    direct_passthrough=True
                )
                response.headers['Content-Type'] = 'multipart/x-mixed-replace; boundary=boundary'
                return response

        except Exception as e:
            downloader.cleanup()
            return f"Download error: {str(e)}", 500

    except Exception as e:
        return f"Server error: {str(e)}", 500

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=7860, debug=False)