All files / src/devices deviceService.ts

96.06% Statements 122/127
88.46% Branches 23/26
100% Functions 38/38
95.5% Lines 106/111

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 24510x 10x 10x                   10x 10x 10x 10x 10x 10x 10x     10x       26x 26x 26x 26x 26x   26x 26x               26x   35x 35x 35x 35x 35x       35x 4x 4x           31x 31x 31x 31x             26x   26x   1x   26x       99x 99x 99x 3x 3x   96x     26x         25x 25x 25x           24x       24x 24x     26x     3x 3x     26x 7x     26x     3x 3x 3x         26x 1x 1x     26x 2x 2x 1x 1x 1x     1x     26x 2x   2x 1x 1x 1x     1x     26x 1x 1x 1x 1x   1x     1x               26x 4x 4x 3x   1x     26x 3x 3x     26x 1x 1x 1x 1x 1x         1x             26x 1x       1x 1x           1x                               26x 1x 1x           26x 2x      
import { Injectable } from '@nestjs/common';
import { v4 as uuidv4 } from 'uuid';
import gql from 'graphql-tag';
import {
  DeviceUuidInputEvent,
  DeviceUuidResponse,
  DeviceMetricsInput,
  DeviceMetricsOutput,
  DeviceStatus,
  DeviceSettings,
} from '../types.d';
import { DeviceType } from './deviceTypes.d';
import { DeviceMetrics } from './deviceMetrics';
import { EnvironmentService } from '../common_services/config';
import { DeviceVerification } from './deviceVerification';
import { DeviceDb } from './deviceDb';
import { DynamodbService, AppSyncClient } from '../common_services';
import { UpdateEventPublisher } from '../common_interfaces';
import { convertDbStreamToSettings } from './deviceUtils';
 
@Injectable()
export class DeviceService extends UpdateEventPublisher {
  deviceDb: DeviceDb;
 
  constructor(
    private readonly dynamodbService: DynamodbService,
    private readonly envService: EnvironmentService,
    private readonly deviceMetrics: DeviceMetrics,
    private readonly deviceVerify: DeviceVerification,
    private readonly appsyncClient: AppSyncClient,
  ) {
    super(appsyncClient, (deviceUuid) => this.getDeviceStatus(deviceUuid));
    this.deviceDb = new DeviceDb(
      this.envService.deviceTableName,
      this.envService.modelSerialGsi,
      this.dynamodbService.documentClient,
      this.envService.accessTokenGsi,
    );
  }
 
  getDeviceUuid = async (
    event: DeviceUuidInputEvent,
  ): Promise<DeviceUuidResponse> => {
    try {
      console.log('device service: getDeviceUuid:', event);
      const { model, serial } = event;
      const response = await this.deviceDb.getDeviceByModelSerial(
        model,
        serial,
      );
      if (response.Items && response.Items.length > 0) {
        const item = response.Items[0];
        return Promise.resolve({
          id: item.id,
          model: item.model,
          serial: item.serial,
        });
      }
      console.log(`Device ${model}, ${serial} doesnt exist, create new uuid.`);
      const id = uuidv4();
      await this.deviceDb.saveDeviceUuid(model, serial, id);
      return Promise.resolve({ id, model, serial });
    } catch (err) {
      console.error(err);
      throw err;
    }
  };
 
  getDeviceMetrics = (deviceUuid: string, type: string) => this.deviceMetrics.getDeviceMetrics(deviceUuid, type);
 
  createDeviceMetrics = async (
    input: DeviceMetricsInput,
  ): Promise<DeviceMetricsOutput> => this.deviceMetrics.createDeviceMetrics(input);
 
  saveDeviceRecord = async (
    deviceUuid: string,
    type: DeviceType,
    data: { [key: string]: any },
  ): Promise<void> => {
    const valid = await this.deviceVerify.isDeviceUuidValid(deviceUuid);
    if (!valid) {
      console.error('Device uuid not found ', deviceUuid);
      throw new Error(`Device uuid not found ${deviceUuid}`);
    }
    await this.deviceDb.updateDeviceRecord(deviceUuid, type, data);
  };
 
  saveDeviceTokens = async (
    deviceUuid: string,
    accessToken: string,
    refreshToken: string,
    idToken?: string,
  ): Promise<void> => {
    const status = DeviceStatus.ACTIVE;
    await this.saveDeviceRecord(deviceUuid, DeviceType.core, {
      accessToken,
      refreshToken,
      idToken,
      status,
    });
    await this.saveDeviceRecord(deviceUuid, DeviceType.settings, {
      status,
    });
    // TODO: use a single hardcoded entityUuid fow now, it will be replaced later
    const entityUuid = '1b1404d7-5c2b-4a14-bf9e-8bdc494e7234';
    await this.saveDeviceRecord(deviceUuid, DeviceType.core, { entityUuid });
  };
 
