Skip to content

Commit

Permalink
Merge pull request #25 from Hacksore/america-api-updates
Browse files Browse the repository at this point in the history
General updates
  • Loading branch information
Sean Boult authored Mar 10, 2020
2 parents a7e97e5 + 5d2eed4 commit 1553c15
Show file tree
Hide file tree
Showing 12 changed files with 918 additions and 934 deletions.
2 changes: 1 addition & 1 deletion lib/controllers/american.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -123,7 +123,7 @@ export class AmericanController implements SessionController {
brandIndicator: vehicleInfo.brandIndicator,
regId: vehicleInfo.regid,
// unsure if this is right but the new endpoint does not seem to have gen
gen: vehicleInfo.modelYear > 2016 ? 2 : 1,
gen: vehicleInfo.modelYear > 2016 ? '2' : '1',
name: vehicleInfo.nickName
}
this.vehicles.push(new AmericanVehicle(config, this));
Expand Down
74 changes: 33 additions & 41 deletions lib/controllers/canadian.controller.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import got from 'got';
import { VehicleStatus, VehicleLocation, Odometer, BlueLinkyConfig, Session } from '../interfaces/common.interfaces';
import { ALL_ENDPOINTS, CA_BASE_URL, CA_ENDPOINTS } from '../constants';
import { VehicleStatus, BlueLinkyConfig, Session } from '../interfaces/common.interfaces';
import { CA_ENDPOINTS } from '../constants';
import { Vehicle } from '../vehicles/vehicle';
import CanadianVehicle from '../vehicles/canadianVehicle';
import SessionController from './controller';

import logger from '../logger';
import { BASE_URL, CLIENT_ORIGIN } from '../constants/canada';
import { REGIONS } from '../constants';

export class CanadianController implements SessionController {
Expand All @@ -22,7 +21,7 @@ export class CanadianController implements SessionController {
refreshToken: '',
controlToken: '',
deviceId: '',
tokenExpiresAt: 0
tokenExpiresAt: 0,
};

private vehicles: Array<CanadianVehicle> = [];
Expand All @@ -38,20 +37,18 @@ export class CanadianController implements SessionController {
deviceUuid: undefined,
};

private timeOffset = -(new Date().getTimezoneOffset() / 60)
private timeOffset = -(new Date().getTimezoneOffset() / 60);

public async refreshAccessToken(): Promise<string> {
const shouldRefreshToken = Math.floor(((+new Date() / 1000)) - this.session.tokenExpiresAt) <= 10;
const shouldRefreshToken = Math.floor(+new Date() / 1000 - this.session.tokenExpiresAt) <= 10;

if (this.session.refreshToken && shouldRefreshToken) {
// TODO , right call ?
const response = await this.request(CA_ENDPOINTS.verifyToken,
{},
{})
const response = await this.request(CA_ENDPOINTS.verifyToken, {}, {});

this.session.accessToken = response.body.access_token;
this.session.refreshToken = response.body.refresh_token;
this.session.tokenExpiresAt = Math.floor((+new Date() / 1000) + response.body.expires_in);
this.session.tokenExpiresAt = Math.floor(+new Date() / 1000 + response.body.expires_in);

return Promise.resolve('Token refreshed');
}
Expand All @@ -60,22 +57,20 @@ export class CanadianController implements SessionController {
}

public async login(): Promise<string> {
console.log('Begin login request');
logger.info('Begin login request');
try {
const response = await this.request(
CA_ENDPOINTS.login,
{
loginId: this.config.username,
password: this.config.password
})
const response = await this.request(CA_ENDPOINTS.login, {
loginId: this.config.username,
password: this.config.password,
});

this.session.accessToken = response.result.accessToken;
this.session.refreshToken = response.result.refreshToken;
this.session.tokenExpiresAt = Math.floor((+new Date()/1000) + response.result.expireIn);
this.session.tokenExpiresAt = Math.floor(+new Date() / 1000 + response.result.expireIn);

return Promise.resolve('login good');
} catch (err) {
return Promise.reject('error: ' + err)
return Promise.reject('error: ' + err);
}
}

Expand All @@ -84,12 +79,11 @@ export class CanadianController implements SessionController {
}

async getVehicles(): Promise<Array<Vehicle>> {
console.log('Begin getVehicleList request');
logger.info('Begin getVehicleList request');
try {
const response = await this.request(
CA_ENDPOINTS.vehicleList, {});
const response = await this.request(CA_ENDPOINTS.vehicleList, {});

const data = response.result
const data = response.result;
if (data.vehicles === undefined) {
this.vehicles = [];
return Promise.reject('No vehicles found for account!');
Expand All @@ -108,47 +102,46 @@ export class CanadianController implements SessionController {
genType: vehicle.genType,
subscriptionEndDate: vehicle.subscriptionEndDate,
mileageForNextService: vehicle.mileageForNextService,
daysForNextService: vehicle.daysForNextService
}
daysForNextService: vehicle.daysForNextService,
};
this.vehicles.push(new CanadianVehicle(config, this));
})
});

