1// Copyright (C) 2022 The Android Open Source Project 2// 3// Licensed under the Apache License, Version 2.0 (the "License"); 4// you may not use this file except in compliance with the License. 5// You may obtain a copy of the License at 6// 7// http://www.apache.org/licenses/LICENSE-2.0 8// 9// Unless required by applicable law or agreed to in writing, software 10// distributed under the License is distributed on an "AS IS" BASIS, 11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12// See the License for the specific language governing permissions and 13// limitations under the License. 14 15import {RecordingError} from '../recording_error_handling'; 16import { 17 OnTargetChangeCallback, 18 RecordingTargetV2, 19 TargetFactory, 20} from '../recording_interfaces_v2'; 21import {isLinux, isMacOs, isWindows} from '../recording_utils'; 22import {targetFactoryRegistry} from '../target_factory_registry'; 23import {HostOsTarget} from '../targets/host_os_target'; 24 25export const HOST_OS_TARGET_FACTORY = 'HostOsTargetFactory'; 26 27export class HostOsTargetFactory implements TargetFactory { 28 readonly kind = HOST_OS_TARGET_FACTORY; 29 private target?: HostOsTarget; 30 private onTargetChange: OnTargetChangeCallback = () => {}; 31 32 connectNewTarget(): Promise<RecordingTargetV2> { 33 throw new RecordingError( 34 'Can not create a new Host OS target.' + 35 'The Host OS target is created at factory initialisation.', 36 ); 37 } 38 39 getName(): string { 40 return 'HostOs'; 41 } 42 43 listRecordingProblems(): string[] { 44 return []; 45 } 46 47 listTargets(): RecordingTargetV2[] { 48 if (this.target) { 49 return [this.target]; 50 } 51 return []; 52 } 53 54 tryEstablishWebsocket(websocketUrl: string) { 55 if (this.target) { 56 if (this.target.getUrl() === websocketUrl) { 57 return; 58 } else { 59 this.target.disconnect(); 60 } 61 } 62 this.target = new HostOsTarget( 63 websocketUrl, 64 this.maybeClearTarget.bind(this), 65 this.onTargetChange, 66 ); 67 this.onTargetChange(); 68 } 69 70 maybeClearTarget(target: HostOsTarget): void { 71 if (this.target === target) { 72 this.target = undefined; 73 this.onTargetChange(); 74 } 75 } 76 77 setOnTargetChange(onTargetChange: OnTargetChangeCallback): void { 78 this.onTargetChange = onTargetChange; 79 } 80} 81 82// We instantiate the host target factory only on Mac, Linux, and Windows. 83if ( 84 isMacOs(navigator.userAgent) || 85 isLinux(navigator.userAgent) || 86 isWindows(navigator.userAgent) 87) { 88 targetFactoryRegistry.register(new HostOsTargetFactory()); 89} 90