EntryAbility.ets 19.3 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 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507

import { FlutterAbility, FlutterEngine,FlutterPlugin, FlutterPluginBinding, EventChannel, EventSink, MethodChannel, MethodCall, MethodResult } from '@ohos/flutter_ohos';
import { GeneratedPluginRegistrant } from '../plugins/GeneratedPluginRegistrant';
import Want from '@ohos.app.ability.Want';
import AbilityConstant from '@ohos.app.ability.AbilityConstant';
import hilog from '@ohos.hilog';
import { notificationManager } from '@kit.NotificationKit';
import { BusinessError } from '@ohos.base';
import { authentication } from '@kit.AccountKit';
import { speechRecognizer } from '@kit.CoreSpeechKit';
import { textRecognition } from '@kit.CoreVisionKit';
import { image } from '@kit.ImageKit';
import { fileIo as fs } from '@kit.CoreFileKit';
import abilityAccessCtrl, { Permissions } from '@ohos.abilityAccessCtrl';
import HuaweiLoginPlugin from '../components/HuaweiLoginView';



export default class EntryAbility extends FlutterAbility {
  private TAG: string = "| com.naji.book |";
  // 通道名称
  public CHANNEL:string = "com.naji/book";

  private channel: MethodChannel | null = null;
  private hasRequestedNotificationEnable: boolean = false;
  private pushIntentValue: Object | null = null;
  private speechEngine: speechRecognizer.SpeechRecognitionEngine | null = null;
  private speechSessionId: string = '';
  private pendingSpeechResult: MethodResult | null = null;
  private speechAccumulatedText: string = '';
  private speechCurrentPartial: string = '';
  private speechListening: boolean = false;
  private imageOcrRunning: boolean = false;

  // private eventChannel?: EventChannel;
  // private eventSink?: EventSink;

  configureFlutterEngine(flutterEngine: FlutterEngine) {
    super.configureFlutterEngine(flutterEngine)
    GeneratedPluginRegistrant.registerWith(flutterEngine)
    this.addPlugin(new HuaweiLoginPlugin());
    this.channel = new MethodChannel(flutterEngine.dartExecutor, this.CHANNEL);
    this.channel.setMethodCallHandler({
      onMethodCall: (call: MethodCall, result: MethodResult) => {
        this.handleMethodCall(call, result);
      }
    });

    // this.eventChannel = new EventChannel(flutterEngine.dartExecutor, 'flutter.ohos.tpns/event_click');
    // this.eventChannel.setStreamHandler({
    //   onListen(args: object, events: EventSink): void {
    //     this.eventSink = events;
    //   },
    //   onCancel(args: object): void {
    //     this.eventSink = undefined;
    //   }
    // });
  }


  onCreate(want: Want, launchParam: AbilityConstant.LaunchParam): void {
    super.onCreate(want, launchParam);
    hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onCreate' + JSON.stringify(want));
    if (want && want.parameters) {
      try {

        // want判断消息是否是腾讯云推送的消息
        // const data = TPushHelper.prototype.parseNotificationMessage(want);

        const data = want.parameters;

        if (data != null) {
          hilog.info(0x0000, 'testTag', '%{public}s', "onCreate" + JSON.stringify(data));
          // 或者使用 Object.keys 方法遍历
          Object.keys(data).forEach(key => {


            if(key.toString()==='tpnsChanel'){
              // 使用 EventSink 发送数据后,dart断的事件监听回调会收到发送的数据。
              const value = data[key];
              console.log(`Key: ${key}, Value: ${typeof value === 'object' ? JSON.stringify(value) : value}`);
              // this.eventSink?.success(value);
              // this.channel?.invokeMethod("getIntent",value)


              this.pushIntentValue = value;
              }       });

        } else {
          hilog.info(0x0000, 'testTag', 'EntryAbility data was null');
          // this.eventSink?.error(0x0000.toString(), 'EntryAbility data was null', null);
        }
      } catch (err) {
        hilog.error(0x0000, 'testTag', 'TPushHelper  parseNotificationMessage exception', err);
        // this.eventSink?.error(0x0000.toString(), 'TPushHelper  parseNotificationMessage exception', err);
      }
    } else {
      hilog.info(0x0000, 'testTag', 'EntryAbility want or want.parameters was null');
      // this.eventSink?.error(0x0000.toString(), 'EntryAbility want or want.parameters was null', null);
    }
  }

