匹配范围
*://*.feishu.cn/docx/**://*.feishu.cn/wiki/**://*.larksuite.com/docx/**://*.larksuite.com/wiki/*feishu-doc-export用途 只读获取当前飞书 docx 或知识库 wiki 中的文档正文及图片文件数据。支持直接文档页面,以及通过 frame-url 选中的文档 iframe。 执行前提 用户已登录,且当前页面具有阅读权限。仅使用当前浏览器会话,不绕过权限。凭据、临时下载地址、图片解密参数始终保留在浏览器中。浏览器脚本不能直接写本机文件,需本地调用器将结果保存到系统临时目录。…
*://*.feishu.cn/docx/**://*.feishu.cn/wiki/**://*.larksuite.com/docx/**://*.larksuite.com/wiki/*1function buildCdnRequestEntry(im) {2 return {3 file_token: im.token,4 width: im.width || 1280,5 height: im.height || 1280,6 policy: 'near',7 };8}9 10function normalizeImageOptions(input = {}) {11 return {12 concurrency: Number(input.concurrency || 5),13 delayMs: Number(input.delayMs || 1200),14 retries: Number(input.retries || 3),15 };16}17 18function buildDirectDownloadPaths(token) {19 return [20 `/space/api/box/stream/download/preview/${token}/?preview_type=16`,21 `/space/api/box/stream/download/all/${token}/`,22 ];23}24 25// Runs in the authorized Feishu frame. Secrets remain in browser memory.26async function fetchImageBrowser(blockId, options = {}) {27 const state = window.__lhFeishuExportV1;28 if (!state || (location.pathname.includes('/wiki/') ? window.DATA?.meta?.token : location.pathname.match(/\/docx\/([A-Za-z0-9_-]+)/)?.[1]) !== state.id) throw Error('FRAME_CHANGED');29 const im = state.all[blockId].data.image;30 const buildEntry = options.buildCdnRequestEntry || buildCdnRequestEntry;31 const buildDirectPaths = options.buildDirectDownloadPaths || buildDirectDownloadPaths;32 const retries = Number(options.retries || 3);33 const retryDelayMs = Number(options.retryDelayMs || 800);34 const headers = {'Content-Type':'application/json'};35 const session = window.__jssdkSession__ || window.__opendoc_state__?.authConfig?.jssdkSession;36 if (session) headers['JsSDK-Session'] = session;37 const finish = async (bytes, encrypted) => {38 let mime;39 if(bytes[0]===137 && bytes[1]===80 && bytes[2]===78 && bytes[3]===71) mime='image/png';40 else if(bytes[0]===255 && bytes[1]===216 && bytes[2]===255) mime='image/jpeg';41 else if(String.fromCharCode(...bytes.slice(0,3))==='GIF') mime='image/gif';42 else if(String.fromCharCode(...bytes.slice(0,4))==='RIFF' && String.fromCharCode(...bytes.slice(8,12))==='WEBP') mime='image/webp';43 else throw Error('NOT_IMAGE_BYTES');44 const bitmap=await createImageBitmap(new Blob([bytes],{type:mime}));45 const width=bitmap.width,height=bitmap.height; bitmap.close();46 state.imageCache.set(im.token,{bytes,mime});47 return {mime,size:bytes.length,width,height,encrypted};48 };49 let lastError;50 for (let attempt = 1; attempt <= retries; attempt++) {51 try {52 const response = await fetch('/space/api/box/file/cdn_url/', {53 method:'POST', credentials:'include', headers,54 body:JSON.stringify([buildEntry(im)])55 });56 const config = await response.json();57 const d = config.data?.[0];58 if (!response.ok || !d?.url || d.permitted === false) throw Error('CDN_CONFIG_DENIED');59 const encrypted = String(d.cipher_type) !== '0';60 const r = await fetch(d.url, {credentials:encrypted?'omit':'include'});61 if (r.status !== 200) throw Error('IMAGE_HTTP_'+r.status);62 let bytes = new Uint8Array(await r.arrayBuffer());63 if (encrypted) {64 const decode = s=>Uint8Array.from(atob(s),c=>c.charCodeAt(0));65 const key = await crypto.subtle.importKey('raw',decode(d.secret),{name:'AES-GCM'},false,['decrypt']);66 bytes = new Uint8Array(await crypto.subtle.decrypt({name:'AES-GCM',iv:decode(d.nonce)},key,bytes));67 }68 if(r.headers.get('access-new-default-thumbnail')) throw Error('DEFAULT_THUMBNAIL');69 return {...await finish(bytes, encrypted),attempt,method:'cdn'};70 } catch (error) {71 lastError = error;72 for (const path of buildDirectPaths(im.token)) {73 try {74 const direct = await fetch(path, {credentials:'include',headers});75 if (direct.status !== 200) continue;76 const bytes = new Uint8Array(await direct.arrayBuffer());77 return {...await finish(bytes, false),attempt,method:'direct'};78 } catch {}79 }80 if (attempt < retries) await new Promise(resolve => setTimeout(resolve, retryDelayMs * attempt));81 }82 }83 throw lastError;84}85 86 87const input = typeof params === 'object' && params ? params : {};88const action = input.action || 'read';89if (!/(^|\.)(feishu\.cn|larksuite\.com)$/.test(location.hostname)) throw Error('UNSUPPORTED_HOST');90const route=location.pathname.match(/\/(docx|wiki)\/([A-Za-z0-9_-]+)/);91const id=route?.[1]==='wiki'?window.DATA?.meta?.token:route?.[2];92if (!id) throw Error('请在飞书 docx 页面或对应 iframe 内执行');93if (input.expectedUrl) {94 const expected = new URL(input.expectedUrl).pathname.split('/').filter(Boolean).pop();95 if (expected !== id && expected !== route?.[2]) throw Error('DOCUMENT_MISMATCH');96}97const integer=(value, fallback, min, max)=>{98 const n=value===undefined?fallback:Number(value);99 if(!Number.isInteger(n)||n<min||n>max)throw Error('INVALID_PARAMETER');return n;100};101if (action !== 'read') {102 const state=window.__lhFeishuExportV1;103 if (!state || state.id !== id) throw Error('CACHE_MISSING_OR_STALE');104 if(action==='release'){delete window.__lhFeishuExportV1; return {ok:true};}105 const index=integer(input.index,0,0,state.images.length-1);106 const image=state.images[index];107 if(action==='image') return {index,...await fetchImageBrowser(image.blockId,{retries:2,retryDelayMs:1200})};108 if(action==='release-image'){state.imageCache.delete(image.token);return {ok:true};}109 if(action==='chunk') {110 const cached=state.imageCache.get(image.token); if(!cached)throw Error('IMAGE_CACHE_MISSING');111 const offset=integer(input.offset,0,0,cached.bytes.length), length=integer(input.length,65536,1,262144);112 const bytes=cached.bytes.slice(offset,offset+length);let binary='';113 for(let i=0;i<bytes.length;i+=8192)binary+=String.fromCharCode(...bytes.subarray(i,i+8192));114 return {base64:btoa(binary),offset,size:cached.bytes.length,mime:cached.mime};115 }116 throw Error('UNKNOWN_ACTION');117}118delete window.__lhFeishuExportV1;119if(window.DATA?.meta?.isPermitted===false)throw Error('DOCUMENT_PERMISSION_DENIED');120const maxPages=integer(input.maxPages,200,1,500);121const all={},sequence=[],seenBlocks=new Set(),seenCursors=new Set(),queue=[''];122let pages=0;123const session=window.__jssdkSession__||window.__opendoc_state__?.authConfig?.jssdkSession;124while(queue.length) {125 if(pages>=maxPages)throw Error('PAGE_LIMIT');126 const cursor=queue.shift();seenCursors.add(cursor);127 const url=new URL('/space/api/docx/pages/client_vars',location.origin);128 url.searchParams.set('id',id);url.searchParams.set('mode','0');url.searchParams.set('limit','1000');129 if(cursor)url.searchParams.set('cursor',cursor);130 const response=await fetch(url,{credentials:'include',headers:session?{'JsSDK-Session':session}:{},signal:AbortSignal.timeout(20000)});131 if(!response.ok)throw Error('DOCUMENT_HTTP_'+response.status);132 const payload=await response.json();if(payload.code!==0)throw Error('DOCUMENT_API_'+payload.code);133 const data=payload.data;if(!data||typeof data.block_map!=='object') {134 if(!data?.has_more)throw Error('INVALID_BLOCK_RESPONSE');135 }136 Object.assign(all,data.block_map||{});137 for(const blockId of data.block_sequence||[])if(!seenBlocks.has(blockId)){seenBlocks.add(blockId);sequence.push(blockId);}138 const next=data.next_cursors?.length?data.next_cursors:(data.has_more&&data.cursor?[data.cursor]:[]);139 let added=0;140 for(const c of next)if(typeof c==='string'&&c&&!seenCursors.has(c)&&!queue.includes(c)){queue.push(c);added++;}141 if(data.has_more&&!added&&!queue.length)throw Error('CURSOR_MISSING_OR_REPEATED');142 if(data.skip_blocks?.length)throw Error('SKIPPED_BLOCKS');143 pages++;144}145const textOf=d=>{146 const text=d?.text?.initialAttributedTexts?.text;147 return typeof text==='object'&&text?Object.keys(text).sort((a,b)=>Number(a)-Number(b)).map(k=>typeof text[k]==='string'?text[k]:'').join('').replace(/\u0000/g,''):'';148};149const images=[],warnings=[],lines=[],visited=new Set(),excluded=new Set();150function exclude(blockId){if(excluded.has(blockId))return;excluded.add(blockId);for(const c of all[blockId]?.data?.children||[])exclude(c);}151for(const [blockId,b] of Object.entries(all))if(b?.data?.hidden)exclude(blockId);152const title=document.title.replace(/\s*-\s*飞书云文档\s*$/,'').replace(/[\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g,'');153lines.push('# '+title,'');154function render(blockId) {155 if(visited.has(blockId)||excluded.has(blockId))return;visited.add(blockId);156 const block=all[blockId];if(!block){warnings.push({blockId,type:'missing'});return;}157 const d=block.data||{};if(d.hidden)return;158 const type=d.type,text=textOf(d);159 if(type==='image') {160 if(d.image?.token){const filename='image-'+String(images.length+1).padStart(3,'0')+'.img';161 images.push({blockId,token:d.image.token,file:filename});lines.push('','');}162 else warnings.push({blockId,type:'missing-image-token'});163 } else if(type==='code'){const fence='`'.repeat(Math.max(3,...[...text.matchAll(/`+/g)].map(x=>x[0].length+1)));lines.push(fence,text,fence,'');}164 else if(text && type!=='page'){165 const prefix=/^heading[1-6]$/.test(type)?'#'.repeat(Number(type.slice(7)))+' ':type==='bullet'?'- ':type==='ordered'?'1. ':type==='todo'?'- ['+(d.todo?.done?'x':' ')+'] ':['quote_container','callout'].includes(type)?'> ':'';166 lines.push(prefix+text,'');167 }168 if(!['page','text','paragraph','heading1','heading2','heading3','heading4','heading5','heading6','bullet','ordered','todo','quote_container','callout','code','image','divider','grid','grid_column'].includes(type))warnings.push({blockId,type:type||'unknown'});169 if(type==='divider')lines.push('---','');170 for(const child of d.children||[])render(child);171}172const root=Object.keys(all).find(k=>all[k]?.data?.type==='page');173if(root)render(root);174for(const blockId of sequence)render(blockId);175if(!root&&!sequence.length&&Object.keys(all).length)throw Error('MISSING_DOCUMENT_ORDER');176if(!Object.keys(all).length)throw Error('EMPTY_DOCUMENT');177window.__lhFeishuExportV1={id,all,images,imageCache:new Map()};178return {title,sourceUrl:location.origin+location.pathname,complete:true,pages,blockCount:Object.keys(all).length,markdown:lines.join('\n'),images:images.map(({blockId,file},index)=>({index,blockId,file})),warnings};179