-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
338 lines (301 loc) · 8.77 KB
/
main.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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
// fortune is a stripped-down implementation of the classic BSD Unix
// fortune command. Unlike the BSD fortune command (or my own Python version,
// at https://github.com/bmc/fortune), this version does not use an index file.
// We have loads of memory these days, and fortunes files aren't that big, so
// it's feasible to load the whole text file in memory, parse it on the fly,
// and randomly choose a resulting fortune.
//
// See the accompanying README for more information.
package main
import (
"bufio"
"bytes"
"encoding/xml"
"fmt"
"io/ioutil"
"log"
"math/rand"
"os"
"path"
"strings"
"time"
"git.sr.ht/~adnano/go-gemini"
"github.com/qpliu/qrencode-go/qrencode"
"github.com/t-900-a/rss"
)
const VERSION = "1.0"
// ---------------------------------------------------------------------------
// Local error object that conforms to the Go error interface.
// ---------------------------------------------------------------------------
type Error struct {
Message string
}
func (e *Error) Error() string {
return e.Message
}
// ---------------------------------------------------------------------------
// Local functions
// ---------------------------------------------------------------------------
// Convenience function to print a message (printf style) to standard error
// and exit with a non-zero exit code.
func die(format string, args ...interface{}) {
os.Stderr.WriteString(fmt.Sprintf(format, args...) + "\n")
os.Exit(1)
}
// Given a path representing a fortune file, load the file, parse it,
// an return an array of fortune strings.
func readFortuneFile(fortuneFile string) ([]string, error) {
content, err := ioutil.ReadFile(fortuneFile)
var fortunes []string = nil
if err == nil {
fortunes = strings.Split(string(content), "\n%\n")
}
return fortunes, err
}
// Given a path representing a fortune file, load the file, parse it,
// choose a random fortune, and display it to standard output. Returns
// a Go error object on error or nil on success.
func getFortune(fortuneFile string) (string, error) {
fortunes, err := readFortuneFile(fortuneFile)
if err == nil {
rand.Seed(time.Now().UTC().UnixNano())
i := rand.Int() % len(fortunes)
return fortunes[i], nil
}
return "", err
}
func getEmoji() string {
var buf bytes.Buffer
rand.Seed(time.Now().UTC().UnixNano())
i := rand.Int() % len(emojis)
buf.WriteRune(emojis[i])
return buf.String()
}
// Parse the command line arguments. For now, this is simple, because this
// program requires very few arguments. If something more complicated is
// needed, consider the Go "flag" module or github.com/docopt/docopt-go
func parseArgs() (string, string, string, string, string, error) {
prog := path.Base(os.Args[0])
usage := fmt.Sprintf(`%s, version %s
Usage:
%s [/path/to/fortune/cookie/file]
%s [payment uri]
%s [tx hash]
%s -h|--help
If the fortune cookie file path is omitted, the contents of environment
variable FORTUNE_FILE will be used. If neither is available, fortune will
abort.`, prog, VERSION, prog, prog)
// TODO REDO variable handling
var fortuneFile string
var websiteUri string
var txHash string
var pmtUri string
var pmtViewKey string
var err error
switch len(os.Args) {
case 2:
fortuneFile = os.Args[1]
case 3:
fortuneFile = os.Args[1]
websiteUri = os.Args[2]
case 4:
fortuneFile = os.Args[1]
websiteUri = os.Args[2]
txHash = os.Args[3]
case 5:
fortuneFile = os.Args[1]
websiteUri = os.Args[2]
txHash = os.Args[3]
pmtUri = os.Args[4]
case 6:
fortuneFile = os.Args[1]
websiteUri = os.Args[2]
txHash = os.Args[3]
pmtUri = os.Args[4]
pmtViewKey = os.Args[5]
case 7:
{
if (os.Args[1] == "-h") || (os.Args[1] == "--help") {
err = &Error{usage}
} else {
fortuneFile = os.Args[1]
}
}
default:
err = &Error{usage}
}
if (err == nil) && (fortuneFile == "") {
err = &Error{"No fortunes parameter and no FORTUNE_FILE " +
"environment variable"}
}
return fortuneFile, websiteUri, txHash, pmtUri, pmtViewKey, err
}
// ---------------------------------------------------------------------------
// Main program
// ---------------------------------------------------------------------------
func main() {
ti := time.Now()
fortuneFile, websiteUri, txHash, pmtUri, pmtViewKey, err := parseArgs()
if err != nil {
die(err.Error())
}
if len(txHash) > 0 {
// tx-notify runs 3 times per transaction, we only want to run the bot 1 time per transaction
file, err := os.OpenFile("lastrun.txt", os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
log.Fatal(err)
}
defer file.Close()
b, err := ioutil.ReadAll(file)
if string(b) == txHash {
log.Fatal("TX already processed")
os.Exit(0)
} else {
_, err := file.WriteAt([]byte(txHash), 0) // Write at 0 beginning
if err != nil {
log.Fatalf("failed writing to file: %s", err)
}
}
}
fortune, err := getFortune(fortuneFile)
if err != nil {
die(err.Error())
}
// write fortune to gemini text
var t gemini.Text
title := getEmoji() + " New Fortune " + getEmoji()
heading := gemini.LineHeading1(title)
t = append(t, heading)
newLine := gemini.LineText("\n")
t = append(t, newLine)
if len(txHash) > 0 {
link := "https://xmrchain.net/tx/" + txHash
txt := "Fortune requested, associated transaction found here"
blockExplorer := &gemini.LineLink{URL: link, Name: txt}
t = append(t, blockExplorer)
}
newLine = gemini.LineText("\n")
t = append(t, newLine)
body := "```" + botsay(fortune) + "```"
scanner := bufio.NewScanner(strings.NewReader(body))
for scanner.Scan() {
fortuneLine := gemini.LineText(scanner.Text())
t = append(t, fortuneLine)
}
dateLine := gemini.LineQuote(ti.Format("2006-01-02T15:04:05Z"))
t = append(t, dateLine)
newLine = gemini.LineText("\n")
t = append(t, newLine)
if len(pmtUri) > 0 {
txt := "Curious about today's fortune? Send any amount of Monero and you will get your very own."
pmtAddress := &gemini.LineLink{URL: pmtUri, Name: txt}
t = append(t, pmtAddress)
// generate qr code to scan
// only works for gemini cli clients
newLine = gemini.LineText("\n")
t = append(t, newLine)
grid, err := qrencode.Encode(pmtUri, qrencode.ECLevelL)
if err != nil {
log.Fatal(err)
}
var b bytes.Buffer
grid.TerminalOutput(&b)
qrCode := "```" + b.String() + "```"
scanner := bufio.NewScanner(strings.NewReader(qrCode))
for scanner.Scan() {
fortuneLine := gemini.LineText(scanner.Text())
t = append(t, fortuneLine)
}
newLine = gemini.LineText("\n")
t = append(t, newLine)
txt = "Don't have any Monero? Learn more here"
link := "https://getmonero.org/"
info := &gemini.LineLink{URL: link, Name: txt}
t = append(t, info)
}
fileName := "fortune_" + ti.Format("2006_01_02_15_04_05") + ".gmi"
file, err := os.Create(fileName)
if err != nil {
log.Fatal(err)
}
defer file.Close()
for _, line := range t {
file.WriteString(line.String() + "\n")
}
// write ATOM FEED
// TODO read and append to existing feed if there
// payment data
var pmtData []rss.AtomLink
pmtLink := rss.AtomLink{
Href: pmtUri,
Rel: "payment",
Type: "application/monero-paymentrequest",
}
pmtData = append(pmtData, pmtLink)
pmtLink = rss.AtomLink{
Href: pmtViewKey,
Rel: "payment",
Type: "application/monero-viewkey",
}
pmtData = append(pmtData, pmtLink)
// feed website
var websiteLink []rss.AtomLink
wbLink := rss.AtomLink{
Href: websiteUri,
}
websiteLink = append(websiteLink, wbLink)
// this item
var itemLink []rss.AtomLink
thisLink := websiteUri + "/gemlog/" + fileName
itmLink := rss.AtomLink{
Href: thisLink,
}
itemLink = append(itemLink, itmLink)
// feed items
var feedItems []rss.AtomItem
feedItem := rss.AtomItem{
Title: title,
Content: rss.RAWContent{RAWContent: "Anon was provided with their fortune, ready for yours?"},
Links: itemLink,
Date: ti.Format("2006-01-02T15:04:05Z"),
ID: fileName,
}
feedItems = append(feedItems, feedItem)
feed := &rss.AtomFeed{
Title: "Fortune Bot",
Description: "Your seer in the Gemini Space",
Author: rss.AtomAuthor{
Name: "Anon",
URI: websiteUri,
Extensions: pmtData,
},
Link: websiteLink,
Items: feedItems,
Updated: ti.Format("2006-01-02T15:04:05Z"),
}
atomFile, err := xml.MarshalIndent(feed, "", " ")
if err != nil {
log.Fatal(err)
}
err = ioutil.WriteFile("atom.xml", atomFile, 0644)
if err != nil {
log.Fatal(err)
}
// write entry to the gemlog
// assumes the script is ran within the /gemlog/ directory
gemlog, err := os.OpenFile("index.gmi", os.O_RDWR|os.O_CREATE, 0644)
if err != nil {
log.Fatal(err)
}
defer gemlog.Close()
var offset int64 = 0
var whence int = 2 // end of file
newPosition, err := gemlog.Seek(offset, whence)
if err != nil {
log.Fatal(err)
}
_, err = gemlog.WriteAt([]byte("\n=> "+fileName+" "+title), newPosition) // Write at end
if err != nil {
log.Fatalf("failed writing to file: %s", err)
}
}