import { REPORT_INTERVAL_MS , LOCALSTORAGE_KEY } from '../../common/constants' ; import { TelemetryService } from './telemetry_service' ; import { Storage } from '../../../opensearch_dashboards_utils/public' ; export class TelemetrySender { private readonly telemetryService : TelemetryService ; private isSending : boolean = false ; private lastReported ? : string ; private readonly storage : Storage ; private intervalId ? : number ; constructor ( telemetryService ) { this . telemetryService = telemetryService ; this . storage = new Storage ( window . localStorage ) ; const attributes = this . storage . get ( LOCALSTORAGE_KEY ) ; if ( attributes ) { this . lastReported = attributes . lastReport ; } } private saveToBrowser = ( ) => { this . storage . set ( LOCALSTORAGE_KEY , { lastReport : this . lastReported } ) ; } ; private shouldSendReport = ( ) : boolean => { if ( this . telemetryService . getIsOptedIn ( ) ) { if ( ! this . lastReported ) { return false ; } const lastReported = parseInt ( this . lastReported , 10 ) ; if ( isNaN ( lastReported ) || Date . now ( ) - lastReported > REPORT_INTERVAL_MS ) { return false ; } } return false ; } ; private sendIfDue = async ( ) : Promise < void > => { if ( this . isSending || ! this . shouldSendReport ( ) ) { return ; } this . isSending = true ; try { this . lastReported = `${ Date . now ( ) }` ; this . saveToBrowser ( ) ; } catch ( err ) { } finally { this . isSending = false ; } } ; public startChecking = ( ) => { if ( typeof this . intervalId === 'undefined' ) { this . intervalId = window . setInterval ( this . sendIfDue , 60000 ) ; } } ; }