Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor misc problems for v9 #21

Merged
merged 9 commits into from
Feb 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
161 changes: 109 additions & 52 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@ import (
"context"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"log/slog"
"net/http"
"os"
"strings"
Expand All @@ -14,8 +15,8 @@ import (
"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"
"golang.org/x/exp/slog"
)

// App struct
Expand All @@ -25,6 +26,7 @@ type App struct {
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.
Expand Down Expand Up @@ -56,69 +58,41 @@ func (a *App) startup(ctx context.Context) {
}
a.logger.Info("Startup", "environment", a.environment)

// 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, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.QuestionDialog,
Title: "認証情報がないよ",
Message: "config.tomlにIDとパスワードを入力してね。\nこのまま沈没するけど、設定ファイルの場所を開く?",
DefaultButton: "Yes",
})
if err != nil {
a.logger.Warn("Error creds not set dialog", "error", err)
}
a.logger.Info(result)
if dialogResults[strings.ToLower(result)] {
a.OpenConfigDirectory()
}
a.logger.Warn("Missing credentials")
err := a.SetXRPCClient()
if err != nil {
runtime.Quit(ctx)
}

auth, err := createSession(cred.Host, cred.Identifier, cred.Password)

err = a.SetScheduler()
if err != nil {
// If auth failed,
result, err := runtime.MessageDialog(a.ctx, runtime.MessageDialogOptions{
Type: runtime.QuestionDialog,
Title: "認証に失敗しました",
Message: fmt.Sprintf("%sへの認証に失敗しました。\nIDとパスワードを確認してください。\nこのまま沈没するけど、設定ファイルの場所を開く?", cred.Host),
DefaultButton: "Yes",
})

if err != nil {
a.logger.Warn("Error creds not set dialog", "error", err)
}
a.logger.Info(result)
if dialogResults[strings.ToLower(result)] {
a.OpenConfigDirectory()
}

a.logger.Warn("Failed creating session, bad identifier or password?", "error", err)
panic(err)
runtime.Quit(ctx)
}
}

xrpcc := &xrpc.Client{
Client: NewHttpClient(),
Host: cred.Host,
Auth: auth,
func (a *App) onDomReady(ctx context.Context) {
slog.Info("Emitting OnDomReady", a.config)
runtime.EventsEmit(ctx, "OnDomReady", "hello")
}

func (a *App) beforeClose(ctx context.Context) bool {
err := a.scheduler.Shutdown()
if err != nil {
a.logger.Warn("Error on scheduler shutdown:", err)
}
a.xrpcc = xrpcc
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("Error: host not set. Check [Credential] section in config file.")
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("Error creating HTTP request:", err)
return nil, fmt.Errorf("failed creating HTTP request: %r", err)
}
req.Header.Set("Content-Type", "application/json")

Expand All @@ -130,11 +104,11 @@ func createSession(host string, identifier string, password string) (*xrpc.AuthI

defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("Error: Unexpected status code: %d", resp.StatusCode)
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("Error reading response body: %v", err)
return nil, fmt.Errorf("failed reading response body: %v", err)
}
var auth xrpc.AuthInfo
err = json.Unmarshal(body, &auth)
Expand All @@ -160,7 +134,7 @@ func NewHttpClient() *http.Client {

func (a *App) Post(text string) string {
a.logger.Info("Post", "text", text)
err := beeep.Notify("まぜそば大陸", fmt.Sprintf("BskyFeedPost: %s", text), "")
beeep.Notify("まぜそば大陸", fmt.Sprintf("BskyFeedPost: %s", text), "")

if a.environment.BuildType == "dev" {
return "<MOCK URI>"
Expand Down Expand Up @@ -198,3 +172,86 @@ func (a *App) OpenLogDirectory() error {
func (a *App) GetVersion() string {
return Version
}

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
}
10 changes: 6 additions & 4 deletions bluesky.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,12 @@ func BskyFeedPost(xrpcc *xrpc.Client, text string) (string, error) {
resp, err := comatproto.RepoCreateRecord(context.TODO(), xrpcc, &comatproto.RepoCreateRecord_Input{
Collection: "app.bsky.feed.post",
Repo: xrpcc.Auth.Did,
Record: &lexutil.LexiconTypeDecoder{&appbsky.FeedPost{
Text: text,
CreatedAt: time.Now().Format("2006-01-02T15:04:05.000Z"),
}},
Record: &lexutil.LexiconTypeDecoder{
Val: &appbsky.FeedPost{
Text: text,
CreatedAt: time.Now().Format("2006-01-02T15:04:05.000Z"),
},
},
})
if err != nil {
return "", fmt.Errorf("failed to create post: %w", err)
Expand Down
17 changes: 15 additions & 2 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ package main

import (
"bytes"
"io/ioutil"
"log"
"os"

"github.com/BurntSushi/toml"
"github.com/adrg/xdg"
Expand All @@ -27,6 +27,10 @@ type windowConfig struct {
Height int
AlwaysOnTop bool
Transparent bool
BackgroundR int
BackgroundG int
BackgroundB int
BackgroundA float64
}

type credConfig struct {
Expand Down Expand Up @@ -56,6 +60,15 @@ func loadOrCreateConfig(configPath string) (Config, error) {
Height: 200,
AlwaysOnTop: true,
Transparent: true,
BackgroundR: 27,
BackgroundG: 38,
BackgroundB: 54,
BackgroundA: 0.5,
},
Credential: credConfig{
Identifier: "ID (e.g. example.bsky.social)",
Password: "App Password (see https://tokimekibluesky-docs.vercel.app/ja/apppassword)",
Host: "https://bsky.social",
},
}
buf := new(bytes.Buffer)
Expand All @@ -69,7 +82,7 @@ func loadOrCreateConfig(configPath string) (Config, error) {
buf.String(),
"=========================================",
)
ioutil.WriteFile(configFile, buf.Bytes(), 0644)
os.WriteFile(configFile, buf.Bytes(), 0644)
config = defaultConfig
}
return config, nil
Expand Down
63 changes: 0 additions & 63 deletions frontend/README.md

This file was deleted.

6 changes: 3 additions & 3 deletions frontend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@
"preview": "vite preview"
},
"devDependencies": {
"@sveltejs/vite-plugin-svelte": "^3.0.2",
"svelte": "^4.2.10",
"vite": "^5.1.1"
"@sveltejs/vite-plugin-svelte": "^1.0.1",
"svelte": "^3.49.0",
"vite": "^3.0.0"
}
}
2 changes: 1 addition & 1 deletion frontend/package.json.md5
Original file line number Diff line number Diff line change
@@ -1 +1 @@
c75f81b1299f8d3675e8103348403c41
3369211da39dcc63e89750b11fced2dd
Loading
Loading