  onForeground(): void {
    super.onForeground();
    this.ensureNotificationEnabled();
  }

  private handleMethodCall(call: MethodCall, result: MethodResult): void {
    switch (call.method) {
      case "getIntent":
        result.success(this.pushIntentValue);
        break;
      case "huaweiLogin":
        this.huaweiLogin(result);
        break;
      case "startSpeechRecognition":
        this.startSpeechRecognition(result);
        break;
      case "stopSpeechRecognition":
        this.stopSpeechRecognition();
        break;
      case "cancelSpeechRecognition":
        this.cancelSpeechRecognition();
        break;
      case "recognizeImageText":
        this.recognizeImageText(call, result);
        break;
      default:
        result.notImplemented();
        break;
    }
  }

  private async ensureMicrophonePermission(): Promise<boolean> {
    const permissions: Array<Permissions> = ['ohos.permission.MICROPHONE'];
    const atManager = abilityAccessCtrl.createAtManager();
    const requestResult = await atManager.requestPermissionsFromUser(this.context, permissions);
    return requestResult.authResults.length > 0 && requestResult.authResults[0] === 0;
  }

  private async recognizeImageText(call: MethodCall, result: MethodResult): Promise<void> {
    if (this.imageOcrRunning) {
      result.error('IMAGE_OCR_BUSY', '图片识别正在进行中', null);
      return;
    }

    const path = call.argument('path') as string;
    if (path === undefined || path === null || path.length === 0) {
      result.error('IMAGE_OCR_INVALID_ARGUMENT', '图片路径为空', null);
      return;
    }

    this.imageOcrRunning = true;
    let file: fs.File | undefined = undefined;
    let pixelMap: image.PixelMap | undefined = undefined;
    try {
      const initResult = await textRecognition.init();
      if (!initResult) {
        throw new Error('OCR engine initialization failed');
      }

      file = fs.openSync(path, fs.OpenMode.READ_ONLY);
      const source = image.createImageSource(file.fd);
      const imageInfo = await source.getImageInfo();
      const decodingOptions: image.DecodingOptions = {
        editable: true,
        desiredPixelFormat: image.PixelMapFormat.RGBA_8888,
        desiredSize: {
          width: imageInfo.size.width,
          height: imageInfo.size.height
        }
      };
      pixelMap = await source.createPixelMap(decodingOptions);

      if (file !== undefined) {
        fs.closeSync(file);
        file = undefined;
      }

      const visionInfo: textRecognition.VisionInfo = {
        pixelMap: pixelMap
      };
      const configuration: textRecognition.TextRecognitionConfiguration = {
        isDirectionDetectionSupported: true
      };
      const ocrResult = await textRecognition.recognizeText(visionInfo, configuration);
      const text = (ocrResult.value ?? '').trim();
      hilog.info(0x0000, this.TAG, 'ImageTextRecognition success: %{public}d chars', text.length);
      result.success(text);
    } catch (error) {
      const businessError = error as BusinessError;
      hilog.error(0x0000, this.TAG, 'ImageTextRecognition failed: %{public}d %{public}s',
        businessError.code ?? 0, businessError.message);
      result.error('IMAGE_OCR_FAILED', '图片文字识别失败', businessError.message);
    } finally {
      if (file !== undefined) {
        try {
          fs.closeSync(file);
        } catch (error) {
          hilog.error(0x0000, this.TAG, 'close image file failed');
        }
      }
      if (pixelMap !== undefined) {
        try {
          await pixelMap.release();
        } catch (error) {
          hilog.error(0x0000, this.TAG, 'release image pixelMap failed');
        }
      }
      try {
        await textRecognition.release();
      } catch (error) {
        hilog.error(0x0000, this.TAG, 'release textRecognition failed');
      }
      this.imageOcrRunning = false;
    }
  }

