summaryrefslogtreecommitdiff
path: root/internal/run.go
blob: aeb2fc215ca11408fa9460d76da1fb70c3d0d271 (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
package internal

import (
	"context"
	"errors"
	"fmt"

	"codeberg.org/snonux/gos/internal/colour"
	"codeberg.org/snonux/gos/internal/config"
	"codeberg.org/snonux/gos/internal/entry"
	"codeberg.org/snonux/gos/internal/platforms"
	"codeberg.org/snonux/gos/internal/platforms/linkedin"
	"codeberg.org/snonux/gos/internal/platforms/mastodon"
	"codeberg.org/snonux/gos/internal/prompt"
	"codeberg.org/snonux/gos/internal/queue"
	"codeberg.org/snonux/gos/internal/schedule"
)

func Run(ctx context.Context, args config.Args) error {
	if err := queue.Run(args); err != nil {
		if !softError(err) {
			return err
		}
		colour.Infoln(err)
	}

	for platform, sizeLimit := range args.Platforms {
		if err := runPlatform(ctx, args, platform, sizeLimit); err != nil {
			if softError(err) {
				colour.Infoln(err)
				continue
			}
			return err
		}
	}

	return nil
}

func runPlatform(ctx context.Context, args config.Args, platform platforms.Platform, sizeLimit int) error {
	en, err := schedule.Run(args, platform)
	switch {
	case errors.Is(err, schedule.ErrNothingToSchedule):
		colour.Infoln("Nothing to be scheduled for", platform)
		return nil
	case errors.Is(err, schedule.ErrNothingQueued):
		colour.Infoln("Nothing queued for", platform)
		return nil
	case err != nil:
		return err
	}
	err = postPlatform(ctx, args, platform, sizeLimit, en)
	if errors.Is(err, prompt.ErrRamdomOther) {
		return runPlatform(ctx, args, platform, sizeLimit)
	}
	return err
}

func postPlatform(ctx context.Context, args config.Args, platform platforms.Platform,
	sizeLimit int, en entry.Entry) (err error) {

	colour.Infoln("Posting", en)
	switch platform.String() {
	case "mastodon":
		err = mastodon.Post(ctx, args, sizeLimit, en)
	case "linkedin":
		err = linkedin.Post(ctx, args, sizeLimit, en)
	default:
		err = fmt.Errorf("Platform '%s' (not yet) implemented", platform)
	}

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

	colour.Successf("Successfully posted message to %s", platform)
	return nil
}

func softError(err error) bool {
	return errors.Is(err, prompt.ErrAborted) || errors.Is(err, prompt.ErrDeleted)
}