converter.ts 12.8 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407
import { BASE_PATH, DOCUMENT_TYPE_MAP, type DocumentType } from './constants';

// --- Types (Strictly Aligned with document-types.ts) ---

export interface EmscriptenFileSystem {
  mkdir(path: string): void;
  readdir(path: string): string[];
  readFile(path: string, options?: { encoding: 'binary' }): Uint8Array;
  writeFile(path: string, data: Uint8Array | string): void;
  unlink(path: string): void;
}

export interface EmscriptenModule {
  FS: EmscriptenFileSystem;
  ccall: (funcName: string, returnType: string, argTypes: string[], args: any[]) => number;
  onRuntimeInitialized: () => void;
}

export interface ConversionResult {
  fileName: string;
  type: DocumentType;
  bin: Uint8Array;
  media: Record<string, string>;
}

declare global {
  interface Window {
    Module: EmscriptenModule;
    DocsAPI?: any;
    Asc?: any;
    XLSX?: any;
    editor?: {
      sendCommand: (args: { command: string; data: any }) => void;
      destroyEditor: () => void;
    };
  }
}

// --- Utilities ---

const scriptLoadPromises = new Map<string, Promise<void>>();

export async function loadScripts(urls: string[]): Promise<void> {
  for (const url of urls) {
    if (scriptLoadPromises.has(url)) {
      await scriptLoadPromises.get(url);
      continue;
    }

    const promise = new Promise<void>((resolve, reject) => {
      // 检查 DOM 中是否已存在该脚本且已加载
      const existingScript = document.querySelector(`script[src="${url}"]`) as HTMLScriptElement;
      if (existingScript) {
        // 如果已经存在,我们假设它正在加载或已加载
        // 但为了安全,我们还是通过监听或状态判断
        if ((existingScript as any)._loaded) {
          resolve();
          return;
        }
        const onLoaded = () => {
          (existingScript as any)._loaded = true;
          existingScript.removeEventListener('load', onLoaded);
          resolve();
        };
        existingScript.addEventListener('load', onLoaded);
        existingScript.addEventListener('error', () => reject(new Error(`Failed to load script: ${url}`)));
        return;
      }

      const script = document.createElement('script');
      script.src = url;
      script.onload = () => {
        (script as any)._loaded = true;
        resolve();
      };
      script.onerror = () => reject(new Error(`Failed to load script: ${url}`));
      document.head.appendChild(script);
    });

    scriptLoadPromises.set(url, promise);
    await promise;
  }
}

// --- X2TConverter Class (Strictly Aligned with lib/document-converter.ts) ---

export class X2TConverter {
  private x2tModule: EmscriptenModule | null = null;
  private isReady = false;
  private initPromise: Promise<EmscriptenModule> | null = null;
  private hasScriptLoaded = false;
  private conversionQueue: Promise<any> = Promise.resolve();

  private readonly WORKING_DIRS = ['/working', '/working/media', '/working/fonts', '/working/themes'];
  private readonly SCRIPT_PATH = `${BASE_PATH}wasm/x2t/x2t.js`;
  private readonly INIT_TIMEOUT = 300000;

  async loadScript(): Promise<void> {
    if (this.hasScriptLoaded) return;
    try {
      await loadScripts([this.SCRIPT_PATH]);
      this.hasScriptLoaded = true;
    } catch (error) {
      console.error('Failed to load X2T WASM script', error);
      throw error;
    }
  }

  async initialize(): Promise<EmscriptenModule> {
    if (this.isReady && this.x2tModule) return this.x2tModule;
    if (this.initPromise) return this.initPromise;
    
    this.initPromise = this.doInitialize().catch(err => {
      this.initPromise = null; // 初始化失败时重置,允许重试
      throw err;
    });
    return this.initPromise;
  }