  private async startSpeechRecognition(result: MethodResult): Promise<void> {
    if (this.speechListening || this.pendingSpeechResult !== null) {
      result.error('SPEECH_BUSY', '语音识别正在进行中', null);
      return;
    }

    this.pendingSpeechResult = result;
    try {
      const hasPermission = await this.ensureMicrophonePermission();
      hilog.info(0x0000, this.TAG, 'SpeechRecognition microphone permission: %{public}s', hasPermission ? 'granted' : 'denied');
      if (!hasPermission) {
        this.pendingSpeechResult = null;
        result.error('MICROPHONE_DENIED', '未获得麦克风权限', null);
        return;
      }

      const engineParams: speechRecognizer.CreateEngineParams = {
        language: 'zh-CN',
        online: 1,
        extraParams: {
          'locate': 'CN',
          'recognizerMode': 'long'
        }
      };
      const engine = await speechRecognizer.createEngine(engineParams);

      const self = this;
      this.speechEngine = engine;
      this.speechSessionId = `speech_${Date.now()}`;
      this.speechAccumulatedText = '';
      this.speechCurrentPartial = '';

      engine.setListener({
        onStart: (sessionId: string, eventMessage: string): void => {
          if (sessionId !== self.speechSessionId) {
            return;
          }
          self.speechListening = true;
          hilog.info(0x0000, self.TAG, 'SpeechRecognition onStart: %{public}s', eventMessage);
        },
        onEvent: (sessionId: string, eventCode: number, eventMessage: string): void => {
          if (sessionId !== self.speechSessionId) {
            return;
          }
          hilog.info(0x0000, self.TAG, 'SpeechRecognition onEvent: %{public}d %{public}s', eventCode, eventMessage);
        },
        onResult: (sessionId: string, recognitionResult: speechRecognizer.SpeechRecognitionResult): void => {
          if (sessionId !== self.speechSessionId || self.pendingSpeechResult === null) {
            return;
          }
          const text = (recognitionResult.result ?? '').trim();
          if (recognitionResult.isFinal) {
            if (text.length > 0) {
              self.speechAccumulatedText = self.speechAccumulatedText + text;
            }
            self.speechCurrentPartial = '';
          } else {
            self.speechCurrentPartial = text;
          }
          hilog.info(0x0000, self.TAG, 'SpeechRecognition onResult: final=%{public}s text=%{public}s',
            recognitionResult.isFinal ? 'true' : 'false', text);
        },
        onComplete: (sessionId: string, eventMessage: string): void => {
          if (sessionId !== self.speechSessionId || !self.speechListening) {
            return;
          }
          self.speechListening = false;
          const text = (self.speechAccumulatedText + self.speechCurrentPartial).trim();
          const pending = self.pendingSpeechResult;
          self.pendingSpeechResult = null;
          self.releaseSpeechEngine();
          hilog.info(0x0000, self.TAG, 'SpeechRecognition onComplete: %{public}s', text);
          pending?.success(text);
        },
        onError: (sessionId: string, errorCode: number, errorMessage: string): void => {
          if (sessionId !== self.speechSessionId || !self.speechListening) {
            return;
          }
          self.speechListening = false;
          const text = (self.speechAccumulatedText + self.speechCurrentPartial).trim();
          const pending = self.pendingSpeechResult;
          self.pendingSpeechResult = null;
          self.releaseSpeechEngine();
          hilog.error(0x0000, self.TAG, 'SpeechRecognition onError: %{public}d %{public}s', errorCode, errorMessage);
          if (text.length > 0) {
            pending?.success(text);
          } else if (errorCode === 1002200003) {
            pending?.error('SPEECH_NO_SPEECH', '没有识别到内容,请重说', errorMessage);
          } else {
            pending?.error('SPEECH_RECOGNITION_ERROR', '语音识别失败,请重试', errorMessage);
          }
        }
      });

      const startParams: speechRecognizer.StartParams = {
        sessionId: this.speechSessionId,
        audioInfo: {
          audioType: 'pcm',
          sampleRate: 16000,
          soundChannel: 1,
          sampleBit: 16
        },
        extraParams: {
          'recognitionMode': 0,
          'maxAudioDuration': 28800000
        }
      };
      this.speechListening = true;
      engine.startListening(startParams);
    } catch (error) {
      const businessError = error as BusinessError;
      this.pendingSpeechResult = null;
      this.releaseSpeechEngine();
      hilog.error(0x0000, this.TAG, 'startSpeechRecognition failed: %{public}s', businessError.message);
      result.error('SPEECH_UNAVAILABLE', '语音识别启动失败,请重试', businessError.message);
    }
  }

