summaryrefslogtreecommitdiff
path: root/internal/platforms/platform.go
blob: 99169f1bc28dcb5522c8587ed36064e97505b041 (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
85
86
87
88
89
90
91
package platforms

import (
	"context"
	"fmt"
	"strings"

	"codeberg.org/snonux/gos/internal/colour"
	"codeberg.org/snonux/gos/internal/config"
	"codeberg.org/snonux/gos/internal/entry"
	"codeberg.org/snonux/gos/internal/platforms/linkedin"
	"codeberg.org/snonux/gos/internal/platforms/mastodon"
	"codeberg.org/snonux/gos/internal/platforms/noop"
)

type Platform string

var aliases = map[string]string{
	"linkedin": "linkedin",
	"li":       "linkedin",
	"mastodon": "mastodon",
	"ma":       "mastodon",
	"no":       "noop",
	"noop":     "noop",
	"xcom":     "xcom",
	"x":        "xcom",
	"twitter":  "xcom",
	"tw":       "xcom",
}

func New(platformStr string) (Platform, error) {
	var p Platform
	name, ok := aliases[strings.ToLower(platformStr)]
	if !ok {
		return p, fmt.Errorf("no such platform: '%s'", platformStr)
	}
	return Platform(name), nil
}

func (p Platform) String() string {
	return string(p)
}

func (p Platform) Post(ctx context.Context, args config.Args, sizeLimit int, en entry.Entry) (err error) {
	colour.Infoln("Posting", en)
	switch p.String() {
	case "mastodon":
		err = mastodon.Post(ctx, args, sizeLimit, en)
	case "linkedin":
		err = linkedin.Post(ctx, args, sizeLimit, en)
	case "noop":
		err = noop.Post(ctx, args, sizeLimit, en)
	default:
		err = fmt.Errorf("Platform '%s' (not yet) implemented", p)
	}

	if err != nil {
		return err
	}
	if err := en.MarkPosted(); err != nil {
		return err
	}

	colour.Successfln("Successfully posted message to %s", p)
	return nil
}

func ExpandAliases(shareTag string) (string, error) {
	parts := strings.Split(shareTag, ":")
	if parts[0] != "share" {
		return "", fmt.Errorf("expected share tag, but got '%s' in '%s'", parts[0], shareTag)
	}

	elems := []string{"share"}
	dedup := make(map[string]struct{}, len(aliases))

	for _, alias := range parts[1:] {
		platformStr, ok := aliases[alias]
		if !ok {
			return "", fmt.Errorf("invalid platform alias '%s' in '%s'", alias, shareTag)
		}
		if _, ok := dedup[platformStr]; ok {
			// Duplicate, ignore
			continue
		}
		elems = append(elems, platformStr)
		dedup[platformStr] = struct{}{}
	}

	return strings.Join(elems, ":"), nil
}