Explorar el Código

appsettings(botsettings now) separated to module

TooManySugar hace 3 años
padre
commit
a133afafef
Se han modificado 10 ficheros con 231 adiciones y 93 borrados
  1. 29 0
      botsettings/file.go
  2. 3 0
      botsettings/go.mod
  3. 128 0
      botsettings/settings.go
  4. 10 6
      connection.go
  5. 2 0
      go.mod
  6. 8 7
      handlers.go
  7. 3 2
      logger.go
  8. 41 11
      main.go
  9. 0 61
      settings.go
  10. 7 6
      update_data.go

+ 29 - 0
botsettings/file.go

@@ -0,0 +1,29 @@
+package botsettings
+
+import (
+	"os"
+	"encoding/json"
+)
+
+func LoadFromFile(filepath string) error {
+	b, err := os.ReadFile(filepath)
+    if err != nil { 
+    	return err
+    }
+
+	return json.Unmarshal(b, &botSettings)
+}
+
+
+func SaveToFile(filepath string) (err error) {
+	res, err := json.MarshalIndent(botSettings, "", "    ")
+	if err != nil {
+        return
+    }
+
+    err = os.WriteFile(filepath, res, 0666)
+    if err != nil {
+		return
+	}
+	return nil
+}

+ 3 - 0
botsettings/go.mod

@@ -0,0 +1,3 @@
+module botsettings
+
+go 1.17

+ 128 - 0
botsettings/settings.go

@@ -0,0 +1,128 @@
+package botsettings
+
+import (
+	// "os"
+	// "fmt"
+	// "log"
+	// "encoding/json"
+)
+
+var botSettings = Init() 
+
+type settings struct{
+	Token 			string
+	ApiUrl 			string
+
+	DbHost 			string
+	DbUser			string `json:"-"`
+	DbPassword 		string `json:"-"`
+	DbName 			string
+
+	FullLogPath 	string
+	ErrorLogPath 	string
+
+	Currency 		string
+}
+
+// type Base interface {
+// 	
+// }
+
+func Init() settings {
+	var s settings
+	return s
+} 
+/*
+ *	'SETs'
+ */
+// SetDbPassword sets botSettings.DbPassword to password
+func SetDbPassword(password string) {
+	botSettings.DbPassword = password	
+}
+// SetDbUser sets botSettings.DbUser to user
+func SetDbUser(user string) {
+	botSettings.DbUser = user	
+}
+
+// func SetParam(param string) {
+// 	botSettings.setParam(param)
+// }
+
+/*
+ *	'GETs'
+ */ 
+func Token() string {
+	return botSettings.Token 
+}
+
+func ApiUrl() string {
+	return botSettings.ApiUrl
+}
+
+// DbHost returns botSettings.DbHost
+func DbHost() string {
+	return botSettings.DbHost
+}
+
+// DbUser returns botSettings.DbUser
+func DbUser() string {
+	return botSettings.DbUser
+}
+
+// DbPassword returns botSettings.DbPassword
+func DbPassword() string {
+	return botSettings.DbPassword
+}
+
+// DbName returns botSettings.DbName
+func DbName() string {
+	return botSettings.DbName
+}
+
+// Currency returns botSettings.Currency
+func Currency() string {
+	return botSettings.Currency
+}
+
+// ErrorLogPath returns botSettings.ErrorLogPath
+func ErrorLogPath() string {
+	return botSettings.ErrorLogPath
+}
+
+// FullLogPath returns botSettings.FullLogPath
+func FullLogPath() string {
+	return botSettings.FullLogPath
+}
+ 
+
+// func (s *settings) setParam(newParam string) {
+// 	s.param = newParam
+// }
+// 
+// func (s *settings) getParam() string {
+// 	return s.param
+// }
+
+// func LoadFromFile(filepath string) error {
+// 	b, err := os.ReadFile(filepath)
+//     if err != nil { 
+//     	return err
+//     }
+// 
+// 	return json.Unmarshal(b, &botSettings)
+// }
+// 
+// 
+// func SaveToFile(filepath string) err error {
+// 	res, err := json.MarshalIndent(s, "", "    ")
+// 	if err != nil {
+//         log.Panic(err)
+//     }
+// 
+//     err = os.WriteFile(filepath, res, 0666)
+//     if err != nil {
+// 		return
+// 	}
+// 	return nil
+// }
+// 

+ 10 - 6
connection.go

