import { Injectable } from '@angular/core' ; import { Message } from './message' ; @ Injectable ( ) export class SmsLoaderService { messages : Message [ ] ; constructor ( ) { } private handleError ( error ) { console . error ( 'An error occurred' , error ) ; return Promise . reject ( error . message || error ) ; } private cleanString ( str ) { return str . replace ( /&#(\d+);&#(\d+);/g , ( match , unit1 , unit2 ) => { let unitA = parseInt ( unit1 ) ; let unitB = parseInt ( unit2 ) ; if ( unitA >= 55296 && unitA <= 57343 ) { return String . fromCodePoint ( unitA , unitB ) ; } else { return match ; } } ) ; } getLoadedMessages ( ) { return new Promise ( ( resolve , reject ) => { resolve ( this . messages ) ; } ) . catch ( this . handleError ) ; } private decodeHtml ( str ) { var txt = document . createElement ( "textarea" ) ; txt . innerHTML = str ; return txt . value ; } loadSMSFile ( file ) { this . messages = new Array < Message > ( ) ; let reader = new FileReader ( ) ; let parser = new DOMParser ( ) ; let xmlDoc ; reader . readAsText ( file , 'UTF-8' ) ; return new Promise ( ( resolve , reject ) => { reader . onload = ( event ) => { var cleanedText = this . cleanString ( event . target . result ) ; xmlDoc = parser . parseFromString ( cleanedText , 'text/xml' ) ; for ( let sms of xmlDoc . getElementsByTagName ( 'sms' ) ) { this . messages . push ( { contactAddress : sms . getAttribute ( 'address' ) , contactName : sms . getAttribute ( 'contact_name' ) , type : parseInt ( sms . getAttribute ( 'type' ) ) , timestamp : sms . getAttribute ( 'date' ) , date : new Date ( parseInt ( sms . getAttribute ( 'date' ) ) ) , body : sms . getAttribute ( 'body' ) } ) ; } for ( let mms of xmlDoc . getElementsByTagName ( 'mms' ) ) { let contactAddress = "" ; let body = "" ; let type = 3 ; for ( let addr of mms . getElementsByTagName ( 'addr' ) ) { if ( ( addr . getAttribute ( 'type' ) == "137" ) || ( contactAddress == 'insert-address-token' ) ) { contactAddress = addr . getAttribute ( 'address' ) ; } if ( contactAddress == 'insert-address-token' ) { type = 4 ; } } for ( let part of mms . getElementsByTagName ( 'part' ) ) { if ( part . getAttribute ( 'ct' ) == "image/jpeg" ) { body = body + '<img style="vertical-align:top" src="data:image/jpeg;base64,' + part . getAttribute ( 'data' ) + '"/>' ; } if ( part . getAttribute ( 'ct' ) == "text/plain" ) { body = body + '<div>' + part . getAttribute ( 'text' ) + '<div/>' ; } } this . messages . push ( { contactAddress : contactAddress , contactName : mms . getAttribute ( 'contact_name' ) , type : type , timestamp : mms . getAttribute ( 'date' ) , date : new Date ( parseInt ( mms . getAttribute ( 'date' ) ) ) , body : body } ) ; } resolve ( ) ; } ; } ) . catch ( this . handleError ) ; } }