shithub: hell

ref: 94a4e8b5be14b7ab94ac62b006509dbc04407910
dir: /config.go/

View raw version
package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"os"
	"time"
)

const configFileName = "config.json"

type Hellprefs struct {
	Apidelay float32 `json:"apidelay"`
}

type account struct {
	MASTODON_CLIENT_ID     string    `json:"MASTODON_CLIENT_ID"`
	MASTODON_CLIENT_SECRET string    `json:"MASTODON_CLIENT_SECRET"`
	MASTODON_ACCESS_TOKEN  string    `json:"MASTODON_ACCESS_TOKEN"`
	URL                    string    `json:"URL"`
	Preferences            Hellprefs `json:"preferences"`
}

func (prefs *Hellprefs) ApiDelayTime() time.Duration {
	delayms := prefs.Apidelay * 1000
	i := int64(delayms)
	return time.Duration(i) * time.Millisecond
}

func fixPrefs(prefs *Hellprefs) (*Hellprefs, bool) {
	var fixed bool
	defaultprefs := initPrefs()
	if prefs == nil {
		return &defaultprefs, true
	}
	if prefs.Apidelay == 0 {
		prefs.Apidelay = defaultprefs.Apidelay
		fixed = true
	}
	return prefs, fixed
}

func initPrefs() Hellprefs {
	prefs := &Hellprefs{
		Apidelay: 2,
	}
	return *prefs
}

func loadConfig() (*account, error) {
	config := &account{}
	// Check if the config file exists
	if _, err := os.Stat(configFileName); os.IsNotExist(err) {
		// no config, create account
		client := ConfigureClient()
		config.URL = "https://eldritch.cafe"
		config.MASTODON_CLIENT_ID = client.Config.ClientID
		config.MASTODON_CLIENT_SECRET = client.Config.ClientSecret
		config.MASTODON_ACCESS_TOKEN = client.Config.AccessToken

		config.Preferences = initPrefs()

		data, err := json.MarshalIndent(config, "", "  ")
		if err != nil {
			return nil, fmt.Errorf("error marshalling config: %w", err)
		}

		err = ioutil.WriteFile(configFileName, data, 0644)
		if err != nil {
			return nil, fmt.Errorf("error writing config file: %w", err)
		}
		return config, nil
	}

	// File exists, load it
	data, err := ioutil.ReadFile(configFileName)
	if err != nil {
		return nil, fmt.Errorf("error reading config file: %w", err)
	}

	err = json.Unmarshal(data, config)
	if err != nil {
		return nil, fmt.Errorf("error unmarshalling config: %w", err)
	}
	prefs := &config.Preferences
	prefs, fixed := fixPrefs(&config.Preferences)
	config.Preferences = *prefs

	if fixed {
		data, err = json.MarshalIndent(config, "", "  ")
		if err != nil {
			return nil, fmt.Errorf("error marshalling config: %w", err)
		}

		err = ioutil.WriteFile(configFileName, data, 0644)
		if err != nil {
			return nil, fmt.Errorf("error writing config file: %w", err)
		}
	}
	return config, nil
}