PlatformHostApiImpl.ets 2.2 KB
import { PlatformHostApi } from '../pigeon/PlatformApi';
import { bundleManager } from '@kit.AbilityKit';
import { deviceInfo } from '@kit.BasicServicesKit';
import { display } from '@kit.ArkUI';
import { web_webview } from '@kit.ArkWeb';

/**
 * PlatformApi HarmonyOS implementation.
 *
 * 组装完整 User-Agent,格式与 Android 端保持一致:
 * `{systemWebViewUA} doublefeel/{versionCode}({versionName})({manufacturer}##{brand}##{model}; OpenHarmony{osVersion}; {height}x{width})(huawei)`
 */
export class PlatformHostApiImpl extends PlatformHostApi {

  getFullUserAgent(): string {
    // 1. 系统 WebView UA
    let systemUa = '';
    try {
      systemUa = web_webview.WebviewController.getDefaultUserAgent();
    } catch (_) {
      systemUa = '';
    }

    // 2. 版本信息(同步读取 bundleInfo)
    let versionCode = 0;
    let versionName = '';
    try {
      const bundleInfo = bundleManager.getBundleInfoForSelfSync(
        bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT
      );
      versionCode = bundleInfo.versionCode;
      versionName = bundleInfo.versionName;
    } catch (_) {}

    // 3. 设备信息(@ohos.deviceInfo 常量,无需异步)
    const manufacturer: string = deviceInfo.manufacture ?? '';
    const brand: string = deviceInfo.brand ?? '';
    const model: string = deviceInfo.productModel ?? '';
    // osFullName 示例:"OpenHarmony 4.1.0",取主版本号数字部分
    const osVersion: string = deviceInfo.osFullName.replace(/[^0-9]/g, '') ?? '';

    // 4. 屏幕物理分辨率:长边为 height,短边为 width
    let screenWidth = 0;
    let screenHeight = 0;
    try {
      const defaultDisplay = display.getDefaultDisplaySync();
      const w = defaultDisplay.width;
      const h = defaultDisplay.height;
      screenWidth = Math.min(w, h);
      screenHeight = Math.max(w, h);
    } catch (_) {}

    // 5. 组装 customAgent(与 Android DeviceInfoUtils.userAgent 格式一致)
    const customAgent =
      `doublefeel/${versionCode}(${versionName})` +
      `(${manufacturer}##${brand}##${model}; OpenHarmony${osVersion}; ${screenHeight}x${screenWidth})` +
      `(huawei)`;

    const full = `${systemUa.trim()} ${customAgent}`.trim();
    return full;
  }
}