add webhook recent deliveries

This commit is contained in:
Unknwon 2015-08-27 23:06:14 +08:00
parent fc2d0e5470
commit 23f42d92c9
18 changed files with 474 additions and 233 deletions

View File

@ -97,6 +97,8 @@ QUEUE_LENGTH = 1000
DELIVER_TIMEOUT = 5 DELIVER_TIMEOUT = 5
; Allow insecure certification ; Allow insecure certification
SKIP_TLS_VERIFY = false SKIP_TLS_VERIFY = false
; Number of history information in each page
PAGING_NUM = 10
[mailer] [mailer]
ENABLED = false ENABLED = false

View File

@ -513,6 +513,11 @@ settings.hooks_desc = Webhooks are much like basic HTTP POST event triggers. Whe
settings.webhook_deletion = Delete Webhook settings.webhook_deletion = Delete Webhook
settings.webhook_deletion_desc = Delete this webhook will remove its information and all delivery history. Do you want to continue? settings.webhook_deletion_desc = Delete this webhook will remove its information and all delivery history. Do you want to continue?
settings.webhook_deletion_success = Webhook has been deleted successfully! settings.webhook_deletion_success = Webhook has been deleted successfully!
settings.webhook.request = Request
settings.webhook.response = Response
settings.webhook.headers = Headers
settings.webhook.payload = Payload
settings.webhook.body = Body
settings.githooks_desc = Git Hooks are powered by Git itself, you can edit files of supported hooks in the list below to perform custom operations. settings.githooks_desc = Git Hooks are powered by Git itself, you can edit files of supported hooks in the list below to perform custom operations.
settings.githook_edit_desc = If the hook is inactive, sample content will be presented. Leaving content to an empty value will disable this hook. settings.githook_edit_desc = If the hook is inactive, sample content will be presented. Leaving content to an empty value will disable this hook.
settings.githook_name = Hook Name settings.githook_name = Hook Name

View File

@ -448,11 +448,11 @@ func CommitRepoAction(userID, repoUserID int64, userName, actEmail string,
RepoID: repo.ID, RepoID: repo.ID,
HookID: w.ID, HookID: w.ID,
Type: w.HookTaskType, Type: w.HookTaskType,
Url: w.URL, URL: w.URL,
BasePayload: payload, BasePayload: payload,
ContentType: w.ContentType, ContentType: w.ContentType,
EventType: HOOK_EVENT_PUSH, EventType: HOOK_EVENT_PUSH,
IsSsl: w.IsSSL, IsSSL: w.IsSSL,
}); err != nil { }); err != nil {
return fmt.Errorf("CreateHookTask: %v", err) return fmt.Errorf("CreateHookTask: %v", err)
} }

View File

@ -236,7 +236,27 @@ func IsErrRepoAlreadyExist(err error) bool {
} }
func (err ErrRepoAlreadyExist) Error() string { func (err ErrRepoAlreadyExist) Error() string {
return fmt.Sprintf("repository already exists [uname: %d, name: %s]", err.Uname, err.Name) return fmt.Sprintf("repository already exists [uname: %s, name: %s]", err.Uname, err.Name)
}
// __ __ ___. .__ __
// / \ / \ ____\_ |__ | |__ ____ ____ | | __
// \ \/\/ // __ \| __ \| | \ / _ \ / _ \| |/ /
// \ /\ ___/| \_\ \ Y ( <_> | <_> ) <
// \__/\ / \___ >___ /___| /\____/ \____/|__|_ \
// \/ \/ \/ \/ \/
type ErrWebhookNotExist struct {
ID int64
}
func IsErrWebhookNotExist(err error) bool {
_, ok := err.(ErrWebhookNotExist)
return ok
}
func (err ErrWebhookNotExist) Error() string {
return fmt.Sprintf("webhook does not exist [id: %d]", err.ID)
} }
// .___ // .___

View File