return Promise.resolve(this.vehicles);
} catch (err) {
return Promise.reject('error: ' + err)
return Promise.reject('error: ' + err);
}
}

//////////////////////////////////////////////////////////////////////////////
// Account
//////////////////////////////////////////////////////////////////////////////

public async myAccount(): Promise<String> {
public async myAccount(): Promise<string> {
logger.info('Begin myAccount request');
try {
const response = await this.request(CA_ENDPOINTS.myAccount, {});
return Promise.resolve(response.result);
} catch (err) {
return Promise.reject('error: ' + err)
return Promise.reject('error: ' + err);
}
}

public async preferedDealer(): Promise<String> {
public async preferedDealer(): Promise<string> {
logger.info('Begin preferedDealer request');
try {
const response = await this.request(CA_ENDPOINTS.preferedDealer, {});
return Promise.resolve(response.result);
} catch (err) {
return Promise.reject('error: ' + err)
return Promise.reject('error: ' + err);
}
}


//////////////////////////////////////////////////////////////////////////////
// Internal
//////////////////////////////////////////////////////////////////////////////

private async request(endpoint, body: object, headers: object = {}, ): Promise<any | null> {
private async request(endpoint, body: object, headers: object = {}): Promise<any | null> {
logger.info(`[${endpoint}] ${JSON.stringify(headers)} ${JSON.stringify(body)}`);
try {
const response = await got(endpoint, {
Expand All @@ -159,22 +152,21 @@ export class CanadianController implements SessionController {
language: 1,
offset: this.timeOffset,
accessToken: this.session.accessToken,
...headers
...headers,
},
body: {
...body
}
...body,
},
});

if (response.body.responseHeader.responseCode != 0)
{
return Promise.reject('bad request: ' + response.body.responseHeader.responseDesc)
if (response.body.responseHeader.responseCode != 0) {
return Promise.reject('bad request: ' + response.body.responseHeader.responseDesc);
}

return Promise.resolve(response.body);
} catch (err) {
console.error(err)
return Promise.reject('error: ' + err)
console.error(err);
return Promise.reject('error: ' + err);
}
}
}
1 change: 1 addition & 0 deletions lib/controllers/european.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,7 @@ export class EuropeanController implements SessionController {

}

// TODO: type this or replace it with
async asyncForEach(array, callback): Promise<any> {
for (let index = 0; index < array.length; index++) {
await callback(array[index], index, array);
Expand Down
32 changes: 16 additions & 16 deletions lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,6 @@ class BlueLinky extends EventEmitter {
...config,
}

console.log(this.config)

if (config.autoLogin === undefined) {
this.config.autoLogin = true;
}
Expand Down Expand Up @@ -79,24 +77,26 @@ class BlueLinky extends EventEmitter {
return this.controller.getVehicles() || [];
}

public getVehicle(): Vehicle|undefined {
if (this.vehicles.length == 0) {
public getVehicle(input: string): Vehicle|undefined {
if (this.vehicles.length === 0) {
throw new Error('No Vehicle found!');
}
if (this.config.vehicleId != undefined) {
try {
return this.vehicles.find(car => car.vehicleId === this.config.vehicleId) as Vehicle;
} catch (err) {
throw new Error('Vehicle not found!');
}
} else if (this.config.vin != undefined) {
try {
return this.vehicles.find(car => car.vin === this.config.vin) as Vehicle;
} catch (err) {
throw new Error('Vehicle not found!');

try {
const foundCar = this.vehicles.find(car => {
car.vin === input ||
car.vehicleId === input
});

if (!foundCar && this.vehicles.length > 0) {
return this.vehicles[0];
}

return foundCar;

} catch (err) {
throw new Error('Vehicle not found!');
}
return this.vehicles[0];
}

public async refreshAccessToken(): Promise<string> {
Expand Down
37 changes: 18 additions & 19 deletions lib/interfaces/canadian.interfaces.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@

export interface CanadianEndpoints {
login: string;
logout: string;
vehicleList: string;
vehicleInfo: string;
lock: string;
unlock: string;
start: string;
stop: string;
locate: string;
hornlight: string,
status: string;
remoteStatus: string;
verifyAccountToken: string;
verifyPin: string;
verifyToken: string;
myAccount: string;
nextService: string;
preferedDealer: string;
login: string;
logout: string;
vehicleList: string;
vehicleInfo: string;
lock: string;
unlock: string;
start: string;
stop: string;
locate: string;
hornlight: string;
status: string;
remoteStatus: string;
verifyAccountToken: string;
verifyPin: string;
verifyToken: string;
myAccount: string;
nextService: string;
preferedDealer: string;
}
2 changes: 1 addition & 1 deletion lib/interfaces/common.interfaces.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ export interface BlueLinkyConfig {
autoLogin: boolean;
pin: string|undefined;
vin: string|undefined;
vehicleId: string|undefined
vehicleId: string|undefined;
deviceUuid: string|undefined;
}

Expand Down
Loading

0 comments on commit 1553c15

Please sign in to comment.