How to use requestSession method in wpt

Best JavaScript code snippet using wpt

Recognizer.ts

Source:Recognizer.ts Github

copy

Full Screen

1import {2 ArgumentNullError,3 ConnectionMessage,4 ConnectionOpenResponse,5 ConnectionState,6 CreateNoDashGuid,7 Deferred,8 Events,9 IAudioSource,10 IAudioStreamNode,11 IConnection,12 IDetachable,13 IEventSource,14 IStreamChunk,15 MessageType,16 PlatformEvent,17 Promise,18 PromiseHelper,19 PromiseResult,20} from "../../common/Exports";21import { AuthInfo, IAuthentication } from "./IAuthentication";22import { IConnectionFactory } from "./IConnectionFactory";23import {24 ConnectingToServiceEvent,25 ListeningStartedEvent,26 RecognitionCompletionStatus,27 RecognitionEndedEvent,28 RecognitionStartedEvent,29 RecognitionTriggeredEvent,30 SpeechDetailedPhraseEvent,31 SpeechEndDetectedEvent,32 SpeechFragmentEvent,33 SpeechHypothesisEvent,34 SpeechRecognitionEvent,35 SpeechRecognitionResultEvent,36 SpeechSimplePhraseEvent,37 SpeechStartDetectedEvent,38} from "./RecognitionEvents";39import { RecognitionMode, RecognizerConfig, SpeechResultFormat } from "./RecognizerConfig";40import { ServiceTelemetryListener } from "./ServiceTelemetryListener.Internal";41import { SpeechConnectionMessage } from "./SpeechConnectionMessage.Internal";42import {43 IDetailedSpeechPhrase,44 ISimpleSpeechPhrase,45 ISpeechEndDetectedResult,46 ISpeechFragment,47 ISpeechStartDetectedResult,48} from "./SpeechResults";49export class Recognizer {50 private authentication: IAuthentication;51 private connectionFactory: IConnectionFactory;52 private audioSource: IAudioSource;53 private recognizerConfig: RecognizerConfig;54 private speechConfigConnectionId: string;55 private connectionFetchPromise: Promise<IConnection>;56 private connectionId: string;57 private authFetchEventId: string;58 public constructor(59 authentication: IAuthentication,60 connectionFactory: IConnectionFactory,61 audioSource: IAudioSource,62 recognizerConfig: RecognizerConfig) {63 if (!authentication) {64 throw new ArgumentNullError("authentication");65 }66 if (!connectionFactory) {67 throw new ArgumentNullError("connectionFactory");68 }69 if (!audioSource) {70 throw new ArgumentNullError("audioSource");71 }72 if (!recognizerConfig) {73 throw new ArgumentNullError("recognizerConfig");74 }75 this.authentication = authentication;76 this.connectionFactory = connectionFactory;77 this.audioSource = audioSource;78 this.recognizerConfig = recognizerConfig;79 }80 public get AudioSource(): IAudioSource {81 return this.audioSource;82 }83 public Recognize = (onEventCallback: (event: SpeechRecognitionEvent) => void, speechContextJson?: string): Promise<boolean> => {84 const requestSession = new RequestSession(this.audioSource.Id(), onEventCallback);85 requestSession.ListenForServiceTelemetry(this.audioSource.Events);86 return this.audioSource87 .Attach(requestSession.AudioNodeId)88 .ContinueWithPromise<boolean>((result: PromiseResult<IAudioStreamNode>) => {89 if (result.IsError) {90 requestSession.OnAudioSourceAttachCompleted(null, true, result.Error);91 throw new Error(result.Error);92 } else {93 requestSession.OnAudioSourceAttachCompleted(result.Result, false);94 }95 const audioNode = result.Result;96 this.FetchConnection(requestSession)97 .OnSuccessContinueWith((connection: IConnection) => {98 const messageRetrievalPromise = this.ReceiveMessage(connection, requestSession);99 const messageSendPromise = this.SendSpeechConfig(requestSession.RequestId, connection, this.recognizerConfig.SpeechConfig.Serialize())100 .OnSuccessContinueWithPromise((_: boolean) => {101 return this.SendSpeechContext(requestSession.RequestId, connection, speechContextJson)102 .OnSuccessContinueWithPromise((_: boolean) => {103 return this.SendAudio(requestSession.RequestId, connection, audioNode, requestSession);104 });105 });106 const completionPromise = PromiseHelper.WhenAll([messageRetrievalPromise, messageSendPromise]);107 completionPromise.On((r: boolean) => {108 requestSession.Dispose();109 this.SendTelemetryData(requestSession.RequestId, connection, requestSession.GetTelemetry());110 }, (error: string) => {111 requestSession.Dispose(error);112 this.SendTelemetryData(requestSession.RequestId, connection, requestSession.GetTelemetry());113 });114 return completionPromise;115 });116 return requestSession.CompletionPromise;117 });118 }119 private FetchConnection = (requestSession: RequestSession, isUnAuthorized: boolean = false): Promise<IConnection> => {120 if (this.connectionFetchPromise) {121 if (this.connectionFetchPromise.Result().IsError122 || this.connectionFetchPromise.Result().Result.State() === ConnectionState.Disconnected) {123 this.connectionId = null;124 this.connectionFetchPromise = null;125 return this.FetchConnection(requestSession);126 } else {127 requestSession.OnPreConnectionStart(this.authFetchEventId, this.connectionId);128 requestSession.OnConnectionEstablishCompleted(200);129 requestSession.ListenForServiceTelemetry(this.connectionFetchPromise.Result().Result.Events);130 return this.connectionFetchPromise;131 }132 }133 this.authFetchEventId = CreateNoDashGuid();134 this.connectionId = CreateNoDashGuid();135 requestSession.OnPreConnectionStart(this.authFetchEventId, this.connectionId);136 const authPromise = isUnAuthorized ? this.authentication.FetchOnExpiry(this.authFetchEventId) : this.authentication.Fetch(this.authFetchEventId);137 this.connectionFetchPromise = authPromise138 .ContinueWithPromise((result: PromiseResult<AuthInfo>) => {139 if (result.IsError) {140 requestSession.OnAuthCompleted(true, result.Error);141 throw new Error(result.Error);142 } else {143 requestSession.OnAuthCompleted(false);144 }145 const connection = this.connectionFactory.Create(this.recognizerConfig, result.Result, this.connectionId);146 requestSession.ListenForServiceTelemetry(connection.Events);147 return connection.Open().OnSuccessContinueWithPromise((response: ConnectionOpenResponse) => {148 if (response.StatusCode === 200) {149 requestSession.OnConnectionEstablishCompleted(response.StatusCode);150 return PromiseHelper.FromResult(connection);151 } else if (response.StatusCode === 403 && !isUnAuthorized) {152 return this.FetchConnection(requestSession, true);153 } else {154 requestSession.OnConnectionEstablishCompleted(response.StatusCode, response.Reason);155 return PromiseHelper.FromError<IConnection>(`Unable to contact server. StatusCode: ${response.StatusCode}, Reason: ${response.Reason}`);156 }157 });158 });159 return this.connectionFetchPromise;160 }161 private ReceiveMessage = (connection: IConnection, requestSession: RequestSession): Promise<boolean> => {162 return connection163 .Read()164 .OnSuccessContinueWithPromise((message: ConnectionMessage) => {165 const connectionMessage = SpeechConnectionMessage.FromConnectionMessage(message);166 if (connectionMessage.RequestId.toLowerCase() === requestSession.RequestId.toLowerCase()) {167 switch (connectionMessage.Path.toLowerCase()) {168 case "turn.start":169 requestSession.OnServiceTurnStartResponse(JSON.parse(connectionMessage.TextBody));170 break;171 case "speech.startDetected":172 requestSession.OnServiceSpeechStartDetectedResponse(JSON.parse(connectionMessage.TextBody));173 break;174 case "speech.hypothesis":175 requestSession.OnServiceSpeechHypothesisResponse(JSON.parse(connectionMessage.TextBody));176 break;177 case "speech.fragment":178 requestSession.OnServiceSpeechFragmentResponse(JSON.parse(connectionMessage.TextBody));179 break;180 case "speech.enddetected":181 requestSession.OnServiceSpeechEndDetectedResponse(JSON.parse(connectionMessage.TextBody));182 break;183 case "speech.phrase":184 if (this.recognizerConfig.IsContinuousRecognition) {185 // For continuous recognition telemetry has to be sent for every phrase as per spec.186 this.SendTelemetryData(requestSession.RequestId, connection, requestSession.GetTelemetry());187 }188 if (this.recognizerConfig.Format === SpeechResultFormat.Simple) {189 requestSession.OnServiceSimpleSpeechPhraseResponse(JSON.parse(connectionMessage.TextBody));190 } else {191 requestSession.OnServiceDetailedSpeechPhraseResponse(JSON.parse(connectionMessage.TextBody));192 }193 break;194 case "turn.end":195 requestSession.OnServiceTurnEndResponse();196 return PromiseHelper.FromResult(true);197 default:198 break;199 }200 }201 return this.ReceiveMessage(connection, requestSession);202 });203 }204 private SendSpeechConfig = (requestId: string, connection: IConnection, speechConfigJson: string) => {205 if (speechConfigJson && this.connectionId !== this.speechConfigConnectionId) {206 this.speechConfigConnectionId = this.connectionId;207 return connection208 .Send(new SpeechConnectionMessage(209 MessageType.Text,210 "speech.config",211 requestId,212 "application/json",213 speechConfigJson));214 }215 return PromiseHelper.FromResult(true);216 }217 private SendSpeechContext = (requestId: string, connection: IConnection, speechContextJson: string) => {218 if (speechContextJson) {219 return connection220 .Send(new SpeechConnectionMessage(221 MessageType.Text,222 "speech.context",223 requestId,224 "application/json",225 speechContextJson));226 }227 return PromiseHelper.FromResult(true);228 }229 private SendTelemetryData = (requestId: string, connection: IConnection, telemetryData: string) => {230 return connection231 .Send(new SpeechConnectionMessage(232 MessageType.Text,233 "telemetry",234 requestId,235 "application/json",236 telemetryData));237 }238 private SendAudio = (239 requestId: string,240 connection: IConnection,241 audioStreamNode: IAudioStreamNode,242 requestSession: RequestSession): Promise<boolean> => {243 // NOTE: Home-baked promises crash ios safari during the invocation244 // of the error callback chain (looks like the recursion is way too deep, and245 // it blows up the stack). The following construct is a stop-gap that does not246 // bubble the error up the callback chain and hence circumvents this problem.247 // TODO: rewrite with ES6 promises.248 const deferred = new Deferred<boolean>();249 const readAndUploadCycle = (_: boolean) => {250 audioStreamNode.Read().On(251 (audioStreamChunk: IStreamChunk<ArrayBuffer>) => {252 // we have a new audio chunk to upload.253 if (requestSession.IsSpeechEnded) {254 // If service already recognized audio end then dont send any more audio255 deferred.Resolve(true);256 return;257 }258 const payload = (audioStreamChunk.IsEnd) ? null : audioStreamChunk.Buffer;259 const uploaded = connection.Send(260 new SpeechConnectionMessage(261 MessageType.Binary, "audio", requestId, null, payload));262 if (!audioStreamChunk.IsEnd) {263 uploaded.OnSuccessContinueWith(readAndUploadCycle);264 } else {265 // the audio stream has been closed, no need to schedule next266 // read-upload cycle.267 deferred.Resolve(true);268 }269 },270 (error: string) => {271 if (requestSession.IsSpeechEnded) {272 // For whatever reason, Reject is used to remove queue subscribers inside273 // the Queue.DrainAndDispose invoked from DetachAudioNode down blow, which274 // means that sometimes things can be rejected in normal circumstances, without275 // any errors.276 deferred.Resolve(true); // TODO: remove the argument, it's is completely meaningless.277 } else {278 // Only reject, if there was a proper error.279 deferred.Reject(error);280 }281 });282 };283 readAndUploadCycle(true);284 return deferred.Promise();285 }286}287// tslint:disable-next-line:max-classes-per-file288class RequestSession {289 private isDisposed: boolean = false;290 private serviceTelemetryListener: ServiceTelemetryListener;291 private detachables: IDetachable[] = new Array<IDetachable>();292 private requestId: string;293 private audioSourceId: string;294 private audioNodeId: string;295 private audioNode: IAudioStreamNode;296 private authFetchEventId: string;297 private connectionId: string;298 private serviceTag: string;299 private isAudioNodeDetached: boolean = false;300 private isCompleted: boolean = false;301 private onEventCallback: (event: SpeechRecognitionEvent) => void;302 private requestCompletionDeferral: Deferred<boolean>;303 constructor(audioSourceId: string, onEventCallback: (event: SpeechRecognitionEvent) => void) {304 this.audioSourceId = audioSourceId;305 this.onEventCallback = onEventCallback;306 this.requestId = CreateNoDashGuid();307 this.audioNodeId = CreateNoDashGuid();308 this.requestCompletionDeferral = new Deferred<boolean>();309 this.serviceTelemetryListener = new ServiceTelemetryListener(this.requestId, this.audioSourceId, this.audioNodeId);310 this.OnEvent(new RecognitionTriggeredEvent(this.RequestId, this.audioSourceId, this.audioNodeId));311 }312 public get RequestId(): string {313 return this.requestId;314 }315 public get AudioNodeId(): string {316 return this.audioNodeId;317 }318 public get CompletionPromise(): Promise<boolean> {319 return this.requestCompletionDeferral.Promise();320 }321 public get IsSpeechEnded(): boolean {322 return this.isAudioNodeDetached;323 }324 public get IsCompleted(): boolean {325 return this.isCompleted;326 }327 public ListenForServiceTelemetry(eventSource: IEventSource<PlatformEvent>): void {328 this.detachables.push(eventSource.AttachListener(this.serviceTelemetryListener));329 }330 public OnAudioSourceAttachCompleted = (audioNode: IAudioStreamNode, isError: boolean, error?: string): void => {331 this.audioNode = audioNode;332 if (isError) {333 this.OnComplete(RecognitionCompletionStatus.AudioSourceError, error);334 } else {335 this.OnEvent(new ListeningStartedEvent(this.requestId, this.audioSourceId, this.audioNodeId));336 }337 }338 public OnPreConnectionStart = (authFetchEventId: string, connectionId: string): void => {339 this.authFetchEventId = authFetchEventId;340 this.connectionId = connectionId;341 this.OnEvent(new ConnectingToServiceEvent(this.requestId, this.authFetchEventId, this.connectionId));342 }343 public OnAuthCompleted = (isError: boolean, error?: string): void => {344 if (isError) {345 this.OnComplete(RecognitionCompletionStatus.AuthTokenFetchError, error);346 }347 }348 public OnConnectionEstablishCompleted = (statusCode: number, reason?: string): void => {349 if (statusCode === 200) {350 this.OnEvent(new RecognitionStartedEvent(this.RequestId, this.audioSourceId, this.audioNodeId, this.authFetchEventId, this.connectionId));351 return;352 } else if (statusCode === 403) {353 this.OnComplete(RecognitionCompletionStatus.UnAuthorized, reason);354 } else {355 this.OnComplete(RecognitionCompletionStatus.ConnectError, reason);356 }357 }358 public OnServiceTurnStartResponse = (response: ITurnStartResponse): void => {359 if (response && response.context && response.context.serviceTag) {360 this.serviceTag = response.context.serviceTag;361 }362 }363 public OnServiceSpeechStartDetectedResponse = (result: ISpeechStartDetectedResult): void => {364 this.OnEvent(new SpeechStartDetectedEvent(this.RequestId, result));365 }366 public OnServiceSpeechHypothesisResponse = (result: ISpeechFragment): void => {367 this.OnEvent(new SpeechHypothesisEvent(this.RequestId, result));368 }369 public OnServiceSpeechFragmentResponse = (result: ISpeechFragment): void => {370 this.OnEvent(new SpeechFragmentEvent(this.RequestId, result));371 }372 public OnServiceSpeechEndDetectedResponse = (result: ISpeechEndDetectedResult): void => {373 this.DetachAudioNode();374 this.OnEvent(new SpeechEndDetectedEvent(this.RequestId, result));375 }376 public OnServiceSimpleSpeechPhraseResponse = (result: ISimpleSpeechPhrase): void => {377 this.OnEvent(new SpeechSimplePhraseEvent(this.RequestId, result));378 }379 public OnServiceDetailedSpeechPhraseResponse = (result: IDetailedSpeechPhrase): void => {380 this.OnEvent(new SpeechDetailedPhraseEvent(this.RequestId, result));381 }382 public OnServiceTurnEndResponse = (): void => {383 this.OnComplete(RecognitionCompletionStatus.Success);384 }385 public OnConnectionError = (error: string): void => {386 this.OnComplete(RecognitionCompletionStatus.UnknownError, error);387 }388 public Dispose = (error?: string): void => {389 if (!this.isDisposed) {390 // we should have completed by now. If we did not its an unknown error.391 this.OnComplete(RecognitionCompletionStatus.UnknownError, error);392 this.isDisposed = true;393 for (const detachable of this.detachables) {394 detachable.Detach();395 }396 this.serviceTelemetryListener.Dispose();397 }398 }399 public GetTelemetry = (): string => {400 return this.serviceTelemetryListener.GetTelemetry();401 }402 private OnComplete = (status: RecognitionCompletionStatus, error?: string): void => {403 if (!this.isCompleted) {404 this.isCompleted = true;405 this.DetachAudioNode();406 this.OnEvent(new RecognitionEndedEvent(this.RequestId, this.audioSourceId, this.audioNodeId, this.authFetchEventId, this.connectionId, this.serviceTag, status, error ? error : ""));407 }408 }409 private DetachAudioNode = (): void => {410 if (!this.isAudioNodeDetached) {411 this.isAudioNodeDetached = true;412 if (this.audioNode) {413 this.audioNode.Detach();414 }415 }416 }417 private OnEvent = (event: SpeechRecognitionEvent): void => {418 this.serviceTelemetryListener.OnEvent(event);419 Events.Instance.OnEvent(event);420 if (this.onEventCallback) {421 this.onEventCallback(event);422 }423 }424}425interface ITurnStartResponse {426 context: ITurnStartContext;427}428interface ITurnStartContext {429 serviceTag: string;...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wpt = require('wpt-api');2const wptAPI = new wpt('A.2a8d7c6e4a6e7b1d92e8a7b6f9b6c7d1');3wptAPI.requestSession({4}).then((data) => {5 console.log(data);6}).catch((err) => {7 console.error(err);8});9### `new WPT(key)`10### `wpt.getLocations()`11### `wpt.getTests()`12### `wpt.getTest(testId)`13### `wpt.requestTest(testOptions)`14### `wpt.requestSession(sessionOptions)`

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run wpt automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful