summaryrefslogtreecommitdiff
path: root/src/hub/src/spreadspace.org/sfive/s5srvForwardPiwik.go
blob: f3f71e75ecd02e7b7441ed5b8dc5a0dc0b06c28e (plain) (blame)
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
//
// sfive
//
// sfive - spreadspace streaming statistics suite is a generic
// statistic collection tool for streaming server infrastuctures.
// The system collects and stores meta data like number of views
// and throughput from a number of streaming servers and stores
// it in a global data store.
// The data acquisition is designed to be generic and extensible in
// order to support different streaming software.
// sfive also contains tools and applications to filter and visualize
// live and recorded data.
//
//
// Copyright (C) 2014-2017 Christian Pointner <equinox@spreadspace.org>
//                         Markus Grüneis <gimpf@gimpf.org>
//
// This file is part of sfive.
//
// sfive is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 3
// as published by the Free Software Foundation.
//
// sfive is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with sfive. If not, see <http://www.gnu.org/licenses/>.
//

package sfive

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net"
	"net/http"
	"net/url"
	"strconv"
	"time"
)

type forwardPiwikBulkRequest struct {
	Requests  []string `json:"requests"`
	TokenAuth string   `json:"token_auth"`
}

func fwdPiwikGetLastUpdateID(piwikURL, siteURL string, siteID uint, token string, client *http.Client, hubUuid string) (lastID int, err error) {
	// TODO: ask piwik what the last update was...
	lastID = 0
	return
}

func (srv Server) forwardPiwikRun(piwikURL, siteURL string, siteID uint, token string, client *http.Client) {
	//	hubUuid := srv.store.GetHubUuid()
tryResync:
	for {
		//		lastID, err := srv.forwardPiwikGetLastUpdateID(piwikURL, siteURL, siteID, token, client, hubUuid)
		lastID, err := srv.store.GetLastUpdateID()
		if err != nil {
			s5l.Printf("srv|fwd-piwik: fetching lastupdate failed: %v", err)
			time.Sleep(5 * time.Second)
			continue tryResync
		}
		s5l.Printf("srv|fwd-piwik: new lastupdate: %d", lastID)

	nextBatch:
		for {
			updates, err := srv.store.GetUpdatesAfter(lastID, 5000)
			if err != nil {
				s5l.Printf("srv|fwd-piwik: reading updates failed: %v", err)
				time.Sleep(500 * time.Millisecond)
				continue nextBatch
			}
			if len(updates) == 0 {
				time.Sleep(1 * time.Second)
				continue nextBatch
			}

			// TODO: move this to seperate function and write to io.PipeWriter
			req := forwardPiwikBulkRequest{TokenAuth: token}
			for _, update := range updates {
				if len(update.Data.Clients) == 0 {
					continue
				}

				for _, client := range update.Data.Clients {
					ip, _, err := net.SplitHostPort(client.IP)
					if err != nil {
						ip = client.IP
					}

					// see: https://developer.piwik.org/api-reference/tracking-api
					q := make(url.Values)
					q.Add("rec", "1")
					q.Add("idsite", strconv.FormatUint(uint64(siteID), 10))
					q.Add("url", fmt.Sprintf("%s/%s/%s/%s/%s", siteURL, update.Stream.ContentID, update.Stream.Format, update.Stream.Quality, update.Hostname))
					q.Add("cip", ip)
					q.Add("cdt", strconv.FormatInt(update.StartTime.Unix(), 10))
					q.Add("ua", client.UserAgent)
					// TODO: add geoip info as soon this is implemented:
					//q.Add("country", ...)    2 Letter Country-Code
					//q.Add("region", ...)     2 Letter Region-Code
					//q.Add("city", ...)
					//q.Add("lat", ...)
					//q.Add("lon", ...)
					req.Requests = append(req.Requests, "?"+q.Encode())
				}
			}

			postData := bytes.Buffer{}
			if err := json.NewEncoder(&postData).Encode(req); err != nil {
				s5l.Panicf("srv|fwd-piwik: encoding updates failed: %v", err)
			}

			// TODO: move this to seperate function and read from io.PipeReader
			resp, err := client.Post(piwikURL, "application/json", &postData)
			if err != nil {
				s5l.Printf("srv|fwd-piwik: posting updates failed: %v", err)
				time.Sleep(1 * time.Second)
				continue tryResync
			}
			if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
				body, _ := ioutil.ReadAll(resp.Body)
				s5l.Printf("srv|fwd-piwik: posting updates failed: %s\n%s", resp.Status, body)
				time.Sleep(1 * time.Second)
				continue tryResync
			}
			resp.Body.Close() // TODO: check result from Piwik

			lastID = findMaxID(updates)
			s5l.Printf("srv|fwd-piwik: successfully forwarded %d updates, new lastid: %d", len(updates), lastID)
		}
	}
}

func (srv Server) RunForwardingPiwik(cfg PiwikForwardConfig) {
	s5l.Printf("srv|fwd-piwik: forwarding to '%s'", cfg.URL)
	defer s5l.Println("srv|fwd-piwik: forwarder stopped")

	srv.forwardPiwikRun(cfg.URL, cfg.SiteURL, cfg.SiteID, cfg.AuthConfig.Token, http.DefaultClient)
}