  private stopSpeechRecognition(): void {
    if (!this.speechListening || this.speechEngine === null || this.speechSessionId === '') {
      return;
    }
    try {
      this.speechEngine.finish(this.speechSessionId);
    } catch (error) {
      const businessError = error as BusinessError;
      hilog.error(0x0000, this.TAG, 'finishSpeechRecognition failed: %{public}s', businessError.message);
      this.completeSpeechRecognitionWithCurrentText();
    }
  }

  private cancelSpeechRecognition(): void {
    if (!this.speechListening || this.speechEngine === null || this.speechSessionId === '') {
      return;
    }

    const sessionId = this.speechSessionId;
    const engine = this.speechEngine;
    const pending = this.pendingSpeechResult;
    this.speechListening = false;
    this.pendingSpeechResult = null;
    try {
      engine.cancel(sessionId);
    } catch (error) {
      hilog.error(0x0000, this.TAG, 'cancelSpeechRecognition failed');
    }
    this.releaseSpeechEngine();
    pending?.success('');
  }

  private completeSpeechRecognitionWithCurrentText(): void {
    if (!this.speechListening) {
      return;
    }
    this.speechListening = false;
    const text = (this.speechAccumulatedText + this.speechCurrentPartial).trim();
    const pending = this.pendingSpeechResult;
    this.pendingSpeechResult = null;
    this.releaseSpeechEngine();
    pending?.success(text);
  }

  private releaseSpeechEngine(): void {
    const engine = this.speechEngine;
    this.speechEngine = null;
    this.speechSessionId = '';
    this.speechAccumulatedText = '';
    this.speechCurrentPartial = '';
    if (engine !== null) {
      try {
        engine.shutdown();
      } catch (error) {
        hilog.error(0x0000, this.TAG, 'releaseSpeechEngine failed');
      }
    }
  }

