package main
import (
"bytes"
"crypto/sha256"
"fmt"
"io/ioutil"
"log"
"net/http"
"strconv"
"time"
)
var telemetryClient * http . Client
func getTelemetryClient ( ) * http . Client {
if telemetryClient == nil {
telemetryClient = & http . Client {
Timeout : time . Second * 10 ,
}
}
return telemetryClient
}
func postTelemetryFromRequest ( tyype string , request * http . Request , app * FrontendApp , content string ) {
account := ""
userId := ""
session , err := app . getSession ( request , app . Domain )
if err == nil {
account = session . Email
userId = strconv . Itoa ( session . TenantId )
}
postTelemetry ( tyype , getRemoteIpFromRequest ( request ) , account , userId , content )
}
func postTelemetry ( tyype string , ip string , account string , userId string , content string ) {
if ip != "" {
ip = fmt . Sprintf ( "&ip=%s" , ip )
}
if account != "" {
account = fmt . Sprintf ( "&account=%s" , account )
}
if userId == "0" {
userId = ""
}
if userId != "" {
userId = fmt . Sprintf ( "&userId=%s" , userId )
}
response , err := getTelemetryClient ( ) . Post (
fmt . Sprintf ( "https://telemetry.greenhouse-alpha.server.garden/?type=%s%s%s%s" , tyype , ip , account , userId ) ,
"text/plain" ,
bytes . NewBufferString ( content ) ,
)
if err != nil {
log . Printf ( "postTelemetry: %s\n" , err )
} else if response . StatusCode > 299 {
responseString := "<read error>"
responseBytes , err := ioutil . ReadAll ( response . Body )
if err == nil {
responseString = string ( responseBytes )
}
log . Printf ( "postTelemetry: HTTP %d: %s\n" , response . StatusCode , responseString )
}
}
func getRemoteIpFromRequest ( request * http . Request ) string {
return request . Header . Get ( "X-Forwarded-For" )
}
func getHashForTelemetry ( app * FrontendApp , secretValue string ) string {
hash1 := sha256 . Sum256 ( [ ] byte ( fmt . Sprintf ( "%s%s" , app . PasswordHashSalt , secretValue ) ) )
return fmt . Sprintf ( "%x" , hash1 [ : 4 ] )
}