import { Session , Message , IMessage , IChatConnectorAddress , IIdentity } from "botbuilder" ; import { ArgumentNullException } from "../Errors" ; import { BotResponse } from "../Models" ; import { IBotMessageFormatter } from "./Interfaces" ; export class BotMessageFormatter implements IBotMessageFormatter { private static imageRegExp = /^(https?:\/\/.+\/(.+)\.(jpg|png|gif|jpeg$))/ ; toBotFrameworkMessage ( session , response ) { if ( ! response ) { throw new ArgumentNullException ( 'response' ) ; } if ( ! response . messages ) { throw new ArgumentNullException ( 'response.messages' ) ; } if ( ! session ) { throw new ArgumentNullException ( 'session' ) ; } const responseAddress = this . cloneAddress ( session . message . address ) ; if ( responseAddress . conversation && responseAddress . conversation . id && response . type === 'send' ) { responseAddress . conversation . id = responseAddress . conversation . id . split ( ';' ) [ 0 ] ; } return response . messages . map ( ( message ) => { if ( typeof message !== 'string' ) { const bfMessage = message as IMessage ; bfMessage . address = responseAddress ; return bfMessage ; } const response = new Message ( session ) ; response . address ( responseAddress ) ; const imageAttachment = this . convertToImageAttachment ( message ) ; if ( imageAttachment ) { response . addAttachment ( imageAttachment ) ; } else { response . text ( message ) ; } return response . toMessage ( ) ; } ) ; } private cloneAddress ( address ) { if ( ! address ) { throw new ArgumentNullException ( 'address' ) ; } return < IChatConnectorAddress > { id : address . id , serviceUrl : address . serviceUrl , channelId : address . channelId , user : < IIdentity > { id : address . user . id , name : address . user . name , isGroup : address . user . isGroup } , bot : < IIdentity > { id : address . bot . id , name : address . bot . name , isGroup : address . bot . isGroup } , conversation : ! address . conversation ? null : < IIdentity > { id : address . conversation . id , name : address . conversation . name , isGroup : address . conversation . isGroup } } ; } private convertToImageAttachment ( message ) { if ( ! message ) { return null ; } const result = BotMessageFormatter . imageRegExp . exec ( message ) ; if ( result ) { return { contentUrl : result [ 1 ] , name : result [ 2 ] , contentType : "image/#{result[3]}" } ; } return null ; } } export default BotMessageFormatter ;