kone

즐겨찾기 영상 벌크 다운로드 스크립트 (모든 화질)

지난 번에

https://gall.dcinside.com/mgallery/board/view?id=grok_prompt&no=9861&fcno=31900

https://gall.dcinside.com/mgallery/board/view?id=grok_prompt&no=9861&fcno=31900

유저 스크립트 이거 하나 공유했었는데, 간단한 기능 추가해서 재공유함

추가된 기능은 영상 업스케일 했을때, 저화질과 고화질 모두 중복으로 다운로드 받는 기능임

UI에 드롭다운으로 모든 화질, 최고 화질, 기본 화질 중 뭘 다운 받을지 선택하게 해놨으니... 걍 기본으로 '모든 화질' 해놓으면 됨

알아서 파일명 뒤에 hd, 1080hd 이런 식으로 붙으니까 구별 가능할거임

예컨대 720으로 영상 만들고 1080으로 업스케일 한 다음 스크립트 돌리면 2개의 파일이 다운로드 된다는 소리 ㅇㅇ

480으로 720, 1080 모두 업스 돌리고 스크립트 돌리면 3개가 다운로드 됨 ㅇㅇ

대신 제한(?)으로는

이미 한 번 다운로드 받았던 영상 id인 경우에, 나중에 업스케일 하고 재다운로드 눌러도 해당 업스 영상이 다운 되지는 않음

이것도 수정은 가능하긴 할텐데 지금은 귀찮아서 수정 안 했어요 ㅋㅋ

아래 내용 복붙해서 탬퍼 몽키같은 유저스크립트 에 추가 ㄱㄱ (제목은 알아서 붙이고)

