-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathcommands.go
329 lines (281 loc) · 7.75 KB
/
commands.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
// -*- tab-width: 4; -*-
package main
import (
"flag"
"fmt"
"log"
"os"
"regexp"
"sort"
"strings"
"time"
"github.com/peterh/liner"
)
func FollowingCommand(args []string) error {
fs := flag.NewFlagSet("following", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
rawFlag := fs.Bool("r", false, "output following users in machine parsable format")
fs.Usage = func() {
fmt.Printf("usage: %s following [arguments]\n\nDisplays a list of users being followed.\n\n", progname)
fs.PrintDefaults()
}
if err := fs.Parse(args); err != nil {
if err == flag.ErrHelp {
return nil
}
return fmt.Errorf("error parsing arguments")
}
if fs.NArg() > 0 {
return fmt.Errorf("too many arguments given")
}
for nick, url := range conf.Following {
if *rawFlag {
PrintFolloweeRaw(nick, url)
} else {
PrintFollowee(nick, url)
}
fmt.Println()
}
return nil
}
func FollowCommand(args []string) error {
fs := flag.NewFlagSet("follow", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
fs.Usage = func() {
fmt.Printf("usage: %s follow <nick> <twturl>\n\nStart following @<nick url>.\n\n", progname)
fs.PrintDefaults()
}
if err := fs.Parse(args); err != nil {
if err == flag.ErrHelp {
return nil
}
return fmt.Errorf("error parsing arguments")
}
if fs.NArg() < 2 {
return fmt.Errorf("too few arguments given")
}
nick := fs.Args()[0]
url := fs.Args()[1]
conf.Following[nick] = url
if err := conf.Write(); err != nil {
return fmt.Errorf("error: writing config failed with %s", err)
}
fmt.Printf("%s successfully started following %s @ %s", yellow("✓"), blue(nick), url)
return nil
}
func UnfollowCommand(args []string) error {
fs := flag.NewFlagSet("unfollow", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
fs.Usage = func() {
fmt.Printf("usage: %s unfollow <nick>\n\nStop following @nick.\n\n", progname)
fs.PrintDefaults()
}
if err := fs.Parse(args); err != nil {
if err == flag.ErrHelp {
return nil
}
return fmt.Errorf("error parsing arguments")
}
if fs.NArg() < 1 {
return fmt.Errorf("too few arguments given")
}
nick := fs.Args()[0]
delete(conf.Following, nick)
if err := conf.Write(); err != nil {
return fmt.Errorf("error: writing config failed with %s", err)
}
fmt.Printf("%s successfully stopped following %s", yellow("✓"), blue(nick))
return nil
}
func TimelineCommand(args []string) error {
fs := flag.NewFlagSet("timeline", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
durationFlag := fs.Duration("d", 0, "only show tweets created at most `duration` back in time. Example: -d 12h")
sourceFlag := fs.String("s", "", "only show timeline for given nick (URL, if dry-run)")
fullFlag := fs.Bool("f", false, "display full timeline (overrides timeline config)")
dryFlag := fs.Bool("n", false, "dry-run, only locally cached tweets")
rawFlag := fs.Bool("r", false, "output tweets in URL-prefixed twtxt format")
reversedFlag := fs.Bool("desc", false, "tweets shown in descending order (newer tweets at top)")
fs.Usage = func() {
fmt.Printf("usage: %s timeline [arguments]\n\nDisplays the timeline.\n\n", progname)
fs.PrintDefaults()
}
if err := fs.Parse(args); err != nil {
if err == flag.ErrHelp {
return nil
}
return fmt.Errorf("error parsing arguments")
}
if fs.NArg() > 0 {
return fmt.Errorf("too many arguments given")
}
if *durationFlag < 0 {
return fmt.Errorf("negative duration doesn't make sense")
}
if *fullFlag {
if *durationFlag > 0 {
return fmt.Errorf("full timeline with duration makes no sense")
}
conf.Timeline = "full"
}
cache := LoadCache(configpath)
cacheLastModified, err := CacheLastModified(configpath)
if err != nil {
return fmt.Errorf("error calculating last modified cache time: %s", err)
}
var sourceURL string
if !*dryFlag {
var sources = conf.Following
if conf.IncludeYourself {
sources[conf.Nick] = conf.Twturl
}
if *sourceFlag != "" {
url, ok := conf.Following[*sourceFlag]
if !ok {
return fmt.Errorf("no source with nick %q", *sourceFlag)
}
sources = make(map[string]string)
sources[*sourceFlag] = url
sourceURL = url
}
cache.FetchTweets(sources)
cache.Store(configpath)
// Did the url for *sourceFlag change?
if sources[*sourceFlag] != conf.Following[*sourceFlag] {
sources[*sourceFlag] = conf.Following[*sourceFlag]
sourceURL = conf.Following[*sourceFlag]
}
}
if debug && *dryFlag {
log.Print("dry run\n")
}
var tweets Tweets
if *sourceFlag != "" {
tweets = cache.GetByURL(sourceURL)
} else {
for _, url := range conf.Following {
tweets = append(tweets, cache.GetByURL(url)...)
}
}
if *reversedFlag {
sort.Sort(sort.Reverse(tweets))
} else {
sort.Sort(tweets)
}
now := time.Now()
for _, tweet := range tweets {
if (*durationFlag > 0 && now.Sub(tweet.Created) <= *durationFlag) ||
(conf.Timeline == "full" && *durationFlag == 0) ||
(conf.Timeline == "new" && tweet.Created.Sub(cacheLastModified) >= 0) {
if !*rawFlag {
PrintTweet(tweet, now)
} else {
PrintTweetRaw(tweet)
}
fmt.Println()
}
}
return nil
}
func TweetCommand(args []string) error {
fs := flag.NewFlagSet("tweet", flag.ContinueOnError)
fs.SetOutput(os.Stdout)
fs.Usage = func() {
fmt.Printf(`usage: %s tweet [words]
or: %s twet [words]
Adds a new tweet to your twtfile. Words are joined together with a single
space. If no words are given, user will be prompted to input the text
interactively.
`, progname, progname)
fs.PrintDefaults()
}
if err := fs.Parse(args); err != nil {
if err == flag.ErrHelp {
return nil
}
return fmt.Errorf("error parsing arguments")
}
twtfile := conf.Twtfile
if twtfile == "" {
return fmt.Errorf("cannot tweet without twtfile set in config")
}
// We don't support shell style ~user/foo.txt :P
if strings.HasPrefix(twtfile, "~/") {
twtfile = strings.Replace(twtfile, "~", homedir, 1)
}
var text string
if fs.NArg() == 0 {
var err error
if text, err = getLine(); err != nil {
return fmt.Errorf("readline: %v", err)
}
} else {
text = strings.Join(fs.Args(), " ")
}
text = strings.TrimSpace(text)
if text == "" {
return fmt.Errorf("cowardly refusing to tweet empty text, or only spaces")
}
text = fmt.Sprintf("%s\t%s\n", time.Now().Format(time.RFC3339), ExpandMentions(text))
f, err := os.OpenFile(twtfile, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
return err
}
defer f.Close()
var n int
if n, err = f.WriteString(text); err != nil {
return err
}
fmt.Printf("appended %d bytes to %s:\n%s", n, conf.Twtfile, text)
return nil
}
func getLine() (string, error) {
l := liner.NewLiner()
defer l.Close()
l.SetCtrlCAborts(true)
l.SetMultiLineMode(true)
l.SetTabCompletionStyle(liner.TabCircular)
l.SetBeep(false)
var tags, nicks []string
for tag := range LoadCache(configpath).GetAll().Tags() {
tags = append(tags, tag)
}
sort.Strings(tags)
for nick := range conf.Following {
nicks = append(nicks, nick)
}
sort.Strings(nicks)
l.SetCompleter(func(line string) (candidates []string) {
i := strings.LastIndexAny(line, "@#")
if i == -1 {
return
}
vocab := nicks
if line[i] == '#' {
vocab = tags
}
i++
for _, item := range vocab {
if strings.HasPrefix(strings.ToLower(item), strings.ToLower(line[i:])) {
candidates = append(candidates, line[:i]+item)
}
}
return
})
return l.Prompt("> ")
}
// Turns "@nick" into "@<nick URL>" if we're following nick.
func ExpandMentions(text string) string {
re := regexp.MustCompile(`@([_a-zA-Z0-9]+)`)
return re.ReplaceAllStringFunc(text, func(match string) string {
parts := re.FindStringSubmatch(match)
mentionednick := parts[1]
for followednick, followedurl := range conf.Following {
if mentionednick == followednick {
return fmt.Sprintf("@<%s %s>", followednick, followedurl)
}
}
// Not expanding if we're not following
return match
})
}