-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
app.go
278 lines (242 loc) · 7.17 KB
/
app.go
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
// Types / Functions under app.go are intended to be used from frontend.
package main
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"log/slog"
"net/http"
"os"
"strings"
"time"
"github.com/adrg/xdg"
"github.com/bluesky-social/indigo/xrpc"
"github.com/gen2brain/beeep"
"github.com/go-co-op/gocron/v2"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// App struct
type App struct {
config Config
ctx context.Context
xrpcc *xrpc.Client
logger *slog.Logger
environment runtime.EnvironmentInfo
scheduler gocron.Scheduler
}
// dialogResults is used for casting Dialog's response to boolean. Note that keys are lowercase.
var dialogResults = map[string]bool{
"ok": true,
"cancel": false,
"abort": false,
"retry": false,
"ignore": false,
"yes": true,
"no": false,
"try again": false,
"continue": false,
}
// NewApp creates a new App application struct
func NewApp() *App {
return &App{}
}
// startup is called when the app starts. The context is saved
// so we can call the runtime methods
func (a *App) startup(ctx context.Context) {
a.ctx = ctx
a.environment = runtime.Environment(ctx)
if a.environment.BuildType == "dev" {
// Use stdout in dev mode
a.logger = slog.New(slog.NewTextHandler(os.Stdout, nil))
}
a.logger.Info("Startup", "environment", a.environment)
err := a.SetXRPCClient()
if err != nil {
runtime.Quit(ctx)
}
err = a.SetScheduler()
if err != nil {
runtime.Quit(ctx)
}
}
func (a *App) beforeClose(ctx context.Context) bool {
err := a.scheduler.Shutdown()
if err != nil {
a.logger.Warn("Error on scheduler shutdown:", err)
}
return false
}
// createSession calls "/xrpc/com.atproto.server.createSession" and returns xrpc.AuthInfo.
func createSession(host string, identifier string, password string) (*xrpc.AuthInfo, error) {
payload := fmt.Sprintf(`{"identifier": "%s", "password": "%s"}`, identifier, password)
if host == "" {
return nil, fmt.Errorf("host not set. check [Credential] section in config file")
}
url := fmt.Sprintf("%s/xrpc/com.atproto.server.createSession", host)
req, err := http.NewRequest("POST", url, bytes.NewBuffer([]byte(payload)))
if err != nil {
return nil, fmt.Errorf("failed creating HTTP request: %r", err)
}
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("failed reading response body: %v", err)
}
var auth xrpc.AuthInfo
err = json.Unmarshal(body, &auth)
if err != nil {
return nil, fmt.Errorf("Error decoding JSON response: %v", err)
}
return &auth, nil
}
func NewHttpClient() *http.Client {
return &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
ForceAttemptHTTP2: true,
MaxIdleConns: 100,
IdleConnTimeout: 90 * time.Second,
TLSHandshakeTimeout: 10 * time.Second,
ExpectContinueTimeout: 1 * time.Second,
},
}
}
func (a *App) Post(text string) string {
a.logger.Info("Post", "text", text)
beeep.Notify("まぜそば大陸", fmt.Sprintf("BskyFeedPost: %s", text), "")
if a.environment.BuildType == "dev" {
return "<MOCK URI>"
}
res, err := BskyFeedPost(a.xrpcc, text)
if err != nil {
errs := fmt.Sprintf("Posting error: %s", err.Error())
a.logger.Error("Post: Error on BskyFeedPost", "error", errs)
return errs
}
a.logger.Info("Posted", "result", res)
return res
}
func (a *App) PostAndForget(text string) {
a.Post(text)
}
func (a *App) Chikuwa(text string) string {
return a.Post(fmt.Sprintf("%s %s", text, time.Now().Format(time.RFC3339)))
}
func (a *App) OpenConfigDirectory() error {
f, _ := xdg.ConfigFile("mazesoba-continent")
a.logger.Info("OpenConfigDirectory", "path", f)
return openDirectory(f)
}
func (a *App) OpenLogDirectory() error {
f, _ := xdg.CacheFile("mazesoba-continent")
a.logger.Info("OpenLogDirectory", "path", f)
return openDirectory(f)
}
func (a *App) SetXRPCClient() error {
// Build xrpc.Client
var auth *xrpc.AuthInfo
cred := a.config.Credential
if cred.Host == "" || cred.Identifier == "" || cred.Password == "" {
a.logger.Warn("Credentials not set!")
result, dialogErr := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.QuestionDialog,
Title: "認証情報がないよ",
Message: "config.tomlにIDとパスワードを入力してね。\nこのまま沈没するけど、設定ファイルの場所を開く?",
DefaultButton: "Yes",
})
if dialogErr != nil {
a.logger.Warn("Error creds not set dialog", "error", dialogErr)
}
a.logger.Info(result)
if dialogResults[strings.ToLower(result)] {
a.OpenConfigDirectory()
}
a.logger.Warn("Missing credentials")
return fmt.Errorf("Couldn't load valid credentials.")
}
auth, authErr := createSession(cred.Host, cred.Identifier, cred.Password)
if authErr != nil {
// If auth failed,
result, dialogErr := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.QuestionDialog,
Title: "認証に失敗したよ",
Message: fmt.Sprintf("%sへの認証に失敗しました。\nIDとパスワードとインターネット接続を確認してね。\n設定ファイルの場所を開く?", cred.Host),
DefaultButton: "Yes",
})
if dialogErr != nil {
a.logger.Warn("Error creds not set dialog", "error", dialogErr)
}
a.logger.Info(result)
if dialogResults[strings.ToLower(result)] {
a.OpenConfigDirectory()
}
a.logger.Warn("Failed creating session, bad identifier or password?", "error", authErr)
return authErr
}
xrpcc := &xrpc.Client{
Client: NewHttpClient(),
Host: cred.Host,
Auth: auth,
}
a.xrpcc = xrpcc
a.logger.Info("Set XRPCC succeeded.")
return nil
}
func (a *App) SetScheduler() error {
s, err := gocron.NewScheduler()
if err != nil {
return err
}
a.scheduler = s
// add a job to the scheduler
j, err := a.scheduler.NewJob(
gocron.DurationJob(
10*time.Minute,
),
gocron.NewTask(
a.SetXRPCClient,
),
)
if err != nil {
a.logger.Warn("Error occurred on SetScheduler: ", err, j)
}
// start the scheduler
a.scheduler.Start()
// err = s.Shutdown()
return nil
}
type AppContext struct {
// AppContext is a struct that contains the context of the app.
// It can be used to marshalize the context to JSON.
// This struct is intended to be used by the frontend.
Identifier string `json:"id"`
Host string `json:"host"`
Version string `json:"version"`
}
func (a *App) GetContext() string {
// Return AppContext in Marshalized JSON
// Intended to be used by the frontend.
// FIXME: This is a workaround to remove "http://" or "https://" from host, until config change.
host := a.config.Credential.Host
// Remove "http://" or "https://" from host
host = strings.TrimPrefix(host, "http://")
host = strings.TrimPrefix(host, "https://")
ac := AppContext{
Version: Version,
Identifier: a.config.Credential.Identifier,
Host: host,
}
data, _ := json.Marshal(ac)
return string(data)
}