  private huaweiLogin(result: MethodResult): void {
    const request = new authentication.HuaweiIDProvider().createLoginWithHuaweiIDRequest();
    request.forceLogin = true;
    request.state = new Date().getTime().toString();

    const controller = new authentication.AuthenticationController(this.context);
    controller.executeRequest(request).then((response: authentication.AuthenticationResponse) => {
      const loginResponse: authentication.LoginWithHuaweiIDResponse =
        response as authentication.LoginWithHuaweiIDResponse;
      const data = loginResponse.data;
      let openID = '';
      let unionID = '';
      let authorizationCode = '';
      let idToken = '';
      if (data != undefined) {
        openID = data.openID;
        unionID = data.unionID;
        authorizationCode = data.authorizationCode ?? '';
        idToken = data.idToken ?? '';
      }

      const resultData: Record<string, string> = {
        'openID': openID,
        'unionID': unionID,
        'authorizationCode': authorizationCode,
        'idToken': idToken
      };
      result.success(resultData);
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'testTag', 'huaweiLogin failed, code: %{public}d, message: %{public}s', err.code, err.message);
      result.error('HUAWEI_LOGIN_ERROR', '华为账号登录失败', err.message);
    });
  }

  private ensureNotificationEnabled(): void {
    if (this.hasRequestedNotificationEnable) {
      return;
    }
    this.hasRequestedNotificationEnable = true;

    notificationManager.isNotificationEnabled().then((enabled: boolean) => {
      hilog.info(0x0000, 'testTag', 'isNotificationEnabled: %{public}s', enabled ? 'true' : 'false');
      if (enabled) {
        return;
      }

      notificationManager.requestEnableNotification(this.context).then(() => {
        hilog.info(0x0000, 'testTag', '%{public}s', 'requestEnableNotification success');
        if (!notificationManager.isNotificationEnabledSync()) {
          notificationManager.openNotificationSettings(this.context).then(() => {
            hilog.info(0x0000, 'testTag', '%{public}s', 'openNotificationSettings success');
          }).catch((err: BusinessError) => {
            hilog.error(0x0000, 'testTag', 'openNotificationSettings failed, code: %{public}d, message: %{public}s', err.code, err.message);
          });
        }
      }).catch((err: BusinessError) => {
        hilog.error(0x0000, 'testTag', 'requestEnableNotification failed, code: %{public}d, message: %{public}s', err.code, err.message);
        notificationManager.openNotificationSettings(this.context).then(() => {
          hilog.info(0x0000, 'testTag', '%{public}s', 'openNotificationSettings success');
        }).catch((openErr: BusinessError) => {
          hilog.error(0x0000, 'testTag', 'openNotificationSettings failed, code: %{public}d, message: %{public}s', openErr.code, openErr.message);
        });
      });
    }).catch((err: BusinessError) => {
      hilog.error(0x0000, 'testTag', 'isNotificationEnabled failed, code: %{public}d, message: %{public}s', err.code, err.message);
    });
  }


  // onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void {
  //   hilog.info(0x0000, 'testTag', '%{public}s', 'Ability onNewWant' + JSON.stringify(want));
  //   if (want && want.parameters) {
  //     try {
  //
  //       // want判断消息是否是腾讯云推送的消息
  //       // const data = TPushHelper.prototype.parseNotificationMessage(want);
  //
  //       const data = want.parameters;
  //
  //       if (data != null) {
  //         hilog.info(0x0000, 'testTag', '%{public}s', "onNewWant" + JSON.stringify(data));
  //         // 或者使用 Object.keys 方法遍历
  //         Object.keys(data).forEach(key => {
  //
  //
  //           if(key.toString()==='tpnsChanel'){
  //             // 使用 EventSink 发送数据后,dart断的事件监听回调会收到发送的数据。
  //             const value = data[key];
  //             console.log(`Key: ${key}, Value: ${typeof value === 'object' ? JSON.stringify(value) : value}`);
  //             this.eventSink?.success(value);
  //             this.channel?.invokeMethod("getIntent",value)
  //
  //           }
  //
  //         });
  //
  //       } else {
  //         hilog.info(0x0000, 'testTag', 'EntryAbility data was null');
  //         this.eventSink?.error(0x0000.toString(), 'EntryAbility data was null', null);
  //       }
  //     } catch (err) {
  //       hilog.error(0x0000, 'testTag', 'TPushHelper  parseNotificationMessage exception', err);
  //       this.eventSink?.error(0x0000.toString(), 'TPushHelper  parseNotificationMessage exception', err);
  //     }
  //   } else {
  //     hilog.info(0x0000, 'testTag', 'EntryAbility want or want.parameters was null');
  //     this.eventSink?.error(0x0000.toString(), 'EntryAbility want or want.parameters was null', null);
  //   }
  //
  //
  // }
}