@@ -5,6 +5,8 @@ import (
 
 	"gorm.io/gorm"
 	"gorm.io/driver/mysql"
+
+	"GoEthemineTelegramBot/botsettings"
 )
 
 type ConnectionProperties struct {
@@ -21,12 +23,14 @@ type Connection struct {
 }
 
 func (c *Connection) Init() {
-	c.ConnProperties.User = appSettings.DbUser
-	c.ConnProperties.Pass = appSettings.DbPassword
-	c.ConnProperties.Host = appSettings.DbHost
-	c.ConnProperties.Db = appSettings.DbName
+	c.ConnProperties.User = botsettings.DbUser()
+	c.ConnProperties.Pass = botsettings.DbPassword()
+	c.ConnProperties.Host = botsettings.DbHost()
+	c.ConnProperties.Db   = botsettings.DbName()
+
 
-	c.DbOpenStr = fmt.Sprintf("%s:%s@tcp(%s)/%s", c.ConnProperties.User, c.ConnProperties.Pass, c.ConnProperties.Host, c.ConnProperties.Db)
+	c.DbOpenStr = fmt.Sprintf("%s:%s@tcp(%s)/%s", 
+		c.ConnProperties.User, c.ConnProperties.Pass, c.ConnProperties.Host, c.ConnProperties.Db)
 	LogInfo.Println("Connecting with:")
 	LogInfo.Println(c.DbOpenStr)
 
@@ -94,4 +98,4 @@ func (c *Connection) UniqueWallets() (wallets []string, err error) {
 		Scan(&wallets)
 
 	return wallets, result.Error
-}
+}

+ 2 - 0
go.mod

@@ -10,6 +10,7 @@ require (
 
 require (
 	GoEthemineTelegramBot/ethermineapi v0.0.0-unpublished // indirect
+	GoEthemineTelegramBot/botsettings v0.0.0-unpublished // indirect
 	github.com/go-sql-driver/mysql v1.6.0 // indirect
 	github.com/jinzhu/inflection v1.0.0 // indirect
 	github.com/jinzhu/now v1.1.2 // indirect
@@ -17,3 +18,4 @@ require (
 )
 
 replace GoEthemineTelegramBot/ethermineapi v0.0.0-unpublished => ./ethermineapi
+replace GoEthemineTelegramBot/botsettings v0.0.0-unpublished => ./botsettings

+ 8 - 7
handlers.go

@@ -10,6 +10,7 @@ import (
 	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
 
 	ethmineapi "GoEthemineTelegramBot/ethermineapi"
+	"GoEthemineTelegramBot/botsettings"
 )
 
 func (c *Connection) AddUser(reqChat *tgbotapi.Chat) (string, error) {
@@ -265,7 +266,7 @@ func (c *Connection) GetLastPayout(chatId int64) string {
 		Find(&dbPayoutRecords)
 	//Line 560 of Program.cs
 	if len(dbPayoutRecords) == 0 {
-		url := fmt.Sprintf("%s/miner/%s/payouts", appSettings.ApiUrl, wallet)
+		url := fmt.Sprintf("%s/miner/%s/payouts", botsettings.ApiUrl(), wallet)
 		var payouts ethmineapi.JsonPayouts
 		err := ethmineapi.UnmasrshalFromUrl(url, &payouts)
 		if err != nil {
@@ -275,7 +276,7 @@ func (c *Connection) GetLastPayout(chatId int64) string {
 		lastPayout := payouts.Data[0]
 
 		message := fmt.Sprintf("Payout date: %s\n", time.Unix(lastPayout.PaidOn, 0).Format("Monday, January 2, 2006 3:04 PM"))
-		message += fmt.Sprintf("Amount: %.5f %s\n", float64(lastPayout.Amount)/math.Pow10(18), appSettings.Currency)
+		message += fmt.Sprintf("Amount: %.5f %s\n", float64(lastPayout.Amount)/math.Pow10(18), botsettings.Currency())
 		message += "Data source: Ethermine API \n"
 
 		return message
@@ -290,10 +291,10 @@ func (c *Connection) GetLastPayout(chatId int64) string {
 	message += fmt.Sprintf("Amount: %.5f ETH\n", float64(dbPayoutRecords[0].Amount)/math.Pow10(18))
 
 	for _, payoutRecord := range dbPayoutRecords {
-		message += fmt.Sprintf("Worker %s paid: %.5f %s\n", //TODO ETH = AppSettings.currency
+		message += fmt.Sprintf("Worker %s paid: %.5f %s\n",
 			payoutRecord.Worker,
 			float64(payoutRecord.Amount)/math.Pow10(18),
-			appSettings.Currency)
+			botsettings.Currency())
 	}
 
 	message += "Data source: Bot database \n"
@@ -304,11 +305,11 @@ func (c *Connection) GetLastPayout(chatId int64) string {
 
 
 func GetActualRate() string {
-	url := fmt.Sprintf("%s/networkStats", appSettings.ApiUrl)
+	url := fmt.Sprintf("%s/networkStats", botsettings.ApiUrl())
 	var networkStats ethmineapi.JsonNetworkStats
 	err := ethmineapi.UnmasrshalFromUrl(url, &networkStats)
 	if err != nil {
-		return fmt.Sprintf("Error with getting data from %s", appSettings.ApiUrl)
+		return fmt.Sprintf("Error with getting data from %s", botsettings.ApiUrl())
 	}
 	data := networkStats.Data
 	actualRate := fmt.Sprintf("ETH: %.2f\nBTC: %.2f", data.Usd, float64(data.Usd)/float64(data.Btc))
@@ -316,7 +317,7 @@ func GetActualRate() string {
 }
 
 func GetActualData(miner string) string {
-	url := fmt.Sprintf("%s/miner/%s/currentStats", appSettings.ApiUrl, miner)
+	url := fmt.Sprintf("%s/miner/%s/currentStats", botsettings.ApiUrl(), miner)
 	var currentStats ethmineapi.JsonCurrentStats
 	err := ethmineapi.UnmasrshalFromUrl(url, &currentStats)
 	if err != nil {

+ 3 - 2
logger.go

@@ -5,6 +5,7 @@ import (
 	"log"
 	"os"
 	"time"
+	"GoEthemineTelegramBot/botsettings"
 )
 
 type customLogWriter struct {
@@ -13,8 +14,8 @@ type customLogWriter struct {
 
 // Initializes Loggers
 func LoggersInit() {
-	fullLogPath := appSettings.FullLogPath
-	errorLogPath := appSettings.ErrorLogPath
+	fullLogPath := botsettings.FullLogPath()
+	errorLogPath := botsettings.ErrorLogPath()
 
 	fullLog, err := os.OpenFile(fullLogPath, os.O_CREATE|os.O_APPEND|os.O_RDWR, 0766)
 	if err != nil {

+ 41 - 11
main.go

@@ -6,15 +6,15 @@ import (
 	"bufio"
 	"os"
 	"time"
+	"strings"
 
 	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
 
-	_ "GoEthemineTelegramBot/ethermineapi"
+	"GoEthemineTelegramBot/botsettings"
 )
 
 
 var (
-	appSettings Settings
 	dBConnector Connection
 	myBotClient tgbotapi.BotAPI
 
@@ -25,12 +25,13 @@ var (
 )
 
 func main() {
-	appSettings.LoadFromFile("config.json")
+	settingsPath := "config.json"
+	LoadSettings(settingsPath)
 
 	LoggersInit()
 	LogInfo.Println("App started")
 
-	botClient, err := tgbotapi.NewBotAPI(appSettings.Token)
+	botClient, err := tgbotapi.NewBotAPI(botsettings.Token())
 	if err != nil {
 		LogError.Panic(err)
 	}
@@ -39,23 +40,28 @@ func main() {
 	LogInfo.Printf("Hello, World! I am user %d and my name is %s.\n", me.ID, me.FirstName)
 
 	if len(os.Args[1:]) >= 2 {
-		appSettings.DbUser = os.Args[1]
-		appSettings.DbPassword = os.Args[2]
+		botsettings.SetDbUser(os.Args[1])
+		botsettings.SetDbPassword(os.Args[2])
 	} else {
+		var username string
 		fmt.Print("DataBase Username:")
-		_, err := fmt.Scanln(&appSettings.DbUser)
+		_, err := fmt.Scanln(&username)
 		if err != nil {
-			LogError.Panic(os.Stderr, err)
+			LogError.Println(os.Stderr, err)
 			return
 		}
+		botsettings.SetDbUser(username)
+
+		var password string 
 		fmt.Print("DataBase Password:")
-		_, err = fmt.Scanln(&appSettings.DbPassword)
+		_, err = fmt.Scanln(&password)
 		if err != nil {
-			LogError.Panic(os.Stderr, err)
+			LogError.Println(os.Stderr, err)
 			return
 		}
+		botsettings.SetDbPassword(password)
 	}
-
+	
 	dBConnector.Init()
 
 	go Updater()
@@ -94,3 +100,27 @@ func Updater() {
 	}
 }
 
+// LoadSettings load settings from settingsPath 
+// and then saves them again for keep up-to-date struct
+func LoadSettings(settingsPath string) {
+	err := botsettings.LoadFromFile(settingsPath)
+	if err != nil {
+		if !strings.Contains(err.Error(), "The system cannot find the file specified") {
+			fmt.Println(err)
+			os.Exit(1)
+    	}
+
+    	path, err := os.Getwd()
+		if err != nil {
+	    	fmt.Println(err)
+	    	os.Exit(1)
+	   	}
+
+		path += "\\"+ settingsPath
+     	fmt.Printf("The system cannot find the config file.\nCreating new config file at:\n%s\n", path)
+      	botsettings.SaveToFile(path)
+      	fmt.Println("Please fill the config file")
+      	os.Exit(0)
+	}
+	botsettings.SaveToFile(settingsPath)
+}

+ 0 - 61
settings.go

@@ -1,61 +0,0 @@
-package main
-
-import (
-	"os"
-	"fmt"
-	"log"
-	"encoding/json"
-
-)
-
-type Settings struct{
-	Token 		string
-	ApiUrl 		string
-
-	DbHost 		string
-	DbUser		string `json:"-"`
-	DbPassword 	string `json:"-"`
-	DbName 		string
-
-	FullLogPath 	string
-	ErrorLogPath 	string
-
-	Currency 	string
-}
-
-func (s *Settings) LoadFromFile(filepath string) {
-	b, err := os.ReadFile(filepath)
-    if err != nil {
-     	if err.Error() == fmt.Sprintf("open %s: The system cannot find the file specified.", filepath) {
-	    	err = nil
-	    	path, err := os.Getwd()
-			if err != nil {
-		    	log.Panic(err)
-		   	}
-			path += "\\"+ filepath
-	     	fmt.Printf("The system cannot find the config file.\nCreating new config file at:\n%s\n",
-	      		path)
-	      	s.SaveToFile(path)
-	      	log.Fatal("Please fill the config file")	
-	    } else {
-		    log.Panic(err)
-	    } 
-      return
-    }
-    propJson := string(b)
-
-	json.Unmarshal([]byte(propJson), &s)
-	s.SaveToFile(filepath)
-}
-
-func (s *Settings) SaveToFile(filepath string) {
-	res, err := json.MarshalIndent(s, "", "    ")
-	if err != nil {
-        log.Panic(err)
-    }
-
-    err = os.WriteFile(filepath, res, 0666)
-    if err != nil {
-		log.Fatal(err)
-	}
-}

+ 7 - 6
update_data.go

@@ -7,6 +7,7 @@ import (
 	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api"
 
 	ethmineapi "GoEthemineTelegramBot/ethermineapi"
+	"GoEthemineTelegramBot/botsettings"
 )
 
 func (c *Connection) UpdateData() {
@@ -24,10 +25,10 @@ func (c *Connection) UpdateData() {
 
 func (c *Connection) UpdateWallet(wallet string) {
 	LogInfo.Printf(">> Getting data for wallet %s\n", wallet)
-	LogInfo.Printf("From: %s/miner/%s/currentStats\n", appSettings.ApiUrl, wallet)
+	LogInfo.Printf("From: %s/miner/%s/currentStats\n", botsettings.ApiUrl(), wallet)
 	
 	// Get current stats for miner
-	currentStats, err := ethmineapi.MinerStats(appSettings.ApiUrl, wallet)
+	currentStats, err := ethmineapi.MinerStats(botsettings.ApiUrl(), wallet)
 	if err != nil {
 		LogWarn.Println(err); return
 	}
@@ -90,9 +91,9 @@ func (c *Connection) UpdateWallet(wallet string) {
 func (c *Connection) UpdateWorkers(newMinerRecord Miner, lastMinerRecord Miner) {
 	// Line 64 of UpdateData.cs
 	LogInfo.Printf("Getting workers data for wallet %s\n", newMinerRecord.Wallet)
-	LogInfo.Printf("From: %s/miner/%s", appSettings.ApiUrl, newMinerRecord.Wallet)
+	LogInfo.Printf("From: %s/miner/%s", botsettings.ApiUrl(), newMinerRecord.Wallet)
 
-	currentWorker, err := ethmineapi.Workers(appSettings.ApiUrl, newMinerRecord.Wallet)
+	currentWorker, err := ethmineapi.Workers(botsettings.ApiUrl(), newMinerRecord.Wallet)
 	if err != nil {
 		LogWarn.Println(err); return
 	}
@@ -104,7 +105,7 @@ func (c *Connection) UpdateWorkers(newMinerRecord Miner, lastMinerRecord Miner)
 	// Unsure is it occurs
 	if len(currentWorker.Data) == 0 { 
 		LogInfo.Printf("data in response from %s for workers of wallet %s not contains workers!\n",
-			appSettings.ApiUrl, newMinerRecord.Wallet)
+			botsettings.ApiUrl(), newMinerRecord.Wallet)
 		return
 	}
 
@@ -165,7 +166,7 @@ func (c *Connection) updateWorker(workerData ethmineapi.WorkerData,
 	//Repeating of line 75 due to update of individual worker 
 	if lastWorkerRecord != (Worker{}) && newMinerRecord.Unpaid < lastMinerRecord.Unpaid {
 		// Adding new payout field to db
-		payouts, err := ethmineapi.Payouts(appSettings.ApiUrl, newWorkerRecord.Wallet)
+		payouts, err := ethmineapi.Payouts(botsettings.ApiUrl(), newWorkerRecord.Wallet)
 		if err != nil {
 			LogError.Println(err); return
 		}