krz/skunky-art

Alternative privacy frontend for DeviantArt.

clone: git clone https://gitbay.org/krz/skunky-art.git

v1.4.0: app/cli.go · raw

  1package app
  2
  3import (
  4	"bufio"
  5	"bytes"
  6	"encoding/json"
  7	"html/template"
  8	"os"
  9	"time"
 10)
 11
 12// ExecuteCommandLineArguments parses argv, applying the flags that override
 13// config and running one-shot commands such as --help and --add-instance. Some
 14// of those commands exit the process rather than return.
 15func ExecuteCommandLineArguments() {
 16	var helpmsg = `SkunkyArt v{{.Version}} [{{.Description}}]
 17Usage:
 18	- [-c|--config] 	| path to config
 19	- [-a|--add-instance]	| generates 'instances.json' and 'INSTANCES.md' files with ur instance
 20	- [-h|--help]		| returns this message
 21Example:
 22	./skunkyart -c config.json
 23Copyright lost+skunk and zerolabs, X11. https://github.com/krazywarez/skunky-art/releases/tag/v{{.Version}}`
 24
 25	a := os.Args[1:]
 26	for n, x := range a {
 27		switch x {
 28		case "-c", "--config":
 29			if len(a) >= 2 {
 30				CFG.cfg = a[n+1]
 31			} else {
 32				exit("Not enought arguments", 1)
 33			}
 34		case "-h", "--help":
 35			var buf bytes.Buffer
 36			t := template.New("help")
 37			tryWithExitStatus(func() error {
 38				if _, err := t.Parse(helpmsg); err != nil {
 39					return err
 40				}
 41				return t.Execute(&buf, &Release)
 42			}(), 1)
 43			exit(buf.String(), 0)
 44		case "-a", "--add-instance":
 45			addInstance()
 46		}
 47	}
 48}
 49
 50type settingsUrls struct {
 51	I2P      string `json:"i2p,omitempty"`
 52	Ygg      string `json:"ygg,omitempty"`
 53	Tor      string `json:"tor,omitempty"`
 54	Clearnet string `json:"clearnet,omitempty"`
 55}
 56
 57type settingsParams struct {
 58	Nsfw   bool   `json:"nsfw"`
 59	Proxy  bool   `json:"proxy"`
 60	HideAI bool   `json:"hide-ai"`
 61	Theme  string `json:"theme"`
 62}
 63
 64type settings struct {
 65	Title       string         `json:"title"`
 66	Country     string         `json:"country"`
 67	ModifiedSrc string         `json:"modified-src,omitempty"`
 68	Urls        settingsUrls   `json:"urls"`
 69	Settings    settingsParams `json:"settings"`
 70}
 71
 72func addInstance() {
 73	prompt := func(txt string, necessary bool) string {
 74		input := bufio.NewScanner(os.Stdin)
 75		for {
 76			print(txt)
 77			print(": ")
 78			input.Scan()
 79
 80			if i := input.Text(); necessary && i == "" {
 81				println("Please specify the", txt)
 82			} else {
 83				return i
 84			}
 85		}
 86	}
 87
 88	var settingsVar struct {
 89		Instances []settings `json:"instances"`
 90	}
 91	// 0644: both files are committed to the repository and are meant to be
 92	// world-readable, so gosec's 0600 default does not apply.
 93	instancesJSON, err := os.OpenFile("instances.json", os.O_CREATE|os.O_WRONLY, 0644) //nolint:gosec // G302
 94	if err != nil {
 95		exit(err.Error(), 1)
 96	}
 97	defer func() { try(instancesJSON.Close()) }()
 98
 99	instancesFile, err := os.OpenFile("INSTANCES.md", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) //nolint:gosec // G302
100	if err != nil {
101		exit(err.Error(), 1)
102	}
103	defer func() { try(instancesFile.Close()) }()
104
105	for {
106		if string(instances) == "" {
107			print("\rDownloading instance list...")
108		} else {
109			println("\r\033[2KDownloaded!")
110			try(json.Unmarshal(instances, &settingsVar))
111
112			settingsVar.Instances = append(settingsVar.Instances, settings{
113				Title:       prompt("Title", true),
114				Country:     prompt("Country", true),
115				ModifiedSrc: prompt("Link to modified sources", false),
116				Settings: settingsParams{
117					Nsfw:   CFG.Nsfw,
118					Proxy:  CFG.Proxy,
119					HideAI: CFG.HideAI,
120					Theme:  CFG.Theme,
121				},
122				Urls: settingsUrls{
123					Clearnet: prompt("Clearnet link", false),
124					Ygg:      prompt("Yggdrasil link", false),
125					Tor:      prompt("Onion link", false),
126					I2P:      prompt("I2P link", false),
127				},
128			})
129
130			j, err := json.MarshalIndent(&settingsVar, "", "    ")
131			try(err)
132
133			try(func() error { _, err := instancesJSON.Write(j); return err }())
134
135			settingsVar := &settingsVar.Instances[len(settingsVar.Instances)-1]
136			var mdstr bytes.Buffer
137
138			mdbuilder := func(yes bool, link string, title string) {
139				switch {
140				case yes && (title != "" && link != ""):
141					mdstr.WriteString("[")
142					mdstr.WriteString(title)
143					mdstr.WriteString("](")
144					mdstr.WriteString(link)
145					mdstr.WriteString(")")
146				case yes && link != "":
147					mdstr.WriteString("[Yes](")
148					mdstr.WriteString(link)
149					mdstr.WriteString(")")
150				case yes:
151					mdstr.WriteString("Yes")
152				default:
153					mdstr.WriteString("No")
154				}
155				mdstr.WriteString("|")
156			}
157
158			mdstr.WriteString("\n|")
159			mdbuilder(settingsVar.Urls.Clearnet != "", settingsVar.Urls.Clearnet, settingsVar.Title)
160
161			urls := []string{settingsVar.Urls.Ygg, settingsVar.Urls.I2P, settingsVar.Urls.Tor}
162			for i, l := 0, len(urls); i < l; i++ {
163				url := urls[i]
164				mdbuilder(url != "", url, "")
165			}
166
167			settings := []bool{settingsVar.Settings.Nsfw, settingsVar.Settings.Proxy}
168			for i, l := 0, len(settings); i < l; i++ {
169				mdbuilder(settings[i], "", "")
170			}
171
172			mdbuilder(settingsVar.ModifiedSrc != "", settingsVar.ModifiedSrc, "")
173
174			mdstr.WriteString(settingsVar.Country)
175			mdstr.WriteString("|")
176
177			try(func() error { _, err := instancesFile.Write(mdstr.Bytes()); return err }())
178			break
179		}
180		time.Sleep(500 * time.Millisecond)
181	}
182	exit("Done! Now add the files 'instances.json' and 'INSTANCES.md' to the 'main' branch in the repository https://github.com/krazywarez/skunky-art", 0)
183}