-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathconstitutional.go
More file actions
178 lines (166 loc) · 5.44 KB
/
constitutional.go
File metadata and controls
178 lines (166 loc) · 5.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"strings"
"time"
"github.com/computersciencehouse/vote/database"
"github.com/computersciencehouse/vote/logging"
"github.com/sirupsen/logrus"
"github.com/slack-go/slack"
"github.com/slack-go/slack/socketmode"
)
type SlackData struct {
AnnouncementsChannel string
Client *socketmode.Client
}
var slackData = SlackData{}
func InitConstitution() {
slackData.AnnouncementsChannel = os.Getenv("VOTE_ANNOUNCEMENTS_CHANNEL_ID")
if slackData.AnnouncementsChannel == "" {
logging.Logger.WithFields(logrus.Fields{"method": "InitConstitution"}).Error("No announcements channel ID specified")
}
appToken := os.Getenv("VOTE_SLACK_APP_TOKEN")
if appToken == "" {
logging.Logger.WithFields(logrus.Fields{"method": "InitSlack"}).Error("No Slack app token specified")
}
if !strings.HasPrefix(appToken, "xapp-") {
logging.Logger.WithFields(logrus.Fields{"method": "InitConstitution"}).Error("Invalid Slack app token (should have prefix \"xapp-\".")
}
botToken := os.Getenv("VOTE_SLACK_BOT_TOKEN")
if botToken == "" {
logging.Logger.WithFields(logrus.Fields{"method": "InitConstitution"}).Error("No Slack bot token specified")
}
if !strings.HasPrefix(botToken, "xoxb-") {
logging.Logger.WithFields(logrus.Fields{"method": "InitConstitution"}).Error("Invalid Slack bot token (should have prefix \"xoxb-\".")
}
api := slack.New(botToken, slack.OptionAppLevelToken(appToken))
slackData.Client = socketmode.New(api)
t := time.Now()
startOfDay := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, time.Local)
nextMidnight := startOfDay.AddDate(0, 0, 1)
fmt.Println(nextMidnight)
fmt.Println(time.Until(nextMidnight))
ticker := time.NewTicker(time.Until(nextMidnight))
first := true
go func() {
for {
select {
case <-ticker.C:
EvaluatePolls()
if first {
ticker.Reset(24 * time.Hour)
first = false
}
case <-oidcClient.quit:
ticker.Stop()
return
}
}
}()
}
// GetEligibleVoters returns a string slice of usernames of eligible voters
func GetEligibleVoters() []string {
htclient := &http.Client{}
req, err := http.NewRequest("GET", CONDITIONAL_GATEKEEP_URL, nil)
if err != nil {
logging.Logger.WithFields(logrus.Fields{"method": "GetUserGatekeep"}).Error(err)
return nil
}
req.Header.Add("X-VOTE-TOKEN", VOTE_TOKEN)
resp, err := htclient.Do(req)
if err != nil {
logging.Logger.WithFields(logrus.Fields{"method": "GetUserGatekeep"}).Error(err)
return nil
}
defer resp.Body.Close()
b, _ := io.ReadAll(resp.Body)
if strings.Contains(string(b), "Users") {
logging.Logger.WithFields(logrus.Fields{"method": "GetUserGatekeep"}).Error("Conditional Gatekeep token is incorrect")
return nil
}
res := make([]string, 0)
err = json.Unmarshal(b, &res)
return res
}
func EvaluatePolls() {
ctx := context.Background()
polls, err := database.GetOpenGatekeepPolls(ctx)
if err != nil {
logging.Logger.WithFields(logrus.Fields{"method": "EvaluatePolls getOpen"}).Error(err)
return
}
for _, poll := range polls {
now := time.Now()
// if OpenedTime + 1 day later is before today, it's been open for less than 24 hours, and we will re-evaluate next run
// if after, it's been more than 24 hours
// we still won't close until 48, but we want to start messaging at 24
if poll.OpenedTime.AddDate(0, 0, 1).After(now) {
continue
}
quorum := CalculateQuorum(*poll)
notVoted := make([]*OIDCUser, 0)
votedCount := 0
// check all voters to see if they have voted
if poll.AllowedUsers == nil {
logging.Logger.WithFields(logrus.Fields{"method": "EvaluatePolls checkQuorum"}).Error(
"Users allowed to vote is nil for \"" + poll.Title + "\" !! This should not happen!!")
continue
}
for _, user := range poll.AllowedUsers {
voted, err := database.HasVoted(ctx, poll.Id, user)
if err != nil {
logging.Logger.WithFields(logrus.Fields{"method": "EvaluatePolls hasVoted"}).Error(err)
continue
}
if voted {
votedCount = votedCount + 1
continue
}
notVoted = append(notVoted, &OIDCUser{Username: user})
}
pollLink := VOTE_HOST + "/poll/" + poll.Id
// quorum not met
if votedCount < quorum {
for _, user := range notVoted {
oidcClient.GetUserInfo(user)
_, _, err = slackData.Client.PostMessage(user.SlackUID,
slack.MsgOptionText(
"Hello, you have not yet voted on \""+poll.Title+"\". We have not yet hit quorum"+
" and we need YOU :index_pointing_at_the_viewer: to complete your responsibility as a "+
"member of house and vote. \n"+pollLink+"\nThank you!", false))
if err != nil {
logging.Logger.WithFields(logrus.Fields{"method": "EvaluatePolls dm"}).Error(err)
continue
}
}
continue
}
// close poll after 48 hours
if poll.OpenedTime.AddDate(0, 0, 2).After(now) {
continue
}
// we close the poll here
err = poll.Close(ctx)
fmt.Println("Time reached, closing poll " + poll.Title)
if err != nil {
logging.Logger.WithFields(logrus.Fields{"method": "EvaluatePolls close"}).Error(err)
continue
}
announceStr := "The vote \"" + poll.Title + "\" has closed."
if !poll.Hidden {
announceStr += " Check out the results at " + pollLink
} else {
announceStr += " Results will be posted shortly."
}
_, _, _, err = slackData.Client.SendMessage(slackData.AnnouncementsChannel,
slack.MsgOptionText(announceStr, false))
if err != nil {
logging.Logger.WithFields(logrus.Fields{"method": "EvaluatePolls announce"}).Error(err)
}
}
}