Skip to content

Commit dc1e919

Browse files
committed
Merge branch 'main' of github.com:script-development/rtcv_scraper_client into main
2 parents 7c0ef63 + 53615d8 commit dc1e919

File tree

3 files changed

+47
-21
lines changed

3 files changed

+47
-21
lines changed

api.go

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"time"
1414
)
1515

16+
// API holds information used to communicate with the RT-CV api
1617
type API struct {
1718
authHeaderValue string
1819
serverLocation string
@@ -21,20 +22,19 @@ type API struct {
2122
MockOptions MockOptions
2223
}
2324

25+
// MockOptions represends options for the RT-CV mocking mode
2426
type MockOptions struct {
2527
Secrets map[string]json.RawMessage `json:"secrets"`
2628
}
2729

30+
// NewAPI creates a new instance of the API
2831
func NewAPI() *API {
2932
return &API{
30-
authHeaderValue: "",
31-
serverLocation: "",
32-
Cache: map[string]time.Time{},
33-
MockMode: false,
34-
MockOptions: MockOptions{},
33+
Cache: map[string]time.Time{},
3534
}
3635
}
3736

37+
// SetCredentials sets the api credentials so we can make fetch requests to RT-CV
3838
func (a *API) SetCredentials(serverLocation, apiKeyID, apiKey string, runAsMockWithOpts *MockOptions) error {
3939
a.MockMode = runAsMockWithOpts != nil
4040
if a.MockMode {
@@ -54,21 +54,24 @@ func (a *API) SetCredentials(serverLocation, apiKeyID, apiKey string, runAsMockW
5454
if apiKey == "" {
5555
return errors.New("api_key cannot be empty")
5656
}
57-
hashedApiKey := sha512.Sum512([]byte(apiKey))
58-
hashedApiKeyStr := hex.EncodeToString(hashedApiKey[:])
59-
a.authHeaderValue = "Basic " + apiKeyID + ":" + hashedApiKeyStr
57+
hashedAPIKey := sha512.Sum512([]byte(apiKey))
58+
hashedAPIKeyStr := hex.EncodeToString(hashedAPIKey[:])
59+
a.authHeaderValue = "Basic " + apiKeyID + ":" + hashedAPIKeyStr
6060

6161
return nil
6262
}
6363

64+
// Get makes a get request to RT-CV
6465
func (a *API) Get(path string, unmarshalResInto interface{}) error {
6566
return a.DoRequest("GET", path, nil, unmarshalResInto)
6667
}
6768

69+
// Post makes a post request to RT-CV
6870
func (a *API) Post(path string, body interface{}, unmarshalResInto interface{}) error {
6971
return a.DoRequest("POST", path, body, unmarshalResInto)
7072
}
7173

74+
// DoRequest makes a http request to RT-CV
7275
func (a *API) DoRequest(method, path string, body, unmarshalResInto interface{}) error {
7376
var reqBody io.ReadCloser
7477
if body != nil {
@@ -115,12 +118,16 @@ func (a *API) DoRequest(method, path string, body, unmarshalResInto interface{})
115118
return nil
116119
}
117120

121+
// NoCredentials returns true if the SetCredentials method was not yet called and we aren't in mock mode
118122
func (a *API) NoCredentials() bool {
119123
return a.authHeaderValue == "" && !a.MockMode
120124
}
121125

126+
// ErrMissingCredentials is returned when the SetCredentials method was not yet called
127+
// while we're trying to execute an action that requires them
122128
var ErrMissingCredentials = errors.New("missing credentials, call set_credentials before this method")
123129

130+
// GetSecret returns a secret from RT-CV
124131
func (a *API) GetSecret(key, encryptionKey string, result interface{}) error {
125132
if a.MockMode {
126133
if a.MockOptions.Secrets == nil {
@@ -138,6 +145,7 @@ func (a *API) GetSecret(key, encryptionKey string, result interface{}) error {
138145
return a.Get(fmt.Sprintf("/api/v1/secrets/myKey/%s/%s", key, encryptionKey), result)
139146
}
140147

148+
// GetUsersSecret returns strictly defined users secret
141149
func (a *API) GetUsersSecret(key, encryptionKey string) ([]UserSecret, error) {
142150
if a.NoCredentials() {
143151
return []UserSecret{}, ErrMissingCredentials
@@ -151,6 +159,7 @@ func (a *API) GetUsersSecret(key, encryptionKey string) ([]UserSecret, error) {
151159
return result, err
152160
}
153161

162+
// GetUserSecret returns strictly defined user secret
154163
func (a *API) GetUserSecret(key, encryptionKey string) (UserSecret, error) {
155164
if a.NoCredentials() {
156165
return UserSecret{}, ErrMissingCredentials
@@ -164,6 +173,7 @@ func (a *API) GetUserSecret(key, encryptionKey string) (UserSecret, error) {
164173
return result, err
165174
}
166175

176+
// CacheEntryExists returns true if the cache entry exists and is not expired
167177
func (a *API) CacheEntryExists(referenceNr string) bool {
168178
cacheEntryInsertionTime, cacheEntryExists := a.Cache[referenceNr]
169179
if cacheEntryExists {
@@ -178,6 +188,7 @@ func (a *API) CacheEntryExists(referenceNr string) bool {
178188
return cacheEntryExists
179189
}
180190

191+
// UserSecret represents the json layout of an user secret
181192
type UserSecret struct {
182193
Username string `json:"username"`
183194
Password string `json:"password"`

main.go

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -85,7 +85,7 @@ func main() {
8585
os.Exit(0)
8686
}
8787

88-
PrintMessage(MessageTypeReady, "waiting for credentials")
88+
MessageTypeReady.Print("waiting for credentials")
8989

9090
api := NewAPI()
9191

@@ -98,26 +98,28 @@ func main() {
9898
var logInputFile *os.File
9999
var err error
100100
if logInput {
101-
logInputFile, err = os.OpenFile("scraper_client_input.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
101+
logInputFile, err = os.OpenFile("scraper_client_input.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0600)
102102
if err != nil {
103-
PrintMessage(MessageTypeError, err.Error())
103+
MessageTypeError.Print(err.Error())
104104
os.Exit(1)
105105
}
106-
defer logInputFile.Close()
107106
}
108107

109108
scanner := bufio.NewScanner(os.Stdin)
110109
err = scanner.Err()
111110
if err != nil {
112-
PrintMessage(MessageTypeError, err.Error())
111+
MessageTypeError.Print(err.Error())
112+
if logInput {
113+
logInputFile.Close()
114+
}
113115
os.Exit(1)
114116
}
115117

116118
for scanner.Scan() {
117119
text := strings.TrimSpace(scanner.Text())
118120
err = scanner.Err()
119121
if err != nil {
120-
PrintMessage(MessageTypeError, err.Error())
122+
MessageTypeError.Print(err.Error())
121123
break
122124
}
123125

@@ -126,14 +128,20 @@ func main() {
126128
logInputFile.Sync()
127129
}
128130

129-
PrintMessage(LoopAction(api, text))
131+
mt, msgContent := LoopAction(api, text)
132+
mt.Print(msgContent)
130133
}
131134

132135
// If the loop stops there is a critical error
133136
// Thus the program should exit with a error code
137+
if logInput {
138+
logInputFile.Close()
139+
}
134140
os.Exit(1)
135141
}
136142

143+
// LoopAction handles one line of input and returns the response
144+
// Note that no-where inside this function we should print to the screen
137145
func LoopAction(api *API, inputJSON string) (msgType MessageType, msgContent interface{}) {
138146
returnErr := func(err error) (msgType MessageType, msgContent interface{}) {
139147
return MessageTypeError, err.Error()
@@ -149,8 +157,8 @@ func LoopAction(api *API, inputJSON string) (msgType MessageType, msgContent int
149157
case "set_credentials":
150158
credentialsArgs := struct {
151159
ServerLocation string `json:"server_location"`
152-
ApiKeyID string `json:"api_key_id"`
153-
ApiKey string `json:"api_key"`
160+
APIKeyID string `json:"api_key_id"`
161+
APIKey string `json:"api_key"`
154162
Mock *MockOptions `json:"mock"` // Null means disabled
155163
}{}
156164
err = json.Unmarshal(input.Content, &credentialsArgs)
@@ -160,8 +168,8 @@ func LoopAction(api *API, inputJSON string) (msgType MessageType, msgContent int
160168

161169
err = api.SetCredentials(
162170
credentialsArgs.ServerLocation,
163-
credentialsArgs.ApiKeyID,
164-
credentialsArgs.ApiKey,
171+
credentialsArgs.APIKeyID,
172+
credentialsArgs.APIKey,
165173
credentialsArgs.Mock,
166174
)
167175
if err != nil {

messages.go

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,17 @@ import (
55
"fmt"
66
)
77

8+
// MessageType represends a response message type
89
type MessageType uint8
910

1011
const (
12+
// MessageTypeReady tells the client is ready to receive messages
1113
MessageTypeReady MessageType = iota
14+
// MessageTypePong is the response of a ping input message
1215
MessageTypePong
16+
// MessageTypeOk is the response of a successful operation
1317
MessageTypeOk
18+
// MessageTypeError is the response of an error
1419
MessageTypeError
1520
)
1621

@@ -29,7 +34,8 @@ func (mt MessageType) String() string {
2934
}
3035
}
3136

32-
func PrintMessage(messageType MessageType, messageContent interface{}) {
37+
// Print prints a json message to screen with the MessageType and messageContent
38+
func (mt MessageType) Print(messageContent interface{}) {
3339
var content []byte
3440

3541
if messageContent != nil {
@@ -44,7 +50,7 @@ func PrintMessage(messageType MessageType, messageContent interface{}) {
4450
Type string `json:"type"`
4551
Content json.RawMessage `json:"content,omitempty"`
4652
}{
47-
Type: messageType.String(),
53+
Type: mt.String(),
4854
Content: content,
4955
})
5056
if err != nil {
@@ -55,6 +61,7 @@ func PrintMessage(messageType MessageType, messageContent interface{}) {
5561
}
5662
}
5763

64+
// InMessage represents the json contents of a stdin line
5865
type InMessage struct {
5966
Type string `json:"type"`
6067
Content json.RawMessage `json:"content"`

0 commit comments

Comments
 (0)