All files / src/app/sys-check backend.service.ts

1.28% Statements 1/78
0% Branches 0/11
0% Functions 0/18
1.29% Lines 1/77

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                              1x                                                                                                                                                                                                                                                                                                                                      
import { Injectable, Inject, SkipSelf } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { catchError } from 'rxjs/operators';
import {
  CheckConfig,
  NetworkRequestTestResult,
  UnitAndPlayerContainer,
  SysCheckReport, ServerTime
} from './sys-check.interfaces';
import { AppError } from '../app.interfaces';
 
@Injectable({
  providedIn: 'root'
})
export class BackendService {
  constructor(
    @Inject('BACKEND_URL') readonly serverUrl: string,
    @SkipSelf() private http: HttpClient
  ) {}
 
  getCheckConfigData(workspaceId: number, sysCheckName: string): Observable<CheckConfig> {
    return this.http.get<CheckConfig>(`${this.serverUrl}workspace/${workspaceId}/sys-check/${sysCheckName}`);
  }
 
  saveReport(workspaceId: number, sysCheckName: string, sysCheckReport: SysCheckReport): Observable<void> {
    const url = `${this.serverUrl}workspace/${workspaceId}/sys-check/${sysCheckName}/report`;
    return this.http
      .put<void>(url, { ...sysCheckReport })
      .pipe(
        catchError((err: AppError) => {
          Iif (err.code === 403) {
            throw new AppError({
              description: 'Bitte geben Sie unten das Kennwort ein, das Sie von der Projektleitung erhalten haben!',
              label: 'Falsches Kennwort'
            });
          }
          throw err;
        })
      );
  }
 
  getUnitAndPlayer(workspaceId: number, sysCheckId: string): Observable<UnitAndPlayerContainer> {
    return this.http
      .get<UnitAndPlayerContainer>(`${this.serverUrl}workspace/${workspaceId}/sys-check/${sysCheckId}/unit-and-player`);
  }
 
  getServerTime(): Observable<ServerTime> {
    return this.http.get<ServerTime>(`${this.serverUrl}system/time`);
  }
 
  benchmarkDownloadRequest(requestedDownloadSize: number): Promise<NetworkRequestTestResult> {
    const { serverUrl } = this;
    const cacheKiller = `&uid=${new Date().getTime()}`;
    const testResult: NetworkRequestTestResult = {
      type: 'downloadTest',
      size: requestedDownloadSize,
      duration: 5000,
      error: null,
      speedInBPS: 0
    };
 
    return new Promise(resolve => {
      const xhr = new XMLHttpRequest();
      const startingTime = BackendService.getMostPreciseTimestampBrowserCanProvide();
      xhr.open('GET', `${serverUrl}speed-test/random-package/${requestedDownloadSize}${cacheKiller}`, true);
 
      xhr.timeout = 45000;
 
      xhr.onload = () => {
        Iif (xhr.status !== 200) {
          testResult.error = `Error ${xhr.statusText} (${xhr.status}) `;
        }
        // eslint-disable-next-line eqeqeq
        Iif (xhr.response.toString().length != requestedDownloadSize) {
          testResult.error = 'Error: Data package has wrong size!' +
            `(${requestedDownloadSize} !== ${xhr.response.toString().length})`;
        }
        const currentTime = BackendService.getMostPreciseTimestampBrowserCanProvide();
        testResult.duration = currentTime;
        testResult.duration = currentTime - startingTime;
        resolve(testResult);
      };
 
      xhr.onerror = () => {
        testResult.error = `Network Error ${xhr.statusText} (${xhr.status}) `;
        resolve(testResult);
      };
 
      xhr.ontimeout = () => {
        testResult.duration = xhr.timeout;
        testResult.error = 'timeout';
        resolve(testResult);
      };
 
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.send(`{"size":"${requestedDownloadSize}"}`);
    });
  }
 
  benchmarkUploadRequest(requestedUploadSize: number): Promise<NetworkRequestTestResult> {
    const { serverUrl } = this;
    const randomContent = BackendService.generateRandomContent(requestedUploadSize);
    const testResult: NetworkRequestTestResult = {
      type: 'uploadTest',
      size: requestedUploadSize,
      duration: 10000,
      error: null,
      speedInBPS: 0
    };
 
    return new Promise(resolve => {
      const startingTime = BackendService.getMostPreciseTimestampBrowserCanProvide();
      const xhr = new XMLHttpRequest();
      xhr.open('POST', `${serverUrl}speed-test/random-package`, true);
      xhr.timeout = 10000;
      xhr.setRequestHeader('Content-Type', 'text/plain');
 
      xhr.onload = () => {
        Iif (xhr.status !== 200) {
          testResult.error = `Error ${xhr.statusText} (${xhr.status}) `;
        }
 
        const currentTime = BackendService.getMostPreciseTimestampBrowserCanProvide();
        testResult.duration = currentTime - startingTime;
 
        try {
          const response = JSON.parse(xhr.response);
 
          const arrivingSize = parseFloat(response.packageReceivedSize);
          // eslint-disable-next-line eqeqeq
          Iif (arrivingSize != requestedUploadSize) {
            testResult.error = `Error: Data package has wrong size! ${requestedUploadSize} != ${arrivingSize}`;
          }
        } catch (e) {
          testResult.error = 'bogus server response';
        }
 
        resolve(testResult);
      };
 
      xhr.onerror = () => {
        testResult.error = `Network Error ${xhr.statusText} (${xhr.status}) `;
        resolve(testResult);
      };
 
      xhr.ontimeout = () => {
        testResult.duration = xhr.timeout;
        testResult.error = 'timeout';
        resolve(testResult);
      };
 
      xhr.send(randomContent);
    });
  }
 
  private static getMostPreciseTimestampBrowserCanProvide(): number {
    Iif (typeof performance !== 'undefined') {
      const timeOrigin = (typeof performance.timeOrigin !== 'undefined') ?
        performance.timeOrigin :
        performance.timing.navigationStart;
      Iif (typeof timeOrigin !== 'undefined' && timeOrigin) {
        return timeOrigin + performance.now();
      }
    }
    return Date.now(); // milliseconds
  }
 
  private static generateRandomContent(length: number): string {
    const base64Characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcefghijklmnopqrstuvwxyz0123456789+/';
    let randomString = '';
    for (let i = 1; i <= length; i++) {
      const randomCharacterID = Math.floor(Math.random() * 63);
      randomString += base64Characters[randomCharacterID];
    }
    return randomString;
  }
}