summaryrefslogtreecommitdiffstats
path: root/services/webhook/packagist.go
blob: f1f3306109e29a8884f6538dad8eceaf6dd4ed41 (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
86
87
88
89
// Copyright 2022 The Gitea Authors. All rights reserved.
// SPDX-License-Identifier: MIT

package webhook

import (
	"context"
	"fmt"
	"html/template"
	"net/http"
	"net/url"

	webhook_model "code.gitea.io/gitea/models/webhook"
	"code.gitea.io/gitea/modules/json"
	"code.gitea.io/gitea/modules/log"
	webhook_module "code.gitea.io/gitea/modules/webhook"
	"code.gitea.io/gitea/services/forms"
)

type packagistHandler struct{}

func (packagistHandler) Type() webhook_module.HookType { return webhook_module.PACKAGIST }
func (packagistHandler) Icon(size int) template.HTML   { return imgIcon("packagist.png", size) }

func (packagistHandler) FormFields(bind func(any)) FormFields {
	var form struct {
		forms.WebhookForm
		Username   string `binding:"Required"`
		APIToken   string `binding:"Required"`
		PackageURL string `binding:"Required;ValidUrl"`
	}
	bind(&form)

	return FormFields{
		WebhookForm: form.WebhookForm,
		URL:         fmt.Sprintf("https://packagist.org/api/update-package?username=%s&apiToken=%s", url.QueryEscape(form.Username), url.QueryEscape(form.APIToken)),
		ContentType: webhook_model.ContentTypeJSON,
		Secret:      "",
		HTTPMethod:  http.MethodPost,
		Metadata: &PackagistMeta{
			Username:   form.Username,
			APIToken:   form.APIToken,
			PackageURL: form.PackageURL,
		},
	}
}

type (
	// PackagistPayload represents a packagist payload
	// as expected by https://packagist.org/about
	PackagistPayload struct {
		PackagistRepository struct {
			URL string `json:"url"`
		} `json:"repository"`
	}

	// PackagistMeta contains the metadata for the webhook
	PackagistMeta struct {
		Username   string `json:"username"`
		APIToken   string `json:"api_token"`
		PackageURL string `json:"package_url"`
	}
)

// Metadata returns packagist metadata
func (packagistHandler) Metadata(w *webhook_model.Webhook) any {
	s := &PackagistMeta{}
	if err := json.Unmarshal([]byte(w.Meta), s); err != nil {
		log.Error("packagistHandler.Metadata(%d): %v", w.ID, err)
	}
	return s
}

// newPackagistRequest creates a request with the [PackagistPayload] for packagist (same payload for all events).
func (packagistHandler) NewRequest(ctx context.Context, w *webhook_model.Webhook, t *webhook_model.HookTask) (*http.Request, []byte, error) {
	meta := &PackagistMeta{}
	if err := json.Unmarshal([]byte(w.Meta), meta); err != nil {
		return nil, nil, fmt.Errorf("packagistHandler.NewRequest meta json: %w", err)
	}

	payload := PackagistPayload{
		PackagistRepository: struct {
			URL string `json:"url"`
		}{
			URL: meta.PackageURL,
		},
	}
	return newJSONRequestWithPayload(payload, w, t, false)
}