aboutsummaryrefslogtreecommitdiff
path: root/cmd/stevents/main.go
blob: 92224a7d682a39a371af9318709750dc4123ede1 (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
// Copyright (C) 2014 The Syncthing Authors.
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at https://mozilla.org/MPL/2.0/.

package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"time"

	_ "go.uber.org/automaxprocs"
)

type event struct {
	ID   int                    `json:"id"`
	Type string                 `json:"type"`
	Time time.Time              `json:"time"`
	Data map[string]interface{} `json:"data"`
}

func main() {
	log.SetOutput(os.Stdout)
	log.SetFlags(0)

	target := flag.String("target", "localhost:8384", "Target Syncthing instance")
	types := flag.String("types", "", "Filter for specific event types (comma-separated)")
	apikey := flag.String("apikey", "", "Syncthing API key")
	flag.Parse()

	if *apikey == "" {
		log.Fatal("Must give -apikey argument")
	}
	var eventsArg string
	if len(*types) > 0 {
		eventsArg = "&events=" + *types
	}

	since := 0
	for {
		req, err := http.NewRequest("GET", fmt.Sprintf("http://%s/rest/events?since=%d%s", *target, since, eventsArg), nil)
		if err != nil {
			log.Fatal(err)
		}
		req.Header.Set("X-API-Key", *apikey)
		res, err := http.DefaultClient.Do(req)
		if err != nil {
			log.Fatal(err)
		}

		var events []event
		err = json.NewDecoder(res.Body).Decode(&events)
		if err != nil {
			log.Fatal(err)
		}
		res.Body.Close()

		for _, event := range events {
			bs, _ := json.MarshalIndent(event, "", "    ")
			log.Printf("%s", bs)
			since = event.ID
		}
	}
}