2020-02-14 10:42:38 +00:00
|
|
|
package webserver
|
|
|
|
|
|
|
|
import (
|
2020-02-14 14:56:10 +00:00
|
|
|
"math/rand"
|
|
|
|
|
|
|
|
irc "git.martyn.berlin/martyn/karaokards/internal/irc"
|
2020-02-14 10:42:38 +00:00
|
|
|
"github.com/gorilla/handlers"
|
|
|
|
"github.com/gorilla/mux"
|
|
|
|
|
2020-06-30 15:30:05 +00:00
|
|
|
"encoding/json"
|
2020-02-14 10:42:38 +00:00
|
|
|
"fmt"
|
|
|
|
"html/template"
|
2020-06-30 15:30:05 +00:00
|
|
|
"io/ioutil"
|
2020-02-14 10:42:38 +00:00
|
|
|
"net/http"
|
2020-03-07 19:42:16 +00:00
|
|
|
"net/url"
|
2020-02-14 10:42:38 +00:00
|
|
|
"os"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
//var store = sessions.NewCookieStore(os.Getenv("SESSION_KEY"))
|
|
|
|
|
2020-03-07 19:42:16 +00:00
|
|
|
type twitchauthresponse struct {
|
2020-06-30 15:30:05 +00:00
|
|
|
Access_token string `json: "access_token"`
|
|
|
|
Expires_in int `json: "expires_in"`
|
|
|
|
Refresh_token string `json: "refresh_token"`
|
|
|
|
Scope []string `json: "scope"`
|
|
|
|
Token_type string `json: "token_type"`
|
2020-03-07 19:42:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type twitchUser struct {
|
2020-06-30 15:30:05 +00:00
|
|
|
Id string `json: "id"`
|
|
|
|
Login string `json: "login"`
|
|
|
|
Display_name string `json: "display_name"`
|
|
|
|
Type string `json: "type"`
|
|
|
|
Broadcaster_type string `json: "affiliate"`
|
|
|
|
Description string `json: "description"`
|
2020-03-07 19:42:16 +00:00
|
|
|
Profile_image_url string `json: "profile_image_url"`
|
|
|
|
Offline_image_url string `json: "offline_image_url"`
|
2020-06-30 15:30:05 +00:00
|
|
|
View_count int `json: "view_count"`
|
2020-03-07 19:42:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type twitchUsersBigResponse struct {
|
|
|
|
Data []twitchUser `json:"data"`
|
|
|
|
}
|
|
|
|
|
2020-02-22 13:05:30 +00:00
|
|
|
var ircBot *irc.KardBot
|
2020-02-14 10:42:38 +00:00
|
|
|
|
|
|
|
func HealthHandler(response http.ResponseWriter, request *http.Request) {
|
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
fmt.Fprint(response, "I'm okay jack!")
|
|
|
|
}
|
|
|
|
|
|
|
|
func NotFoundHandler(response http.ResponseWriter, request *http.Request) {
|
|
|
|
response.Header().Add("X-Template-File", "html"+request.URL.Path)
|
2020-02-21 19:52:19 +00:00
|
|
|
response.WriteHeader(404)
|
2020-02-14 10:42:38 +00:00
|
|
|
tmpl := template.Must(template.ParseFiles("web/404.html"))
|
|
|
|
tmpl.Execute(response, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
func CSSHandler(response http.ResponseWriter, request *http.Request) {
|
|
|
|
response.Header().Add("Content-type", "text/css")
|
|
|
|
tmpl := template.Must(template.ParseFiles("web/cover.css"))
|
|
|
|
tmpl.Execute(response, nil)
|
|
|
|
}
|
|
|
|
|
|
|
|
func RootHandler(response http.ResponseWriter, request *http.Request) {
|
|
|
|
request.URL.Path = "/index.html"
|
|
|
|
TemplateHandler(response, request)
|
|
|
|
}
|
|
|
|
|
|
|
|
func TemplateHandler(response http.ResponseWriter, request *http.Request) {
|
|
|
|
response.Header().Add("X-Template-File", "web"+request.URL.Path)
|
|
|
|
type TemplateData struct {
|
2020-02-14 14:56:10 +00:00
|
|
|
Prompt string
|
|
|
|
AvailCount int
|
|
|
|
ChannelCount int
|
|
|
|
MessageCount int
|
2020-03-07 19:42:16 +00:00
|
|
|
ClientID string
|
|
|
|
BaseURI string
|
2020-02-14 10:42:38 +00:00
|
|
|
}
|
|
|
|
// tmpl, err := template.New("html"+request.URL.Path).Funcs(template.FuncMap{
|
|
|
|
// "ToUpper": strings.ToUpper,
|
|
|
|
// "ToLower": strings.ToLower,
|
|
|
|
// }).ParseFiles("html"+request.URL.Path)
|
|
|
|
_ = strings.ToLower("Hello")
|
|
|
|
if strings.Index(request.URL.Path, "/") < 0 {
|
|
|
|
http.Error(response, "No slashes wat - "+request.URL.Path, http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
basenameSlice := strings.Split(request.URL.Path, "/")
|
|
|
|
basename := basenameSlice[len(basenameSlice)-1]
|
|
|
|
//fmt.Fprintf(response, "%q", basenameSlice)
|
|
|
|
tmpl, err := template.New(basename).Funcs(template.FuncMap{
|
|
|
|
"ToUpper": strings.ToUpper,
|
|
|
|
"ToLower": strings.ToLower,
|
|
|
|
}).ParseFiles("web" + request.URL.Path)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(response, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
// NotFoundHandler(response, request)
|
|
|
|
// return
|
|
|
|
}
|
2020-06-30 15:30:05 +00:00
|
|
|
var td = TemplateData{ircBot.Prompts[rand.Intn(len(ircBot.Prompts))], len(ircBot.Prompts), ircBot.ActiveChannels(), 0, ircBot.AppCredentials.ClientID, "https://" + ircBot.Config.ExternalUrl}
|
2020-02-14 10:42:38 +00:00
|
|
|
err = tmpl.Execute(response, td)
|
|
|
|
if err != nil {
|
|
|
|
http.Error(response, err.Error(), http.StatusInternalServerError)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-22 13:05:30 +00:00
|
|
|
func LeaveHandler(response http.ResponseWriter, request *http.Request) {
|
|
|
|
request.URL.Path = "/bye.html"
|
2020-02-21 19:52:19 +00:00
|
|
|
TemplateHandler(response, request)
|
|
|
|
}
|
|
|
|
|
2020-02-22 13:05:30 +00:00
|
|
|
func AdminHandler(response http.ResponseWriter, request *http.Request) {
|
|
|
|
vars := mux.Vars(request)
|
|
|
|
if vars["key"] != ircBot.ChannelData[vars["channel"]].AdminKey {
|
|
|
|
UnauthorizedHandler(response, request)
|
|
|
|
return
|
2020-02-22 13:08:01 +00:00
|
|
|
}
|
2020-02-22 13:05:30 +00:00
|
|
|
type TemplateData struct {
|
2020-02-22 13:08:01 +00:00
|
|
|
Channel string
|
|
|
|
Command string
|
|
|
|
ExtraStrings string
|
|
|
|
SinceTime time.Time
|
2020-03-07 19:42:16 +00:00
|
|
|
SinceTimeUTC string
|
2020-02-22 13:08:01 +00:00
|
|
|
Leaving bool
|
2020-03-07 19:42:16 +00:00
|
|
|
HasLeft bool
|
2020-02-22 13:05:30 +00:00
|
|
|
}
|
|
|
|
channelData := ircBot.ChannelData[vars["channel"]]
|
2020-03-07 19:42:16 +00:00
|
|
|
var td = TemplateData{channelData.Name, channelData.Command, channelData.ExtraStrings, channelData.JoinTime, channelData.JoinTime.Format(irc.UTCFormat), false, channelData.HasLeft}
|
2020-02-22 13:05:30 +00:00
|
|
|
|
|
|
|
if request.Method == "POST" {
|
|
|
|
request.ParseForm()
|
2020-02-22 13:08:01 +00:00
|
|
|
if strings.Join(request.PostForm["leave"], ",") == "Leave twitch channel" {
|
2020-02-22 13:05:30 +00:00
|
|
|
td.Leaving = true
|
2020-02-22 13:08:01 +00:00
|
|
|
} else if strings.Join(request.PostForm["reallyleave"], ",") == "Really leave twitch channel" {
|
2020-03-07 19:42:16 +00:00
|
|
|
record := ircBot.ChannelData[vars["channel"]]
|
|
|
|
record.HasLeft = true
|
|
|
|
ircBot.ChannelData[vars["channel"]] = record
|
2020-02-22 13:05:30 +00:00
|
|
|
ircBot.LeaveChannel(vars["channel"])
|
2020-03-07 19:42:16 +00:00
|
|
|
ircBot.Database.Write("channelData", vars["channel"], record)
|
2020-02-22 13:05:30 +00:00
|
|
|
LeaveHandler(response, request)
|
|
|
|
return
|
|
|
|
}
|
2020-03-07 19:42:16 +00:00
|
|
|
if strings.Join(request.PostForm["join"], ",") == "Come on in" {
|
|
|
|
record := ircBot.ChannelData[vars["channel"]]
|
|
|
|
td.HasLeft = false
|
|
|
|
record.Name = vars["channel"]
|
|
|
|
record.JoinTime = time.Now()
|
|
|
|
record.HasLeft = false
|
|
|
|
if record.Command == "" {
|
|
|
|
record.Command = "card"
|
|
|
|
}
|
|
|
|
ircBot.Database.Write("channelData", vars["channel"], record)
|
|
|
|
ircBot.ChannelData[vars["channel"]] = record
|
|
|
|
td = TemplateData{record.Name, record.Command, record.ExtraStrings, record.JoinTime, record.JoinTime.Format(irc.UTCFormat), false, record.HasLeft}
|
|
|
|
ircBot.JoinChannel(record.Name)
|
|
|
|
}
|
2020-02-22 13:05:30 +00:00
|
|
|
sourceData := ircBot.ChannelData[vars["channel"]]
|
2020-02-22 13:08:01 +00:00
|
|
|
if strings.Join(request.PostForm["Command"], ",") != "" {
|
|
|
|
sourceData.Command = strings.Join(request.PostForm["Command"], ",")
|
2020-02-22 13:05:30 +00:00
|
|
|
td.Command = sourceData.Command
|
|
|
|
ircBot.ChannelData[vars["channel"]] = sourceData
|
|
|
|
}
|
2020-02-22 13:08:01 +00:00
|
|
|
if strings.Join(request.PostForm["ExtraStrings"], ",") != sourceData.ExtraStrings {
|
|
|
|
sourceData.ExtraStrings = strings.Join(request.PostForm["ExtraStrings"], ",")
|
2020-02-22 13:05:30 +00:00
|
|
|
td.ExtraStrings = sourceData.ExtraStrings
|
|
|
|
ircBot.ChannelData[vars["channel"]] = sourceData
|
|
|
|
}
|
2020-02-22 13:08:01 +00:00
|
|
|
ircBot.Database.Write("channelData", vars["channel"], sourceData)
|
2020-02-22 13:05:30 +00:00
|
|
|
}
|
|
|
|
tmpl := template.Must(template.ParseFiles("web/admin.html"))
|
|
|
|
tmpl.Execute(response, td)
|
|
|
|
}
|
|
|
|
|
|
|
|
func UnauthorizedHandler(response http.ResponseWriter, request *http.Request) {
|
|
|
|
response.Header().Add("X-Template-File", "html"+request.URL.Path)
|
|
|
|
response.WriteHeader(401)
|
|
|
|
tmpl := template.Must(template.ParseFiles("web/401.html"))
|
|
|
|
tmpl.Execute(response, nil)
|
|
|
|
}
|
|
|
|
|
2020-06-30 15:30:05 +00:00
|
|
|
func twitchHTTPClient(call string, bearer string) (string, error) {
|
2020-03-07 19:42:16 +00:00
|
|
|
url := "https://api.twitch.tv/helix/" + call
|
|
|
|
var bearerHeader = "Bearer " + bearer
|
|
|
|
|
2020-06-30 15:30:05 +00:00
|
|
|
req, err := http.NewRequest("GET", url, nil)
|
|
|
|
req.Header.Add("Authorization", bearerHeader)
|
2020-03-07 19:42:16 +00:00
|
|
|
|
2020-06-30 15:30:05 +00:00
|
|
|
client := &http.Client{}
|
2020-03-07 19:42:16 +00:00
|
|
|
resp, err := client.Do(req)
|
|
|
|
if err != nil {
|
2020-06-30 15:30:05 +00:00
|
|
|
return "", err
|
2020-03-07 19:42:16 +00:00
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
|
|
body, _ := ioutil.ReadAll(resp.Body)
|
2020-06-30 15:30:05 +00:00
|
|
|
return string([]byte(body)), nil
|
2020-03-07 19:42:16 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func TwitchAdminHandler(response http.ResponseWriter, request *http.Request) {
|
2020-06-30 15:30:05 +00:00
|
|
|
|
2020-03-07 19:42:16 +00:00
|
|
|
vars := mux.Vars(request)
|
2020-06-30 15:30:05 +00:00
|
|
|
if vars["code"] != "" {
|
2020-03-07 19:42:16 +00:00
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
resp, err := http.PostForm(
|
2020-06-30 15:30:05 +00:00
|
|
|
"https://id.twitch.tv/oauth2/token",
|
2020-03-07 19:42:16 +00:00
|
|
|
url.Values{
|
2020-06-30 15:30:05 +00:00
|
|
|
"client_id": {ircBot.AppCredentials.ClientID},
|
2020-03-07 19:42:16 +00:00
|
|
|
"client_secret": {ircBot.AppCredentials.Password},
|
2020-06-30 15:30:05 +00:00
|
|
|
"code": {vars["code"]},
|
|
|
|
"grant_type": {"authorization_code"},
|
|
|
|
"redirect_uri": {"https://" + ircBot.Config.ExternalUrl + "/twitchadmin"}})
|
2020-03-07 19:42:16 +00:00
|
|
|
if err != nil {
|
|
|
|
response.WriteHeader(500)
|
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
fmt.Fprint(response, "ERROR: "+err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
response.WriteHeader(500)
|
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
fmt.Fprint(response, "ERROR: "+err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var oauthResponse twitchauthresponse
|
|
|
|
err = json.Unmarshal(body, &oauthResponse)
|
|
|
|
if err != nil {
|
|
|
|
response.WriteHeader(500)
|
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
fmt.Fprint(response, "ERROR: "+err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
usersResponse, err := twitchHTTPClient("users", oauthResponse.Access_token)
|
|
|
|
if err != nil {
|
|
|
|
response.WriteHeader(500)
|
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
fmt.Fprint(response, "ERROR: "+err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
var usersObject twitchUsersBigResponse
|
|
|
|
err = json.Unmarshal([]byte(usersResponse), &usersObject)
|
|
|
|
if err != nil {
|
|
|
|
response.WriteHeader(500)
|
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
fmt.Fprint(response, "ERROR: "+err.Error())
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
if len(usersObject.Data) != 1 {
|
|
|
|
response.WriteHeader(500)
|
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
fmt.Fprint(response, "ERROR: Twitch returned not 1 user for the request!")
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
user := usersObject.Data[0]
|
|
|
|
|
2020-06-30 15:30:05 +00:00
|
|
|
magicCode := ircBot.ReadOrCreateChannelKey(user.Login)
|
|
|
|
url := "https://" + ircBot.Config.ExternalUrl + "/admin/" + user.Login + "/" + magicCode
|
|
|
|
http.Redirect(response, request, url, http.StatusFound)
|
2020-03-07 19:42:16 +00:00
|
|
|
|
|
|
|
} else {
|
2020-06-30 15:30:05 +00:00
|
|
|
|
2020-03-07 19:42:16 +00:00
|
|
|
fmt.Fprintf(response, "I'm not okay jack! %v \n", vars)
|
2020-06-30 15:30:05 +00:00
|
|
|
for key, val := range vars {
|
2020-03-07 19:42:16 +00:00
|
|
|
fmt.Fprint(response, "%s = %s\n", key, val)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-06-30 15:30:05 +00:00
|
|
|
func TwitchBackendHandler(response http.ResponseWriter, request *http.Request) {
|
2020-03-07 19:42:16 +00:00
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
vars := mux.Vars(request)
|
|
|
|
// fmt.Fprintf(response, "I'm okay jack! %v \n", vars)
|
|
|
|
// for key, val := range(vars) {
|
|
|
|
// fmt.Fprint(response, "%s = %s\n", key, val)
|
|
|
|
// }
|
2020-06-30 15:30:05 +00:00
|
|
|
|
|
|
|
if vars["code"] != "" {
|
2020-03-07 19:42:16 +00:00
|
|
|
// https://id.twitch.tv/oauth2/token
|
|
|
|
// ?client_id=<your client ID>
|
2020-06-30 15:30:05 +00:00
|
|
|
// &client_secret=<your client secret>
|
|
|
|
// &code=<authorization code received above>
|
|
|
|
// &grant_type=authorization_code
|
2020-03-07 19:42:16 +00:00
|
|
|
// &redirect_uri=<your registered redirect URI>
|
2020-06-30 15:30:05 +00:00
|
|
|
|
2020-03-07 19:42:16 +00:00
|
|
|
// ircBot.AppCredentials.ClientID
|
|
|
|
// ircBot.AppCredentials.Password
|
|
|
|
// vars["oauthtoken"]
|
|
|
|
// authorization_code
|
|
|
|
// "https://"+ircBot.Config.ExternalUrl+/twitchadmin
|
|
|
|
fmt.Println("Asking twitch for more...")
|
|
|
|
resp, err := http.PostForm(
|
2020-06-30 15:30:05 +00:00
|
|
|
"https://id.twitch.tv/oauth2/token",
|
2020-03-07 19:42:16 +00:00
|
|
|
url.Values{
|
2020-06-30 15:30:05 +00:00
|
|
|
"client_id": {ircBot.AppCredentials.ClientID},
|
2020-03-07 19:42:16 +00:00
|
|
|
"client_secret": {ircBot.AppCredentials.Password},
|
2020-06-30 15:30:05 +00:00
|
|
|
"code": {vars["code"]},
|
|
|
|
"grant_type": {"authorization_code"},
|
|
|
|
"redirect_uri": {"https://" + ircBot.Config.ExternalUrl + "/twitchadmin"}})
|
2020-03-07 19:42:16 +00:00
|
|
|
if err != nil {
|
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
fmt.Fprint(response, "ERROR: "+err.Error())
|
|
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
body, err := ioutil.ReadAll(resp.Body)
|
|
|
|
if err != nil {
|
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
fmt.Fprint(response, "ERROR: "+err.Error())
|
|
|
|
}
|
|
|
|
response.Header().Add("Content-type", "text/plain")
|
|
|
|
fmt.Fprint(response, string(body))
|
|
|
|
} else {
|
|
|
|
UnauthorizedHandler(response, request)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-02-22 13:05:30 +00:00
|
|
|
func HandleHTTP(passedIrcBot *irc.KardBot) {
|
2020-02-14 14:56:10 +00:00
|
|
|
ircBot = passedIrcBot
|
2020-02-14 10:42:38 +00:00
|
|
|
r := mux.NewRouter()
|
|
|
|
loggedRouter := handlers.LoggingHandler(os.Stdout, r)
|
|
|
|
r.NotFoundHandler = http.HandlerFunc(NotFoundHandler)
|
|
|
|
r.HandleFunc("/", RootHandler)
|
|
|
|
r.HandleFunc("/healthz", HealthHandler)
|
2020-02-22 13:05:30 +00:00
|
|
|
r.HandleFunc("/web/{.*}", TemplateHandler)
|
|
|
|
r.PathPrefix("/static/").Handler(http.FileServer(http.Dir("./web/")))
|
2020-02-14 10:42:38 +00:00
|
|
|
r.HandleFunc("/cover.css", CSSHandler)
|
2020-02-21 19:52:19 +00:00
|
|
|
r.HandleFunc("/admin/{channel}/{key}", AdminHandler)
|
2020-03-07 19:42:16 +00:00
|
|
|
//r.HandleFunc("/twitchadmin", TwitchAdminHandler)
|
|
|
|
//r.HandleFunc("/twitchtobackend", TwitchBackendHandler)
|
2020-06-30 15:30:05 +00:00
|
|
|
r.Path("/twitchtobackend").Queries("access_token", "{access_token}", "scope", "{scope}", "token_type", "{token_type}").HandlerFunc(TwitchBackendHandler)
|
|
|
|
r.Path("/twitchadmin").Queries("code", "{code}", "scope", "{scope}").HandlerFunc(TwitchAdminHandler)
|
2020-02-14 10:42:38 +00:00
|
|
|
http.Handle("/", r)
|
|
|
|
srv := &http.Server{
|
|
|
|
Handler: loggedRouter,
|
|
|
|
Addr: "0.0.0.0:5353",
|
|
|
|
WriteTimeout: 15 * time.Second,
|
|
|
|
ReadTimeout: 15 * time.Second,
|
|
|
|
}
|
|
|
|
fmt.Println("Listening on 0.0.0.0:5353")
|
|
|
|
srv.ListenAndServe()
|
|
|
|
}
|