@ -84,6 +84,11 @@ func init() {
new(UpdateTask), new(HookTask), new(UpdateTask), new(HookTask),
new(Team), new(OrgUser), new(TeamUser), new(TeamRepo), new(Team), new(OrgUser), new(TeamUser), new(TeamRepo),
new(Notice), new(EmailAddress)) new(Notice), new(EmailAddress))
gonicNames := []string{"SSL"}
for _, name := range gonicNames {
core.LintGonicMapper[name] = true
}
} }
func LoadModelsConfig() { func LoadModelsConfig() {

View File

@ -7,21 +7,20 @@ package models
import ( import (
"crypto/tls" "crypto/tls"
"encoding/json" "encoding/json"
"errors" "fmt"
"io/ioutil" "io/ioutil"
"strings"
"sync" "sync"
"time" "time"
"github.com/go-xorm/xorm"
"github.com/gogits/gogs/modules/httplib" "github.com/gogits/gogs/modules/httplib"
"github.com/gogits/gogs/modules/log" "github.com/gogits/gogs/modules/log"
"github.com/gogits/gogs/modules/setting" "github.com/gogits/gogs/modules/setting"
"github.com/gogits/gogs/modules/uuid" "github.com/gogits/gogs/modules/uuid"
) )
var (
ErrWebhookNotExist = errors.New("Webhook does not exist")
)
type HookContentType int type HookContentType int
const ( const (
@ -103,6 +102,11 @@ func (w *Webhook) GetSlackHook() *Slack {
return s return s
} }
// History returns history of webhook by given conditions.
func (w *Webhook) History(page int) ([]*HookTask, error) {
return HookTasks(w.ID, page)
}
// UpdateEvent handles conversion from HookEvent to Events. // UpdateEvent handles conversion from HookEvent to Events.
func (w *Webhook) UpdateEvent() error { func (w *Webhook) UpdateEvent() error {
data, err := json.Marshal(w.HookEvent) data, err := json.Marshal(w.HookEvent)
@ -124,14 +128,14 @@ func CreateWebhook(w *Webhook) error {
return err return err
} }
// GetWebhookById returns webhook by given ID. // GetWebhookByID returns webhook by given ID.
func GetWebhookById(hookId int64) (*Webhook, error) { func GetWebhookByID(id int64) (*Webhook, error) {
w := &Webhook{ID: hookId} w := new(Webhook)
has, err := x.Get(w) has, err := x.Id(id).Get(w)
if err != nil { if err != nil {
return nil, err return nil, err
} else if !has { } else if !has {
return nil, ErrWebhookNotExist return nil, ErrWebhookNotExist{id}
} }
return w, nil return w, nil
} }
@ -271,29 +275,99 @@ type Payload struct {
} }
func (p Payload) GetJSONPayload() ([]byte, error) { func (p Payload) GetJSONPayload() ([]byte, error) {
data, err := json.Marshal(p) data, err := json.MarshalIndent(p, "", " ")
if err != nil { if err != nil {
return []byte{}, err return []byte{}, err
} }
return data, nil return data, nil
} }
// HookRequest represents hook task request information.
type HookRequest struct {
Headers map[string]string `json:"headers"`
}
// HookResponse represents hook task response information.
type HookResponse struct {
Status int `json:"status"`
Headers map[string]string `json:"headers"`
Body string `json:"body"`
}
// HookTask represents a hook task. // HookTask represents a hook task.
type HookTask struct { type HookTask struct {
ID int64 `xorm:"pk autoincr"` ID int64 `xorm:"pk autoincr"`
RepoID int64 `xorm:"INDEX"` RepoID int64 `xorm:"INDEX"`
HookID int64 HookID int64
Uuid string UUID string
Type HookTaskType Type HookTaskType
Url string URL string
BasePayload `xorm:"-"` BasePayload `xorm:"-"`
PayloadContent string `xorm:"TEXT"` PayloadContent string `xorm:"TEXT"`
ContentType HookContentType ContentType HookContentType
EventType HookEventType EventType HookEventType
IsSsl bool IsSSL bool
IsDelivered bool IsDelivered bool
Delivered int64 Delivered int64
DeliveredString string `xorm:"-"`
// History info.
IsSucceed bool IsSucceed bool
RequestContent string `xorm:"TEXT"`
RequestInfo *HookRequest `xorm:"-"`
ResponseContent string `xorm:"TEXT"`
ResponseInfo *HookResponse `xorm:"-"`
}
func (t *HookTask) BeforeUpdate() {
if t.RequestInfo != nil {
t.RequestContent = t.MarshalJSON(t.RequestInfo)
}
if t.ResponseInfo != nil {
t.ResponseContent = t.MarshalJSON(t.ResponseInfo)
}
}
func (t *HookTask) AfterSet(colName string, _ xorm.Cell) {
var err error
switch colName {
case "delivered":
t.DeliveredString = time.Unix(0, t.Delivered).Format("2006-01-02 15:04:05 MST")
case "request_content":
if len(t.RequestContent) == 0 {
return
}
t.RequestInfo = &HookRequest{}
if err = json.Unmarshal([]byte(t.RequestContent), t.RequestInfo); err != nil {
log.Error(3, "Unmarshal[%d]: %v", t.ID, err)
}
case "response_content":
if len(t.ResponseContent) == 0 {
return
}
t.ResponseInfo = &HookResponse{}
if err = json.Unmarshal([]byte(t.ResponseContent), t.ResponseInfo); err != nil {
log.Error(3, "Unmarshal[%d]: %v", t.ID, err)
}
}
}
func (t *HookTask) MarshalJSON(v interface{}) string {
p, err := json.Marshal(v)
if err != nil {
log.Error(3, "Marshal[%d]: %v", t.ID, err)
}
return string(p)
}
// HookTasks returns a list of hook tasks by given conditions.
func HookTasks(hookID int64, page int) ([]*HookTask, error) {
tasks := make([]*HookTask, 0, setting.Webhook.PagingNum)
return tasks, x.Limit(setting.Webhook.PagingNum, (page-1)*setting.Webhook.PagingNum).Desc("id").Find(&tasks)
} }
// CreateHookTask creates a new hook task, // CreateHookTask creates a new hook task,
@ -303,7 +377,7 @@ func CreateHookTask(t *HookTask) error {
if err != nil { if err != nil {
return err return err
} }
t.Uuid = uuid.NewV4().String() t.UUID = uuid.NewV4().String()
t.PayloadContent = string(data) t.PayloadContent = string(data)
_, err = x.Insert(t) _, err = x.Insert(t)
return err return err
@ -348,9 +422,11 @@ func (q *hookQueue) AddRepoID(id int64) {
var HookQueue *hookQueue var HookQueue *hookQueue
func deliverHook(t *HookTask) { func deliverHook(t *HookTask) {
t.IsDelivered = true
timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second timeout := time.Duration(setting.Webhook.DeliverTimeout) * time.Second
req := httplib.Post(t.Url).SetTimeout(timeout, timeout). req := httplib.Post(t.URL).SetTimeout(timeout, timeout).
Header("X-Gogs-Delivery", t.Uuid). Header("X-Gogs-Delivery", t.UUID).
Header("X-Gogs-Event", string(t.EventType)). Header("X-Gogs-Event", string(t.EventType)).
SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify}) SetTLSClientConfig(&tls.Config{InsecureSkipVerify: setting.Webhook.SkipTLSVerify})
@ -361,42 +437,68 @@ func deliverHook(t *HookTask) {
req.Param("payload", t.PayloadContent) req.Param("payload", t.PayloadContent)
} }
t.IsDelivered = true // Record delivery information.
t.RequestInfo = &HookRequest{
// FIXME: record response. Headers: map[string]string{},
switch t.Type {
case GOGS:
{
if resp, err := req.Response(); err != nil {
log.Error(5, "Delivery: %v", err)
} else {
resp.Body.Close()
t.IsSucceed = true
}
}
case SLACK:
{
if resp, err := req.Response(); err != nil {
log.Error(5, "Delivery: %v", err)
} else {
defer resp.Body.Close()
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error(5, "%s", err)
} else {
if string(contents) != "ok" {
log.Error(5, "slack failed with: %s", string(contents))
} else {
t.IsSucceed = true
}
}
}
} }
for k, vals := range req.Headers() {
t.RequestInfo.Headers[k] = strings.Join(vals, ",")
} }
t.ResponseInfo = &HookResponse{
Headers: map[string]string{},
}
defer func() {
t.Delivered = time.Now().UTC().UnixNano() t.Delivered = time.Now().UTC().UnixNano()
if t.IsSucceed { if t.IsSucceed {
log.Trace("Hook delivered(%s): %s", t.Uuid, t.PayloadContent) log.Trace("Hook delivered: %s", t.UUID)
}
// Update webhook last delivery status.
w, err := GetWebhookByID(t.HookID)
if err != nil {
log.Error(5, "GetWebhookByID: %v", err)
return
}
if t.IsSucceed {
w.LastStatus = HOOK_STATUS_SUCCEED
} else {
w.LastStatus = HOOK_STATUS_FAILED
}
if err = UpdateWebhook(w); err != nil {
log.Error(5, "UpdateWebhook: %v", err)
return
}
}()
resp, err := req.Response()
if err != nil {
t.ResponseInfo.Body = fmt.Sprintf("Delivery: %v", err)
return
}
defer resp.Body.Close()
// Status code is 20x can be seen as succeed.
t.IsSucceed = resp.StatusCode/100 == 2
t.ResponseInfo.Status = resp.StatusCode
for k, vals := range resp.Header {
t.ResponseInfo.Headers[k] = strings.Join(vals, ",")
}
p, err := ioutil.ReadAll(resp.Body)
if err != nil {
t.ResponseInfo.Body = fmt.Sprintf("read body: %s", err)
return
}
t.ResponseInfo.Body = string(p)
switch t.Type {
case SLACK:
if t.ResponseInfo.Body != "ok" {
log.Error(5, "slack failed with: %s", t.ResponseInfo.Body)
t.IsSucceed = false
}
} }
} }

File diff suppressed because one or more lines are too long

View File

@ -5,8 +5,6 @@
package httplib package httplib
// NOTE: last sync 57e62e5 on Oct 29, 2014.
import ( import (
"bytes" "bytes"
"crypto/tls" "crypto/tls"
@ -27,7 +25,7 @@ import (
"time" "time"
) )
var defaultSetting = BeegoHttpSettings{false, "beegoServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false} var defaultSetting = Settings{false, "GogsServer", 60 * time.Second, 60 * time.Second, nil, nil, nil, false}
var defaultCookieJar http.CookieJar var defaultCookieJar http.CookieJar
var settingMutex sync.Mutex var settingMutex sync.Mutex
@ -39,7 +37,7 @@ func createDefaultCookie() {
} }
// Overwrite default settings // Overwrite default settings
func SetDefaultSetting(setting BeegoHttpSettings) { func SetDefaultSetting(setting Settings) {
settingMutex.Lock() settingMutex.Lock()
defer settingMutex.Unlock() defer settingMutex.Unlock()
defaultSetting = setting defaultSetting = setting
@ -51,8 +49,8 @@ func SetDefaultSetting(setting BeegoHttpSettings) {
} }
} }
// return *BeegoHttpRequest with specific method // return *Request with specific method
func newBeegoRequest(url, method string) *BeegoHttpRequest { func newBeegoRequest(url, method string) *Request {
var resp http.Response var resp http.Response
req := http.Request{ req := http.Request{
Method: method, Method: method,
@ -61,36 +59,35 @@ func newBeegoRequest(url, method string) *BeegoHttpRequest {
ProtoMajor: 1, ProtoMajor: 1,
ProtoMinor: 1, ProtoMinor: 1,
} }
return &BeegoHttpRequest{url, &req, map[string]string{}, map[string]string{}, defaultSetting, &resp, nil} return &Request{url, &req, map[string]string{}, map[string]string{}, defaultSetting, &resp, nil}
} }
// Get returns *BeegoHttpRequest with GET method. // Get returns *Request with GET method.
func Get(url string) *BeegoHttpRequest { func Get(url string) *Request {
return newBeegoRequest(url, "GET") return newBeegoRequest(url, "GET")
} }
// Post returns *BeegoHttpRequest with POST method. // Post returns *Request with POST method.
func Post(url string) *BeegoHttpRequest { func Post(url string) *Request {
return newBeegoRequest(url, "POST") return newBeegoRequest(url, "POST")
} }
// Put returns *BeegoHttpRequest with PUT method. // Put returns *Request with PUT method.
func Put(url string) *BeegoHttpRequest { func Put(url string) *Request {
return newBeegoRequest(url, "PUT") return newBeegoRequest(url, "PUT")
} }
// Delete returns *BeegoHttpRequest DELETE method. // Delete returns *Request DELETE method.
func Delete(url string) *BeegoHttpRequest { func Delete(url string) *Request {
return newBeegoRequest(url, "DELETE") return newBeegoRequest(url, "DELETE")
} }
// Head returns *BeegoHttpRequest with HEAD method. // Head returns *Request with HEAD method.
func Head(url string) *BeegoHttpRequest { func Head(url string) *Request {
return newBeegoRequest(url, "HEAD") return newBeegoRequest(url, "HEAD")
} }
// BeegoHttpSettings type Settings struct {
type BeegoHttpSettings struct {
ShowDebug bool ShowDebug bool
UserAgent string UserAgent string
ConnectTimeout time.Duration ConnectTimeout time.Duration
@ -101,93 +98,97 @@ type BeegoHttpSettings struct {
EnableCookie bool EnableCookie bool
} }
// BeegoHttpRequest provides more useful methods for requesting one url than http.Request. // HttpRequest provides more useful methods for requesting one url than http.Request.
type BeegoHttpRequest struct { type Request struct {
url string url string
req *http.Request req *http.Request
params map[string]string params map[string]string
files map[string]string files map[string]string
setting BeegoHttpSettings setting Settings
resp *http.Response resp *http.Response
body []byte body []byte
} }
// Change request settings // Change request settings
func (b *BeegoHttpRequest) Setting(setting BeegoHttpSettings) *BeegoHttpRequest { func (r *Request) Setting(setting Settings) *Request {
b.setting = setting r.setting = setting
return b return r
} }
// SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password. // SetBasicAuth sets the request's Authorization header to use HTTP Basic Authentication with the provided username and password.
func (b *BeegoHttpRequest) SetBasicAuth(username, password string) *BeegoHttpRequest { func (r *Request) SetBasicAuth(username, password string) *Request {
b.req.SetBasicAuth(username, password) r.req.SetBasicAuth(username, password)
return b return r
} }
// SetEnableCookie sets enable/disable cookiejar // SetEnableCookie sets enable/disable cookiejar
func (b *BeegoHttpRequest) SetEnableCookie(enable bool) *BeegoHttpRequest { func (r *Request) SetEnableCookie(enable bool) *Request {
b.setting.EnableCookie = enable r.setting.EnableCookie = enable
return b return r
} }
// SetUserAgent sets User-Agent header field // SetUserAgent sets User-Agent header field
func (b *BeegoHttpRequest) SetUserAgent(useragent string) *BeegoHttpRequest { func (r *Request) SetUserAgent(useragent string) *Request {
b.setting.UserAgent = useragent r.setting.UserAgent = useragent
return b return r
} }
// Debug sets show debug or not when executing request. // Debug sets show debug or not when executing request.
func (b *BeegoHttpRequest) Debug(isdebug bool) *BeegoHttpRequest { func (r *Request) Debug(isdebug bool) *Request {
b.setting.ShowDebug = isdebug r.setting.ShowDebug = isdebug
return b return r
} }
// SetTimeout sets connect time out and read-write time out for BeegoRequest. // SetTimeout sets connect time out and read-write time out for BeegoRequest.
func (b *BeegoHttpRequest) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *BeegoHttpRequest { func (r *Request) SetTimeout(connectTimeout, readWriteTimeout time.Duration) *Request {
b.setting.ConnectTimeout = connectTimeout r.setting.ConnectTimeout = connectTimeout
b.setting.ReadWriteTimeout = readWriteTimeout r.setting.ReadWriteTimeout = readWriteTimeout
return b return r
} }
// SetTLSClientConfig sets tls connection configurations if visiting https url. // SetTLSClientConfig sets tls connection configurations if visiting https url.
func (b *BeegoHttpRequest) SetTLSClientConfig(config *tls.Config) *BeegoHttpRequest { func (r *Request) SetTLSClientConfig(config *tls.Config) *Request {
b.setting.TlsClientConfig = config r.setting.TlsClientConfig = config
return b return r
} }
// Header add header item string in request. // Header add header item string in request.
func (b *BeegoHttpRequest) Header(key, value string) *BeegoHttpRequest { func (r *Request) Header(key, value string) *Request {
b.req.Header.Set(key, value) r.req.Header.Set(key, value)
return b return r
}
func (r *Request) Headers() http.Header {
return r.req.Header
} }
// Set the protocol version for incoming requests. // Set the protocol version for incoming requests.
// Client requests always use HTTP/1.1. // Client requests always use HTTP/1.1.
func (b *BeegoHttpRequest) SetProtocolVersion(vers string) *BeegoHttpRequest { func (r *Request) SetProtocolVersion(vers string) *Request {
if len(vers) == 0 { if len(vers) == 0 {
vers = "HTTP/1.1" vers = "HTTP/1.1"
} }
major, minor, ok := http.ParseHTTPVersion(vers) major, minor, ok := http.ParseHTTPVersion(vers)
if ok { if ok {
b.req.Proto = vers r.req.Proto = vers
b.req.ProtoMajor = major r.req.ProtoMajor = major
b.req.ProtoMinor = minor r.req.ProtoMinor = minor
} }
return b return r
} }
// SetCookie add cookie into request. // SetCookie add cookie into request.
func (b *BeegoHttpRequest) SetCookie(cookie *http.Cookie) *BeegoHttpRequest { func (r *Request) SetCookie(cookie *http.Cookie) *Request {
b.req.Header.Add("Cookie", cookie.String()) r.req.Header.Add("Cookie", cookie.String())
return b return r
} }
// Set transport to // Set transport to
func (b *BeegoHttpRequest) SetTransport(transport http.RoundTripper) *BeegoHttpRequest { func (r *Request) SetTransport(transport http.RoundTripper) *Request {
b.setting.Transport = transport r.setting.Transport = transport
return b return r
} }
// Set http proxy // Set http proxy
@ -197,47 +198,47 @@ func (b *BeegoHttpRequest) SetTransport(transport http.RoundTripper) *BeegoHttpR
// u, _ := url.ParseRequestURI("http://127.0.0.1:8118") // u, _ := url.ParseRequestURI("http://127.0.0.1:8118")
// return u, nil // return u, nil
// } // }
func (b *BeegoHttpRequest) SetProxy(proxy func(*http.Request) (*url.URL, error)) *BeegoHttpRequest { func (r *Request) SetProxy(proxy func(*http.Request) (*url.URL, error)) *Request {
b.setting.Proxy = proxy r.setting.Proxy = proxy
return b return r
} }
// Param adds query param in to request. // Param adds query param in to request.
// params build query string as ?key1=value1&key2=value2... // params build query string as ?key1=value1&key2=value2...
func (b *BeegoHttpRequest) Param(key, value string) *BeegoHttpRequest { func (r *Request) Param(key, value string) *Request {
b.params[key] = value r.params[key] = value
return b return r
} }
func (b *BeegoHttpRequest) PostFile(formname, filename string) *BeegoHttpRequest { func (r *Request) PostFile(formname, filename string) *Request {
b.files[formname] = filename r.files[formname] = filename
return b return r
} }
// Body adds request raw body. // Body adds request raw body.
// it supports string and []byte. // it supports string and []byte.
func (b *BeegoHttpRequest) Body(data interface{}) *BeegoHttpRequest { func (r *Request) Body(data interface{}) *Request {
switch t := data.(type) { switch t := data.(type) {
case string: case string:
bf := bytes.NewBufferString(t) bf := bytes.NewBufferString(t)
b.req.Body = ioutil.NopCloser(bf) r.req.Body = ioutil.NopCloser(bf)
b.req.ContentLength = int64(len(t)) r.req.ContentLength = int64(len(t))
case []byte: case []byte:
bf := bytes.NewBuffer(t) bf := bytes.NewBuffer(t)
b.req.Body = ioutil.NopCloser(bf) r.req.Body = ioutil.NopCloser(bf)
b.req.ContentLength = int64(len(t)) r.req.ContentLength = int64(len(t))
} }
return b return r
} }
func (b *BeegoHttpRequest) getResponse() (*http.Response, error) { func (r *Request) getResponse() (*http.Response, error) {
if b.resp.StatusCode != 0 { if r.resp.StatusCode != 0 {
return b.resp, nil return r.resp, nil
} }
var paramBody string var paramBody string
if len(b.params) > 0 { if len(r.params) > 0 {
var buf bytes.Buffer var buf bytes.Buffer
for k, v := range b.params { for k, v := range r.params {
buf.WriteString(url.QueryEscape(k)) buf.WriteString(url.QueryEscape(k))
buf.WriteByte('=') buf.WriteByte('=')
buf.WriteString(url.QueryEscape(v)) buf.WriteString(url.QueryEscape(v))
@ -247,18 +248,18 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
paramBody = paramBody[0 : len(paramBody)-1] paramBody = paramBody[0 : len(paramBody)-1]
} }
if b.req.Method == "GET" && len(paramBody) > 0 { if r.req.Method == "GET" && len(paramBody) > 0 {
if strings.Index(b.url, "?") != -1 { if strings.Index(r.url, "?") != -1 {
b.url += "&" + paramBody r.url += "&" + paramBody
} else { } else {
b.url = b.url + "?" + paramBody r.url = r.url + "?" + paramBody
} }
} else if b.req.Method == "POST" && b.req.Body == nil { } else if r.req.Method == "POST" && r.req.Body == nil {
if len(b.files) > 0 { if len(r.files) > 0 {
pr, pw := io.Pipe() pr, pw := io.Pipe()
bodyWriter := multipart.NewWriter(pw) bodyWriter := multipart.NewWriter(pw)
go func() { go func() {
for formname, filename := range b.files { for formname, filename := range r.files {
fileWriter, err := bodyWriter.CreateFormFile(formname, filename) fileWriter, err := bodyWriter.CreateFormFile(formname, filename)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
@ -274,53 +275,53 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
log.Fatal(err) log.Fatal(err)
} }
} }
for k, v := range b.params { for k, v := range r.params {
bodyWriter.WriteField(k, v) bodyWriter.WriteField(k, v)
} }
bodyWriter.Close() bodyWriter.Close()
pw.Close() pw.Close()
}() }()
b.Header("Content-Type", bodyWriter.FormDataContentType()) r.Header("Content-Type", bodyWriter.FormDataContentType())
b.req.Body = ioutil.NopCloser(pr) r.req.Body = ioutil.NopCloser(pr)
} else if len(paramBody) > 0 { } else if len(paramBody) > 0 {
b.Header("Content-Type", "application/x-www-form-urlencoded") r.Header("Content-Type", "application/x-www-form-urlencoded")
b.Body(paramBody) r.Body(paramBody)
} }
} }
url, err := url.Parse(b.url) url, err := url.Parse(r.url)
if err != nil { if err != nil {
return nil, err return nil, err
} }
b.req.URL = url r.req.URL = url
trans := b.setting.Transport trans := r.setting.Transport
if trans == nil { if trans == nil {
// create default transport // create default transport
trans = &http.Transport{ trans = &http.Transport{
TLSClientConfig: b.setting.TlsClientConfig, TLSClientConfig: r.setting.TlsClientConfig,
Proxy: b.setting.Proxy, Proxy: r.setting.Proxy,
Dial: TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout), Dial: TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout),
} }
} else { } else {
// if b.transport is *http.Transport then set the settings. // if r.transport is *http.Transport then set the settings.
if t, ok := trans.(*http.Transport); ok { if t, ok := trans.(*http.Transport); ok {
if t.TLSClientConfig == nil { if t.TLSClientConfig == nil {
t.TLSClientConfig = b.setting.TlsClientConfig t.TLSClientConfig = r.setting.TlsClientConfig
} }
if t.Proxy == nil { if t.Proxy == nil {
t.Proxy = b.setting.Proxy t.Proxy = r.setting.Proxy
} }
if t.Dial == nil { if t.Dial == nil {
t.Dial = TimeoutDialer(b.setting.ConnectTimeout, b.setting.ReadWriteTimeout) t.Dial = TimeoutDialer(r.setting.ConnectTimeout, r.setting.ReadWriteTimeout)
} }
} }
} }
var jar http.CookieJar var jar http.CookieJar
if b.setting.EnableCookie { if r.setting.EnableCookie {
if defaultCookieJar == nil { if defaultCookieJar == nil {
createDefaultCookie() createDefaultCookie()
} }
@ -334,30 +335,30 @@ func (b *BeegoHttpRequest) getResponse() (*http.Response, error) {
Jar: jar, Jar: jar,
} }
if len(b.setting.UserAgent) > 0 && len(b.req.Header.Get("User-Agent")) == 0 { if len(r.setting.UserAgent) > 0 && len(r.req.Header.Get("User-Agent")) == 0 {
b.req.Header.Set("User-Agent", b.setting.UserAgent) r.req.Header.Set("User-Agent", r.setting.UserAgent)
} }
if b.setting.ShowDebug { if r.setting.ShowDebug {
dump, err := httputil.DumpRequest(b.req, true) dump, err := httputil.DumpRequest(r.req, true)
if err != nil { if err != nil {
println(err.Error()) println(err.Error())
} }
println(string(dump)) println(string(dump))
} }
resp, err := client.Do(b.req) resp, err := client.Do(r.req)
if err != nil { if err != nil {
return nil, err return nil, err
} }
b.resp = resp r.resp = resp
return resp, nil return resp, nil
} }
// String returns the body string in response. // String returns the body string in response.
// it calls Response inner. // it calls Response inner.
func (b *BeegoHttpRequest) String() (string, error) { func (r *Request) String() (string, error) {
data, err := b.Bytes() data, err := r.Bytes()
if err != nil { if err != nil {
return "", err return "", err
} }
@ -367,11 +368,11 @@ func (b *BeegoHttpRequest) String() (string, error) {
// Bytes returns the body []byte in response. // Bytes returns the body []byte in response.
// it calls Response inner. // it calls Response inner.
func (b *BeegoHttpRequest) Bytes() ([]byte, error) { func (r *Request) Bytes() ([]byte, error) {
if b.body != nil { if r.body != nil {
return b.body, nil return r.body, nil
} }
resp, err := b.getResponse() resp, err := r.getResponse()
if err != nil { if err != nil {
return nil, err return nil, err
} }
@ -383,20 +384,20 @@ func (b *BeegoHttpRequest) Bytes() ([]byte, error) {
if err != nil { if err != nil {
return nil, err return nil, err
} }
b.body = data r.body = data
return data, nil return data, nil
} }
// ToFile saves the body data in response to one file. // ToFile saves the body data in response to one file.
// it calls Response inner. // it calls Response inner.
func (b *BeegoHttpRequest) ToFile(filename string) error { func (r *Request) ToFile(filename string) error {
f, err := os.Create(filename) f, err := os.Create(filename)
if err != nil { if err != nil {
return err return err
} }
defer f.Close() defer f.Close()
resp, err := b.getResponse() resp, err := r.getResponse()
if err != nil { if err != nil {
return err return err
} }
@ -410,8 +411,8 @@ func (b *BeegoHttpRequest) ToFile(filename string) error {
// ToJson returns the map that marshals from the body bytes as json in response . // ToJson returns the map that marshals from the body bytes as json in response .
// it calls Response inner. // it calls Response inner.
func (b *BeegoHttpRequest) ToJson(v interface{}) error { func (r *Request) ToJson(v interface{}) error {
data, err := b.Bytes() data, err := r.Bytes()
if err != nil { if err != nil {
return err return err
} }
@ -421,8 +422,8 @@ func (b *BeegoHttpRequest) ToJson(v interface{}) error {
// ToXml returns the map that marshals from the body bytes as xml in response . // ToXml returns the map that marshals from the body bytes as xml in response .
// it calls Response inner. // it calls Response inner.
func (b *BeegoHttpRequest) ToXml(v interface{}) error { func (r *Request) ToXml(v interface{}) error {
data, err := b.Bytes() data, err := r.Bytes()
if err != nil { if err != nil {
return err return err
} }
@ -431,8 +432,8 @@ func (b *BeegoHttpRequest) ToXml(v interface{}) error {
} }
// Response executes request client gets response mannually. // Response executes request client gets response mannually.
func (b *BeegoHttpRequest) Response() (*http.Response, error) { func (r *Request) Response() (*http.Response, error) {
return b.getResponse() return r.getResponse()
} }
// TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field. // TimeoutDialer returns functions of connection dialer with timeout settings for http.Transport Dial field.

View File

@ -82,6 +82,7 @@ var (
DeliverTimeout int DeliverTimeout int
SkipTLSVerify bool SkipTLSVerify bool
Types []string Types []string
PagingNum int
} }
// Repository settings. // Repository settings.
@ -601,6 +602,7 @@ func newWebhookService() {
Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5) Webhook.DeliverTimeout = sec.Key("DELIVER_TIMEOUT").MustInt(5)
Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool() Webhook.SkipTLSVerify = sec.Key("SKIP_TLS_VERIFY").MustBool()
Webhook.Types = []string{"gogs", "slack"} Webhook.Types = []string{"gogs", "slack"}
Webhook.PagingNum = sec.Key("PAGING_NUM").MustInt(10)
} }
func NewServices() { func NewServices() {

File diff suppressed because one or more lines are too long

View File

@ -341,10 +341,6 @@ function initRepository() {
// Diff // Diff
if ($('.repository.diff').length > 0) { if ($('.repository.diff').length > 0) {
$('.diff-detail-box .toggle.button').click(function () {
$($(this).data('target')).slideToggle(100);
})
var $counter = $('.diff-counter'); var $counter = $('.diff-counter');
if ($counter.length < 1) { if ($counter.length < 1) {
return; return;
@ -406,6 +402,11 @@ $(document).ready(function () {
} }
} }
}); });
$('.tabular.menu .item').tab();
$('.toggle.button').click(function () {
$($(this).data('target')).slideToggle(100);
});
// Dropzone // Dropzone
if ($('#dropzone').length > 0) { if ($('#dropzone').length > 0) {

View File

@ -7,6 +7,19 @@ body {
img { img {
border-radius: 3px; border-radius: 3px;
} }
pre {
font: 12px Consolas, "Liberation Mono", Menlo, Courier, monospace;
&.raw {
padding: 7px 12px;
margin: 10px 0;
background-color: #f8f8f8;
border: 1px solid #ddd;
border-radius: 3px;
font-size: 13px;
line-height: 1.5;
overflow: auto;
}
}
.full.height { .full.height {
padding: 0; padding: 0;
margin: 0 0 -@footer-margin*2 0; margin: 0 0 -@footer-margin*2 0;
@ -121,6 +134,10 @@ img {
&.thin { &.thin {
font-weight: normal; font-weight: normal;
} }
&.middle {
vertical-align: middle;
}
} }
.message { .message {

View File

@ -624,7 +624,7 @@
} }
} }
.hook.list { .hook.list {
.item:not(:first-child) { > .item:not(:first-child) {
border-top: 1px solid #eaeaea; border-top: 1px solid #eaeaea;
} }
.item { .item {
@ -632,6 +632,40 @@
.octicon, .octicon,
.fa { .fa {
width: 20px; width: 20px;
text-align: center;
}
}
}
.hook.history.list {
.item {
padding-left: 13px;
.meta {
.ui.right {
margin-top: 5px;
.time {
font-size: 12px;
}
}
}
.info {
margin-top: 10px;
.tabular.menu {
.item {
font-weight: 500;
}
}
.tab.segment {
border: none;
padding: 0;
padding-top: 10px;
box-shadow: none;
* {
color: #666;
}
pre {
word-wrap: break-word;
}
}
} }
} }
} }

View File

@ -121,7 +121,7 @@ func CreateRepoHook(ctx *middleware.Context, form api.CreateHookOption) {
// PATCH /repos/:username/:reponame/hooks/:id // PATCH /repos/:username/:reponame/hooks/:id
// https://developer.github.com/v3/repos/hooks/#edit-a-hook // https://developer.github.com/v3/repos/hooks/#edit-a-hook
func EditRepoHook(ctx *middleware.Context, form api.EditHookOption) { func EditRepoHook(ctx *middleware.Context, form api.EditHookOption) {
w, err := models.GetWebhookById(ctx.ParamsInt64(":id")) w, err := models.GetWebhookByID(ctx.ParamsInt64(":id"))
if err != nil { if err != nil {
ctx.JSON(500, &base.ApiJsonErr{"GetWebhookById: " + err.Error(), base.DOC_URL}) ctx.JSON(500, &base.ApiJsonErr{"GetWebhookById: " + err.Error(), base.DOC_URL})
return return

View File

@ -417,15 +417,22 @@ func SlackHooksNewPost(ctx *middleware.Context, form auth.NewSlackHookForm) {
ctx.Redirect(orCtx.Link + "/settings/hooks") ctx.Redirect(orCtx.Link + "/settings/hooks")
} }
func checkWebhook(ctx *middleware.Context) *models.Webhook { func checkWebhook(ctx *middleware.Context) (*OrgRepoCtx, *models.Webhook) {
w, err := models.GetWebhookById(ctx.ParamsInt64(":id")) orCtx, err := getOrgRepoCtx(ctx)
if err != nil { if err != nil {
if err == models.ErrWebhookNotExist { ctx.Handle(500, "getOrgRepoCtx", err)
ctx.Handle(404, "GetWebhookById", nil) return nil, nil
} else {
ctx.Handle(500, "GetWebhookById", err)
} }
return nil ctx.Data["BaseLink"] = orCtx.Link
w, err := models.GetWebhookByID(ctx.ParamsInt64(":id"))
if err != nil {
if models.IsErrWebhookNotExist(err) {
ctx.Handle(404, "GetWebhookByID", nil)
} else {
ctx.Handle(500, "GetWebhookByID", err)
}
return nil, nil
} }
switch w.HookTaskType { switch w.HookTaskType {
@ -436,7 +443,12 @@ func checkWebhook(ctx *middleware.Context) *models.Webhook {
ctx.Data["HookType"] = "gogs" ctx.Data["HookType"] = "gogs"
} }
w.GetEvent() w.GetEvent()
return w
ctx.Data["History"], err = w.History(1)
if err != nil {
ctx.Handle(500, "History", err)
}
return orCtx, w
} }
func WebHooksEdit(ctx *middleware.Context) { func WebHooksEdit(ctx *middleware.Context) {
@ -444,17 +456,11 @@ func WebHooksEdit(ctx *middleware.Context) {
ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true ctx.Data["PageIsSettingsHooksEdit"] = true
ctx.Data["Webhook"] = checkWebhook(ctx) orCtx, w := checkWebhook(ctx)
if ctx.Written() { if ctx.Written() {
return return
} }
ctx.Data["Webhook"] = w
orCtx, err := getOrgRepoCtx(ctx)
if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err)
return
}
ctx.Data["BaseLink"] = orCtx.Link
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(200, orCtx.NewTemplate)
} }
@ -464,19 +470,12 @@ func WebHooksEditPost(ctx *middleware.Context, form auth.NewWebhookForm) {
ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true ctx.Data["PageIsSettingsHooksEdit"] = true
w := checkWebhook(ctx) orCtx, w := checkWebhook(ctx)
if ctx.Written() { if ctx.Written() {
return return
} }
ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w
orCtx, err := getOrgRepoCtx(ctx)
if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err)
return
}
ctx.Data["BaseLink"] = orCtx.Link
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(200, orCtx.NewTemplate)
return return
@ -511,19 +510,12 @@ func SlackHooksEditPost(ctx *middleware.Context, form auth.NewSlackHookForm) {
ctx.Data["PageIsSettingsHooks"] = true ctx.Data["PageIsSettingsHooks"] = true
ctx.Data["PageIsSettingsHooksEdit"] = true ctx.Data["PageIsSettingsHooksEdit"] = true
w := checkWebhook(ctx) orCtx, w := checkWebhook(ctx)
if ctx.Written() { if ctx.Written() {
return return
} }
ctx.Data["Webhook"] = w ctx.Data["Webhook"] = w
orCtx, err := getOrgRepoCtx(ctx)
if err != nil {
ctx.Handle(500, "getOrgRepoCtx", err)
return
}
ctx.Data["BaseLink"] = orCtx.Link
if ctx.HasError() { if ctx.HasError() {
ctx.HTML(200, orCtx.NewTemplate) ctx.HTML(200, orCtx.NewTemplate)
return return
@ -588,6 +580,7 @@ func TriggerHook(ctx *middleware.Context) {
return return
} }
models.HookQueue.AddRepoID(repo.ID) models.HookQueue.AddRepoID(repo.ID)
ctx.Status(200)
} }
func GitHooks(ctx *middleware.Context) { func GitHooks(ctx *middleware.Context) {

View File

@ -2,7 +2,66 @@
<h4 class="ui top attached header"> <h4 class="ui top attached header">
{{.i18n.Tr "repo.settings.recent_deliveries"}} {{.i18n.Tr "repo.settings.recent_deliveries"}}
</h4> </h4>
<div class="ui attached segment"> <div class="ui attached table segment">
Coming soon! <div class="ui hook history list">
{{range .History}}
<div class="item">
<div class="meta">
{{if .IsSucceed}}
<span class="text green"><i class="octicon octicon-check"></i></span>
{{else}}
<span class="text red"><i class="octicon octicon-alert"></i></span>
{{end}}
<a class="ui blue sha label toggle button" data-target="#info-{{.ID}}">{{.UUID}}</a>
<div class="ui right">
<span class="text grey time">
{{.DeliveredString}}
</span>
</div>
</div>
<div class="info hide" id="info-{{.ID}}">
<div class="ui top attached tabular menu">
<a class="item active" data-tab="request-{{.ID}}">{{$.i18n.Tr "repo.settings.webhook.request"}}</a>
<a class="item" data-tab="response-{{.ID}}">
{{$.i18n.Tr "repo.settings.webhook.response"}}
{{if .ResponseInfo}}
{{if .IsSucceed}}
<span class="ui green label">{{.ResponseInfo.Status}}</span>
{{else}}
<span class="ui red label">500</span>
{{end}}
{{else}}
<span class="ui label">N/A</span>
{{end}}
</a>
</div>
<div class="ui bottom attached tab segment active" data-tab="request-{{.ID}}">
{{if .RequestInfo}}
<h5>{{$.i18n.Tr "repo.settings.webhook.headers"}}</h5>
<pre class="raw"><strong>Request URL:</strong> {{.URL}}
<strong>Request method:</strong> POST
{{ range $key, $val := .RequestInfo.Headers }}<strong>{{$key}}:</strong> {{$val}}
{{end}}</pre>
<h5>{{$.i18n.Tr "repo.settings.webhook.payload"}}</h5>
<pre class="raw">{{.PayloadContent}}</pre>
{{else}}
N/A
{{end}}
</div>
<div class="ui bottom attached tab segment" data-tab="response-{{.ID}}">
{{if .ResponseInfo}}
<h5>{{$.i18n.Tr "repo.settings.webhook.headers"}}</h5>
<pre class="raw">{{ range $key, $val := .ResponseInfo.Headers }}<strong>{{$key}}:</strong> {{$val}}
{{end}}</pre>
<h5>{{$.i18n.Tr "repo.settings.webhook.body"}}</h5>
<pre class="raw">{{.ResponseInfo.Body}}</pre>
{{else}}
N/A
{{end}}
</div>
</div>
</div>
{{end}}
</div>
</div> </div>
{{end}} {{end}}

View File

@ -19,7 +19,7 @@
{{range .Tokens}} {{range .Tokens}}
<div class="item ui grid"> <div class="item ui grid">
<div class="one wide column"> <div class="one wide column">
<i class="ssh-key-state-indicator fa fa-circle{{if .HasRecentActivity}} active invert poping up{{else}}-o{{end}}" {{if .HasRecentActivity}}data-content="{{$.i18n.Tr "settings.token_state_desc"}}" data-variation="inverted"{{end}}></i> <i class="ssh-key-state-indicator fa fa-circle{{if .HasRecentActivity}} active invert poping up{{else}}-o{{end}}" {{if .HasRecentActivity}}data-content="{{$.i18n.Tr "settings.token_state_desc"}}" data-variation="inverted tiny"{{end}}></i>
</div> </div>
<div class="one wide column"> <div class="one wide column">
<i class="fa fa-send fa-2x left"></i> <i class="fa fa-send fa-2x left"></i>

View File

@ -19,7 +19,7 @@
{{range .Keys}} {{range .Keys}}
<div class="item ui grid"> <div class="item ui grid">
<div class="one wide column"> <div class="one wide column">
<i class="ssh-key-state-indicator fa fa-circle{{if .HasRecentActivity}} active invert poping up{{else}}-o{{end}}" {{if .HasRecentActivity}}data-content="{{$.i18n.Tr "settings.key_state_desc"}}" data-variation="inverted"{{end}}></i> <i class="ssh-key-state-indicator fa fa-circle{{if .HasRecentActivity}} active invert poping up{{else}}-o{{end}}" {{if .HasRecentActivity}}data-content="{{$.i18n.Tr "settings.key_state_desc"}}" data-variation="inverted tiny"{{end}}></i>
</div> </div>
<div class="one wide column"> <div class="one wide column">
<i class="mega-octicon octicon-key left"></i> <i class="mega-octicon octicon-key left"></i>