quick fix bug

Former-commit-id: 254861b97deafa875745337149291285056d9f30
botanswer
AnisB 3 years ago
parent 82a5f2c2cb
commit d99e4858f7

@ -5,22 +5,22 @@
package main package main
import ( import (
"fmt"
"log"
"os"
"flag"
"net/http"
"io/ioutil"
"encoding/json" "encoding/json"
"encoding/xml"
"errors" "errors"
"gosrc.io/xmpp" "flag"
"gosrc.io/xmpp/stanza" "fmt"
"github.com/spf13/pflag" "github.com/spf13/pflag"
"github.com/spf13/viper" "github.com/spf13/viper"
"strings" "gosrc.io/xmpp"
"strconv" "gosrc.io/xmpp/stanza"
"io/ioutil"
"log"
"net/http"
"os"
"path" "path"
"encoding/xml" "strconv"
"strings"
"time" "time"
) )
@ -28,23 +28,23 @@ const (
// APIEndpoint = "https://hodlhodl.com/api/v1" // APIEndpoint = "https://hodlhodl.com/api/v1"
//TestAPIEndpoint = "https://hhtestnet.com/api/v1" //TestAPIEndpoint = "https://hhtestnet.com/api/v1"
//APIkey = "***REMOVED***" //APIkey = "***REMOVED***"
JobSchedulerInterval = 60 * time.Second JobSchedulerInterval = 60 * time.Second
// Config // Config
infoFormat = "====== " infoFormat = "====== "
defaultConfigFilePath = "./" defaultConfigFilePath = "./"
configFileName = "config" configFileName = "config"
configType = "yaml" configType = "yaml"
logStanzasOn = "logger_on" logStanzasOn = "logger_on"
logFilePath = "logfile_path" logFilePath = "logfile_path"
//Keys in config //Keys in config
serverAddressKey = "full_address" serverAddressKey = "full_address"
clientJid = "jid" clientJid = "jid"
clientPass = "pass" clientPass = "pass"
configContactSep = ";" configContactSep = ";"
APIEndPoint = "testapiendpoint" APIEndPoint = "testapiendpoint"
APIKey = "apikey" APIKey = "apikey"
) )
var ( var (
@ -72,16 +72,13 @@ type Notification struct {
type config struct { type config struct {
Server map[string]string `mapstructure:"server"` Server map[string]string `mapstructure:"server"`
Client map[string]string `mapstructure:"client"` Client map[string]string `mapstructure:"client"`
Contacts string `string:"contact"` Recipient string `string:"recipient"`
Hodlhodl map[string]string `mapstructure:"hodlhodl"` Hodlhodl map[string]string `mapstructure:"hodlhodl"`
LogStanzas map[string]string `mapstructure:"logstanzas"` LogStanzas map[string]string `mapstructure:"logstanzas"`
} }
func main() { func main() {
//body:= strings.NewReader(' -X POST -H "Authorization: Bearer ***REMOVED***" -H "Content-Type: application/json"`) //body:= strings.NewReader(' -X POST -H "Authorization: Bearer ***REMOVED***" -H "Content-Type: application/json"`)
// ============================================================ // ============================================================
// Parse the flag with the config directory path as argument // Parse the flag with the config directory path as argument
@ -115,21 +112,20 @@ func main() {
func startClient(config *config) { func startClient(config *config) {
// Client Setup // Client Setup
clientCfg := &xmpp.Config { clientCfg := &xmpp.Config{
TransportConfiguration: xmpp.TransportConfiguration{ TransportConfiguration: xmpp.TransportConfiguration{
Address: config.Server[serverAddressKey], Address: config.Server[serverAddressKey],
}, },
Jid: config.Client[clientJid], Jid: config.Client[clientJid],
Credential: xmpp.Password(config.Client[clientPass]), Credential: xmpp.Password(config.Client[clientPass]),
Insecure: true, Insecure: true,
} }
var err error var err error
var client *xmpp.Client var client *xmpp.Client
router := xmpp.NewRouter() router := xmpp.NewRouter()
errorHandler:= func(err error) { errorHandler := func(err error) {
fmt.Println(err.Error()) fmt.Println(err.Error())
} }
@ -160,48 +156,44 @@ func startClient(config *config) {
/*cm := xmpp.NewStreamManager(client, nil) /*cm := xmpp.NewStreamManager(client, nil)
log.Fatal(cm.Run())*/ log.Fatal(cm.Run())*/
// ==================== // ====================
// Start working // Start working
// fmt.Println("CONFIG.HODLHDOL :", config.Hodlhodl[APIKey]) // fmt.Println("CONFIG.HODLHDOL :", config.Hodlhodl[APIKey])
timer := time.NewTicker(5 * time.Second) timer := time.NewTicker(JobSchedulerInterval)
notifications := make(chan string, 100) notifications := make(chan string, 100)
go startMessaging(client, config, notifications) go startMessaging(client, config, notifications)
for { for {
select { select {
case <- timer.C: case <-timer.C:
fmt.Println("cheking notifs ...") fmt.Println("cheking notifs ...")
notifications <- gethdlNotif(config.Hodlhodl[APIKey], config.Hodlhodl[APIEndPoint]) notifications <- gethdlNotif(config.Hodlhodl[APIKey], config.Hodlhodl[APIEndPoint])
} }
} }
} }
func startMessaging(client xmpp.Sender, config *config, notifications chan string) { func startMessaging(client xmpp.Sender, config *config, notifications chan string) {
fmt.Println("START MESSAGING") fmt.Println("START MESSAGING")
currentContact := strings.Split(config.Contacts, configContactSep)[1] recipient := config.Recipient
fmt.Println(infoFormat+"Now sending messages to "+currentContact+" in a private conversation\n") fmt.Println(infoFormat + "Now sending messages to " + recipient + " in a private conversation\n")
fmt.Println("currentContacts", currentContact) fmt.Println("currentContacts", recipient)
for { for {
select { select {
case notif := <-notifications: case notif := <-notifications:
// Test if notif is nil or skip this loop // Test if notif is nil or skip this loop
if notif == "" { break ;} if notif == "" {
break
}
fmt.Println("sending notification through xmpp") fmt.Println("sending notification through xmpp")
reply := stanza.Message{Attrs: stanza.Attrs{To: currentContact, Type: stanza.MessageTypeChat}, Body: notif} reply := stanza.Message{Attrs: stanza.Attrs{To: recipient, Type: stanza.MessageTypeChat}, Body: notif}
if logger != nil { if logger != nil {
raw, _ := xml.Marshal(reply) raw, _ := xml.Marshal(reply)
logger.Println(string(raw)) logger.Println(string(raw))
@ -218,18 +210,18 @@ func startMessaging(client xmpp.Sender, config *config, notifications chan strin
} }
} }
func gethdlNotif(APIKey string, APIEndPoint string ) string { func gethdlNotif(APIKey string, APIEndPoint string) string {
fmt.Println("get notif") fmt.Println("get notif")
req, err := http.NewRequest("POST", APIEndPoint + "/notifications/read", nil) req, err := http.NewRequest("POST", APIEndPoint+"/notifications/read", nil)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
} }
req.Header.Add("Authorization", "Bearer " + APIKey) req.Header.Add("Authorization", "Bearer "+APIKey)
req.Header.Set("Content-Type", "application/json") req.Header.Set("Content-Type", "application/json")
resp, err := http.DefaultClient.Do(req) resp, err := http.DefaultClient.Do(req)
if err!= nil { if err != nil {
fmt.Println(err) fmt.Println(err)
} }
@ -238,21 +230,21 @@ func gethdlNotif(APIKey string, APIEndPoint string ) string {
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
} else { } else {
res:= Notification{} res := Notification{}
json.Unmarshal([]byte(body), &res) json.Unmarshal([]byte(body), &res)
//fmt.Println("RESULT title", res.Notifications[0].Title) //fmt.Println("RESULT title", res.Notifications[0].Title)
//fmt.Println("RESULT body", res.Notifications[0].Body) //fmt.Println("RESULT body", res.Notifications[0].Body)
//fmt.Println("res: ", res) //fmt.Println("res: ", res)
//fmt.Println("res.Notifications: ", res.Notifications) //fmt.Println("res.Notifications: ", res.Notifications)
if (len(res.Notifications) > 0) { if len(res.Notifications) > 0 {
//fmt.Println("type of notif = ", reflect.TypeOf(res.Notifications[0])) //fmt.Println("type of notif = ", reflect.TypeOf(res.Notifications[0]))
fmt.Println("Join: ", strings.Join([]string{res.Notifications[0].Title, res.Notifications[0].Body}, " ")) fmt.Println("Join: ", strings.Join([]string{res.Notifications[0].Title, res.Notifications[0].Body}, " "))
//fmt.Println("RESULT stirng(body)", string(body)) //fmt.Println("RESULT stirng(body)", string(body))
//fmt.Println("RESULTAT", string(body)) //fmt.Println("RESULTAT", string(body))
notif := strings.Join([]string{res.Notifications[0].Title, res.Notifications[0].Body}, " ") notif := strings.Join([]string{res.Notifications[0].Title, res.Notifications[0].Body}, " ")
return notif return notif
} }
} }
defer resp.Body.Close() defer resp.Body.Close()
@ -260,11 +252,6 @@ func gethdlNotif(APIKey string, APIEndPoint string ) string {
return "" return ""
} }
func readConfig() *config { func readConfig() *config {
viper.SetConfigName(configFileName) // name of config file (without extension) viper.SetConfigName(configFileName) // name of config file (without extension)
viper.BindPFlags(pflag.CommandLine) viper.BindPFlags(pflag.CommandLine)
@ -286,7 +273,7 @@ func readConfig() *config {
} }
// Check if we have contacts to message // Check if we have contacts to message
if len(strings.TrimSpace(config.Contacts)) == 0 { if len(strings.TrimSpace(config.Recipient)) == 0 {
log.Panicln("You appear to have no contacts to message !") log.Panicln("You appear to have no contacts to message !")
} }
// Check logging // Check logging
@ -307,7 +294,6 @@ func errorHandler(err error) {
killChan <- err killChan <- err
} }
func isDirectory(path string) (bool, error) { func isDirectory(path string) (bool, error) {
fileInfo, err := os.Stat(path) fileInfo, err := os.Stat(path)
if err != nil { if err != nil {
@ -315,4 +301,3 @@ func isDirectory(path string) (bool, error) {
} }
return fileInfo.IsDir(), err return fileInfo.IsDir(), err
} }

Loading…
Cancel
Save