You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

101 lines
2.3 KiB

package main
import (
"context"
"crypto/tls"
"encoding/xml"
"flag"
"fmt"
"io/ioutil"
"net/http"
"os"
"time"
mailgun "github.com/mailgun/mailgun-go"
log "github.com/sirupsen/logrus"
)
const (
appVersion = "1.0.1"
infoURI = "https://idlerpg.lolhosting.net/xml.php"
msgTemplate = `Dear %s
You seem to be offline based on https://idlerpg.lolhosting.net/xml.php?player=%s`
)
var (
domain = os.Getenv("MG_DOMAIN")
mgAPIKey = os.Getenv("MG_API_KEY")
)
type Player struct {
XMLName xml.Name `xml:"player"`
Username string `xml:"username"`
Level int `xml:"level"`
Online bool `xml:"online"`
}
func init() {
log.SetFormatter(&log.JSONFormatter{})
}
func getUserInfo(username string) Player {
client := &http.Client{}
http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true}
request, _ := http.NewRequest("GET", infoURI, nil)
request.Header.Add("Accept", "text/xml")
query := request.URL.Query()
query.Add("player", username)
request.URL.RawQuery = query.Encode()
response, err := client.Do(request)
if err != nil {
panic(err.Error())
}
defer response.Body.Close()
content, _ := ioutil.ReadAll(response.Body)
var info Player
xml.Unmarshal(content, &info)
return info
}
func isOnline(username string) bool {
return getUserInfo(username).Online
}
func sendEmailNotification(username string, email string) {
mg := mailgun.NewMailgun(domain, mgAPIKey)
sender := fmt.Sprintf("no-reply@%s", domain)
subject := fmt.Sprintf("[%s] IdleRPG Notifier", time.Now().Format("2006-01-02"))
body := fmt.Sprintf(msgTemplate, username, username)
message := mg.NewMessage(sender, subject, body, email)
ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
defer cancel()
resp, id, err := mg.Send(ctx, message)
log.Infoln("Resp:", resp, "; ID:", id, "; err:", err)
}
func main() {
version := flag.Bool("version", false, "App version")
username := flag.String("username", "", "IdleRPG Username")
email := flag.String("email", "", "Send notification if user is offline")
flag.Parse()
if *version {
fmt.Println(appVersion)
return
}
if *username == "" {
panic("Username is not specified")
}
if *email != "" && !isOnline(*username) {
log.Infoln("Notify user:", *username)
sendEmailNotification(*username, *email)
}
}