  private async doInitialize(): Promise<EmscriptenModule> {
    await this.loadScript();
    
    // 增加一个重试机制等待 window.Module 出现
    const getModule = async (retries = 100): Promise<EmscriptenModule> => {
      if (window.Module) return window.Module;
      if (retries <= 0) throw new Error('X2T module not found after script load');
      await new Promise(resolve => setTimeout(resolve, 50));
      return getModule(retries - 1);
    };

    const x2t = await getModule();

    // 关键:检测 WASM 内存堆栈是否已经挂载
    // 只有 HEAPU8 及其 buffer 存在,FS 操作才不会报 "reading 'buffer'" 错误
    const checkMemoryReady = (m: any) => {
      return m && m.FS && m.HEAPU8 && m.HEAPU8.buffer;
    };

    return new Promise((resolve, reject) => {
      const timeoutId = setTimeout(() => {
        if (!this.isReady) reject(new Error('X2T initialization timeout (Memory not ready)'));
      }, this.INIT_TIMEOUT);

      // 如果模块和内存已经初始化完成
      if (checkMemoryReady(x2t)) {
        clearTimeout(timeoutId);
        this.WORKING_DIRS.forEach(dir => {
          try { x2t.FS.mkdir(dir); } catch (e) {}
        });
        this.x2tModule = x2t;
        this.isReady = true;
        resolve(x2t);
        return;
      }

      // 增加轮询检查,防止 onRuntimeInitialized 已经触发过的情况
      const checkTimer = setInterval(() => {
        if (checkMemoryReady(x2t)) {
          clearInterval(checkTimer);
          clearTimeout(timeoutId);
          this.WORKING_DIRS.forEach(dir => {
            try { x2t.FS.mkdir(dir); } catch (e) {}
          });
          this.x2tModule = x2t;
          this.isReady = true;
          resolve(x2t);
        }
      }, 50);

      x2t.onRuntimeInitialized = () => {
        if (this.isReady) return; // 轮询可能已经完成了
        
        if (checkMemoryReady(x2t)) {
          clearInterval(checkTimer);
          clearTimeout(timeoutId);
          this.WORKING_DIRS.forEach(dir => {
            try { x2t.FS.mkdir(dir); } catch (e) {}
          });
          this.x2tModule = x2t;
          this.isReady = true;
          console.log('X2T module initialized via runtime event');
          resolve(x2t);
        }
      };
    });
  }

  private createConversionParams(fromPath: string, toPath: string, additionalParams = ''): string {
    return `<?xml version="1.0" encoding="utf-8"?>
<TaskQueueDataConvert xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <m_sFileFrom>${fromPath}</m_sFileFrom>
  <m_sThemeDir>/working/themes</m_sThemeDir>
  <m_sFileTo>${toPath}</m_sFileTo>
  <m_bIsNoBase64>false</m_bIsNoBase64>
  ${additionalParams}
</TaskQueueDataConvert>`;
  }

  private async readMediaFiles(): Promise<Record<string, string>> {
    const media: Record<string, string> = {};
    if (!this.x2tModule) return media;
    try {
      const files = this.x2tModule.FS.readdir('/working/media/');
      for (const file of files) {
        if (file === '.' || file === '..') continue;
        try {
          const fileData = this.x2tModule.FS.readFile(`/working/media/${file}`);
          const blob = new Blob([fileData as any]);
          media[`media/${file}`] = URL.createObjectURL(blob);
        } catch (e) {}
      }
    } catch (e) {}
    return media;
  }