  saveDevicePhone = async (
    deviceUuid: string,
    phone: string,
  ): Promise<void> => {
    await this.saveDeviceRecord(deviceUuid, DeviceType.settings, { phone });
  };
 
  saveDevicePin = async (deviceUuid: string, pin: string): Promise<void> => {
    await this.saveDeviceRecord(deviceUuid, DeviceType.settings, { pin });
  };
 
  saveEntity = async (
    deviceUuid: string,
    entityUuid: string,
  ): Promise<void> => {
    await this.saveDeviceRecord(deviceUuid, DeviceType.core, { entityUuid });
    await this.saveDeviceRecord(deviceUuid, DeviceType.settings, {
      entityUuid,
    });
  };
 
  saveSite = async (deviceUuid: string, siteUuid: string): Promise<void> => {
    await this.saveDeviceRecord(deviceUuid, DeviceType.core, { siteUuid });
    await this.saveDeviceRecord(deviceUuid, DeviceType.settings, { siteUuid });
  };
 
  getEntityUuidByAccessToken = async (accessToken: string): Promise<string> => {
    const output = await this.deviceDb.getDeviceByAccessToken(accessToken);
    if (typeof output.Items !== 'undefined' && output.Items.length > 0) {
      const { entityUuid } = output.Items[0];
      Eif (entityUuid) {
        return entityUuid;
      }
    }
    throw new Error('Invalid access token.');
  };
 
  getRefreshTokenByUuid = async (deviceUuid: string) => {
    const output = await this.deviceDb.getDeviceByUuid(deviceUuid);
 
    if (typeof output.Items !== 'undefined' && output.Items.length > 0) {
      const { refreshToken } = output.Items[0];
      Eif (refreshToken) {
        return refreshToken;
      }
    }
    throw new Error('getRefreshTokenByUuid: Invalid deviceUuid.');
  };
 
  deactivateDevice = async (deviceUuid: string) => {
    const status = 'INACTIVE';
    const accessToken = status;
    const refreshToken = status;
    const idToken = status;
 
    await this.saveDeviceRecord(deviceUuid, DeviceType.settings, {
      status,
    });
    await this.saveDeviceRecord(deviceUuid, DeviceType.core, {
      status,
      accessToken,
      refreshToken,
      idToken,
    });
  };
 
  getDeviceStatus = async (deviceUuid: string): Promise<DeviceStatus> => {
    const device = await this.deviceDb.getDeviceByUuid(deviceUuid);
    if (device.Items && device.Items.length > 0) {
      return device.Items[0].status as DeviceStatus;
    }
    throw new Error(`Invalid device uuid ${deviceUuid}`);
  };
 
  saveDeviceStatus = async (deviceUuid: string, status: DeviceStatus) => {
    await this.saveDeviceRecord(deviceUuid, DeviceType.core, { status });
    await this.saveDeviceRecord(deviceUuid, DeviceType.settings, { status });
  };
 
  updateDeviceSettings = async (deviceSettings: DeviceSettings) => {
    const deviceUuid = deviceSettings.id;
    const settings = { ...deviceSettings };
    delete settings.id;
    try {
      await this.deviceDb.updateDeviceRecord(
        deviceUuid,
        DeviceType.settings,
        settings,
      );
      return true;
    } catch (error) {
      console.error(error);
      return false;
    }
  };
 
  getDeviceSettings = async (deviceUuid: string) => {
    const device = await this.deviceDb.getDeviceRecordByType(
      deviceUuid,
      DeviceType.settings,
    );
    Eif (device.Items && device.Items.length > 0) {
      return device.Items[0] as DeviceSettings;
    }
    throw new Error(`Invalid device uuid ${deviceUuid}`);
  };
 
  prepareUpdateEventRequest(item: any, keys: any) {
    return {
      mutation: gql`
        mutation PublishDeviceSettingsUpdate(
          $item: DeviceSettingsInput!
        ) {
          publishDeviceSettingsUpdateEvent(deviceSettings: $item) {
            ${keys}
          }
        }
      `,
      variables: {
        item,
      },
    };
  }
 
  onDeviceSettingsStream = async (event: any): Promise<void> => {
    console.info('device settings stream event:', JSON.stringify(event));
    await this.publishUpdateEventToSubscribers<DeviceSettings>(
      event,
      convertDbStreamToSettings,
    );
  };
 
  onDeviceSettingsUpdate = async (accessToken: string) => {
    await this.deviceVerify.checkAccessToken(accessToken);
  };
}