```

// UserScript

// @name Grok Saved Videos Downloader

// @version 1.2

// @description Grok의 saved(좋아요) 영상을 날짜 범위로 일괄 다운로드. 업스케일된 최고 화질 자동 선택, 이미 받은 영상 건너뛰기.

// @match https://grok.com/*

// @icon https://www.google.com/s2/favicons?sz=64&domain=grok.com

// @grant none

// @license MIT

// /UserScript

// Based on the MIT-licensed "Grok Favorites Batch Download".

// MIT License — 자유롭게 사용·수정·재배포하셔도 됩니다.

(function () {

'use strict';

/* ---------- Namespaced identity (kept separate so it never collides) ---------- */

const SETTINGS_KEY = 'GROK_VIDEO_DL_SETTINGS'; // independent from old GROK_DOWNLOAD_SETTINGS

const HISTORY_KEY = 'GROK_VIDEO_DL_HISTORY'; // independent from old GROK_DOWNLOAD_FILES

const LAUNCHER_ID = 'grok-video-dl-launcher';

const PANEL_ID = 'grok-video-dl-panel';

/* ---------- Storage (settings + download history) ---------- */

const Settings = {

load() { try { return JSON.parse(localStorage.getItem(SETTINGS_KEY) || '{}'); } catch { return {}; } },

save(key, value) {

const s = this.load();

s[key] = value;

localStorage.setItem(SETTINGS_KEY, JSON.stringify(s));

}

};

const History = {

_urls: null,

load() {

if (this._urls === null) {

try { this._urls = JSON.parse(localStorage.getItem(HISTORY_KEY) || '[]'); }

catch { this._urls = []; }

}

return this._urls;

},

has(url) { return this.load().includes(url); },

add(url) {

const urls = this.load();

if (!urls.includes(url)) {

urls.push(url);

localStorage.setItem(HISTORY_KEY, JSON.stringify(urls));

}

},

clear() { this._urls = []; localStorage.removeItem(HISTORY_KEY); }

};

/* ---------- Small DOM helper ---------- */

const el = (tag, styles = {}, props = {}) => {

const node = document.createElement(tag);

Object.assign(node.style, styles);

Object.assign(node, props);

return node;

};

const todayStr = () => {

const d = new Date();

const p = n => String(n).padStart(2, '0');

return ${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())};

};

/* ---------- Network / download ---------- */

function downloadBlob(filename, blob) {

const url = URL.createObjectURL(blob);

const a = el('a', { display: 'none' }, { href: url, download: filename });

document.body.appendChild(a);

a.click();

a.remove();

URL.revokeObjectURL(url);

}

// Some Grok video assets require credentials, others reject them — try the preferred mode, fall back to the other.

async function fetchVideoBlob(url, preferCredentials, signal) {

const attempt = async (creds) => {

const r = await fetch(url, { method: 'GET', mode: 'cors', credentials: creds, signal });

if (!r.ok) { const e = new Error(HTTP ${r.status} ${r.statusText}); e.status = r.status; throw e; }

return r.blob();

};

try {

return await attempt(preferCredentials ? 'include' : 'omit');

} catch (err) {

if (err.name === 'AbortError') throw err;

if (err.status === 404) throw err; // genuinely missing — don't retry with other credentials

return await attempt(preferCredentials ? 'omit' : 'include');

}

}

// Try higher-resolution upscale variants first, fall back to the original. Returns the first that exists.

async function fetchBest(candidates, preferCredentials, signal) {

let lastErr;

for (const c of candidates) {

try {

const blob = await fetchVideoBlob(c.url, preferCredentials, signal);

return { blob, suffix: c.suffix };

} catch (e) {

if (e.name === 'AbortError') throw e;

lastErr = e; // 404 / error → try the next (lower) variant

}

}

throw lastErr || new Error('다운로드 가능한 버전 없음');

}

async function fetchMediaPage(cursor, signal) {

const resp = await fetch('https://grok.com/rest/media/post/list', {

method: 'POST',

mode: 'cors',

credentials: 'include',

referrer: 'https://grok.com/imagine',

body: JSON.stringify({ limit: 100, filter: { source: 'MEDIA_POST_SOURCE_LIKED' }, cursor }),

signal

});

if (!resp.ok) throw new Error(Media list failed: HTTP ${resp.status});

return resp.json(); // { posts, nextCursor }

}

// Posts can nest childPosts; flatten into a single list.

function flatten(posts) {

const out = [];

const walk = (list) => {

for (const item of list || []) {

out.push(item);

walk(item.childPosts);

}

};

walk(posts);

return out;

}

// Grok stores upscales in the SAME folder, only the filename changes:

// generated_video.mp4 (original — 480p or 720p native)

// generated_video_hd.mp4 (720p upscale)

// generated_video_1080_hd.mp4 (1080p upscale)

// The list API only returns the original, so we probe higher variants first and take the best that exists.

function videoVariants(url) {

const id = url.split('/').slice(-2)[0]; // the <id> folder = unique per video

const preferCredentials = !url.includes('imagine-public.x.ai');

const m = url.match(/^(.*\/)generated_video\.mp4(\?.*)?$/);

if (!m) {

// Unknown URL shape (e.g. imagine-public images/clips) — just use it as-is.

const base = url.split('/').pop().split('.').slice(0, -1).join('.');

return { id: base || id, preferCredentials, candidates: [{ url, suffix: '' }] };

}

const dir = m[1], q = m[2] || '';

return {

id, preferCredentials,

candidates: [

{ url: ${dir}generated_video_1080_hd.mp4${q}, suffix: '_1080hd' },

{ url: ${dir}generated_video_hd.mp4${q}, suffix: '_hd' },

{ url: ${dir}generated_video.mp4${q}, suffix: '' },

]

};

}

/* ---------- Core: collect videos in date range, then download ---------- */

async function collectVideos({ startDate, endDate }, signal, onStatus) {

const videos = [];

const startMs = startDate.getTime(), endMs = endDate.getTime();

let cursor, posts, page = 0;

do {

if (signal && signal.aborted) throw new DOMException('Cancelled', 'AbortError');

const res = await fetchMediaPage(cursor, signal);

posts = res.posts || [];

cursor = res.nextCursor;

page++;

let pageNewest = -Infinity;

for (const m of flatten(posts)) {

const ts = new Date(m.createTime).getTime();

if (!Number.isNaN(ts)) pageNewest = Math.max(pageNewest, ts);

if (!m.mediaUrl || !m.mimeType || !m.mimeType.startsWith('video')) continue;

if (ts >= startMs && ts <= endMs) videos.push(m);

}

onStatus(videos.length, page);

// The liked feed is newest-first. Once an entire page is older than the start

// date, every later (older) page is too — so we can stop instead of crawling

// the whole history. (If you ever see videos missing for an old date range,

// tell me and I'll disable this early-stop.)

if (pageNewest !== -Infinity && pageNewest < startMs) break;

} while (cursor && posts.length);

return videos;

}

async function downloadVideos(videos, { concurrency, skipHistory, quality }, signal, hooks) {

const targets = skipHistory ? videos.filter(v => !History.has(v.mediaUrl)) : videos;

const stats = { success: 0, failed: 0, skipped: videos.length - targets.length, files: 0 };

let done = 0;

hooks.progress(0, targets.length);

const active = [];

for (const v of targets) {

if (signal && signal.aborted) throw new DOMException('Cancelled', 'AbortError');

const task = (async () => {

const url = v.mediaUrl;

const { id, preferCredentials, candidates } = videoVariants(url);

const ext = v.mimeType.split('/')[1] || 'mp4';

try {

let n = 0;

if (quality === 'original') {

// Only the base file (generated_video.mp4 / the as-is URL).

const base = candidates.find(c => c.suffix === '') || candidates[candidates.length - 1];

const blob = await fetchVideoBlob(base.url, preferCredentials, signal);

downloadBlob(${id}.${ext}, blob);

n = 1;

} else if (quality === 'all') {

// Every variant that actually exists (1, 2 or 3 files).

for (const c of candidates) {

try {

const blob = await fetchVideoBlob(c.url, preferCredentials, signal);

downloadBlob(${id}${c.suffix}.${ext}, blob);

n++;

} catch (e) {

if (e.name === 'AbortError') throw e; // missing variant → skip

}

}

if (n === 0) throw new Error('다운로드 가능한 버전 없음');

} else {

// 'best' (default): highest available variant only.

const { blob, suffix } = await fetchBest(candidates, preferCredentials, signal);

downloadBlob(${id}${suffix}.${ext}, blob);

n = 1;

}

History.add(url); // dedup on the stable base URL

stats.success++;

stats.files += n;

} catch (e) {

if (e.name === 'AbortError') throw e;

stats.failed++;

hooks.log(실패: ${id} — ${e.message}, 'error');

} finally {

done++;

hooks.progress(done, targets.length);

}

})();

const p = task.then(() => active.splice(active.indexOf(p), 1));

active.push(p);

if (active.length >= concurrency) await Promise.race(active);

}

await Promise.all(active);

return stats;

}

async function runDownload(opts, ui) {

const signal = ui.abort ? ui.abort.signal : null;

ui.log('영상 목록을 가져오는 중…');

const videos = await collectVideos(opts, signal, (n, p) => ui.status(목록 수집 중… ${p}페이지째 (영상 ${n}개)));

if (!videos.length) { ui.log('해당 기간에 받을 영상이 없습니다.', 'error'); return; }

ui.log(총 ${videos.length}개 영상 발견. 다운로드를 시작합니다…);

const stats = await downloadVideos(videos, opts, signal, {

progress: (c, t) => ui.progress(c, t),

log: (m, type) => ui.log(m, type)

});

ui.log('==============================');

ui.log(완료 — 성공 ${stats.success}개 (파일 ${stats.files}개) / 실패 ${stats.failed} / 건너뜀 ${stats.skipped}, 'success');

}

/* ---------- UI ---------- */

function buildUI(onRun) {

const s = Settings.load();

const panel = el('div', {

position: 'fixed', right: '1rem', top: '3rem', zIndex: '2147483647',

width: '320px', maxWidth: '90vw', boxSizing: 'border-box',

background: '#0b0b0c', color: '#e6e6e6', border: '1px solid #333',

borderRadius: '10px', padding: '16px', font: '13px/1.45 sans-serif',

boxShadow: '0 8px 30px rgba(0,0,0,0.5)', display: 'none',

flexDirection: 'column', gap: '12px'

}, { id: PANEL_ID });

const header = el('div', { display: 'flex', justifyContent: 'space-between', alignItems: 'center' });

const title = el('span', { fontWeight: '700', fontSize: '15px' }, { textContent: 'Grok 영상 다운로더' });

const close = el('span', { cursor: 'pointer', color: '#aaa', fontSize: '18px', padding: '0 4px' }, { textContent: '✕' });

close.onmouseover = () => close.style.color = '#fff';

close.onmouseout = () => close.style.color = '#aaa';

header.append(title, close);

const dateRow = el('div', { display: 'flex', gap: '8px' });

const mkDate = (label, value) => {

const wrap = el('div', { display: 'flex', flexDirection: 'column', flex: '1', gap: '4px' });

const lab = el('label', { fontSize: '11px', color: '#bbb' }, { textContent: label });

const inp = el('input', { padding: '6px', borderRadius: '6px', border: '1px solid #444', background: '#161618', color: '#eee' });

inp.type = 'date';

inp.max = todayStr();

inp.value = value || todayStr();

wrap.append(lab, inp);

return { wrap, inp };

};

const startDate = mkDate('시작일', s.startDate);

const endDate = mkDate('종료일', '');

dateRow.append(startDate.wrap, endDate.wrap);

startDate.inp.addEventListener('change', e => { Settings.save('startDate', e.target.value); endDate.inp.min = e.target.value; });

const optRow = el('div', { display: 'flex', gap: '14px', alignItems: 'flex-end', flexWrap: 'wrap' });

const qualityWrap = el('div', { display: 'flex', flexDirection: 'column', gap: '4px' });

const qualityLab = el('label', { fontSize: '11px', color: '#bbb' }, { textContent: '화질' });

const quality = el('select', { padding: '6px', borderRadius: '6px', border: '1px solid #444', background: '#161618', color: '#eee' });

[['best', '최고화질만'], ['original', '기본 화질만'], ['all', '모든 화질']].forEach(([val, label]) =>

quality.appendChild(el('option', {}, { value: val, textContent: label })));

quality.value = s.quality || 'best';

quality.addEventListener('change', e => Settings.save('quality', e.target.value));

qualityWrap.append(qualityLab, quality);

const concWrap = el('div', { display: 'flex', flexDirection: 'column', gap: '4px' });

const concLab = el('label', { fontSize: '11px', color: '#bbb' }, { textContent: '동시 다운로드' });

const conc = el('input', { width: '56px', padding: '6px', borderRadius: '6px', border: '1px solid #444', background: '#161618', color: '#eee' });

conc.type = 'number'; conc.min = '1'; conc.max = '10'; conc.value = s.concurrency || 3;

conc.addEventListener('change', e => Settings.save('concurrency', parseInt(e.target.value, 10) || 3));

concWrap.append(concLab, conc);

const skipLab = el('label', { display: 'flex', alignItems: 'center', gap: '6px', cursor: 'pointer', fontSize: '12px', paddingBottom: '6px' });

const skip = el('input');

skip.type = 'checkbox';

skip.checked = s.skipHistory !== undefined ? s.skipHistory : true;

skip.addEventListener('change', e => Settings.save('skipHistory', e.target.checked));

skipLab.append(skip, el('span', {}, { textContent: '이미 받은 영상 건너뛰기' }));

optRow.append(qualityWrap, concWrap, skipLab);

const btnRow = el('div', { display: 'flex', gap: '8px', flexWrap: 'wrap' });

const mkBtn = (text, bg) => el('button', {

padding: '8px 14px', border: 'none', borderRadius: '6px', color: '#fff',

fontWeight: '600', cursor: 'pointer', background: bg

}, { textContent: text });

const dlBtn = mkBtn('다운로드', '#1d9bf0');

const cancelBtn = mkBtn('취소', '#dc3545'); cancelBtn.style.display = 'none';

const clearBtn = mkBtn('히스토리 초기화', '#6c757d');

btnRow.append(dlBtn, cancelBtn, clearBtn);

const progWrap = el('div', { display: 'none' });

const progBg = el('div', { width: '100%', height: '8px', background: '#333', borderRadius: '4px', overflow: 'hidden' });

const progFill = el('div', { width: '0%', height: '100%', background: '#28a745', transition: 'width 0.2s' });

const progText = el('div', { fontSize: '11px', color: '#bbb', textAlign: 'center', marginTop: '4px', fontFamily: 'monospace' });

progBg.append(progFill);

progWrap.append(progBg, progText);

const log = el('div', {

height: '120px', overflowY: 'auto', background: '#161618', color: '#7CFC7C',

fontFamily: 'monospace', fontSize: '11px', padding: '6px', borderRadius: '6px',

border: '1px solid #333', whiteSpace: 'pre-wrap', boxSizing: 'border-box'

});

panel.append(header, dateRow, optRow, btnRow, progWrap, log);

const ui = {

abort: null,

mount() { if (!panel.isConnected) document.body.appendChild(panel); },

show() { this.mount(); panel.style.display = 'flex'; },

hide() { panel.style.display = 'none'; },

toggle() { panel.style.display === 'flex' ? this.hide() : this.show(); },

log(msg, type) {

const line = el('div', {}, { textContent: [${new Date().toLocaleTimeString()}] ${msg} });

if (type === 'error') line.style.color = '#ff6b6b';

if (type === 'success') line.style.color = '#51cf66';

log.appendChild(line);

log.scrollTop = log.scrollHeight;

},

clearLog() { log.textContent = ''; },

status(msg) { progWrap.style.display = 'block'; progFill.style.width = '0%'; progText.textContent = msg; },

progress(cur, total) {

progWrap.style.display = 'block';

const pct = total > 0 ? Math.round(cur / total * 100) : 0;

progFill.style.width = pct + '%';

progText.textContent = ${cur} / ${total};

},

resetProgress() { progWrap.style.display = 'none'; progFill.style.width = '0%'; progText.textContent = ''; }

};

close.onclick = () => ui.hide();

clearBtn.onclick = () => {

if (confirm('다운로드 히스토리를 초기화할까요? 이전에 받은 영상도 다시 받게 됩니다.')) {

History.clear();

ui.log('히스토리를 초기화했습니다.', 'success');

}

};

const validate = () => {

const a = startDate.inp.value, b = endDate.inp.value;

if (!a || !b) { alert('시작일과 종료일을 모두 선택하세요.'); return false; }

if (a > b) { alert('시작일이 종료일보다 늦습니다.'); return false; }

return true;

};

dlBtn.onclick = async () => {

if (!validate()) return;

ui.clearLog();

ui.resetProgress();

ui.abort = new AbortController();

dlBtn.style.display = 'none';

cancelBtn.style.display = 'inline-block';

const opts = {

startDate: new Date(startDate.inp.value + 'T00:00:00'),

endDate: new Date(endDate.inp.value + 'T23:59:59.999'),

concurrency: parseInt(conc.value, 10) || 3,

skipHistory: skip.checked,

quality: quality.value

};

try {

await onRun(opts, ui);

} catch (e) {

if (e.name === 'AbortError') ui.log('취소되었습니다.', 'error');

else { console.error(e); ui.log('오류: ' + e.message, 'error'); }

} finally {

ui.abort = null;

dlBtn.style.display = 'inline-block';

cancelBtn.style.display = 'none';

}

};

cancelBtn.onclick = () => { if (ui.abort) ui.abort.abort(); };

return ui;

}

function buildLauncher(onClick) {

const btn = el('div', {

position: 'fixed', top: '0.75rem', right: '1rem', zIndex: '2147483646',

display: 'inline-flex', alignItems: 'center', gap: '8px', cursor: 'pointer',

background: '#1d9bf0', color: '#fff', padding: '6px 12px', borderRadius: '9999px',

fontSize: '14px', fontWeight: '600', fontFamily: 'sans-serif',

boxShadow: '0 2px 8px rgba(0,0,0,0.35)', transition: 'background-color 0.2s', userSelect: 'none'

}, { id: LAUNCHER_ID });

btn.innerHTML =

'<span>영상 다운로드</span>' +

'<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"></path><polyline points="7 10 12 15 17 10"></polyline><line x1="12" x2="12" y1="15" y2="3"></line></svg>';

btn.onmouseover = () => btn.style.background = '#1a8cd8';

btn.onmouseout = () => btn.style.background = '#1d9bf0';

btn.addEventListener('click', (e) => { e.stopPropagation(); onClick(); });

return btn;

}

// Robust SPA URL-change detection (the old script's div>h1 mount is gone — this is DOM-independent).

function onUrlChange(cb) {

const fire = () => cb(location.href);

window.addEventListener('popstate', fire);

for (const m of ['pushState', 'replaceState']) {

const orig = history[m];

history[m] = function (...args) { const r = orig.apply(this, args); fire(); return r; };

}

}

/* ---------- Boot ---------- */

const ui = buildUI(runDownload);

const sync = () => {

const onSaved = location.href.includes('/imagine/saved');

const existing = document.getElementById(LAUNCHER_ID);

if (onSaved) {

if (!existing) document.body.appendChild(buildLauncher(() => ui.toggle()));

} else {

if (existing) existing.remove();

ui.hide();

}

};

onUrlChange(sync);

sync(); // handle direct load / refresh on the saved page

})();

```

---

원작자: 꼬순견(seem5765)

원문: https://gall.dcinside.com/mgallery/board/view/?id=grok_prompt&no=10877

출처: 디시인사이드 그록 프롬프트 마이너 갤러리 (팁과 강좌, 2026-06-28 17:05:31)

0
0 comments
All
Title
Body