Spaces:
Running
Running
File size: 10,363 Bytes
38fdde1 14e8051 38fdde1 14e8051 38fdde1 14e8051 38fdde1 14e8051 38fdde1 14e8051 38fdde1 14e8051 38fdde1 14e8051 38fdde1 | 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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | package main
import (
"fmt"
"io"
"log"
"net/http"
"net/url"
"path"
"strings"
"time"
)
func main() {
// Handler untuk download dengan path
http.HandleFunc("/download/", downloadPathHandler)
// Handler untuk download dengan query parameter (backward compatibility)
http.HandleFunc("/download", downloadQueryHandler)
// Handler untuk serve HTML generator
http.HandleFunc("/", serveHTMLHandler)
log.Println("π Server running on http://localhost:7860")
log.Println("π₯ Generator: http://localhost:7860")
log.Println("π₯ Download: http://localhost:7860/download/{domain}/{path}")
log.Println("π₯ Download (with .mp4): http://localhost:7860/download/mp4/{domain}/{path}")
log.Fatal(http.ListenAndServe(":7860", nil))
}
// Handler untuk serve HTML file
func serveHTMLHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
http.ServeFile(w, r, "index.html")
}
// Handler untuk download dengan path /download/{domain}/{path} atau /download/mp4/{domain}/{path}
func downloadPathHandler(w http.ResponseWriter, r *http.Request) {
// Ambil path setelah /download/
pathStr := strings.TrimPrefix(r.URL.Path, "/download/")
// Pisahkan berdasarkan slash
parts := strings.Split(pathStr, "/")
if len(parts) < 2 {
http.Error(w, "Invalid URL format. Use: /download/{domain}/{path} or /download/mp4/{domain}/{path}", http.StatusBadRequest)
return
}
var targetURL string
hasMp4Format := false
// Cek apakah ada format mp4 di awal (penanda bahwa URL asli sudah ada .mp4)
if parts[0] == "mp4" {
// Format: /download/mp4/{domain}/{path} β URL asli sudah ada .mp4
hasMp4Format = true
parts = parts[1:] // Hapus "mp4" dari array
}
// Ambil domain (parts[0]) dan path (sisanya)
if len(parts) < 2 {
http.Error(w, "Invalid URL format. Need domain and path", http.StatusBadRequest)
return
}
domain := parts[0]
pathParts := parts[1:]
pathStr2 := strings.Join(pathParts, "/")
// Bangun URL target berdasarkan format
if hasMp4Format {
// Ada /mp4/ di URL β URL asli sudah memiliki .mp4, langsung gunakan
targetURL = "https://" + domain + "/" + pathStr2
} else {
// Tidak ada /mp4/ di URL β URL asli tidak ada .mp4
// HAPUS .mp4 dari akhir path (karena proxy URL ditambahi .mp4 untuk remote upload)
if strings.HasSuffix(pathStr2, ".mp4") {
pathStr2 = strings.TrimSuffix(pathStr2, ".mp4")
}
targetURL = "https://" + domain + "/" + pathStr2
}
log.Printf("π₯ HasMp4Format: %v, Target URL: %s", hasMp4Format, targetURL)
// Proxy download STREAMING dengan HEAD request
downloadProxyStreamWithHead(w, r, targetURL)
}
// Handler untuk download dengan query parameter (backward compatibility)
func downloadQueryHandler(w http.ResponseWriter, r *http.Request) {
encodedURL := r.URL.Query().Get("url")
if encodedURL == "" {
http.Error(w, "Parameter 'url' required", http.StatusBadRequest)
return
}
targetURL, err := url.QueryUnescape(encodedURL)
if err != nil {
http.Error(w, "Invalid URL", http.StatusBadRequest)
return
}
log.Printf("π₯ Downloading: %s", targetURL)
downloadProxyStreamWithHead(w, r, targetURL)
}
// Fungsi proxy download dengan HEAD request terlebih dahulu
func downloadProxyStreamWithHead(w http.ResponseWriter, r *http.Request, targetURL string) {
// Ambil nama file dari URL
filename := path.Base(targetURL)
if !strings.HasSuffix(filename, ".mp4") {
filename = "video.mp4"
}
log.Printf("π₯ Streaming: %s", targetURL)
// STEP 1: HEAD request untuk mendapatkan metadata
headReq, err := http.NewRequest("HEAD", targetURL, nil)
if err != nil {
http.Error(w, "Failed to create HEAD request", http.StatusInternalServerError)
return
}
// Set headers untuk HEAD request
headReq.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36")
headReq.Header.Set("Referer", targetURL)
headReq.Header.Set("Accept", "*/*")
headReq.Header.Set("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
headReq.Header.Set("Accept-Encoding", "gzip, deflate, br")
headReq.Header.Set("Cache-Control", "no-cache")
headReq.Header.Set("Pragma", "no-cache")
headReq.Header.Set("Sec-Fetch-Dest", "video")
headReq.Header.Set("Sec-Fetch-Mode", "no-cors")
headReq.Header.Set("Sec-Fetch-Site", "same-origin")
headReq.Header.Set("Connection", "keep-alive")
client := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
DisableCompression: false,
ResponseHeaderTimeout: 30 * time.Second,
},
}
// Eksekusi HEAD request
headResp, err := client.Do(headReq)
if err != nil {
log.Printf("β οΈ HEAD request failed: %v, fallback to normal GET", err)
// Fallback ke GET biasa
downloadProxyStream(w, r, targetURL)
return
}
defer headResp.Body.Close()
// Ambil Content-Length dari HEAD
contentLength := headResp.ContentLength
log.Printf("π HEAD response - Content-Length: %d bytes (%.2f MB)", contentLength, float64(contentLength)/(1024*1024))
// STEP 2: GET request untuk streaming
req, err := http.NewRequest("GET", targetURL, nil)
if err != nil {
http.Error(w, "Failed to create request", http.StatusInternalServerError)
return
}
// Set headers lengkap (sama seperti sebelumnya)
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36")
req.Header.Set("Referer", targetURL)
req.Header.Set("Accept", "*/*")
req.Header.Set("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Set("Accept-Encoding", "gzip, deflate, br")
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Pragma", "no-cache")
req.Header.Set("Sec-Fetch-Dest", "video")
req.Header.Set("Sec-Fetch-Mode", "no-cors")
req.Header.Set("Sec-Fetch-Site", "same-origin")
req.Header.Set("Connection", "keep-alive")
// Forward Range header jika ada
if rangeHeader := r.Header.Get("Range"); rangeHeader != "" {
req.Header.Set("Range", rangeHeader)
}
// Eksekusi GET request
resp, err := client.Do(req)
if err != nil {
http.Error(w, fmt.Sprintf("Download failed: %v", err), http.StatusInternalServerError)
log.Printf("β Error: %v", err)
return
}
defer resp.Body.Close()
// Cek status code
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
http.Error(w, fmt.Sprintf("Status: %d", resp.StatusCode), resp.StatusCode)
log.Printf("β Status: %d", resp.StatusCode)
return
}
log.Printf("β
Connected, Status: %d", resp.StatusCode)
// Set header untuk download
w.Header().Set("Content-Type", "video/mp4")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
// Gunakan Content-Length dari HEAD (lebih akurat)
if contentLength > 0 {
w.Header().Set("Content-Length", fmt.Sprintf("%d", contentLength))
} else if resp.ContentLength > 0 {
w.Header().Set("Content-Length", fmt.Sprintf("%d", resp.ContentLength))
}
// Forward header lainnya
if resp.Header.Get("Accept-Ranges") != "" {
w.Header().Set("Accept-Ranges", resp.Header.Get("Accept-Ranges"))
}
if resp.Header.Get("Content-Range") != "" {
w.Header().Set("Content-Range", resp.Header.Get("Content-Range"))
}
// Set status code
w.WriteHeader(resp.StatusCode)
// STREAMING: Kirim langsung
buf := make([]byte, 64*1024) // 64KB buffer (lebih besar)
written, err := io.CopyBuffer(w, resp.Body, buf)
if err != nil {
log.Printf("β Error streaming: %v", err)
return
}
log.Printf("β
Stream complete: %s (%.2f MB)", filename, float64(written)/(1024*1024))
}
// Fallback: Proxy streaming tanpa HEAD (untuk backup)
func downloadProxyStream(w http.ResponseWriter, r *http.Request, targetURL string) {
filename := path.Base(targetURL)
if !strings.HasSuffix(filename, ".mp4") {
filename = "video.mp4"
}
log.Printf("π₯ Streaming (fallback): %s", targetURL)
req, err := http.NewRequest("GET", targetURL, nil)
if err != nil {
http.Error(w, "Failed to create request", http.StatusInternalServerError)
return
}
req.Header.Set("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/109.0.0.0 Safari/537.36")
req.Header.Set("Referer", targetURL)
req.Header.Set("Accept", "*/*")
req.Header.Set("Accept-Language", "en-GB,en-US;q=0.9,en;q=0.8")
req.Header.Set("Accept-Encoding", "gzip, deflate, br")
req.Header.Set("Cache-Control", "no-cache")
req.Header.Set("Pragma", "no-cache")
req.Header.Set("Sec-Fetch-Dest", "video")
req.Header.Set("Sec-Fetch-Mode", "no-cors")
req.Header.Set("Sec-Fetch-Site", "same-origin")
req.Header.Set("Connection", "keep-alive")
if rangeHeader := r.Header.Get("Range"); rangeHeader != "" {
req.Header.Set("Range", rangeHeader)
}
client := &http.Client{
Timeout: 15 * time.Minute,
Transport: &http.Transport{
MaxIdleConns: 100,
MaxIdleConnsPerHost: 100,
IdleConnTimeout: 90 * time.Second,
DisableCompression: false,
ResponseHeaderTimeout: 30 * time.Second,
},
}
resp, err := client.Do(req)
if err != nil {
http.Error(w, fmt.Sprintf("Download failed: %v", err), http.StatusInternalServerError)
log.Printf("β Error: %v", err)
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusPartialContent {
http.Error(w, fmt.Sprintf("Status: %d", resp.StatusCode), resp.StatusCode)
log.Printf("β Status: %d", resp.StatusCode)
return
}
w.Header().Set("Content-Type", "video/mp4")
w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s", filename))
if resp.ContentLength > 0 {
w.Header().Set("Content-Length", fmt.Sprintf("%d", resp.ContentLength))
}
if resp.Header.Get("Accept-Ranges") != "" {
w.Header().Set("Accept-Ranges", resp.Header.Get("Accept-Ranges"))
}
if resp.Header.Get("Content-Range") != "" {
w.Header().Set("Content-Range", resp.Header.Get("Content-Range"))
}
w.WriteHeader(resp.StatusCode)
buf := make([]byte, 64*1024)
written, err := io.CopyBuffer(w, resp.Body, buf)
if err != nil {
log.Printf("β Error streaming: %v", err)
return
}
log.Printf("β
Stream complete (fallback): %s (%.2f MB)", filename, float64(written)/(1024*1024))
} |