diff --git a/src/vpn.ts b/src/vpn.ts index fe668c9..c71e0da 100644 --- a/src/vpn.ts +++ b/src/vpn.ts @@ -2,18 +2,21 @@ import { Config, ConnectOptions } from './interfaces'; const path = require('path'); // eslint-disable-line -export const $ = require('@ammora/nodobjc'); // eslint-disable-line - export class Bridge { private vpnManager: any; private readonly config?: Config = {}; - constructor(options: ConnectOptions, config?: Config) { + private $: any; + + private fwImported = false; + + private readonly options: any; + + constructor(options?: ConnectOptions, config?: Config) { this.config = config; - this.importFramework(); - this.create(options); + this.options = options; } private get log(): any { @@ -30,7 +33,26 @@ export class Bridge { return log; } + get objC(): any { + if (this.$ !== undefined) { + return this.$; + } + + try { + this.$ = require('@ammora/nodobjc'); // eslint-disable-line + } catch (e) { + this.log.info('Error import Objc: ', e.message); + throw e; + } + + return this.$; + } + private importFramework(): void { + if (this.fwImported) { + return; + } + let frameworkPath = this.config?.frameworkPath; if (frameworkPath === null || frameworkPath === undefined) { @@ -40,9 +62,10 @@ export class Bridge { const fwPath: string = path.join(frameworkPath, 'VPNManager.framework'); this.log.info('VPNManager Framework path: ' + fwPath); - $.import(fwPath); + this.objC.import(fwPath); this.log.info('VPNManager Framework import'); + this.fwImported = true; } get manager(): any { @@ -50,8 +73,9 @@ export class Bridge { } create(options: ConnectOptions): this { + this.importFramework(); const json = JSON.stringify(options); - this.vpnManager = $.VPNManager('alloc')('initWithJson', $(json)); + this.vpnManager = this.objC.VPNManager('alloc')('initWithJson', this.objC(json)); this.log.info('VPNManager created'); @@ -59,9 +83,16 @@ export class Bridge { } connect(username: string, password: string): void { - // @todo async/await + if (this.vpnManager === undefined && this.options !== undefined) { + this.create(this.options); + } + + if (this.vpnManager === undefined) { + throw new Error('VPNManager no created!'); + } + const self = this; // eslint-disable-line - const block = $(function(_self: any, isSuccess: any) { + const block = this.objC(function(_self: any, isSuccess: any) { // @todo get NSError self.log.info('VPNManager connecting'); if (isSuccess === true) { @@ -72,7 +103,7 @@ export class Bridge { self.log.info(`VPNManager error`); }, ['v',['?','B']]); - this.vpnManager('connect', $(username), 'password', $(password), 'complete', block); + this.vpnManager('connect', this.objC(username), 'password', this.objC(password), 'complete', block); } }