  // 严格同步源码的 sanitizeFileName
  private sanitizeFileName(input: string): string {
    if (typeof input !== 'string' || !input.trim()) return 'file.bin';
    const parts = input.split('.');
    const ext = parts.pop() || 'bin';
    const name = parts.join('.');
    const illegalChars = /[/?<>\\:*|"]/g;
    const controlChars = /[\x00-\x1f\x80-\x9f]/g;
    const reservedPattern = /^\.+$/;
    const unsafeChars = /[&'%!"{}[\]]/g;
    let sanitized = name
      .replace(illegalChars, '')
      .replace(controlChars, '')
      .replace(reservedPattern, '')
      .replace(unsafeChars, '');
    sanitized = sanitized.trim() || 'file';
    return `${sanitized.slice(0, 200)}.${ext}`;
  }

  private executeConversion(paramsPath: string): void {
    if (!this.x2tModule) throw new Error('X2T module not initialized');
    const result = this.x2tModule.ccall('main1', 'number', ['string'], [paramsPath]);
    if (result !== 0) throw new Error(`Conversion failed with code: ${result}`);
  }

  async convertDocument(file: File): Promise<ConversionResult> {
    // 使用队列确保同一时间只有一个转换任务在执行,防止 WASM 模块内部状态并发冲突
    const nextTask = this.conversionQueue.then(async () => {
      await this.initialize();
      const fileName = file.name;
      const fileExt = fileName.split('.').pop()?.toLowerCase() || '';
      const documentType = DOCUMENT_TYPE_MAP[fileExt];
      if (!documentType) throw new Error(`Unsupported file format: ${fileExt}`);

      try {
        const arrayBuffer = await file.arrayBuffer();
        const data = new Uint8Array(arrayBuffer);
        const sanitizedName = this.sanitizeFileName(fileName);
        
        const inputPath = `/working/${sanitizedName}`;
        const outputPath = `${inputPath}.bin`;

        this.x2tModule!.FS.writeFile(inputPath, data);
        const params = this.createConversionParams(inputPath, outputPath, '');
        this.x2tModule!.FS.writeFile('/working/params.xml', params);

        this.executeConversion('/working/params.xml');

        const result = this.x2tModule!.FS.readFile(outputPath);
        const media = await this.readMediaFiles();

        // 清理工作目录中的临时文件,防止内存泄漏和并发干扰
        const cleanup = (dir: string) => {
          try {
            this.x2tModule!.FS.readdir(dir).forEach(f => {
              if (f !== '.' && f !== '..') {
                const fullPath = dir === '/' ? `/${f}` : `${dir}/${f}`;
                if (this.WORKING_DIRS.includes(fullPath)) return;
                try {
                  const stat = (this.x2tModule!.FS as any).stat(fullPath);
                  if ((this.x2tModule!.FS as any).isDir(stat.mode)) {
                    cleanup(fullPath);
                  } else {
                    this.x2tModule!.FS.unlink(fullPath);
                  }
                } catch (e) {
                  try { this.x2tModule!.FS.unlink(fullPath); } catch (e2) {}
                }
              }
            });
          } catch (e) {}
        };
        
        cleanup('/working');

        return {
          fileName: sanitizedName,
          type: documentType,
          bin: result,
          media,
        };
      } catch (error) {
        throw error;
      }
    });

    // 无论成功还是失败,都更新队列以允许下一个任务
    this.conversionQueue = nextTask.catch(() => {});
    return nextTask;
  }
}

const x2tConverter = new X2TConverter();

// --- Editor Functions (Strictly Aligned with lib/onlyoffice-editor.ts) ---

export async function createEditorInstance(config: {
  fileName: string;
  fileType: string;
  binData: Uint8Array;
  media: Record<string, string>;
  elementId: string;
  onReady?: () => void;
}): Promise<any> {
  const { fileName, fileType, binData, media, elementId, onReady } = config;

  const container = document.getElementById(elementId);
  if (container) {
    while (container.firstChild) container.removeChild(container.firstChild);
  }

  await new Promise(resolve => setTimeout(resolve, 200));

  if (!window.Asc) (window as any).Asc = {};
  window.Asc.bIsLocalFonts = false;

  const editorCfg = {
    width: "100%",
    height: "100%",
    document: {
      title: fileName,
      url: fileName,
      fileType: fileType,
    },
    editorConfig: {
      lang: 'zh-CN',
      user: { id: 'local', name: 'User' },
      customization: {
        help: false,
        about: false,
      },
    },
  };
  const editor = new window.DocsAPI.DocEditor(elementId, {
    ...editorCfg,
    events: {
      onAppReady: () => {
        if (media) {
          editor?.sendCommand({ command: 'asc_setImageUrls', data: { urls: media } });
        }
        editor?.sendCommand({
          command: 'asc_openDocument',
          data: { buf: binData }
        });
        // asc_openDocument 注入方式不会触发 onDocumentReady,延迟 1.5s 后主动回调
        let readyCalled = false;
        const callReady = () => {
          if (!readyCalled) {
            readyCalled = true;
            if (onReady) onReady();
          }
        };
        setTimeout(callReady, 1500);
      },
      onDocumentReady: () => {
        if (onReady) onReady();
      },
      onError: (event: any) => {
        console.error('[OnlyOffice] error:', event);
      },
    },
  });

  return editor;
}

// --- Main Operation ---

export async function openDocument(file: File, elementId: string, onReady?: () => void): Promise<any> {
  try {
    if (!window.DocsAPI) {
      await loadScripts([`${BASE_PATH}web-apps/apps/api/documents/api.js`]);
    }
    await x2tConverter.loadScript();

    const result = await x2tConverter.convertDocument(file);

    const editor = await createEditorInstance({
      fileName: file.name,
      fileType: file.name.split('.').pop()?.toLowerCase() || '',
      binData: result.bin,
      media: result.media,
      elementId,
      onReady,
    });

    return editor;
  } catch (error: any) {
    console.error('Failed to open document:', error);
    throw error;
  }
}