inject.js aktualisiert

This commit is contained in:
2025-12-21 15:19:03 +00:00
parent a89785a5c8
commit 7f7a59f54f

952
inject.js
View File

@@ -1,396 +1,558 @@
(function () { (function () {
const scriptElement = document.currentScript; const scriptElement = document.currentScript;
const extensionId = scriptElement ? scriptElement.getAttribute("data-extension-id") : null; const extensionId = scriptElement ? scriptElement.getAttribute("data-extension-id") : null;
console.log('inject.js running, extensionId=', extensionId); console.log('inject.js running, extensionId=', extensionId);
// Empfang von "downloadRequested" (kommt vom content script) // Empfang von "downloadRequested" (kommt vom content script)
document.addEventListener("downloadRequested", function(e) { document.addEventListener("downloadRequested", function(e) {
try { try {
let t = e.detail.url; let t = e.detail.url;
let l = e.detail.name; let l = e.detail.name;
let r = e.detail.version; let r = e.detail.version;
let o = e.detail.clientId; let o = e.detail.clientId;
let n = e.detail.locale; let n = e.detail.locale;
tel_download_video(t, l, r, o, n); tel_download_video(t, l, r, o, n);
} catch (err) { } catch (err) {
console.error('Error in downloadRequested handler', err); console.error('Error in downloadRequested handler', err);
} }
}); });
document.addEventListener("imageDownloadRequested", function(e) { document.addEventListener("imageDownloadRequested", function(e) {
try { try {
let t = e.detail.url; let t = e.detail.url;
let l = e.detail.name; let l = e.detail.name;
tel_download_image(t, l); tel_download_image(t, l);
} catch (err) { } catch (err) {
console.error('Error in imageDownloadRequested handler', err); console.error('Error in imageDownloadRequested handler', err);
} }
}); });
// Hilfsfunktion: progress-bar-container document.addEventListener("audioDownloadRequested", function(e) {
function ensureProgressContainer() { try {
let container = document.getElementById("tel-downloader-progress-bar-container"); let t = e.detail.url;
if (!container) { let l = e.detail.name;
container = document.createElement("div"); tel_download_audio(t, l);
container.id = "tel-downloader-progress-bar-container"; } catch (err) {
container.style.position = "fixed"; console.error('Error in audioDownloadRequested handler', err);
container.style.bottom = "0"; }
container.style.right = "0"; });
container.style.display = "flex";
container.style.flexDirection = "column"; document.addEventListener("documentDownloadRequested", function(e) {
container.style.gap = "0.4rem"; try {
container.style.padding = "0.4rem"; let t = e.detail.url;
container.style.zIndex = "1600"; let l = e.detail.name;
document.body.appendChild(container); tel_download_document(t, l);
} } catch (err) {
return container; console.error('Error in documentDownloadRequested handler', err);
} }
});
const createProgressBar = (id, filename) => {
const dark = document.querySelector("html")?.classList?.contains("night") || // Hilfsfunktion: progress-bar-container
document.querySelector("html")?.classList?.contains("theme-dark"); function ensureProgressContainer() {
const container = ensureProgressContainer(); let container = document.getElementById("tel-downloader-progress-bar-container");
container.style.zIndex = location.pathname.startsWith("/k/") ? "4" : "1600"; if (!container) {
container = document.createElement("div");
const n = document.createElement("div"); container.id = "tel-downloader-progress-bar-container";
n.id = "tel-downloader-progress-" + id; container.style.position = "fixed";
n.style.width = "20rem"; container.style.bottom = "0";
n.style.marginTop = "0.4rem"; container.style.right = "0";
n.style.padding = "0.6rem"; container.style.display = "flex";
n.style.backgroundColor = dark ? "rgba(0,0,0,0.6)" : "rgba(0,0,0,0.3)"; container.style.flexDirection = "column";
n.style.borderRadius = "8px"; container.style.gap = "0.4rem";
n.style.boxShadow = "0 4px 12px rgba(0,0,0,0.2)"; container.style.padding = "0.4rem";
n.style.color = "white"; container.style.zIndex = "1600";
n.style.fontFamily = "sans-serif"; document.body.appendChild(container);
}
const s = document.createElement("div"); return container;
s.style.display = "flex"; }
s.style.justifyContent = "space-between";
s.style.alignItems = "center"; const createProgressBar = (id, filename) => {
const dark = document.querySelector("html")?.classList?.contains("night") ||
const i = document.createElement("p"); document.querySelector("html")?.classList?.contains("theme-dark");
i.className = "filename"; const container = ensureProgressContainer();
i.style.margin = 0; container.style.zIndex = location.pathname.startsWith("/k/") ? "4" : "1600";
i.style.color = "white";
i.style.fontSize = "0.9rem"; const n = document.createElement("div");
i.style.overflow = "hidden"; n.id = "tel-downloader-progress-" + id;
i.style.textOverflow = "ellipsis"; n.style.width = "20rem";
i.style.whiteSpace = "nowrap"; n.style.marginTop = "0.4rem";
i.innerText = filename || "video"; n.style.padding = "0.6rem";
n.style.backgroundColor = dark ? "rgba(0,0,0,0.6)" : "rgba(0,0,0,0.3)";
const d = document.createElement("div"); n.style.borderRadius = "8px";
d.style.cursor = "pointer"; n.style.boxShadow = "0 4px 12px rgba(0,0,0,0.2)";
d.style.fontSize = "1.2rem"; n.style.color = "white";
d.style.color = dark ? "#8a8a8a" : "white"; n.style.fontFamily = "sans-serif";
d.innerHTML = "×";
d.onclick = function() { const s = document.createElement("div");
if (n.parentElement) n.parentElement.removeChild(n); s.style.display = "flex";
}; s.style.justifyContent = "space-between";
s.style.alignItems = "center";
const a = document.createElement("div");
a.className = "progress"; const i = document.createElement("p");
a.style.backgroundColor = "#e2e2e2"; i.className = "filename";
a.style.position = "relative"; i.style.margin = 0;
a.style.width = "100%"; i.style.color = "white";
a.style.height = "1.6rem"; i.style.fontSize = "0.9rem";
a.style.borderRadius = "2rem"; i.style.overflow = "hidden";
a.style.overflow = "hidden"; i.style.textOverflow = "ellipsis";
a.style.marginTop = "0.6rem"; i.style.whiteSpace = "nowrap";
i.innerText = filename || "video";
const c = document.createElement("p");
c.style.position = "absolute"; const d = document.createElement("div");
c.style.zIndex = 5; d.style.cursor = "pointer";
c.style.left = "50%"; d.style.fontSize = "1.2rem";
c.style.top = "50%"; d.style.color = dark ? "#8a8a8a" : "white";
c.style.transform = "translate(-50%, -50%)"; d.innerHTML = "×";
c.style.margin = 0; d.onclick = function() {
c.style.color = "black"; if (n.parentElement) n.parentElement.removeChild(n);
c.style.fontSize = "0.85rem"; };
c.innerText = "0%";
const a = document.createElement("div");
const p = document.createElement("div"); a.className = "progress";
p.style.position = "absolute"; a.style.backgroundColor = "#e2e2e2";
p.style.height = "100%"; a.style.position = "relative";
p.style.width = "0%"; a.style.width = "100%";
p.style.backgroundColor = "#3390ec"; a.style.height = "1.6rem";
p.style.left = "0"; a.style.borderRadius = "2rem";
p.style.top = "0"; a.style.overflow = "hidden";
a.style.marginTop = "0.6rem";
a.appendChild(c);
a.appendChild(p); const c = document.createElement("p");
s.appendChild(i); c.style.position = "absolute";
s.appendChild(d); c.style.zIndex = 5;
n.appendChild(s); c.style.left = "50%";
n.appendChild(a); c.style.top = "50%";
container.appendChild(n); c.style.transform = "translate(-50%, -50%)";
}; c.style.margin = 0;
c.style.color = "black";
const updateProgress = (id, filename, percent) => { c.style.fontSize = "0.85rem";
let r = document.getElementById("tel-downloader-progress-" + id); c.innerText = "0%";
if (!r) return;
const p = document.createElement("div");
const fname = filename || r.querySelector("p.filename")?.innerText || "video"; p.style.position = "absolute";
r.querySelector("p.filename").innerText = fname; p.style.height = "100%";
p.style.width = "0%";
const prog = r.querySelector("div.progress"); p.style.backgroundColor = "#3390ec";
if (!prog) return; p.style.left = "0";
p.style.top = "0";
const txt = prog.querySelector("p");
const bar = prog.querySelector("div"); a.appendChild(c);
if (txt) txt.innerText = (percent || 0) + "%"; a.appendChild(p);
if (bar) bar.style.width = (percent || 0) + "%"; s.appendChild(i);
}; s.appendChild(d);
n.appendChild(s);
const completeProgress = (id, clientId, filename, version, locale) => { n.appendChild(a);
let n = document.getElementById("tel-downloader-progress-" + id); container.appendChild(n);
if (!n) return; };
let prog = n.querySelector("div.progress"); const updateProgress = (id, filename, percent) => {
if (prog) { let r = document.getElementById("tel-downloader-progress-" + id);
let txt = prog.querySelector("p"); if (!r) return;
if (txt) txt.innerText = "Completed";
let bar = prog.querySelector("div"); const fname = filename || r.querySelector("p.filename")?.innerText || "video";
if (bar) { r.querySelector("p.filename").innerText = fname;
bar.style.backgroundColor = "#40DCA5";
bar.style.width = "100%"; const prog = r.querySelector("div.progress");
} if (!prog) return;
}
const txt = prog.querySelector("p");
document.dispatchEvent(new CustomEvent('telDownloaderCompleted', { const bar = prog.querySelector("div");
detail: { if (txt) txt.innerText = (percent || 0) + "%";
extensionId: extensionId, if (bar) bar.style.width = (percent || 0) + "%";
action: "videoProgressCompleted", };
videoId: id,
clientId: clientId, const completeProgress = (id, clientId, filename, version, locale) => {
name: filename, let n = document.getElementById("tel-downloader-progress-" + id);
version: version, if (!n) return;
locale: locale
} let prog = n.querySelector("div.progress");
})); if (prog) {
}; let txt = prog.querySelector("p");
if (txt) txt.innerText = "Completed";
const AbortProgress = id => { let bar = prog.querySelector("div");
let t = document.getElementById("tel-downloader-progress-" + id); if (bar) {
if (!t) return; bar.style.backgroundColor = "#40DCA5";
bar.style.width = "100%";
let prog = t.querySelector("div.progress"); }
let txt = prog?.querySelector("p"); }
if (txt) {
txt.innerText = "Download failed. Try again"; document.dispatchEvent(new CustomEvent('telDownloaderCompleted', {
txt.style.fontSize = "12px"; detail: {
} extensionId: extensionId,
let bar = prog?.querySelector("div"); action: "videoProgressCompleted",
if (bar) { videoId: id,
bar.style.backgroundColor = "#D16666"; clientId: clientId,
bar.style.width = "100%"; name: filename,
} version: version,
}; locale: locale
}
// Filename helper }));
function sanitizeFilenamePreserveFriendly(name) { };
if (!name) return 'video';
return name.toString().replace(/[\/\\\?\%\*\:\|\"\<\>]/g, "_").trim(); const AbortProgress = id => {
} let t = document.getElementById("tel-downloader-progress-" + id);
if (!t) return;
// Download-Funktion mit automatischem Dateinamen - OPTIMIERT FÜR GESCHWINDIGKEIT
function tel_download_video(e, t, l, r, o) { let prog = t.querySelector("div.progress");
if (!e) { let txt = prog?.querySelector("p");
console.error('No url provided to tel_download_video'); if (txt) {
return; txt.innerText = "Download failed. Try again";
} txt.style.fontSize = "12px";
}
let baseName = sanitizeFilenamePreserveFriendly(t || 'video'); let bar = prog?.querySelector("div");
const hasExt = /\.\w{1,5}$/.test(baseName); if (bar) {
const id = (Math.random() + 1).toString(36).substring(2, 10) + "_" + Date.now().toString(); bar.style.backgroundColor = "#D16666";
bar.style.width = "100%";
const finishDownload = (blob, finalName) => { }
try { };
const url = URL.createObjectURL(blob);
const link = document.createElement("a"); // Filename helper
document.body.appendChild(link); function sanitizeFilenamePreserveFriendly(name) {
link.href = url; if (!name) return 'video';
link.download = finalName; return name.toString().replace(/[\/\\\?\%\*\:\|\"\<\>]/g, "_").trim();
link.click(); }
document.body.removeChild(link);
setTimeout(() => URL.revokeObjectURL(url), 2000); // Download-Funktion mit automatischem Dateinamen - OPTIMIERT FÜR GESCHWINDIGKEIT
} catch (err) { function tel_download_video(e, t, l, r, o) {
console.error('Error finishing download', err); if (!e) {
AbortProgress(id); console.error('No url provided to tel_download_video');
} return;
}; }
createProgressBar(id, baseName + (hasExt ? '' : '.mp4')); let baseName = sanitizeFilenamePreserveFriendly(t || 'video');
updateProgress(id, baseName + (hasExt ? '' : '.mp4'), 0); const hasExt = /\.\w{1,5}$/.test(baseName);
const id = (Math.random() + 1).toString(36).substring(2, 10) + "_" + Date.now().toString();
// GESCHWINDIGKEITS-OPTIMIERUNG: Größere Chunks + parallele Downloads
const chunkSize = 10 * 1024 * 1024; // 10MB chunks (statt 1MB) const finishDownload = (blob, finalName) => {
const maxParallel = 3; // 3 parallele Downloads try {
let chunks = []; const url = URL.createObjectURL(blob);
let totalSize = null; const link = document.createElement("a");
let detectedExt = "mp4"; document.body.appendChild(link);
let activeDownloads = 0; link.href = url;
let downloadComplete = false; link.download = finalName;
link.click();
// Zuerst: Hole die Gesamtgröße document.body.removeChild(link);
fetch(e, { setTimeout(() => URL.revokeObjectURL(url), 2000);
method: "HEAD", } catch (err) {
credentials: "include" console.error('Error finishing download', err);
}).then(res => { AbortProgress(id);
const contentLength = res.headers.get("Content-Length"); }
const contentType = res.headers.get("Content-Type") || ""; };
const mime = contentType.split(";")[0] || "";
if (mime.startsWith("video/")) { createProgressBar(id, baseName + (hasExt ? '' : '.mp4'));
detectedExt = mime.split("/")[1] || detectedExt; updateProgress(id, baseName + (hasExt ? '' : '.mp4'), 0);
}
// GESCHWINDIGKEITS-OPTIMIERUNG: Größere Chunks + parallele Downloads
if (contentLength) { const chunkSize = 10 * 1024 * 1024; // 10MB chunks (statt 1MB)
totalSize = parseInt(contentLength, 10); const maxParallel = 3; // 3 parallele Downloads
console.log('Total file size:', (totalSize / 1024 / 1024).toFixed(2), 'MB'); let chunks = [];
let totalSize = null;
// Berechne wie viele Chunks wir brauchen let detectedExt = "mp4";
const numChunks = Math.ceil(totalSize / chunkSize); let activeDownloads = 0;
chunks = new Array(numChunks).fill(null); let downloadComplete = false;
// Starte parallele Downloads // Zuerst: Hole die Gesamtgröße
for (let i = 0; i < Math.min(maxParallel, numChunks); i++) { fetch(e, {
downloadChunk(i); method: "HEAD",
} credentials: "include"
} else { }).then(res => {
// Fallback: sequentieller Download ohne Größeninfo const contentLength = res.headers.get("Content-Length");
sequentialDownload(); const contentType = res.headers.get("Content-Type") || "";
} const mime = contentType.split(";")[0] || "";
}).catch(err => { if (mime.startsWith("video/")) {
console.warn('HEAD request failed, using sequential download'); detectedExt = mime.split("/")[1] || detectedExt;
sequentialDownload(); }
});
if (contentLength) {
function downloadChunk(chunkIndex) { totalSize = parseInt(contentLength, 10);
if (downloadComplete || chunkIndex >= chunks.length) return; console.log('Total file size:', (totalSize / 1024 / 1024).toFixed(2), 'MB');
activeDownloads++; // Berechne wie viele Chunks wir brauchen
const start = chunkIndex * chunkSize; const numChunks = Math.ceil(totalSize / chunkSize);
const end = Math.min(start + chunkSize - 1, totalSize - 1); chunks = new Array(numChunks).fill(null);
fetch(e, { // Starte parallele Downloads
method: "GET", for (let i = 0; i < Math.min(maxParallel, numChunks); i++) {
headers: { Range: `bytes=${start}-${end}` }, downloadChunk(i);
credentials: "include" }
}).then(res => { } else {
if (![200, 206].includes(res.status)) { // Fallback: sequentieller Download ohne Größeninfo
throw Error("Non 200/206 response: " + res.status); sequentialDownload();
} }
return res.blob(); }).catch(err => {
}).then(blob => { console.warn('HEAD request failed, using sequential download');
chunks[chunkIndex] = blob; sequentialDownload();
activeDownloads--; });
// Update Progress function downloadChunk(chunkIndex) {
const downloaded = chunks.filter(c => c !== null).length; if (downloadComplete || chunkIndex >= chunks.length) return;
const percent = Math.round(100 * downloaded / chunks.length);
updateProgress(id, baseName + (hasExt ? "" : "." + detectedExt), percent); activeDownloads++;
const start = chunkIndex * chunkSize;
// Check ob fertig const end = Math.min(start + chunkSize - 1, totalSize - 1);
if (chunks.every(c => c !== null)) {
downloadComplete = true; fetch(e, {
const finalName = hasExt ? baseName : (baseName + "." + detectedExt); method: "GET",
const merged = new Blob(chunks, { type: "video/" + detectedExt }); headers: { Range: `bytes=${start}-${end}` },
finishDownload(merged, finalName); credentials: "include"
completeProgress(id, r, finalName, l, o); }).then(res => {
} else { if (![200, 206].includes(res.status)) {
// Starte nächsten Chunk throw Error("Non 200/206 response: " + res.status);
const nextChunk = chunks.findIndex(c => c === null); }
if (nextChunk !== -1) { return res.blob();
downloadChunk(nextChunk); }).then(blob => {
} chunks[chunkIndex] = blob;
} activeDownloads--;
}).catch(err => {
console.error('Chunk download error:', err); // Update Progress
activeDownloads--; const downloaded = chunks.filter(c => c !== null).length;
// Retry nach kurzer Pause const percent = Math.round(100 * downloaded / chunks.length);
setTimeout(() => downloadChunk(chunkIndex), 500); updateProgress(id, baseName + (hasExt ? "" : "." + detectedExt), percent);
});
} // Check ob fertig
if (chunks.every(c => c !== null)) {
function sequentialDownload() { downloadComplete = true;
// Fallback: Sequentieller Download für Server ohne Range-Support const finalName = hasExt ? baseName : (baseName + "." + detectedExt);
let blobs = [], s = 0; const merged = new Blob(chunks, { type: "video/" + detectedExt });
finishDownload(merged, finalName);
const rangedFetch = () => { completeProgress(id, r, finalName, l, o);
fetch(e, { } else {
method: "GET", // Starte nächsten Chunk
headers: { Range: `bytes=${s}-` }, const nextChunk = chunks.findIndex(c => c === null);
credentials: "include" if (nextChunk !== -1) {
}).then(res2 => { downloadChunk(nextChunk);
if (![200, 206].includes(res2.status)) { }
throw Error("Non 200/206 response: " + res2.status); }
} }).catch(err => {
console.error('Chunk download error:', err);
const contentType2 = res2.headers.get("Content-Type") || ""; activeDownloads--;
const mime2 = contentType2.split(";")[0] || ""; // Retry nach kurzer Pause
if (mime2.startsWith("video/")) { setTimeout(() => downloadChunk(chunkIndex), 500);
detectedExt = mime2.split("/")[1] || detectedExt; });
} }
const cr = res2.headers.get("Content-Range"); function sequentialDownload() {
if (cr) { // Fallback: Sequentieller Download für Server ohne Range-Support
const match = cr.match(/^bytes (\d+)-(\d+)\/(\d+)$/); let blobs = [], s = 0;
if (match) {
const start = parseInt(match[1], 10); const rangedFetch = () => {
const end = parseInt(match[2], 10); fetch(e, {
const total = parseInt(match[3], 10); method: "GET",
headers: { Range: `bytes=${s}-` },
s = end + 1; credentials: "include"
totalSize = total; }).then(res2 => {
if (![200, 206].includes(res2.status)) {
const percent = Math.min(100, Math.round(100 * s / totalSize)); throw Error("Non 200/206 response: " + res2.status);
updateProgress(id, baseName + (hasExt ? "" : "." + detectedExt), percent); }
}
} else if (res2.status === 200) { const contentType2 = res2.headers.get("Content-Type") || "";
const contentLength = res2.headers.get("Content-Length"); const mime2 = contentType2.split(";")[0] || "";
if (contentLength) { if (mime2.startsWith("video/")) {
totalSize = parseInt(contentLength, 10); detectedExt = mime2.split("/")[1] || detectedExt;
} }
}
const cr = res2.headers.get("Content-Range");
return res2.blob(); if (cr) {
}).then(chunkBlob => { const match = cr.match(/^bytes (\d+)-(\d+)\/(\d+)$/);
blobs.push(chunkBlob); if (match) {
const start = parseInt(match[1], 10);
if (totalSize && s >= totalSize) { const end = parseInt(match[2], 10);
const finalName = hasExt ? baseName : (baseName + "." + detectedExt); const total = parseInt(match[3], 10);
const merged = new Blob(blobs, { type: "video/" + detectedExt });
finishDownload(merged, finalName); s = end + 1;
completeProgress(id, r, finalName, l, o); totalSize = total;
} else {
setTimeout(rangedFetch, 10); const percent = Math.min(100, Math.round(100 * s / totalSize));
} updateProgress(id, baseName + (hasExt ? "" : "." + detectedExt), percent);
}).catch(err2 => { }
console.error('Sequential download error', err2); } else if (res2.status === 200) {
AbortProgress(id); const contentLength = res2.headers.get("Content-Length");
}); if (contentLength) {
}; totalSize = parseInt(contentLength, 10);
}
rangedFetch(); }
}
} return res2.blob();
}).then(chunkBlob => {
const tel_download_image = (src, suggestedName) => { blobs.push(chunkBlob);
try {
const safe = sanitizeFilenamePreserveFriendly(suggestedName || 'image') + "_" + Date.now() + ".jpg"; if (totalSize && s >= totalSize) {
const a = document.createElement("a"); const finalName = hasExt ? baseName : (baseName + "." + detectedExt);
document.body.appendChild(a); const merged = new Blob(blobs, { type: "video/" + detectedExt });
a.href = src; finishDownload(merged, finalName);
a.download = safe; completeProgress(id, r, finalName, l, o);
a.click(); } else {
document.body.removeChild(a); setTimeout(rangedFetch, 10);
} catch (err) { }
console.error('tel_download_image error', err); }).catch(err2 => {
} console.error('Sequential download error', err2);
}; AbortProgress(id);
});
window.telDownloader = { };
startVideo: tel_download_video,
startImage: tel_download_image rangedFetch();
}; }
}
const tel_download_image = (src, suggestedName) => {
try {
console.log('=== IMAGE DOWNLOAD START ===');
console.log('Image URL:', src);
console.log('Suggested name:', suggestedName);
const baseName = sanitizeFilenamePreserveFriendly(suggestedName || 'telegram_image');
const hasExt = /\.(jpg|jpeg|png|gif|webp)$/i.test(baseName);
const finalName = hasExt ? baseName : (baseName + '.jpg');
fetch(src, {
method: "GET",
credentials: "include"
}).then(res => {
if (!res.ok) throw new Error("Fetch failed: " + res.status);
// Detect image type
const contentType = res.headers.get("Content-Type") || "";
let ext = "jpg";
if (contentType.includes("png")) ext = "png";
else if (contentType.includes("gif")) ext = "gif";
else if (contentType.includes("webp")) ext = "webp";
const finalNameWithExt = hasExt ? baseName : (baseName + '.' + ext);
return res.blob().then(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = finalNameWithExt;
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 2000);
console.log('Image downloaded:', finalNameWithExt);
});
}).catch(err => {
console.error('Image download error:', err);
alert('Bild-Download fehlgeschlagen. Versuche es erneut.');
});
} catch (err) {
console.error('tel_download_image error', err);
}
};
const tel_download_audio = (src, suggestedName) => {
try {
console.log('=== AUDIO DOWNLOAD START ===');
console.log('Audio URL:', src);
console.log('Suggested name:', suggestedName);
const baseName = sanitizeFilenamePreserveFriendly(suggestedName || 'telegram_audio');
const hasExt = /\.(mp3|ogg|wav|m4a|opus)$/i.test(baseName);
const id = (Math.random() + 1).toString(36).substring(2, 10) + "_" + Date.now().toString();
createProgressBar(id, baseName + (hasExt ? '' : '.mp3'));
updateProgress(id, baseName + (hasExt ? '' : '.mp3'), 0);
fetch(src, {
method: "GET",
credentials: "include"
}).then(res => {
if (!res.ok) throw new Error("Fetch failed: " + res.status);
const contentType = res.headers.get("Content-Type") || "";
let ext = "mp3";
if (contentType.includes("ogg")) ext = "ogg";
else if (contentType.includes("wav")) ext = "wav";
else if (contentType.includes("m4a")) ext = "m4a";
else if (contentType.includes("opus")) ext = "opus";
const finalName = hasExt ? baseName : (baseName + '.' + ext);
return res.blob().then(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = finalName;
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 2000);
updateProgress(id, finalName, 100);
completeProgress(id, null, finalName, null, null);
console.log('Audio downloaded:', finalName);
});
}).catch(err => {
console.error('Audio download error:', err);
AbortProgress(id);
});
} catch (err) {
console.error('tel_download_audio error', err);
}
};
const tel_download_document = (src, suggestedName) => {
try {
console.log('=== DOCUMENT DOWNLOAD START ===');
console.log('Document URL:', src);
console.log('Suggested name:', suggestedName);
const baseName = sanitizeFilenamePreserveFriendly(suggestedName || 'telegram_file');
const hasExt = /\.\w{2,5}$/i.test(baseName);
const id = (Math.random() + 1).toString(36).substring(2, 10) + "_" + Date.now().toString();
createProgressBar(id, baseName);
updateProgress(id, baseName, 0);
fetch(src, {
method: "GET",
credentials: "include"
}).then(res => {
if (!res.ok) throw new Error("Fetch failed: " + res.status);
const contentType = res.headers.get("Content-Type") || "";
let ext = "";
// Erkenne Extension aus Content-Type
if (contentType.includes("zip")) ext = "zip";
else if (contentType.includes("rar")) ext = "rar";
else if (contentType.includes("pdf")) ext = "pdf";
else if (contentType.includes("msword")) ext = "doc";
else if (contentType.includes("spreadsheet")) ext = "xlsx";
else if (contentType.includes("audio/mpeg")) ext = "mp3";
else if (contentType.includes("audio/")) ext = "mp3";
const finalName = hasExt ? baseName : (baseName + (ext ? '.' + ext : ''));
return res.blob().then(blob => {
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
document.body.appendChild(a);
a.href = url;
a.download = finalName;
a.click();
document.body.removeChild(a);
setTimeout(() => URL.revokeObjectURL(url), 2000);
updateProgress(id, finalName, 100);
completeProgress(id, null, finalName, null, null);
console.log('Document downloaded:', finalName);
});
}).catch(err => {
console.error('Document download error:', err);
AbortProgress(id);
});
} catch (err) {
console.error('tel_download_document error', err);
}
};
window.telDownloader = {
startVideo: tel_download_video,
startImage: tel_download_image,
startAudio: tel_download_audio,
startDocument: tel_download_document
};
})(); })();