summaryrefslogtreecommitdiffstats
path: root/modules/hooks/hooks.go
blob: 2b53dbfbbda3bf379737dd27d4e6c3704f5b1813 (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
// Copyright 2014 The Gogs Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package hooks

import (
	"encoding/json"
	"time"

	"github.com/gogits/gogs/modules/httplib"
	"github.com/gogits/gogs/modules/log"
)

// Hook task types.
const (
	HTT_WEBHOOK = iota + 1
	HTT_SERVICE
)

type PayloadAuthor struct {
	Name  string `json:"name"`
	Email string `json:"email"`
}

type PayloadCommit struct {
	Id      string         `json:"id"`
	Message string         `json:"message"`
	Url     string         `json:"url"`
	Author  *PayloadAuthor `json:"author"`
}

// Payload represents payload information of hook.
type Payload struct {
	Secret  string           `json:"secret"`
	Ref     string           `json:"ref"`
	Commits []*PayloadCommit `json:"commits"`
	Pusher  *PayloadAuthor   `json:"pusher"`
}

// HookTask represents hook task.
type HookTask struct {
	Type int
	Url  string
	*Payload
	ContentType int
	IsSsl       bool
}

var (
	taskQueue = make(chan *HookTask, 1000)
)

// AddHookTask adds new hook task to task queue.
func AddHookTask(t *HookTask) {
	taskQueue <- t
}

func init() {
	go handleQueue()
}

func handleQueue() {
	for {
		select {
		case t := <-taskQueue:
			// Only support JSON now.
			data, err := json.MarshalIndent(t.Payload, "", "\t")
			if err != nil {
				log.Error("hooks.handleQueue(json): %v", err)
				continue
			}

			_, err = httplib.Post(t.Url).SetTimeout(5*time.Second, 5*time.Second).
				Body(data).Response()
			if err != nil {
				log.Error("hooks.handleQueue: Fail to deliver hook: %v", err)
				continue
			}
			log.Info("Hook delivered")
		}
	}
}