drivel/drivel.go

490 lines
12 KiB
Go
Raw Normal View History

2019-01-01 19:35:22 +01:00
package main
import (
"encoding/json"
"errors"
2020-09-27 11:46:52 +02:00
"flag"
2019-01-01 19:35:22 +01:00
"fmt"
2020-10-11 13:14:57 +02:00
goutil "git.gutmet.org/goutil.git/misc"
2019-01-01 19:35:22 +01:00
"io/ioutil"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
2020-09-18 20:49:46 +02:00
"time"
2019-01-01 19:35:22 +01:00
)
const (
2020-09-27 11:46:52 +02:00
CHARACTER_LIMIT = 280
WIPE_KEEP_DAYS = 10
STATUS_ENDPOINT = "https://api.twitter.com/1.1/statuses/update.json"
MENTIONS_ENDPOINT = "https://api.twitter.com/1.1/statuses/mentions_timeline.json?tweet_mode=extended&count=200"
HOME_ENDPOINT = "https://api.twitter.com/1.1/statuses/home_timeline.json?tweet_mode=extended&count=200"
TIMELINE_ENDPOINT = "https://api.twitter.com/1.1/statuses/user_timeline.json?tweet_mode=extended&count=200"
LIKES_TIMELINE_ENDPOINT = "https://api.twitter.com/1.1/favorites/list.json?tweet_mode=extended&count=200"
LOOKUP_ENDPOINT = "https://api.twitter.com/1.1/statuses/lookup.json?tweet_mode=extended"
RETWEET_ENDPOINT = "https://api.twitter.com/1.1/statuses/retweet/"
LIKE_ENDPOINT = "https://api.twitter.com/1.1/favorites/create.json"
DESTROY_STATUS_ENDPOINT = "https://api.twitter.com/1.1/statuses/destroy/"
DESTROY_LIKE_ENDPOINT = "https://api.twitter.com/1.1/favorites/destroy.json"
2019-01-01 19:35:22 +01:00
)
func optLogFatal(decorum string, err error) {
2020-09-18 23:22:42 +02:00
if err != nil && err.Error() != "" {
2019-01-01 19:35:22 +01:00
fmt.Fprintln(os.Stderr, "drivel: "+decorum+": "+err.Error())
os.Exit(-1)
}
}
2020-09-27 11:46:52 +02:00
func get(url string) []byte {
return _send(url, nil, false)
}
2020-09-27 11:46:52 +02:00
func send(url string, vals url.Values) []byte {
return _send(url, vals, true)
}
2020-09-27 11:46:52 +02:00
func _send(url string, vals url.Values, usePost bool) []byte {
2019-01-01 19:35:22 +01:00
log := func(err error) {
v, _ := json.Marshal(vals)
2020-09-18 23:22:42 +02:00
optLogFatal("get/post "+url+" "+string(v), err)
2019-01-01 19:35:22 +01:00
}
var resp *http.Response
var err error
if usePost {
resp, err = client.PostForm(url, vals)
} else {
resp, err = client.Get(url)
}
2019-01-01 19:35:22 +01:00
log(err)
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
2020-08-08 12:00:45 +02:00
if resp.StatusCode < 200 || resp.StatusCode > 299 {
2020-08-08 11:52:42 +02:00
fmt.Fprintln(os.Stderr, "response:", resp, "\n")
fmt.Fprintln(os.Stderr, "body:", string(body), "\n")
log(errors.New("HTTP status " + fmt.Sprint(resp.StatusCode)))
}
2019-01-01 19:35:22 +01:00
log(err)
return body
}
func lastSpace(slice []rune) int {
for i := len(slice) - 1; i >= 0; i-- {
if slice[i] == ' ' {
return i
2019-01-01 19:35:22 +01:00
}
}
return -1
2019-01-01 19:35:22 +01:00
}
func splitStatus(status string) []string {
characterLimit := CHARACTER_LIMIT
// Twitter has an insane definition of what counts as a character
// ( see https://developer.twitter.com/en/docs/counting-characters )
// - as a crude approximation, anything outside LATIN-1 halfs the limit
for _, ch := range status {
if ch > 0x10FF {
characterLimit = CHARACTER_LIMIT / 2
break
}
}
asRunes := []rune(status)
2019-01-01 19:35:22 +01:00
split := []string{}
for len(asRunes) != 0 {
var limit int
if len(asRunes) <= characterLimit {
limit = len(asRunes)
2019-01-01 19:35:22 +01:00
} else {
limit = lastSpace(asRunes[0:characterLimit])
if limit == -1 {
limit = characterLimit
} else {
limit = limit + 1
}
2019-01-01 19:35:22 +01:00
}
split = append(split, string(asRunes[0:limit]))
asRunes = asRunes[limit:]
2019-01-01 19:35:22 +01:00
}
return split
}
func splitArguments(args []string) data {
if len(args) < 1 {
fmt.Fprintln(os.Stderr, "Usage: drivel status STATUS [FILE1 FILE2 ...]")
2019-01-01 19:35:22 +01:00
os.Exit(-1)
}
d := data{}
d.status = splitStatus(args[0])
for _, arg := range args[1:] {
2019-01-01 19:35:22 +01:00
exitIfInvalid(arg)
switch kind(arg) {
case PIC:
d.pics = append(d.pics, arg)
case GIF:
d.gifs = append(d.gifs, arg)
case VIDEO:
d.videos = append(d.videos, arg)
default:
optLogFatal("splitArguments", errors.New("Unsupported file: "+arg))
}
}
return d
}
func tweet(status string, mediaIDs []ObjectID, previousID ObjectID) Status {
2019-01-01 19:35:22 +01:00
log := func(err error) { optLogFatal("tweet "+status, err) }
request := UpdateStatusRequest(status, mediaIDs, previousID)
2020-09-27 11:46:52 +02:00
body := send(STATUS_ENDPOINT, request)
var tweet Status
err := json.Unmarshal(body, &tweet)
2019-01-01 19:35:22 +01:00
log(err)
log(tweet)
return tweet
2019-01-01 19:35:22 +01:00
}
type data struct {
status []string
pics []string
gifs []string
videos []string
}
func (d *data) getStatus(i int) string {
return goutil.StrSliceAt(d.status, i)
}
func (d *data) getGif(i int) string {
return goutil.StrSliceAt(d.gifs, i)
}
func (d *data) getVideo(i int) string {
return goutil.StrSliceAt(d.videos, i)
}
2020-09-27 11:46:52 +02:00
func (d *data) uploadPics(from, to int) []ObjectID {
2019-01-01 19:35:22 +01:00
pics := goutil.StrSlice(d.pics, from, to)
2020-09-27 11:46:52 +02:00
return uploadAll(pics)
2019-01-01 19:35:22 +01:00
}
2020-09-27 11:46:52 +02:00
func (d *data) uploadGif(i int) []ObjectID {
2019-01-01 19:35:22 +01:00
gif := d.getGif(i)
2020-09-27 11:46:52 +02:00
return uploadAll([]string{gif})
2019-01-01 19:35:22 +01:00
}
2020-09-27 11:46:52 +02:00
func (d *data) uploadVideo(i int) []ObjectID {
2019-01-01 19:35:22 +01:00
vid := d.getVideo(i)
2020-09-27 11:46:52 +02:00
return uploadAll([]string{vid})
2019-01-01 19:35:22 +01:00
}
func (d *data) push(previous ObjectID) []Status {
2019-01-01 19:35:22 +01:00
empty := false
i, g, v := 0, 0, 0
tweets := []Status{}
if d == nil {
return tweets
}
2019-01-01 19:35:22 +01:00
for !empty {
empty = true
status := d.getStatus(i)
mediaIDs := []ObjectID{}
if status != "" {
empty = false
}
from := i * 4
to := (i + 1) * 4
2020-09-27 11:46:52 +02:00
mediaIDs = d.uploadPics(from, to)
2019-01-01 19:35:22 +01:00
if len(mediaIDs) == 0 {
2020-09-27 11:46:52 +02:00
mediaIDs = d.uploadGif(g)
2019-01-01 19:35:22 +01:00
g++
}
if len(mediaIDs) == 0 {
2020-09-27 11:46:52 +02:00
mediaIDs = d.uploadVideo(v)
2019-01-01 19:35:22 +01:00
v++
}
if len(mediaIDs) > 0 {
empty = false
}
if !empty {
t := tweet(status, mediaIDs, previous)
tweets = append(tweets, t)
previous = ObjectID(t.Id_str)
2019-01-01 19:35:22 +01:00
i++
}
}
return tweets
2019-01-01 19:35:22 +01:00
}
func updateStatus(args []string, previous ObjectID, embedTweet ObjectID) []Status {
d := splitArguments(args)
2020-09-19 22:12:59 +02:00
if embedTweet != "" {
2020-09-27 11:46:52 +02:00
tweets := _lookup([]string{string(embedTweet)})
2020-09-19 22:12:59 +02:00
if len(tweets) == 1 {
d.status[0] += " " + tweets[0].URL()
}
}
return d.push(previous)
}
func PrintTweets(tweets []Status, userFilter hashset) {
for _, tweet := range tweets {
if !userFilter.contains(tweet.User.Screen_name) {
fmt.Println(tweet.String())
fmt.Println("---------")
}
}
2020-09-17 21:30:51 +02:00
}
func status(args []string) error {
tweets := updateStatus(args, "", "")
PrintTweets(tweets, nil)
return nil
}
2020-09-17 21:44:57 +02:00
func reply(args []string) error {
if len(args) < 2 {
fmt.Fprintln(os.Stderr, "Usage: drivel reply TWEET_ID MESSAGE [FILE1 FILE2 ...]")
2020-09-17 21:44:57 +02:00
os.Exit(-1)
}
tweets := updateStatus(args[1:], ObjectID(args[0]), "")
PrintTweets(tweets, nil)
2020-09-19 22:12:59 +02:00
return nil
}
func quote(args []string) error {
if len(args) < 2 {
fmt.Println(os.Stderr, "Usage: drivel quote TWEET_ID MESSAGE [FILE1 FILE2 ...]")
2020-09-19 22:12:59 +02:00
os.Exit(-1)
}
tweets := updateStatus(args[1:], "", ObjectID(args[0]))
PrintTweets(tweets, nil)
2020-09-17 21:44:57 +02:00
return nil
}
2020-09-27 11:46:52 +02:00
func _lookup(ids []string) []Status {
2020-09-19 22:12:59 +02:00
log := func(err error) { optLogFatal("lookup "+strings.Join(ids, ","), err) }
2020-09-27 11:46:52 +02:00
body := get(LOOKUP_ENDPOINT + LookupParameters(ids))
2020-09-19 22:12:59 +02:00
var tweets []Status
err := json.Unmarshal(body, &tweets)
log(err)
return tweets
}
func lookup(args []string) error {
if len(args) < 1 {
fmt.Fprintln(os.Stderr, "USAGE: drivel lookup TWEET_ID1 [TWEET_ID2 TWEET_ID3 ...]")
os.Exit(-1)
}
2020-09-27 11:46:52 +02:00
tweets := _lookup(args)
PrintTweets(tweets, nil)
return nil
}
func timeline(endpoint string) []Status {
2020-09-17 21:44:57 +02:00
log := func(err error) { optLogFatal("timeline", err) }
2020-09-27 11:46:52 +02:00
body := get(endpoint)
2020-09-17 21:44:57 +02:00
var tweets []Status
err := json.Unmarshal(body, &tweets)
log(err)
2020-09-27 11:46:52 +02:00
return tweets
2020-09-17 21:44:57 +02:00
}
func mentions(args []string) error {
tweets := timeline(MENTIONS_ENDPOINT)
PrintTweets(tweets, mentionsFilter)
return nil
}
2020-09-17 21:44:57 +02:00
func home(args []string) error {
tweets := timeline(HOME_ENDPOINT)
PrintTweets(tweets, homeFilter)
2020-09-17 21:30:51 +02:00
return nil
}
func userTimeline(flags userTimelineFlags, args []string) error {
tweets := timeline(TIMELINE_ENDPOINT + UserTimelineParameters(flags, args[0]))
PrintTweets(tweets, nil)
2020-09-20 20:37:12 +02:00
return nil
}
type userTimelineFlags struct {
withReplies bool
}
func userTimelineCommand() (goutil.CommandFlagsInit, goutil.CommandFunc) {
f := userTimelineFlags{}
flagsInit := func(s *flag.FlagSet) {
s.BoolVar(&f.withReplies, "with-replies", false, "include replies in timeline")
}
return flagsInit, func(args []string) error { return userTimeline(f, args) }
}
2020-09-19 22:31:09 +02:00
func retweet(args []string) error {
log := func(err error) { optLogFatal("retweet", err) }
if len(args) != 1 {
fmt.Fprintln(os.Stderr, "USAGE: drivel retweet TWEET_ID")
os.Exit(-1)
}
id := args[0]
2020-09-27 11:46:52 +02:00
tweets := _lookup([]string{id})
2020-09-19 22:31:09 +02:00
if len(tweets) != 1 {
log(errors.New("Could not find tweet " + id))
}
2020-09-27 11:46:52 +02:00
body := send(RETWEET_ENDPOINT+RetweetParameters(id), nil)
2020-09-19 22:31:09 +02:00
var retweet Status
err := json.Unmarshal(body, &retweet)
log(err)
PrintTweets([]Status{retweet}, nil)
2020-09-19 22:31:09 +02:00
return nil
}
2020-09-18 09:18:32 +02:00
func like(args []string) error {
log := func(err error) { optLogFatal("like", err) }
if len(args) != 1 {
fmt.Fprintln(os.Stderr, "USAGE: drivel like TWEET_ID")
os.Exit(-1)
}
2020-09-27 11:46:52 +02:00
body := send(LIKE_ENDPOINT, LikeRequest(args[0]))
2020-09-18 09:18:32 +02:00
var tweet Status
err := json.Unmarshal(body, &tweet)
log(err)
PrintTweets([]Status{tweet}, nil)
2020-09-18 09:18:32 +02:00
return nil
}
2020-09-27 11:46:52 +02:00
func unlike(id string) {
log := func(err error) { optLogFatal("unlike", err) }
body := send(DESTROY_LIKE_ENDPOINT, UnlikeRequest(id))
var tweet Status
err := json.Unmarshal(body, &tweet)
log(err)
fmt.Println("Unliked", tweet.Id_str)
}
func destroyStatus(id string) {
log := func(err error) { optLogFatal("destroy", err) }
body := send(DESTROY_STATUS_ENDPOINT+DestroyParameters(id), nil)
var tweet Status
err := json.Unmarshal(body, &tweet)
log(err)
fmt.Println("Destroyed", tweet.Id_str)
}
func wipeTimeline(likes bool, keepDays int) {
var endpoint string
if likes {
endpoint = LIKES_TIMELINE_ENDPOINT
} else {
endpoint = TIMELINE_ENDPOINT
}
n := 0
now := time.Now()
tweets := timeline(endpoint)
2020-09-27 11:46:52 +02:00
for {
for _, tweet := range tweets {
daysSince := now.Sub(tweet.Created_at.Time).Hours() / 24
if tweet.Created_at != (TwitterTime{}) && daysSince >= float64(keepDays) {
if likes {
unlike(tweet.Id_str)
} else {
destroyStatus(tweet.Id_str)
}
n++
if n >= 200 {
fmt.Println("reached limit of 200")
return
}
}
}
newTweets := timeline(endpoint)
2020-09-27 11:46:52 +02:00
if !equals(newTweets, tweets) {
tweets = newTweets
} else {
return
}
}
}
func wipe(flags wipeFlags) error {
wipeTimeline(true, flags.keepDays)
wipeTimeline(false, flags.keepDays)
return nil
}
type wipeFlags struct {
keepDays int
}
func wipeCommand() (goutil.CommandFlagsInit, goutil.CommandFunc) {
f := wipeFlags{}
flagsInit := func(s *flag.FlagSet) {
s.IntVar(&f.keepDays, "keep-days", WIPE_KEEP_DAYS, "don't wipe the last N days")
2020-09-27 11:46:52 +02:00
}
return flagsInit, func([]string) error { return wipe(f) }
}
type hashset map[string]interface{}
func makeHashset() hashset {
return make(map[string]interface{})
}
func (s hashset) add(member string) {
if s != nil {
s[member] = nil
}
}
func (s hashset) contains(member string) bool {
if s == nil {
return false
}
if _, ok := s[member]; ok {
return true
} else {
return false
}
}
func setFilters(appDir string) {
getHashset := func(s string, err error) hashset {
set := makeHashset()
if err == nil {
for _, id := range strings.Split(s, "\n") {
2020-10-15 14:56:43 +02:00
if trimmed := strings.TrimSpace(id); trimmed != "" {
set.add(trimmed)
}
}
}
return set
}
homeFilter = getHashset(goutil.ReadFile(filepath.Join(appDir, "FilterHome")))
mentionsFilter = getHashset(goutil.ReadFile(filepath.Join(appDir, "FilterMentions")))
}
2020-09-27 11:46:52 +02:00
var client *http.Client
var homeFilter hashset
var mentionsFilter hashset
2020-09-27 11:46:52 +02:00
func main() {
2020-09-27 11:46:52 +02:00
client = getClient()
setFilters(appDir())
commands := []goutil.Command{
goutil.NewCommand("status", status, "post a status with message and/or media"),
2020-09-17 21:44:57 +02:00
goutil.NewCommand("home", home, "get your home timeline"),
goutil.NewCommand("mentions", mentions, "get your mention timeline"),
goutil.NewCommandWithFlags("timeline", userTimelineCommand, "get timeline of a specific user"),
goutil.NewCommand("lookup", lookup, "lookup tweets with specific IDs"),
2020-09-17 21:30:51 +02:00
goutil.NewCommand("reply", reply, "reply to a tweet with a specific ID"),
2020-09-19 22:12:59 +02:00
goutil.NewCommand("quote", quote, "quote retweet a tweet with a specific ID"),
2020-09-19 22:31:09 +02:00
goutil.NewCommand("retweet", retweet, "retweet a tweet with a specific ID"),
2020-09-18 09:18:32 +02:00
goutil.NewCommand("like", like, "like a tweet with a specific ID"),
2020-09-27 11:46:52 +02:00
goutil.NewCommandWithFlags("wipe", wipeCommand, "wipe your timeline and likes"),
}
err := goutil.Execute(commands)
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
2019-01-01 19:35:22 +01:00
}