// ==UserScript== // @name 豆包千问无水印素材提取 // @namespace http://tampermonkey.net/ // @version 1.0.19 // @description 在豆包/Dola/千问对话页面提取无水印图片/视频,支持一键下载 // @description:en Extract watermark-free images/videos from Doubao, Dola, and Qianwen with one-click download // @author 无印豆包 // @homepage https://github.com/ihmily/doubao-nomark // @supportURL https://github.com/ihmily/doubao-nomark/issues // @match https://www.doubao.com/thread/* // @match https://www.doubao.com/share/* // @match https://www.doubao.com/chat/* // @match https://www.doubao.com/creativity/canvas_workspace* // @match https://www.dola.com/thread/* // @match https://www.dola.com/share/* // @match https://www.dola.com/chat/* // @match https://www.qianwen.com/chat/* // @match https://www.qianwen.com/share/chat/* // @grant GM_download // @grant GM_xmlhttpRequest // @grant unsafeWindow // @connect snssdk.com // @connect *.snssdk.com // @connect douyinvod.com // @connect *.douyinvod.com // @connect byteintlapi.com // @connect *.byteintlapi.com // @connect dola.com // @connect *.dola.com // @license MIT // @run-at document-end // @icon data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20width%3D%221em%22%20height%3D%221em%22%20viewBox%3D%220%200%2024%2024%22%3E%3Cpath%20d%3D%22M0%200h24v24H0z%22%20fill%3D%22none%22%2F%3E%3Cg%20fill%3D%22none%22%20stroke%3D%22currentColor%22%20stroke-linecap%3D%22round%22%20stroke-linejoin%3D%22round%22%20stroke-width%3D%221.5%22%3E%3Cpath%20d%3D%22M2.5%2013.5v-7h19v7c0%203.771%200%205.657-1.172%206.828S17.272%2021.5%2013.5%2021.5h-3c-3.771%200-5.657%200-6.828-1.172S2.5%2017.271%202.5%2013.5m0-7l.6-.8c1.178-1.57%201.767-2.355%202.611-2.778C6.556%202.5%207.537%202.5%209.5%202.5h5c1.963%200%202.944%200%203.789.422c.845.423%201.433%201.208%202.611%202.778l.6.8%22%2F%3E%3Cpath%20d%3D%22M15%2014.5s-2.21%203-3%203s-3-3-3-3m3%202.5v-6.5%22%2F%3E%3C%2Fg%3E%3C%2Fsvg%3E // ==/UserScript== (function() { 'use strict'; console.log('%c[无印豆包] 脚本开始执行', 'color: #667eea; font-size: 14px; font-weight: bold'); const pageWindow = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window; const NativeReadableStream = pageWindow.ReadableStream || ReadableStream; const NativeResponse = pageWindow.Response || Response; const DOUBAO_HOSTS = new Set(['www.doubao.com', 'www.dola.com']); console.log('[无印豆包] 当前 URL:', pageWindow.location.href); function isDoubaoHost() { return DOUBAO_HOSTS.has(pageWindow.location.hostname); } function getDoubaoOrigin() { return pageWindow.location.hostname === 'www.dola.com' ? pageWindow.location.origin : 'https://www.doubao.com'; } function isDoubaoSharePage() { return isDoubaoHost() && ( pageWindow.location.pathname.includes('/thread/') || pageWindow.location.pathname.includes('/share/') ); } let chatImages = []; let chatVideos = []; let floatingBtnElement = null; let mountObserver = null; const processedFallbackApis = new Set(); const NOMARK_BUTTON_HOST_ID = 'doubao-nomark-button-host'; const QAAB_SALT_HEX = '4dd4c2e6b83162090e52b3c7a6733ba4' + '1cb2462b829ab58a196b39db57177524' + 'f49baf7f08e8d68d26a72e37c1a95a2f' + '1f05a51892aef2949732b62a38aadd58'; const NOMARK_ICON_SVG = ` `; const DBX_BUTTON_CLASS = 'flex shrink-0 items-center justify-center font-[400] whitespace-nowrap select-none [&_svg]:shrink-0 text-[16px] leading-[24px] gap-[4px] rounded-dbx-sm p-[4px] transition-colors duration-150 ease-out bg-transparent hover:bg-dbx-fill-trans-10-hover [&:is(:where(:is([aria-haspopup="dialog"],[aria-haspopup="menu"])[data-state="open"]:not([data-slot="alert-dialog-trigger"])),:where(:is([aria-haspopup="dialog"],[aria-haspopup="menu"])[data-state="open"]:not([data-slot="alert-dialog-trigger"])_*))]:bg-dbx-fill-trans-10-hover outline-transparent outline-none [&_svg:not([class*="size-"])]:size-[18px] [&_svg[data-dbx-name=button-caret]:not([class*="size-"])]:size-[12px] relative h-fit cursor-pointer text-(--dbx-text-primary)'; function updateButtonCount() { setButtonCount(chatImages.length + chatVideos.length); } function normalizeImageUrl(url) { return typeof url === 'string' ? url.replace(/&/g, '&') : ''; } function addChatImage(imageInfo, logLabel = '[无印豆包] 获取到新图片') { const url = normalizeImageUrl(imageInfo?.url); if (!url) return false; const width = imageInfo.width || 0; const height = imageInfo.height || 0; const existingImage = chatImages.find(img => img.url === url); if (existingImage) { if (!existingImage.width && width) existingImage.width = width; if (!existingImage.height && height) existingImage.height = height; return false; } chatImages.push({ url, width, height }); console.log(`${logLabel}:`, url, `${width} × ${height}`); updateButtonCount(); return true; } function parseCanvasDocumentImages(data) { const items = data?.data?.snapshot?.doc?.items; if (!items || typeof items !== 'object' || Array.isArray(items)) return; for (const item of Object.values(items)) { const rawValue = item?.asset?.image_info?.image_ori_raw; const rawImages = Array.isArray(rawValue) ? rawValue : [rawValue]; for (const rawImage of rawImages) { if (!rawImage) continue; addChatImage(rawImage, '[无印豆包][画布] 获取到原始图片'); } } } function getCreationImageInfo(creation) { const imageData = creation?.image?.image_ori_raw; if (typeof imageData === 'string') { return { url: imageData, width: 0, height: 0 }; } if (imageData && typeof imageData === 'object' && imageData.url) { return { url: imageData.url, width: imageData.width || 0, height: imageData.height || 0 }; } return null; } function getDoubaoBlockCreations(block) { const content = block?.content_v2 || block?.content || block; const data = typeof content === 'string' ? parseJsonString(content) : content; const creations = data?.creation_block?.creations || []; const media = data?.rich_media_layout_block?.media || []; return [ ...(Array.isArray(creations) ? creations : []), ...(Array.isArray(media) ? media.map(item => item?.creation).filter(Boolean) : []) ]; } function addChatVideo(videoInfo) { if (!videoInfo || !videoInfo.url) return; if (chatVideos.find(v => v.vid === videoInfo.vid || v.url === videoInfo.url)) return; chatVideos.push(videoInfo); console.log('[无印豆包] 获取到新视频:', videoInfo.vid, videoInfo.url); updateButtonCount(); } const originalXHROpen = pageWindow.XMLHttpRequest.prototype.open; const originalXHRSend = pageWindow.XMLHttpRequest.prototype.send; pageWindow.XMLHttpRequest.prototype.open = function(method, url, ...args) { this._url = url; // console.log('[无印豆包] XHR open:', method, url); return originalXHROpen.apply(this, [method, url, ...args]); }; pageWindow.XMLHttpRequest.prototype.send = function(...args) { const url = this._url; this.addEventListener('load', function() { if (url && url.includes('/creativity/canvas_workspace/doc/get')) { try { const data = this.responseType === 'json' && this.response ? this.response : JSON.parse(this.responseText); parseCanvasDocumentImages(data); } catch (error) { console.warn('[无印豆包][画布] XHR 响应解析失败:', error); } return; } if (url && (url.includes('/im/chain/single'))) { try { const data = JSON.parse(this.responseText); // console.log('[无印豆包] XHR 拦截到聊天接口数据:', data); // console.log('[无印豆包] downlink_body 存在:', !!data?.downlink_body); // console.log('[无印豆包] pull_singe_chain_downlink_body 存在:', !!data?.downlink_body?.pull_singe_chain_downlink_body); // console.log('[无印豆包] messages 存在:', !!data?.downlink_body?.pull_singe_chain_downlink_body?.messages); const messages = data?.downlink_body?.pull_singe_chain_downlink_body?.messages; if (messages && Array.isArray(messages)) { console.log('[无印豆包] 开始解析 messages,数量:', messages.length); parseChatHistoryImages(messages); processDoubaoFallbackVideos(data, this.responseText); } else { console.warn('[无印豆包] messages 不是数组或不存在'); processDoubaoFallbackVideos(data, this.responseText); } } catch (e) { console.error('[无印豆包] XHR 解析聊天数据失败:', e); } } }); return originalXHRSend.apply(this, args); }; console.log('[无印豆包] XHR 拦截已安装'); const originalFetch = pageWindow.fetch; pageWindow.fetch = async function(...args) { const url = args[0]; const requestUrl = typeof url === 'string' ? url : (url?.url || ''); if (requestUrl && requestUrl.includes('/creativity/canvas_workspace/doc/get')) { const response = await originalFetch.apply(this, args); response.clone().json().then(parseCanvasDocumentImages).catch(() => {}); return response; } if (requestUrl && requestUrl.includes('/im/chain/single')) { const response = await originalFetch.apply(this, args); response.clone().text().then(text => { try { const data = JSON.parse(text); const messages = data?.downlink_body?.pull_singe_chain_downlink_body?.messages; if (Array.isArray(messages)) { console.log('[无印豆包] Fetch 解析 chain/single messages,数量:', messages.length); parseChatHistoryImages(messages); } processDoubaoFallbackVideos(data, text); } catch (e) { console.warn('[无印豆包] Fetch chain/single 解析失败:', e); } }).catch(() => {}); return response; } if (url && (typeof url === 'string') && url.includes('qianwen.com/api/v1/session/msg/list')) { console.log('[无印豆包] 检测到千问 session msg list 请求:', url); const response = await originalFetch.apply(this, args); response.clone().json().then(data => { const chats = data.data?.list || []; for (const chat of chats) { const messages = chat?.response_messages || []; parseQianwenMessages(messages); } }).catch(() => {}); return response; } if (url && (typeof url === 'string') && url.includes('qianwen.com/api/v1/share/info')) { console.log('[无印豆包] 检测到千问 share chat 请求:', url); const response = await originalFetch.apply(this, args); response.clone().json().then(data => { const chats = data.data.session?.record_list || []; for (const chat of chats) { const messages = chat?.response_messages || []; parseQianwenMessages(messages); } }).catch(() => {}); return response; } if (url && (typeof url === 'string') && url.includes('qianwen.com/api/v1/chat/snap')) { console.log('[无印豆包] 检测到千问 EventStream 请求:', url); const response = await originalFetch.apply(this, args); const reader = response.body.getReader(); const decoder = new TextDecoder(); const stream = new NativeReadableStream({ async start(controller) { let buffer = ''; let waitingForData = false; while (true) { const { done, value } = await reader.read(); if (done) break; buffer += decoder.decode(value, { stream: true }); const lines = buffer.split('\n'); buffer = lines.pop(); for (const line of lines) { if (line.trimEnd() === 'event:complete') { waitingForData = true; } else if (waitingForData && line.startsWith('data:')) { waitingForData = false; try { const jsonStr = line.substring(5).trim(); const data = JSON.parse(jsonStr); parseQianwenMessages(data?.data?.messages); } catch (e) { console.warn('[无印豆包][千问] data 行解析失败:', e.message); } } else if (line.trim() === '') { waitingForData = false; } } controller.enqueue(value); } controller.close(); } }); return new NativeResponse(stream, { headers: response.headers, status: response.status, statusText: response.statusText }); } if (url && url.includes('/chat/completion')) { console.log('[无印豆包] ✨ 检测到 EventStream 请求:', url); const response = await originalFetch.apply(this, args); const reader = response.body.getReader(); const decoder = new TextDecoder(); const stream = new NativeReadableStream({ async start(controller) { while (true) { const { done, value } = await reader.read(); if (done) break; const chunk = decoder.decode(value, { stream: true }); // console.log('[无印豆包] 收到数据块:', chunk.substring(0, 100)); const lines = chunk.split('\n'); for (const line of lines) { if (line.startsWith('data: ')) { try { const jsonStr = line.substring(6); if (jsonStr.includes('image_ori') || jsonStr.includes('fallback_api')) { const data = JSON.parse(jsonStr); if (jsonStr.includes('fallback_api')) { processDoubaoFallbackVideos(data, jsonStr); } if (data.event_data || data.patch_op) { parseStreamChunk(data); } } } catch (e) { console.log('[无印豆包] 解析行失败:', e.message); } } } // 传递数据给原始响应 controller.enqueue(value); } controller.close(); } }); return new NativeResponse(stream, { headers: response.headers, status: response.status, statusText: response.statusText }); } return originalFetch.apply(this, args); }; console.log('[无印豆包] Fetch 拦截已安装'); function parseQianwenMessages(messages) { if (!Array.isArray(messages)) { return; } for (const message of messages) { if (message?.mime_type !== 'multi_load/iframe') continue; const multiLoad = message?.meta_data?.multi_load; if (!Array.isArray(multiLoad)) { continue; } for (const item of multiLoad) { const displayList = item?.content?.display_list; if (!Array.isArray(displayList)) { continue; } for (const display of displayList) { const imageObj = display?.image?.[0]; if (!imageObj?.url) continue; const { url, width = 0, height = 0 } = imageObj; addChatImage({ url, width, height }, '[无印豆包][千问] 获取到图片'); } } } } function parseStreamChunk(data) { try { if (!data.event_data && !data.patch_op) { return; } let creations = []; if (data.patch_op) { for (const op of data.patch_op) { if ( op.patch_value && Array.isArray(op.patch_value.content_block) ) { for (const block of op.patch_value.content_block) { creations.push(...getDoubaoBlockCreations(block)); } } } if (creations.length === 0) { const extPatch = data.patch_op.find(op => op.patch_value && typeof op.patch_value === 'object' && op.patch_value.ext?.creation_full_content ); if (extPatch) { try { const creationFullContent = extPatch.patch_value.ext.creation_full_content; const creationFullContent_obj = JSON.parse(creationFullContent); for (const item of creationFullContent_obj) { creations.push(...getDoubaoBlockCreations(item?.BlockInfo?.BlockContent)); } } catch (e) { console.warn('Failed to parse creation_full_content:', e); } } } }else{ let eventData; try { eventData = JSON.parse(data.event_data); } catch (e) { console.log('[无印豆包] 解析 event_data 失败:', e); return; } if (!eventData.message?.content) { return; } let messageContent; try { messageContent = JSON.parse(eventData.message.content); } catch (e) { console.log('[无印豆包] 解析 message.content 失败:', e); return; } if (!messageContent.creations || !Array.isArray(messageContent.creations)) { return; } creations = messageContent.creations; } for (const creation of creations) { if (creation?.video) { handleDoubaoCreationVideo(creation); }else{ addChatImage(getCreationImageInfo(creation)); } } } catch (e) { console.error('[无印豆包] 解析 StreamChunk 失败:', e); } } async function getDoubaoVideoInfo(vid) { if (!vid) { console.warn('[无印豆包] getDoubaoVideoInfo: vid 为空'); return null; } const params = { version_code: '20800', language: 'zh-CN', device_platform: 'web', aid: '497858', real_aid: '497858', pkg_type: 'release_version', device_id: '', pc_version: '2.51.7', region: '', sys_region: '', samantha_web: '1', 'use-olympus-account': '1', web_tab_id: '', }; const queryString = new URLSearchParams(params).toString(); const doubaoOrigin = getDoubaoOrigin(); const apiUrl = `${doubaoOrigin}/samantha/media/get_play_info?${queryString}`; try { const response = await fetch(apiUrl, { method: 'POST', credentials: 'include', headers: { 'Content-Type': 'application/json', 'origin': doubaoOrigin, }, body: JSON.stringify({ key: vid }), }); const result = await response.json(); if (!result || !result.data) { console.warn('[无印豆包] API返回数据格式异常,可能链接已失效:', result); return null; } const originalMediaInfo = result.data.original_media_info || {}; const meta = originalMediaInfo.meta || {}; const videoInfo = { vid: vid, width: meta.width || 0, height: meta.height || 0, definition: meta.definition || '', duration: meta.duration || 0, codec_type: meta.codec_type || '', poster_url: result.data.poster_url || '', url: originalMediaInfo.main_url || '', }; console.log('[无印豆包] 获取无水印视频成功:', vid, videoInfo.url); return videoInfo; } catch (e) { console.error('[无印豆包] 获取视频播放信息失败:', e); return null; } } function handleDoubaoCreationVideo(creation) { processDoubaoFallbackVideos(creation, safeJsonStringify(creation)); } function safeJsonStringify(value) { try { return JSON.stringify(value) || ''; } catch { return ''; } } function processDoubaoFallbackVideos(json, rawBody = '') { const fallbackApis = findDoubaoFallbackApis(json, rawBody); if (!fallbackApis.length) return; console.log('[无印豆包] 找到 fallback_api 数量:', fallbackApis.length); removeLegacyDoubaoVideos(); for (const fallbackApi of fallbackApis) { processDoubaoFallbackApi(fallbackApi); } } function processDoubaoFallbackApi(fallbackApi) { if (processedFallbackApis.has(fallbackApi)) return; processedFallbackApis.add(fallbackApi); getDoubaoVideoInfoFromFallbackApi(fallbackApi) .then(info => addChatVideo(info)) .catch(error => console.warn('[无印豆包] fallback_api 解析失败:', error)); } function extractShareFallbackApis(root) { const apis = new Set(); const scripts = root.querySelectorAll( 'script[data-script-src="modern-run-router-data-fn"], script[data-script-src="modern-run-window-fn"]' ); for (const script of scripts) { const rawArgs = script.getAttribute('data-fn-args'); if (!rawArgs) continue; try { const data = JSON.parse(decodeHtmlJson(rawArgs)); for (const api of findDoubaoFallbackApis(data, rawArgs)) apis.add(api); } catch (_) { /* Ignore unrelated route data. */ } } if (root === document && pageWindow._ROUTER_DATA) { for (const api of findDoubaoFallbackApis(pageWindow._ROUTER_DATA)) apis.add(api); } return [...apis]; } function decodeHtmlJson(value) { let text = String(value || ''); for (let index = 0; index < 3; index++) { const decoded = text .replace(/&|&/g, '&') .replace(/"|"/g, '"'); if (decoded === text) break; text = decoded; } return text; } async function loadSharePageVideos() { const apis = new Set(extractShareFallbackApis(document)); try { const response = await originalFetch.call(pageWindow, pageWindow.location.href, { credentials: 'include', }); if (response.ok) { const html = await response.text(); const Parser = pageWindow.DOMParser || DOMParser; const page = new Parser().parseFromString(html, 'text/html'); for (const api of extractShareFallbackApis(page)) apis.add(api); } } catch (error) { console.warn('[无印豆包] 获取分享页 HTML 失败:', error); } console.log('[无印豆包] 分享页 fallback_api 数量:', apis.size); removeLegacyDoubaoVideos(); for (const fallbackApi of apis) processDoubaoFallbackApi(fallbackApi); } async function getDoubaoVideoInfoFromFallbackApi(fallbackApi) { const apiUrl = replaceQueryParams(fallbackApi, { channel: 'no', codec_type: '8', logo_type: 'unwatermarked', }); const payload = await requestJson(apiUrl); const data = getVideoData(payload); const picked = pickMainUrlEntry(data); if (!picked?.token) { console.warn('[无印豆包] fallback_api 未找到 main_url:', apiUrl); return null; } const videoUrl = await decodeMainUrl(picked.token, findKeySeedDeep(payload)); if (!videoUrl) { console.warn('[无印豆包] fallback_api main_url 解码失败:', apiUrl); return null; } const meta = picked.entry || {}; console.log('[无印豆包] fallback_api 获取无水印视频成功:', videoUrl); return { vid: data.vid || data.video_id || meta.vid || meta.video_id || apiUrl, source: 'fallback_api', width: Number(meta.vwidth || meta.width || data.vwidth || data.width || 0), height: Number(meta.vheight || meta.height || data.vheight || data.height || 0), definition: meta.definition || data.definition || '', duration: Number(meta.duration || data.duration || 0), codec_type: meta.codec_type || data.codec_type || '', poster_url: data.poster_url || data.poster || '', url: videoUrl, }; } function removeLegacyDoubaoVideos() { const nextVideos = chatVideos.filter(video => video?.source === 'fallback_api'); if (nextVideos.length === chatVideos.length) return; chatVideos = nextVideos; updateButtonCount(); console.log('[无印豆包] 已移除旧 vid/get_play_info 视频,避免下载水印源'); } function requestJson(url) { return new Promise((resolve, reject) => { if (typeof GM_xmlhttpRequest === 'function') { GM_xmlhttpRequest({ method: 'GET', url, headers: { accept: 'application/json,text/plain,*/*', }, onload: (response) => { if (response.status < 200 || response.status >= 300) { reject(new Error(`请求失败: ${response.status}`)); return; } try { const body = response.responseText || response.response; resolve(typeof body === 'string' ? JSON.parse(body) : body); } catch (error) { reject(error); } }, onerror: () => reject(new Error('请求失败')), ontimeout: () => reject(new Error('请求超时')), }); return; } originalFetch.call(pageWindow, url, { method: 'GET', credentials: 'omit', headers: { accept: 'application/json,text/plain,*/*', }, }) .then(response => response.json()) .then(resolve) .catch(reject); }); } function findDoubaoFallbackApis(json, rawBody = '') { const apis = new Set(); for (const value of findValuesByKey(json, 'fallback_api')) { addFallbackApi(apis, value); } const body = typeof rawBody === 'string' ? rawBody : ''; const patterns = [ /fallback_api\\":\\"(.*?)\\"/g, /"fallback_api"\s*:\s*"([^"]+)"/g, ]; for (const pattern of patterns) { let match = pattern.exec(body); while (match) { addFallbackApi(apis, decodeJsonEscapedFragment(match[1])); match = pattern.exec(body); } } return Array.from(apis); } function addFallbackApi(apis, value) { if (typeof value !== 'string' || !value) return; const url = decodeJsonEscapedFragment(value); if (isHttpUrl(url)) { apis.add(url); } } function decodeJsonEscapedFragment(value) { let text = value; for (let index = 0; index < 3; index++) { try { const decoded = JSON.parse(`"${text.replace(/"/g, '\\"')}"`); if (decoded === text) break; text = decoded; } catch { break; } } return text.replace(/\\u0026/g, '&').replace(/\\\//g, '/'); } function replaceQueryParams(url, params) { const parsedUrl = new URL(url); for (const [key, value] of Object.entries(params)) { parsedUrl.searchParams.set(key, value); } return parsedUrl.toString(); } function getVideoData(payload) { const videoInfo = payload?.video_info || payload?.data?.video_info || payload; const data = videoInfo?.data || videoInfo; return data && typeof data === 'object' ? data : {}; } function pickMainUrlEntry(data) { const videoList = data?.video_list; const entries = videoList && typeof videoList === 'object' && Object.keys(videoList).length ? Object.values(videoList) : [data]; let best = null; for (const entry of entries) { if (!entry || typeof entry !== 'object') continue; const token = entry.main_url || entry.play_url || ''; if (typeof token !== 'string' || !token.trim()) continue; const score = Number(entry.bitrate || entry.real_bitrate || 0) + Number(entry.vwidth || entry.width || 0) * Number(entry.vheight || entry.height || 0); if (!best || score > best.score) { best = { token: token.trim(), score, entry }; } } return best; } function findKeySeedDeep(value, depth = 0) { if (depth > 10 || value == null) return ''; if (typeof value === 'string') { let match = value.match(/(?:^|[?&])key_seed=([^&"'<>\\\s]+)/i); if (match) return decodeURIComponent(match[1]); match = value.match(/["']key_seed["']\s*:\s*["']([^"']+)/i); return match ? decodeURIComponent(match[1]) : ''; } if (typeof value !== 'object') return ''; if (typeof value.key_seed === 'string' && value.key_seed.trim()) { return value.key_seed.trim(); } for (const item of Object.values(value)) { const hit = findKeySeedDeep(item, depth + 1); if (hit) return hit; } return ''; } async function decodeMainUrl(token, keySeed = '') { if (isHttpUrl(token)) return token; const plainUrl = tryDecodeBase64Url(token); if (plainUrl) return plainUrl; if (token.startsWith('qAAB') && keySeed) { return await decodeQaabToken(token, keySeed); } return ''; } function tryDecodeBase64Url(token) { const bytes = base64DecodeLoose(token); if (!bytes) return ''; const text = asciiUrlFromBytes(bytes); return isHttpUrl(text) ? text : ''; } function base64DecodeLoose(text) { const input = String(text || '').trim(); const variants = [ input, input.replace(/[$@#]/g, char => ({ '$': '_', '@': '/', '#': '.' }[char])), input.replace(/[$@#]/g, char => ({ '$': '+', '@': '/', '#': '=' }[char])), ]; const seen = new Set(); for (const candidate of variants) { if (!candidate || seen.has(candidate)) continue; seen.add(candidate); try { const normalized = padBase64(candidate).replace(/-/g, '+').replace(/_/g, '/'); const binary = atob(normalized); const bytes = new Uint8Array(binary.length); for (let index = 0; index < binary.length; index++) { bytes[index] = binary.charCodeAt(index); } return bytes; } catch { // Try the next variant. } } return null; } function padBase64(text) { const pad = (4 - (text.length % 4)) % 4; return text + '='.repeat(pad); } function asciiUrlFromBytes(bytes) { if (!bytes || !bytes.length) return ''; for (const byte of bytes) { if (byte !== 9 && byte !== 10 && byte !== 13 && (byte < 32 || byte > 126)) { return ''; } } return new TextDecoder().decode(bytes); } async function decodeQaabToken(token, keySeed) { const data = base64DecodeLoose(token); const seed = base64DecodeLoose(keySeed); if (!data || !seed) return ''; const digest1 = await crypto.subtle.digest('SHA-512', seed.slice(0, 32)); const salt = hexToBytes(QAAB_SALT_HEX); const digest2Input = concatBytes(new Uint8Array(digest1), salt); const digest2 = new Uint8Array(await crypto.subtle.digest('SHA-512', digest2Input)); const key = digest2.slice(0, 16); const iv = digest2.slice(16, 32); const attempts = []; if (data.length >= 4 && data[0] === 0xa8 && data[1] === 0x00 && data[2] === 0x01 && data[3] === 0x00) { attempts.push({ payload: data.slice(4), key, iv }); attempts.push({ payload: data.slice(4), key: iv, iv: key }); if (data.length > 36) { attempts.push({ payload: data.slice(36), key, iv: data.slice(20, 36) }); attempts.push({ payload: data.slice(36), key, iv }); } } else { attempts.push({ payload: data, key, iv }); } for (const attempt of attempts) { const url = await decryptAesCbcUrl(attempt.payload, attempt.key, attempt.iv); if (url) return url; } return ''; } async function decryptAesCbcUrl(payload, keyBytes, ivBytes) { if (!payload.length || payload.length % 16 !== 0) return ''; try { const key = await crypto.subtle.importKey('raw', keyBytes, 'AES-CBC', false, ['decrypt']); const plain = new Uint8Array(await crypto.subtle.decrypt({ name: 'AES-CBC', iv: ivBytes }, key, payload)); const direct = asciiUrlFromBytes(plain); if (isHttpUrl(direct)) return direct; const stripped = stripPkcs7(plain); const url = asciiUrlFromBytes(stripped); return isHttpUrl(url) ? url : ''; } catch { return ''; } } function stripPkcs7(bytes) { if (!bytes || !bytes.length) return new Uint8Array(); const pad = bytes[bytes.length - 1]; if (pad < 1 || pad > 16 || pad > bytes.length) return bytes; for (let index = bytes.length - pad; index < bytes.length; index++) { if (bytes[index] !== pad) return bytes; } return bytes.slice(0, bytes.length - pad); } function hexToBytes(hex) { const bytes = new Uint8Array(hex.length / 2); for (let index = 0; index < bytes.length; index++) { bytes[index] = parseInt(hex.slice(index * 2, index * 2 + 2), 16); } return bytes; } function concatBytes(first, second) { const bytes = new Uint8Array(first.length + second.length); bytes.set(first, 0); bytes.set(second, first.length); return bytes; } function findValuesByKey(value, targetKey) { const values = []; walkJsonAndStrings(value, (node) => { if (!node || typeof node !== 'object' || Array.isArray(node)) return; if (Object.prototype.hasOwnProperty.call(node, targetKey)) { values.push(node[targetKey]); } }); return values; } function walkJsonAndStrings(value, visitor, seen = new Set()) { if (value == null) return; if (typeof value === 'string') { const parsed = parseJsonString(value); if (parsed !== null) { walkJsonAndStrings(parsed, visitor, seen); } return; } if (typeof value !== 'object' || seen.has(value)) return; seen.add(value); visitor(value); if (Array.isArray(value)) { for (const item of value) { walkJsonAndStrings(item, visitor, seen); } return; } for (const key of Object.keys(value)) { walkJsonAndStrings(value[key], visitor, seen); } } function parseJsonString(text) { const trimmed = text.trim(); if (!trimmed || (!trimmed.startsWith('{') && !trimmed.startsWith('['))) { return null; } try { return JSON.parse(trimmed); } catch { return null; } } function isHttpUrl(url) { return typeof url === 'string' && /^https?:\/\//i.test(url); } function parseChatHistoryImages(messages) { if (!Array.isArray(messages)) return; let addedCount = 0; try { for (const item of messages) { try { for (const content of item.content_block || []) { for (const creation of getDoubaoBlockCreations(content)) { if (creation?.video) { handleDoubaoCreationVideo(creation); }else{ if (addChatImage(getCreationImageInfo(creation), '[无印豆包] 找到图片')) { addedCount++; } } } } } catch (e) { console.log('[无印豆包] 解析消息失败:', e); continue; } } } catch (e) { console.log('[无印豆包] 解析消息失败:', e); } if (addedCount > 0) { console.log('[无印豆包] 合并聊天图片,新增', addedCount, '张,共', chatImages.length, '张'); } } function parseChatRouterImages() { const pages = pageWindow._ROUTER_DATA?.loaderData?.chat_layout; if (!pages) return; for (const page of Object.values(pages)) { const messages = page?.messageList?.message_list; if (Array.isArray(messages)) parseChatHistoryImages(messages); } } function extractSharePageImagesLegacy() { try { const imageList = []; const addCreationMedia = (creation) => { if (creation?.video) { handleDoubaoCreationVideo(creation); return; } const imageData = creation?.image?.image_ori_raw; if (!imageData) return; let imageUrl = ''; let width = 0; let height = 0; if (typeof imageData === 'string') { imageUrl = imageData.replace(/&/g, '&'); } else if (typeof imageData === 'object' && imageData.url) { imageUrl = imageData.url.replace(/&/g, '&'); width = imageData.width || 0; height = imageData.height || 0; } if (imageUrl && !imageList.find(img => img.url === imageUrl)) { imageList.push({ url: imageUrl, width: width, height: height }); console.log('[无印豆包] 找到图片:', imageUrl, `${width} × ${height}`); } }; const parseMessageSnapshot = (messageSnapshot) => { if (!Array.isArray(messageSnapshot)) return; console.log('[无印豆包] 找到消息列表,共', messageSnapshot.length, '条消息'); for (const message of messageSnapshot) { for (const block of message.content_block || []) { try { const creations = getDoubaoBlockCreations(block); for (const creation of creations) { addCreationMedia(creation); } } catch (e) { continue; } } } }; const parseRouterDataItem = (data) => { if (typeof data === 'object' && data?.data?.message_snapshot?.message_list) { parseMessageSnapshot(data.data.message_snapshot.message_list); return; } if (Array.isArray(data) && data.length) { const routerDataFnArg = data[0]?.routerDataFnArgs?.[0]; if (!routerDataFnArg) return; const routerData = typeof routerDataFnArg === 'string' ? JSON.parse(routerDataFnArg) : routerDataFnArg; parseMessageSnapshot(routerData?.data?.message_snapshot?.message_list); } }; const scriptElement = document.querySelector( 'script[data-script-src="modern-run-router-data-fn"], script[data-script-src="modern-run-window-fn"][data-fn-name="mergeLoaderData"]' ); if (scriptElement) { const dataFnArgs = scriptElement.getAttribute('data-fn-args'); if (dataFnArgs) { const jsonStr = dataFnArgs.replace(/"/g, '"'); const jsonData = JSON.parse(jsonStr); processDoubaoFallbackVideos(jsonData, jsonStr); for (const data of jsonData) { parseRouterDataItem(data); } console.log('[无印豆包] 提取完成,共找到', imageList.length, '张图片'); return imageList; } } console.error('[无印豆包] 未找到任何可用的数据源'); return []; } catch (error) { console.error('[无印豆包] 提取图片失败:', error); return []; } } // Share pages have changed shape several times. Walk every route payload // recursively so both normal creations and Work rich-media creations are found. function collectSharePageMedia(value, imageList, depth = 0, seen = new Set()) { if (depth > 40 || value == null) return; if (typeof value === 'string') { const text = decodeHtmlJson(value).trim(); if (text.startsWith('{') || text.startsWith('[')) { try { collectSharePageMedia(JSON.parse(text), imageList, depth + 1, seen); } catch (_) { /* Ignore ordinary text fields. */ } } return; } if (typeof value !== 'object' || seen.has(value)) return; seen.add(value); for (const creation of getDoubaoBlockCreations(value)) { if (creation?.video) { handleDoubaoCreationVideo(creation); continue; } const image = getCreationImageInfo(creation); const url = normalizeImageUrl(image?.url); if (!url || imageList.some(item => item.url === url)) continue; imageList.push({ url, width: image.width || 0, height: image.height || 0 }); console.log('[无印豆包] 找到图片:', url, `${image.width || 0} × ${image.height || 0}`); } for (const item of Object.values(value)) { collectSharePageMedia(item, imageList, depth + 1, seen); } } function extractSharePageImages(root = document) { const imageList = []; const scripts = root.querySelectorAll( 'script[data-script-src="modern-run-router-data-fn"], script[data-script-src="modern-run-window-fn"]' ); for (const script of scripts) { const rawArgs = script.getAttribute('data-fn-args'); if (!rawArgs) continue; try { const data = JSON.parse(decodeHtmlJson(rawArgs)); processDoubaoFallbackVideos(data, rawArgs); collectSharePageMedia(data, imageList); } catch (_) { /* Ignore unrelated route data. */ } } if (root === document && pageWindow._ROUTER_DATA) { collectSharePageMedia(pageWindow._ROUTER_DATA, imageList); } console.log('[无印豆包] 分享页提取完成,共找到', imageList.length, '张图片'); return imageList; } function extractImages() { if (isDoubaoHost() && ( pageWindow.location.pathname.includes('/chat/') || pageWindow.location.pathname.includes('/creativity/canvas_workspace') )) { console.log('[无印豆包] 豆包聊天界面,返回已缓存的', chatImages.length, '张图片'); return chatImages; } else if (pageWindow.location.hostname.includes('qianwen.com') && pageWindow.location.pathname.includes('/chat/')) { return chatImages; }else{ const images = extractSharePageImages(); chatImages = images; console.log('[无印豆包] 豆包分享界面,返回已缓存的', images.length, '张图片'); return images; } } function extractVideos() { console.log('[无印豆包] 当前视频缓存数:', chatVideos.length); return chatVideos; } function createDownloadTask(url, filename) { let settled = false; let rejectDownload = null; let abortDownload = null; const promise = new Promise((resolve, reject) => { rejectDownload = reject; const finish = () => { if (settled) return; settled = true; console.log('[无印豆包] 下载完成:', filename); resolve(); }; const fail = (error) => { if (settled) return; settled = true; console.error('[无印豆包] 下载失败:', error); reject(error); }; console.log('[无印豆包] 开始下载:', url); if (typeof GM_download === 'function') { try { const download = GM_download({ url, name: filename, saveAs: false, onload: finish, onerror: fail, ontimeout: () => fail(new Error('下载超时')), }); if (download && typeof download.abort === 'function') { abortDownload = () => download.abort(); } } catch (error) { fail(error); } return; } const controller = typeof AbortController !== 'undefined' ? new AbortController() : null; abortDownload = () => controller?.abort(); fetch(url, { signal: controller?.signal }) .then(response => response.blob()) .then(blob => { const blobUrl = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = blobUrl; a.download = filename; document.body.appendChild(a); a.click(); document.body.removeChild(a); setTimeout(() => URL.revokeObjectURL(blobUrl), 100); finish(); }) .catch(fail); }); return { promise, abort() { if (settled) return; settled = true; try { if (abortDownload) abortDownload(); } catch (error) { console.warn('[无印豆包] 取消下载失败:', error); } rejectDownload(new Error('下载已取消')); }, }; } async function downloadImage(url, filename) { try { await createDownloadTask(url, filename).promise; return true; } catch (error) { if (error?.message === '下载已取消') return false; alert('下载失败,请重试'); return false; } } function getBatchFilePrefix() { const pad = value => String(value).padStart(2, '0'); const now = new Date(); const platformCode = pageWindow.location.hostname.includes('qianwen.com') ? 'Q' : 'D'; const date = `${now.getFullYear()}${pad(now.getMonth() + 1)}${pad(now.getDate())}`; const time = `${pad(now.getHours())}${pad(now.getMinutes())}${pad(now.getSeconds())}`; return `${date}${platformCode}_${time}`; } function getBatchFileExtension(url, mimeType, type) { const mimeExtensions = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/gif': 'gif', 'image/avif': 'avif', 'video/mp4': 'mp4', 'video/webm': 'webm', 'video/quicktime': 'mov' }; const normalizedMimeType = (mimeType || '').split(';', 1)[0].trim().toLowerCase(); if (mimeExtensions[normalizedMimeType]) return mimeExtensions[normalizedMimeType]; try { const pathname = new URL(url, pageWindow.location.href).pathname; const match = pathname.match(/\.([a-z0-9]{1,5})$/i); if (match) return match[1].toLowerCase() === 'jpeg' ? 'jpg' : match[1].toLowerCase(); } catch (_) { // Use the media type fallback when a resource URL cannot be parsed. } return type === 'video' ? 'mp4' : 'png'; } function triggerBlobDownload(blob, filename) { const objectUrl = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = objectUrl; link.download = filename; document.body.appendChild(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(objectUrl), 1000); } async function downloadBatchAsZip(items, type, options = {}) { const files = []; const failedIndexes = []; const filePrefix = getBatchFilePrefix(); let successCount = 0; for (let index = 0; index < items.length; index += 1) { if (options.isCancelled?.()) { return { cancelled: true, successCount, failedIndexes }; } const item = items[index]; const media = item?.data || item; const resourceUrl = media?.url; const itemIndex = Number.isInteger(item?.index) ? item.index : index; try { if (!resourceUrl) throw new Error('empty resource URL'); const blob = await fetchImageBlob(resourceUrl); // Read the response bytes before writing them to the ZIP archive. const data = await blob.arrayBuffer(); const extension = getBatchFileExtension(resourceUrl, blob.type, type); const filename = `${type}_${filePrefix}_${String(itemIndex + 1).padStart(2, '0')}.${extension}`; files.push({ filename, data: new Uint8Array(data) }); successCount += 1; } catch (error) { failedIndexes.push(itemIndex + 1); console.warn('[无印豆包] ZIP 中单项下载失败:', itemIndex + 1, error); } finally { options.onProgress?.(index + 1, items.length); } } if (options.isCancelled?.()) { return { cancelled: true, successCount, failedIndexes }; } if (!successCount) throw new Error('没有可加入 ZIP 的素材'); console.log('[无印豆包] 开始生成 ZIP,文件数:', successCount); options.onZipProgress?.(0); const archiveData = buildStoredZip(files, options.onZipProgress); options.onZipProgress?.(100); const BlobConstructor = pageWindow.Blob || Blob; const archive = new BlobConstructor([archiveData], { type: 'application/zip' }); console.log('[无印豆包] ZIP 生成完成,大小:', archive.size); const date = new Date().toISOString().slice(0, 10); triggerBlobDownload(archive, `doubao_${type}s_${date}.zip`); return { cancelled: false, successCount, failedIndexes }; } function buildStoredZip(files, onProgress) { const encoder = new TextEncoder(); const parts = []; const central = []; let offset = 0; let centralSize = 0; const crcTable = new Uint32Array(256); for (let n = 0; n < 256; n++) { let c = n; for (let k = 0; k < 8; k++) c = c & 1 ? (c >>> 1) ^ 0xedb88320 : c >>> 1; crcTable[n] = c >>> 0; } for (let i = 0; i < files.length; i++) { const { data } = files[i]; const name = encoder.encode(files[i].filename); if (name.length > 65535 || data.length > 0xffffffff || offset > 0xffffffff) { throw new Error('素材过大,无法生成标准 ZIP'); } let crc = 0xffffffff; for (const byte of data) crc = (crc >>> 8) ^ crcTable[(crc ^ byte) & 255]; crc = (crc ^ 0xffffffff) >>> 0; const local = new Uint8Array(30 + name.length); const l = new DataView(local.buffer); l.setUint32(0, 0x04034b50, true); l.setUint16(4, 20, true); l.setUint16(6, 0x0800, true); // UTF-8 names l.setUint32(14, crc, true); l.setUint32(18, data.length, true); l.setUint32(22, data.length, true); l.setUint16(26, name.length, true); local.set(name, 30); parts.push(local, data); const directory = new Uint8Array(46 + name.length); const d = new DataView(directory.buffer); d.setUint32(0, 0x02014b50, true); d.setUint16(4, 20, true); d.setUint16(6, 20, true); d.setUint16(8, 0x0800, true); d.setUint32(16, crc, true); d.setUint32(20, data.length, true); d.setUint32(24, data.length, true); d.setUint16(28, name.length, true); d.setUint32(42, offset, true); directory.set(name, 46); central.push(directory); offset += local.length + data.length; centralSize += directory.length; onProgress?.((i + 1) / files.length * 90); } if (files.length > 65535 || offset + centralSize > 0xffffffff) { throw new Error('素材总量过大,无法生成标准 ZIP'); } const end = new Uint8Array(22); const e = new DataView(end.buffer); e.setUint32(0, 0x06054b50, true); e.setUint16(8, files.length, true); e.setUint16(10, files.length, true); e.setUint32(12, centralSize, true); e.setUint32(16, offset, true); return new Blob([...parts, ...central, end], { type: 'application/zip' }); } function getMediaExtension(url, type) { try { const pathname = new URL(url, pageWindow.location.href).pathname; const match = pathname.match(/\.([a-z0-9]{2,5})$/i); if (match) return `.${match[1].toLowerCase()}`; } catch (e) { // Ignore malformed URLs and fall back to a safe default extension. } return type === 'video' ? '.mp4' : '.png'; } function getDownloadFilename(type, index, url) { const prefix = type === 'video' ? 'doubao_video' : 'doubao_image'; return `${prefix}_${index + 1}${getMediaExtension(url, type)}`; } function fetchImageBlobWithGM(url) { return new Promise((resolve, reject) => { if (typeof GM_xmlhttpRequest !== 'function') { reject(new Error('GM_xmlhttpRequest 不可用')); return; } GM_xmlhttpRequest({ method: 'GET', url, responseType: 'blob', timeout: 30000, onload: (response) => { if (response.status >= 200 && response.status < 300 && response.response) { resolve(response.response); return; } reject(new Error(`图片请求失败: ${response.status}`)); }, onerror: () => reject(new Error('图片请求失败')), ontimeout: () => reject(new Error('图片请求超时')), }); }); } async function fetchImageBlob(url) { const controller = typeof AbortController === 'function' ? new AbortController() : null; const timeoutId = controller ? setTimeout(() => controller.abort(), 30000) : null; try { const response = await fetch(url, controller ? { signal: controller.signal } : undefined); if (!response.ok) { throw new Error(`图片请求失败: ${response.status}`); } return await response.blob(); } catch (error) { console.warn('[无印豆包] fetch 读取图片失败,尝试 GM_xmlhttpRequest:', error); return fetchImageBlobWithGM(url); } finally { if (timeoutId) clearTimeout(timeoutId); } } function convertBlobToPng(blob) { if (blob.type === 'image/png') { return Promise.resolve(blob); } return new Promise((resolve, reject) => { const img = new Image(); const objectUrl = URL.createObjectURL(blob); img.onload = () => { try { const canvas = document.createElement('canvas'); canvas.width = img.naturalWidth || img.width; canvas.height = img.naturalHeight || img.height; const ctx = canvas.getContext('2d'); ctx.drawImage(img, 0, 0); canvas.toBlob((pngBlob) => { URL.revokeObjectURL(objectUrl); if (pngBlob) { resolve(pngBlob); } else { reject(new Error('图片转换失败')); } }, 'image/png'); } catch (error) { URL.revokeObjectURL(objectUrl); reject(error); } }; img.onerror = () => { URL.revokeObjectURL(objectUrl); reject(new Error('图片加载失败')); }; img.src = objectUrl; }); } async function copyImageToClipboard(url) { if (!navigator.clipboard?.write || typeof ClipboardItem === 'undefined') { throw new Error('当前浏览器不支持复制图片到剪贴板'); } const imageBlob = await fetchImageBlob(url); const pngBlob = await convertBlobToPng(imageBlob); await navigator.clipboard.write([ new ClipboardItem({ 'image/png': pngBlob }) ]); } function isOwnElement(el) { if (!el) return false; return Boolean(el.closest && ( el.closest(`#${NOMARK_BUTTON_HOST_ID}`) || el.closest('#doubao-nomark-modal') )); } function isVisible(el) { if (!el || !el.isConnected || isOwnElement(el)) return false; const style = window.getComputedStyle(el); if (style.display === 'none' || style.visibility === 'hidden' || Number(style.opacity) === 0) { return false; } const rect = el.getBoundingClientRect(); return rect.width > 0 && rect.height > 0 && rect.bottom > 0 && rect.right > 0 && rect.top < window.innerHeight && rect.left < window.innerWidth; } function findTopBarMount() { const headerLeftButton = Array.from(document.querySelectorAll('button[data-dbx-name="button"]')).find(button => { if (!isVisible(button)) return false; const container = button.parentElement; if (!container || !container.matches('div.flex-row.flex')) return false; const className = String(container.className || ''); if (!className.includes('gap-8')) return false; if (!className.includes('overflow-hidden') && !className.includes('pl-g-header-left-padding')) return false; const rect = container.getBoundingClientRect(); return rect.top < 100 && rect.height > 20 && rect.height < 80; }); return headerLeftButton?.parentElement || null; } function getNomarkButtonHost() { return document.getElementById(NOMARK_BUTTON_HOST_ID) || floatingBtnElement?.closest(`#${NOMARK_BUTTON_HOST_ID}`) || null; } function mountNomarkButtonHost() { const buttonHost = getNomarkButtonHost(); if (!buttonHost || !document.body) return; const mount = findTopBarMount(); if (mount) { mount.classList.remove('overflow-hidden'); mount.style.overflow = 'visible'; const nativeButtons = Array.from(mount.children).filter(child => { return child.matches?.('button[data-dbx-name="button"]') && !isOwnElement(child); }); const anchor = nativeButtons[nativeButtons.length - 1]; const nextNode = anchor?.nextSibling || null; if (buttonHost.parentElement !== mount || buttonHost.previousSibling !== anchor) { mount.insertBefore(buttonHost, nextNode); } buttonHost.classList.remove('fallback'); return; } if (buttonHost.parentElement !== document.body) { document.body.appendChild(buttonHost); } buttonHost.classList.add('fallback'); } function startMountObserver() { if (mountObserver || !document.documentElement) return; mountObserver = new MutationObserver(() => { const buttonHost = getNomarkButtonHost(); const mount = findTopBarMount(); if (mount) { mount.classList.remove('overflow-hidden'); mount.style.overflow = 'visible'; } if (!buttonHost || !buttonHost.isConnected || buttonHost.classList.contains('fallback')) { mountNomarkButtonHost(); } }); mountObserver.observe(document.documentElement, { childList: true, subtree: true }); } function setButtonCount(count) { if (!floatingBtnElement) return; const countElement = floatingBtnElement.querySelector('.count'); if (!countElement) return; const totalCount = Number(count) || 0; countElement.textContent = String(totalCount); countElement.classList.toggle('show', totalCount > 0); } function createFloatingButton() { if (document.documentElement.dataset.doubaoNomarkPanel) { console.log('[无印豆包] 检测到浏览器扩展,跳过油猴界面初始化'); return; } if (document.getElementById(NOMARK_BUTTON_HOST_ID)) return; const button = document.createElement('div'); button.innerHTML = `
`; document.body.appendChild(button); let modal = document.getElementById('doubao-nomark-modal'); if (modal && modal.parentElement !== document.body) { document.body.appendChild(modal); } floatingBtnElement = document.getElementById('doubao-nomark-btn'); mountNomarkButtonHost(); startMountObserver(); const floatingBtn = floatingBtnElement; const closeBtn = modal.querySelector('.close-btn'); const mediaContainer = document.getElementById('media-container'); const tabButtons = modal.querySelectorAll('.media-tab'); const selectAllBtn = modal.querySelector('.btn-select-all'); const clearSelectionBtn = modal.querySelector('.btn-clear-selection'); const batchDownloadBtn = modal.querySelector('.btn-batch-download'); let currentImages = []; let currentVideos = []; let activeTab = 'image'; let batchDownloading = false; let batchCancelRequested = false; let imagePreviewOverlay = null; function closeImagePreview() { if (imagePreviewOverlay) { imagePreviewOverlay.classList.remove('show'); } } function getImagePreviewOverlay() { if (imagePreviewOverlay) return imagePreviewOverlay; imagePreviewOverlay = document.createElement('div'); imagePreviewOverlay.id = 'doubao-nomark-image-preview'; imagePreviewOverlay.innerHTML = '图片预览'; imagePreviewOverlay.addEventListener('click', closeImagePreview); document.body.appendChild(imagePreviewOverlay); return imagePreviewOverlay; } function showImagePreview(image) { if (!image?.url) return; const overlay = getImagePreviewOverlay(); const img = overlay.querySelector('img'); img.src = image.url; img.alt = '图片预览'; overlay.classList.add('show'); } function formatDuration(sec) { if (!sec || sec <= 0) return ''; const s = Math.floor(sec); const m = Math.floor(s / 60); const r = s % 60; return `${m}:${r.toString().padStart(2, '0')}`; } function updateTabLabels() { tabButtons.forEach(btn => { const isImageTab = btn.dataset.tab === 'image'; btn.textContent = isImageTab ? `图片(${currentImages.length})` : `视频(${currentVideos.length})`; btn.classList.toggle('active', btn.dataset.tab === activeTab); btn.setAttribute('aria-selected', btn.dataset.tab === activeTab ? 'true' : 'false'); }); } function updateImageCount() { const images = extractImages(); const videos = extractVideos(); currentImages = images; currentVideos = videos; const totalCount = images.length + videos.length; setButtonCount(totalCount); updateTabLabels(); return { images, videos }; } function getMediaList(type = activeTab) { return type === 'image' ? currentImages : currentVideos; } function getMediaItem(type, index) { return getMediaList(type)[index] || null; } function clearAllSelections() { mediaContainer.querySelectorAll('.media-select').forEach(input => { input.checked = false; }); } function setCurrentTabSelection(checked) { mediaContainer.querySelectorAll(`.media-select[data-type="${activeTab}"]`).forEach(input => { input.checked = checked; }); } function getSelectedCurrentMediaItems() { return Array.from(mediaContainer.querySelectorAll(`.media-select[data-type="${activeTab}"]:checked`)) .map(input => { const index = parseInt(input.dataset.index, 10); const data = getMediaItem(activeTab, index); return data ? { type: activeTab, index, data } : null; }) .filter(Boolean); } function updateBatchButton() { batchDownloadBtn.textContent = batchDownloading ? `取消打包 ${batchDownloadBtn.dataset.progress || '0/0'}` : '批量下载'; batchDownloadBtn.classList.toggle('danger', batchDownloading); } function cancelBatchDownload() { if (!batchDownloading) return; batchCancelRequested = true; } async function runBatchDownload() { if (batchDownloading) { cancelBatchDownload(); return; } const selectedItems = getSelectedCurrentMediaItems(); if (selectedItems.length === 0) { alert('请先选择要下载的素材'); return; } batchDownloading = true; batchCancelRequested = false; batchDownloadBtn.dataset.progress = `0/${selectedItems.length}`; updateBatchButton(); let zipDownloaded = false; try { const result = await downloadBatchAsZip(selectedItems, activeTab, { isCancelled: () => batchCancelRequested, onProgress: (completed, total) => { batchDownloadBtn.dataset.progress = `${completed}/${total}`; updateBatchButton(); }, onZipProgress: percent => { batchDownloadBtn.dataset.progress = `生成 ZIP ${Math.round(percent)}%`; updateBatchButton(); } }); if (result.cancelled) { return; } if (result.failedIndexes.length) { alert(`ZIP 已下载,但有 ${result.failedIndexes.length} 个素材失败`); } batchDownloadBtn.textContent = '✓ 已打包'; zipDownloaded = true; setTimeout(() => { if (!batchDownloading) batchDownloadBtn.textContent = '批量下载'; }, 2500); } catch (error) { console.error('[无印豆包] 批量打包失败:', error); alert(error?.message || '批量下载失败,请重试'); } finally { batchDownloading = false; batchCancelRequested = false; delete batchDownloadBtn.dataset.progress; if (!zipDownloaded) updateBatchButton(); batchDownloadBtn.classList.toggle('danger', batchDownloading); } } function renderEmptyState(type) { const isImage = type === 'image'; mediaContainer.innerHTML = `
${isImage ? '🖼️' : '🎬'}
当前页面没有找到${isImage ? '图片' : '视频'}
可以切换到另一个标签查看已提取的素材
`; } function renderMedia(type = activeTab) { const mediaItems = type === 'image' ? currentImages.map((image, index) => ({ type: 'image', data: image, index })) : currentVideos.map((video, index) => ({ type: 'video', data: video, index })); if (mediaItems.length === 0) { renderEmptyState(type); return; } mediaContainer.innerHTML = mediaItems.map((item) => { if (item.type === 'image') { const image = item.data; const resolution = (image.width && image.height) ? `${image.width} × ${image.height}` : ''; return `
图片 ${item.index + 1} ${resolution ? `
${resolution}
` : ''}
${resolution ? `${resolution}` : ''}
`; } const video = item.data; const resolution = (video.width && video.height) ? `${video.width} × ${video.height}` : ''; const duration = formatDuration(video.duration); const posterAttr = video.poster_url ? ` poster="${video.poster_url}"` : ''; return `
▶
${resolution ? `${resolution}` : ''} ${duration ? `⏱ ${duration}` : ''}
`; }).join(''); mediaContainer.querySelectorAll('.btn-media-download').forEach(btn => { btn.addEventListener('click', async (e) => { e.stopPropagation(); const type = btn.dataset.type; const index = parseInt(btn.dataset.index, 10); const media = getMediaItem(type, index); if (!media) return; btn.textContent = '下载中'; const filename = getDownloadFilename(type, index, media.url); const success = await downloadImage(media.url, filename); if (!success) { btn.textContent = '下载'; return; } btn.classList.add('success'); btn.textContent = '✓ 已下载'; setTimeout(() => { btn.classList.remove('success'); btn.textContent = '下载'; }, 2000); }); }); mediaContainer.querySelectorAll('.btn-media-copy').forEach(btn => { btn.addEventListener('click', async (e) => { e.stopPropagation(); const type = btn.dataset.type; const index = parseInt(btn.dataset.index, 10); const media = getMediaItem(type, index); if (!media) return; const defaultText = type === 'image' ? '复制' : '地址'; btn.textContent = '复制中'; try { if (type === 'image') { await copyImageToClipboard(media.url); } else { await navigator.clipboard.writeText(media.url); } btn.classList.add('success'); btn.textContent = '✓ 已复制'; setTimeout(() => { btn.classList.remove('success'); btn.textContent = defaultText; }, 2000); } catch (err) { console.error('复制失败:', err); btn.textContent = defaultText; alert(type === 'image' ? '复制图片失败,请重试' : '复制地址失败,请重试'); } }); }); mediaContainer.querySelectorAll('.media-card').forEach(card => { const checkbox = card.querySelector('.media-select'); if (!checkbox) return; card.querySelector('.video-click-top')?.addEventListener('click', () => { checkbox.checked = !checkbox.checked; }); }); mediaContainer.querySelectorAll('.media-preview img').forEach(img => { img.addEventListener('click', (e) => { e.stopPropagation(); const preview = img.closest('.media-preview'); const index = parseInt(preview?.dataset.index || '', 10); const image = getMediaItem('image', index); showImagePreview(image); }); }); mediaContainer.querySelectorAll('.video-click-bottom').forEach(zone => { zone.addEventListener('click', () => { const preview = zone.closest('.media-preview'); const video = preview?.querySelector('video'); const indicator = zone.querySelector('.video-play-indicator'); if (!video || !indicator) return; if (video.paused) { video.play().then(() => { indicator.textContent = 'Ⅱ'; }).catch(err => { console.error('视频播放失败:', err); }); } else { video.pause(); indicator.textContent = '▶'; } }); }); mediaContainer.querySelectorAll('.media-preview video').forEach(video => { video.addEventListener('pause', () => { const indicator = video.closest('.media-preview')?.querySelector('.video-play-indicator'); if (indicator) indicator.textContent = '▶'; }); video.addEventListener('play', () => { const indicator = video.closest('.media-preview')?.querySelector('.video-play-indicator'); if (indicator) indicator.textContent = 'Ⅱ'; }); video.addEventListener('ended', () => { const indicator = video.closest('.media-preview')?.querySelector('.video-play-indicator'); if (indicator) indicator.textContent = '▶'; }); }); } floatingBtn.addEventListener('click', () => { const { images, videos } = updateImageCount(); activeTab = images.length === 0 && videos.length > 0 ? 'video' : 'image'; updateTabLabels(); if (images.length === 0 && videos.length === 0) { mediaContainer.innerHTML = `
🖼️
当前页面没有找到图片或视频
`; } else { renderMedia(activeTab); } modal.classList.add('show'); }); tabButtons.forEach(btn => { btn.addEventListener('click', () => { clearAllSelections(); activeTab = btn.dataset.tab; updateTabLabels(); renderMedia(activeTab); }); }); selectAllBtn.addEventListener('click', () => { setCurrentTabSelection(true); }); clearSelectionBtn.addEventListener('click', () => { setCurrentTabSelection(false); }); batchDownloadBtn.addEventListener('click', runBatchDownload); closeBtn.addEventListener('click', () => { modal.classList.remove('show'); closeImagePreview(); }); modal.addEventListener('click', (e) => { if (e.target === modal) { modal.classList.remove('show'); closeImagePreview(); } }); updateImageCount(); } let initRetryCount = 0; const MAX_RETRY = 10; function initScript() { console.log('[无印豆包] 脚本已加载'); if (pageWindow.location.pathname.includes('/chat/') || pageWindow.location.pathname.includes('/creativity/canvas_workspace')) { if (isDoubaoHost() && pageWindow.location.pathname.includes('/chat/')) { parseChatRouterImages(); } createFloatingButton(); return; } const hasScriptData = !!document.querySelector( 'script[data-script-src="modern-run-router-data-fn"], script[data-script-src="modern-run-window-fn"]' ); const hasRouterData = !!window._ROUTER_DATA; if (!hasScriptData && !hasRouterData) { initRetryCount++; if (initRetryCount < MAX_RETRY) { console.warn(`[无印豆包] 页面数据仍未加载,等待中... (${initRetryCount}/${MAX_RETRY})`); setTimeout(initScript, 500); return; } else { console.warn('[无印豆包] 页面数据加载超时,仍创建按钮(可能无法提取历史图片)'); } } if (isDoubaoSharePage()) { chatImages = extractSharePageImages(); loadSharePageVideos(); } createFloatingButton(); } if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', initScript); } else if (document.readyState === 'interactive') { if (document.body) { initScript(); } else { document.addEventListener('DOMContentLoaded', initScript); } } else { initScript(); } })();