ngx-network
Version:
get and tracking the network speed with simplest way ever
156 lines (149 loc) • 7.3 kB
JavaScript
import * as i1 from '@angular/common/http';
import { HttpClientModule, HttpRequest, HttpEventType } from '@angular/common/http';
import * as i0 from '@angular/core';
import { NgModule, Injectable, Inject } from '@angular/core';
import { BehaviorSubject, Subscription, Observable } from 'rxjs';
import { throttleTime, filter, takeLast, tap, map, finalize, concatMap } from 'rxjs/operators';
var Units;
(function (Units) {
Units["kb/s"] = "kb/s";
Units["mb/s"] = "mb/s";
Units["gb/s"] = "gb/s";
Units["tb/s"] = "tb/s";
})(Units || (Units = {}));
const NGX_NETWORK_CONFIG = 'NGX_NETWORK_CONFIG';
class NgxNetworkModule {
static forRoot(config) {
return {
ngModule: NgxNetworkModule,
providers: [
NgxNetworkService,
{
provide: NGX_NETWORK_CONFIG,
useValue: {
url: (config === null || config === void 0 ? void 0 : config.url) || `https://raw.githubusercontent.com/mahmoudshahin1111/ngx-network/master/src/assets/mocks/1mb.jpg`,
speedUnit: (config === null || config === void 0 ? void 0 : config.speedUnit) || Units['mb/s'],
delay: (config === null || config === void 0 ? void 0 : config.delay) || 100
}
}
],
};
}
}
NgxNetworkModule.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0, type: NgxNetworkModule, deps: [], target: i0.ɵɵFactoryTarget.NgModule });
NgxNetworkModule.ɵmod = i0.ɵɵngDeclareNgModule({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0, type: NgxNetworkModule, imports: [HttpClientModule] });
NgxNetworkModule.ɵinj = i0.ɵɵngDeclareInjector({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0, type: NgxNetworkModule, imports: [[HttpClientModule]] });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0, type: NgxNetworkModule, decorators: [{
type: NgModule,
args: [{
imports: [HttpClientModule],
}]
}] });
class NgxNetworkService {
constructor(config, http) {
this.config = config;
this.http = http;
this.speedChanged$ = new BehaviorSubject({
speed: 0,
unit: config.speedUnit,
});
this.onSpeedChanged$ = this.speedChanged$.asObservable().pipe(throttleTime(this.config.delay), filter((payload) => payload.speed !== 0));
this.startSendingPayloadSubscription = new Subscription();
this.lastPayloadSize = 0;
this.lastTime = 0;
}
getSpeed() {
if (this.startSendingPayloadSubscription) {
this.startSendingPayloadSubscription.unsubscribe();
}
this.startSendingPayloadSubscription = this.startSendingPayload(this.config.url, false).subscribe();
return this.onSpeedChanged$;
}
onSpeedChanged() {
if (this.startSendingPayloadSubscription) {
this.startSendingPayloadSubscription.unsubscribe();
}
this.startSendingPayloadSubscription = this.startSendingPayload(this.config.url, true).subscribe();
return this.onSpeedChanged$;
}
startSendingPayload(url, repeatRequest) {
this.lastTime = 0;
this.lastPayloadSize = 0;
const randomQuery = `q=${Math.round(Math.random() * 99959).toString()}`;
if (!repeatRequest) {
return this.sendRequest(url, randomQuery).pipe(takeLast(1), tap((payload) => {
this.speedChanged$.next(payload);
}), map((e) => null));
}
return this.sendRequest(url, randomQuery).pipe(tap((payload) => {
this.speedChanged$.next(payload);
}), finalize(() => {
if (!repeatRequest)
return;
this.startSendingPayloadSubscription.unsubscribe();
this.startSendingPayloadSubscription = this.startSendingPayload(url, repeatRequest).subscribe();
}), map((e) => null));
}
sendRequest(url, params) {
const request = new HttpRequest('GET', url, {
params,
responseType: 'arraybuffer',
reportProgress: true,
});
return this.http
.request(request)
.pipe(concatMap((httpEvent) => this.handleHttpEvents(httpEvent)));
}
handleHttpEvents(e) {
return new Observable((subscriber) => {
if (e.type === HttpEventType.DownloadProgress) {
let currentTime = Date.now();
const elapseTimeForEveryPayload = currentTime - this.lastTime;
const elapseTimeSecs = elapseTimeForEveryPayload / 1000;
let speed = this.speedChanged$.getValue().speed.toString();
const currentPayloadSize = e.loaded;
const downloadPayloadSize = Math.abs(currentPayloadSize - this.lastPayloadSize);
switch (this.config.speedUnit) {
case Units['kb/s']:
speed = Number(downloadPayloadSize / 1024 / elapseTimeSecs).toFixed(3);
break;
case Units['mb/s']:
speed = Number(downloadPayloadSize / Math.pow(1024, 2) / elapseTimeSecs).toFixed(3);
break;
case Units['gb/s']:
speed = Number(downloadPayloadSize / Math.pow(1024, 3) / elapseTimeSecs).toFixed(3);
break;
case Units['tb/s']:
speed = Number(downloadPayloadSize / Math.pow(1024, 4) / elapseTimeSecs).toFixed(3);
break;
}
this.lastPayloadSize = e.loaded;
this.lastTime = Date.now();
subscriber.next({
speed: Number(Number(speed) === 0 ? this.speedChanged$.getValue().speed : speed),
unit: this.config.speedUnit,
});
}
subscriber.complete();
});
}
}
NgxNetworkService.ɵfac = i0.ɵɵngDeclareFactory({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0, type: NgxNetworkService, deps: [{ token: NGX_NETWORK_CONFIG }, { token: i1.HttpClient }], target: i0.ɵɵFactoryTarget.Injectable });
NgxNetworkService.ɵprov = i0.ɵɵngDeclareInjectable({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0, type: NgxNetworkService, providedIn: 'root' });
i0.ɵɵngDeclareClassMetadata({ minVersion: "12.0.0", version: "12.1.5", ngImport: i0, type: NgxNetworkService, decorators: [{
type: Injectable,
args: [{
providedIn: 'root'
}]
}], ctorParameters: function () { return [{ type: undefined, decorators: [{
type: Inject,
args: [NGX_NETWORK_CONFIG]
}] }, { type: i1.HttpClient }]; } });
/*
* Public API Surface of ngx-network
*/
/**
* Generated bundle index. Do not edit.
*/
export { NGX_NETWORK_CONFIG, NgxNetworkModule, NgxNetworkService, Units };
//# sourceMappingURL=ngx-network.js.map