g2i/g2i/idec.go

108 lines
2.3 KiB
Go
Raw Permalink Normal View History

2019-03-14 18:42:15 +03:00
package g2i
import (
2019-03-16 16:24:35 +03:00
"encoding/json"
"text/template"
2019-03-14 18:42:15 +03:00
"bytes"
"github.com/google/go-github/github"
2019-03-16 16:24:35 +03:00
idec "github.com/idec-net/go-idec"
log "github.com/sirupsen/logrus"
2019-03-14 18:42:15 +03:00
)
type IDECClient struct {
2019-03-16 16:24:35 +03:00
FetchConfig idec.FetchConfig
2019-03-15 16:56:16 +03:00
authstring string
2019-03-14 18:42:15 +03:00
config *Config
2019-03-16 16:24:35 +03:00
TopPostID string
2019-03-14 18:42:15 +03:00
}
func NewIDECClient(config *Config) *IDECClient {
return &IDECClient{
2019-03-15 16:56:16 +03:00
config: config,
authstring: config.IDEC.Authstring,
2019-03-16 16:24:35 +03:00
FetchConfig: idec.FetchConfig{
2019-03-14 18:42:15 +03:00
Limit: config.IDEC.Fetch.Limit,
Offset: config.IDEC.Fetch.Offset,
Node: config.IDEC.NodeURL,
Echoes: config.IDEC.Fetch.Echoes,
},
2019-03-16 16:24:35 +03:00
TopPostID: config.IDEC.TopPostID,
2019-03-14 18:42:15 +03:00
}
}
type HelloMessage struct {
Sources, Name, Owner, Repo string
Issues []*github.Issue
}
2019-03-16 16:24:35 +03:00
func (i *IDECClient) PostHello() error {
2019-03-14 18:42:15 +03:00
message := idec.PointMessage{}
2019-03-16 16:24:35 +03:00
message.Echo = i.FetchConfig.Echoes[0]
message.To = "All"
message.Repto = "@repto:" + i.config.IDEC.TopPostID
message.Subg = i.config.IDEC.MessageSubg
2019-03-14 18:42:15 +03:00
body := &bytes.Buffer{}
2019-03-16 16:24:35 +03:00
err := i.config.generateTemplate("hello_message.tpl", i.config.IDEC.HelloMessageTemplatePath, i.config.Github, body)
2019-03-14 18:42:15 +03:00
if err != nil {
log.Print("Error", err.Error())
2019-03-16 16:24:35 +03:00
return err
2019-03-14 18:42:15 +03:00
}
message.Body = body.String()
2019-03-16 16:24:35 +03:00
b64message := message.PrepareMessageForSend()
err = i.FetchConfig.PostMessage(i.authstring, b64message)
if err != nil {
log.Error(err)
return err
}
return nil
}
func (i *IDECClient) PostComment(event github.Event) error {
var post idec.PointMessage
comment, err := i.generateCommentTemplate(event)
if err != nil {
return err
}
post.Echo = i.FetchConfig.Echoes[0]
post.To = "All"
post.Repto = "@repto:" + i.TopPostID
post.Body = comment
post.Subg = i.config.IDEC.MessageSubg
b64message := post.PrepareMessageForSend()
err = i.FetchConfig.PostMessage(i.authstring, b64message)
return err
}
func (i *IDECClient) generateCommentTemplate(event github.Event) (string, error) {
payload, err := event.RawPayload.MarshalJSON()
if err != nil {
return "", err
}
var ghic GithubIssueComment
err = json.Unmarshal(payload, &ghic)
if err != nil {
return "", err
}
body := &bytes.Buffer{}
t, err := template.New("comment.tpl").ParseFiles(i.config.IDEC.CommentTemplatePath)
if err != nil {
return "", err
}
err = t.Execute(body, ghic)
if err != nil {
return "", err
}
log.Debug(body.String())
return body.String(), nil
2019-03-14 18:42:15 +03:00
}