aboutsummaryrefslogtreecommitdiff
path: root/web/mastodon/examples/mkapp.go
blob: 04dd666942aebf5cc276f2cb37954379567a389d (plain)
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
//go:build ignore

package main

import (
	"bufio"
	"context"
	"fmt"
	"log"
	"os"
	"strings"
	"time"

	"within.website/x/web/mastodon"
)

func promptInput(prompt string) (string, error) {
	fmt.Fprint(os.Stderr, prompt)
	fmt.Fprint(os.Stderr, ": ")
	reader := bufio.NewReader(os.Stdin)
	// ReadString will block until the delimiter is entered
	input, err := reader.ReadString('\n')
	if err != nil {
		return "", err
	}

	// remove the delimeter from the string
	input = strings.TrimSuffix(input, "\n")
	return input, nil
}

func main() {
	instance, err := promptInput("URL of the mastodon server (incl https://)")
	if err != nil {
		log.Fatal(err)
	}

	cli, err := mastodon.Unauthenticated("Xe/x test", "https://within.website/.x.botinfo", instance)
	if err != nil {
		log.Fatal(err)
	}

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
	defer cancel()

	app, err := cli.CreateApplication(ctx, mastodon.CreateApplicationRequest{
		ClientName:   "Xe/x test",
		RedirectURIs: "urn:ietf:wg:oauth:2.0:oob", // default if not set
		Scopes:       "read write follow push",    // default if not set
		Website:      "https://within.website/.x.botinfo",
	})

	if err != nil {
		log.Fatal(err)
	}

	authURL, err := cli.AuthorizeURL(app, "read write follow push")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(authURL)

	code, err := promptInput("please paste the code")
	if err != nil {
		log.Fatal(err)
	}

	tokenInfo, err := cli.FetchToken(ctx, app, code, "read write follow push")
	if err != nil {
		log.Fatal(err)
	}

	cli, err = mastodon.Authenticated("Xe/x test", "https://within.website/.x.botinfo", instance, tokenInfo.AccessToken)
	if err != nil {
		log.Fatal(err)
	}

	if err := cli.VerifyCredentials(ctx); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("MASTODON_CLIENT_ID=%s\nMASTODON_CLIENT_SECRET=%s\nMASTODON_INSTANCE=%s\nMASTODON_TOKEN=%s", app.ClientID, app.ClientSecret, instance, tokenInfo.AccessToken)
}