Open platform to collect and prioritize feedback
feature: add webhooks (#980)
Théo SZANTO33e35ac0f5ac
diff --git a/app/actions/webhook.go b/app/actions/webhook.gonew file mode 100644index 000000000..537a9eb31--- /dev/null+++ b/app/actions/webhook.go@@ -0,0 +1,137 @@+package actions++import (+ "context"+ "github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/enum"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/validate"+)++type CreateEditWebhook struct {+ Name string `json:"name"`+ Type enum.WebhookType `json:"type"`+ Status enum.WebhookStatus `json:"status"`+ Url string `json:"url"`+ Content string `json:"content"`+ HttpMethod string `json:"http_method"`+ HttpHeaders entity.HttpHeaders `json:"http_headers"`+}++// IsAuthorized returns true if current user is authorized to perform this action+func (action *CreateEditWebhook) IsAuthorized(_ context.Context, user *entity.User) bool {+ return user != nil && user.IsAdministrator()+}++// Validate if current model is valid+func (action *CreateEditWebhook) Validate(ctx context.Context, _ *entity.User) *validate.Result {+ result := validate.Success()++ if action.Name == "" {+ result.AddFieldFailure("name", "Name is required.")+ } else if len(action.Name) > 60 {+ result.AddFieldFailure("name", "Name must have less than 60 characters.")+ }++ if action.Type == 0 {+ result.AddFieldFailure("type", "Type is required.")+ } else if action.Type != enum.WebhookNewPost &&+ action.Type != enum.WebhookNewComment &&+ action.Type != enum.WebhookChangeStatus &&+ action.Type != enum.WebhookDeletePost {+ result.AddFieldFailure("type", "Type must be valid.")+ }++ if action.Status == 0 {+ result.AddFieldFailure("status", "Status is required.")+ }++ runCompileCheck := action.Status == enum.WebhookEnabled+ if action.Url == "" {+ result.AddFieldFailure("url", "URL template is required.")+ runCompileCheck = false+ } else if len(action.Url) > 1_000 {+ result.AddFieldFailure("url", "URL template must have less than 1 000 characters.")+ runCompileCheck = false+ }++ if len(action.Content) > 100_000 {+ result.AddFieldFailure("content", "Content template must have less than 100 000 characters.")+ runCompileCheck = false+ }++ if runCompileCheck {+ previewWebhook := &cmd.PreviewWebhook{+ Type: action.Type,+ Url: action.Url,+ Content: action.Content,+ }+ if err := bus.Dispatch(ctx, previewWebhook); err != nil {+ return validate.Error(err)+ }++ if previewWebhook.Result.Url.Error != "" {+ result.AddFieldFailure("url", "URL template must compile to enable the Webhook.")+ } else if messages := validate.URL(ctx, previewWebhook.Result.Url.Value); len(messages) > 0 {+ result.AddFieldFailure("url", messages...)+ }++ if previewWebhook.Result.Content.Error != "" {+ result.AddFieldFailure("content", "Content template must compile to enable the Webhook.")+ }+ }++ if action.HttpMethod == "" {+ result.AddFieldFailure("http_method", "HTTP Method is required.")+ } else if len(action.HttpMethod) > 50 {+ result.AddFieldFailure("http_method", "HTTP Method must have less than 50 characters.")+ }++ if len(action.Content) > 10_000 {+ result.AddFieldFailure("content", "Content must have less than 10 000 characters.")+ }++ for header, value := range action.HttpHeaders {+ if header == "" {+ result.AddFieldFailure("header-"+header, "HTTP Header Name is required.")+ } else if len(header) > 200 {+ result.AddFieldFailure("header-"+header, "HTTP Header Name must have less than 200 characters.")+ }++ if value == "" {+ result.AddFieldFailure("value-"+header, "HTTP Header Value is required.")+ } else if len(value) > 1_000 {+ result.AddFieldFailure("value-"+header, "HTTP Header Value must have less than 1 000 characters.")+ }+ }++ return result+}++type PreviewWebhook struct {+ Type enum.WebhookType `json:"type"`+ Url string `json:"url"`+ Content string `json:"content"`+}++// IsAuthorized returns true if current user is authorized to perform this action+func (action *PreviewWebhook) IsAuthorized(_ context.Context, user *entity.User) bool {+ return user != nil && user.IsAdministrator()+}++// Validate if current model is valid+func (action *PreviewWebhook) Validate(context.Context, *entity.User) *validate.Result {+ result := validate.Success()++ if action.Type == 0 {+ result.AddFieldFailure("type", "Type is required.")+ } else if action.Type != enum.WebhookNewPost &&+ action.Type != enum.WebhookNewComment &&+ action.Type != enum.WebhookChangeStatus &&+ action.Type != enum.WebhookDeletePost {+ result.AddFieldFailure("type", "Type must be valid.")+ }++ return result+}diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 7b559294f..c237ad314 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -159,6 +159,13 @@ func routes(r *web.Engine) *web.Engine {ui.Get("/admin/export", handlers.Page("Export · Site Settings", "", "Export.page"))ui.Get("/admin/export/posts.csv", handlers.ExportPostsToCSV())ui.Get("/admin/export/backup.zip", handlers.ExportBackupZip())+ ui.Get("/admin/webhooks", handlers.ManageWebhooks())+ ui.Post("/_api/admin/webhook", handlers.CreateWebhook())+ ui.Put("/_api/admin/webhook/:id", handlers.UpdateWebhook())+ ui.Delete("/_api/admin/webhook/:id", handlers.DeleteWebhook())+ ui.Get("/_api/admin/webhook/test/:id", handlers.TestWebhook())+ ui.Post("/_api/admin/webhook/preview", handlers.PreviewWebhook())+ ui.Get("/_api/admin/webhook/props/:type", handlers.GetWebhookProps())ui.Post("/_api/admin/settings/general", handlers.UpdateSettings())ui.Post("/_api/admin/settings/advanced", handlers.UpdateAdvancedSettings())ui.Post("/_api/admin/settings/privacy", handlers.UpdatePrivacy())diff --git a/app/cmd/server.go b/app/cmd/server.goindex 35df87c61..7a4ad23fa 100644--- a/app/cmd/server.go+++ b/app/cmd/server.go@@ -27,6 +27,7 @@ import (_ "github.com/getfider/fider/app/services/log/sql"_ "github.com/getfider/fider/app/services/oauth"_ "github.com/getfider/fider/app/services/sqlstore/postgres"+ _ "github.com/getfider/fider/app/services/webhook")//RunServer starts the Fider Serverdiff --git a/app/handlers/webhook.go b/app/handlers/webhook.gonew file mode 100644index 000000000..9f950a5d0--- /dev/null+++ b/app/handlers/webhook.go@@ -0,0 +1,160 @@+package handlers++import (+ "github.com/getfider/fider/app/actions"+ "github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/enum"+ "github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/web"+ "strconv"+)++// ManageWebhooks is the page used by administrators to configure webhooks+func ManageWebhooks() web.HandlerFunc {+ return func(c *web.Context) error {+ allWebhooks := &query.ListAllWebhooks{}+ if err := bus.Dispatch(c, allWebhooks); err != nil {+ return c.Failure(err)+ }++ return c.Page(web.Props{+ Title: "Manage Webhooks · Site Settings",+ ChunkName: "ManageWebhooks.page",+ Data: web.Map{+ "webhooks": allWebhooks.Result,+ },+ })+ }+}++func CreateWebhook() web.HandlerFunc {+ return func(c *web.Context) error {+ action := &actions.CreateEditWebhook{}+ if result := c.BindTo(action); !result.Ok {+ return c.HandleValidation(result)+ }++ createWebhook := &query.CreateEditWebhook{+ ID: 0,+ Name: action.Name,+ Type: action.Type,+ Status: action.Status,+ Url: action.Url,+ Content: action.Content,+ HttpMethod: action.HttpMethod,+ HttpHeaders: action.HttpHeaders,+ }+ if err := bus.Dispatch(c, createWebhook); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{"id": createWebhook.Result})+ }+}++func UpdateWebhook() web.HandlerFunc {+ return func(c *web.Context) error {+ _id := c.Param("id")+ id, err := strconv.Atoi(_id)+ if err != nil {+ return c.Failure(err)+ }++ action := &actions.CreateEditWebhook{}+ if result := c.BindTo(action); !result.Ok {+ return c.HandleValidation(result)+ }++ updateWebhook := &query.CreateEditWebhook{+ ID: id,+ Name: action.Name,+ Type: action.Type,+ Status: action.Status,+ Url: action.Url,+ Content: action.Content,+ HttpMethod: action.HttpMethod,+ HttpHeaders: action.HttpHeaders,+ }+ if action.Status == enum.WebhookFailed {+ updateWebhook.Status = enum.WebhookDisabled+ }+ if err := bus.Dispatch(c, updateWebhook); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})+ }+}++func DeleteWebhook() web.HandlerFunc {+ return func(c *web.Context) error {+ _id := c.Param("id")+ id, err := strconv.Atoi(_id)+ if err != nil {+ return c.Failure(err)+ }++ deleteWebhook := &query.DeleteWebhook{ID: id}+ if err = bus.Dispatch(c, deleteWebhook); err != nil {+ return c.Failure(err)+ }++ return c.Ok(web.Map{})+ }+}++func TestWebhook() web.HandlerFunc {+ return func(c *web.Context) error {+ _id := c.Param("id")+ id, err := strconv.Atoi(_id)+ if err != nil {+ return c.Failure(err)+ }++ triggerWebhook := &cmd.TestWebhook{ID: id}+ if err = bus.Dispatch(c, triggerWebhook); err != nil {+ return c.Failure(err)+ }++ return c.Ok(triggerWebhook.Result)+ }+}++func PreviewWebhook() web.HandlerFunc {+ return func(c *web.Context) error {+ action := &actions.PreviewWebhook{}+ if result := c.BindTo(action); !result.Ok {+ return c.HandleValidation(result)+ }++ previewWebhook := &cmd.PreviewWebhook{+ Type: action.Type,+ Url: action.Url,+ Content: action.Content,+ }+ if err := bus.Dispatch(c, previewWebhook); err != nil {+ return c.Failure(err)+ }++ return c.Ok(previewWebhook.Result)+ }+}++func GetWebhookProps() web.HandlerFunc {+ return func(c *web.Context) error {+ rawType := c.Param("type")+ var webhookType enum.WebhookType+ err := webhookType.UnmarshalText([]byte(rawType))+ if err != nil {+ return c.Failure(err)+ }++ webhookProps := &cmd.GetWebhookProps{Type: webhookType}+ if err := bus.Dispatch(c, webhookProps); err != nil {+ return c.Failure(err)+ }++ return c.Ok(webhookProps.Result)+ }+}diff --git a/app/models/cmd/tenant.go b/app/models/cmd/tenant.goindex 18b7e2809..f4fc9eedb 100644--- a/app/models/cmd/tenant.go+++ b/app/models/cmd/tenant.go@@ -11,7 +11,7 @@ import (type CreateTenant struct {Name stringSubdomain string- Status int+ Status enum.TenantStatusResult *entity.Tenant}diff --git a/app/models/cmd/webhook.go b/app/models/cmd/webhook.gonew file mode 100644index 000000000..94cbfd7de--- /dev/null+++ b/app/models/cmd/webhook.go@@ -0,0 +1,32 @@+package cmd++import (+ "github.com/getfider/fider/app/models/dto"+ "github.com/getfider/fider/app/models/enum"+ "github.com/getfider/fider/app/pkg/webhook"+)++type TestWebhook struct {+ ID int++ Result *dto.WebhookTriggerResult+}++type TriggerWebhooks struct {+ Type enum.WebhookType+ Props webhook.Props+}++type PreviewWebhook struct {+ Type enum.WebhookType+ Url string+ Content string++ Result *dto.WebhookPreviewResult+}++type GetWebhookProps struct {+ Type enum.WebhookType++ Result webhook.Props+}diff --git a/app/models/dto/props.go b/app/models/dto/props.goindex 42de9a971..5a95b3472 100644--- a/app/models/dto/props.go+++ b/app/models/dto/props.go@@ -25,3 +25,10 @@ func (p Props) Merge(props Props) Props {}return new}++// Append add the given props to current props+func (p Props) Append(props Props) {+ for k, v := range props {+ p[k] = v+ }+}diff --git a/app/models/dto/webhook.go b/app/models/dto/webhook.gonew file mode 100644index 000000000..4ee3d3ab3--- /dev/null+++ b/app/models/dto/webhook.go@@ -0,0 +1,28 @@+package dto++import (+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/pkg/webhook"+)++type WebhookTriggerResult struct {+ Webhook *entity.Webhook `json:"webhook"`+ Props webhook.Props `json:"props"`+ Success bool `json:"success"`+ Url string `json:"url"`+ Content string `json:"content"`+ StatusCode int `json:"status_code"`+ Message string `json:"message"`+ Error string `json:"error"`+}++type WebhookPreviewResult struct {+ Url PreviewedField `json:"url"`+ Content PreviewedField `json:"content"`+}++type PreviewedField struct {+ Value string `json:"value,omitempty"`+ Message string `json:"message,omitempty"`+ Error string `json:"error,omitempty"`+}diff --git a/app/models/entity/post.go b/app/models/entity/post.goindex 763004b47..98273b017 100644--- a/app/models/entity/post.go+++ b/app/models/entity/post.go@@ -1,6 +1,7 @@package entityimport (+ "fmt""time""github.com/getfider/fider/app/models/enum"@@ -28,6 +29,10 @@ func (i *Post) CanBeVoted() bool {return i.Status != enum.PostCompleted && i.Status != enum.PostDeclined && i.Status != enum.PostDuplicate}+func (i *Post) Url(baseURL string) string {+ return fmt.Sprintf("%s/posts/%d/%s", baseURL, i.Number, i.Slug)+}+//PostResponse is a staff response to a given posttype PostResponse struct {Text string `json:"text"`@@ -43,3 +48,7 @@ type OriginalPost struct {Slug string `json:"slug"`Status enum.PostStatus `json:"status"`}++func (i *OriginalPost) Url(baseURL string) string {+ return fmt.Sprintf("%s/posts/%d/%s", baseURL, i.Number, i.Slug)+}diff --git a/app/models/entity/tenant.go b/app/models/entity/tenant.goindex 1b3afe5f4..7643c3157 100644--- a/app/models/entity/tenant.go+++ b/app/models/entity/tenant.go@@ -1,17 +1,19 @@package entity+import "github.com/getfider/fider/app/models/enum"+//Tenant represents a tenanttype Tenant struct {- ID int `json:"id"`- Name string `json:"name"`- Subdomain string `json:"subdomain"`- Invitation string `json:"invitation"`- WelcomeMessage string `json:"welcomeMessage"`- CNAME string `json:"cname"`- Status int `json:"status"`- Locale string `json:"locale"`- IsPrivate bool `json:"isPrivate"`- LogoBlobKey string `json:"logoBlobKey"`- CustomCSS string `json:"-"`- IsEmailAuthAllowed bool `json:"isEmailAuthAllowed"`+ ID int `json:"id"`+ Name string `json:"name"`+ Subdomain string `json:"subdomain"`+ Invitation string `json:"invitation"`+ WelcomeMessage string `json:"welcomeMessage"`+ CNAME string `json:"cname"`+ Status enum.TenantStatus `json:"status"`+ Locale string `json:"locale"`+ IsPrivate bool `json:"isPrivate"`+ LogoBlobKey string `json:"logoBlobKey"`+ CustomCSS string `json:"-"`+ IsEmailAuthAllowed bool `json:"isEmailAuthAllowed"`}diff --git a/app/models/entity/webhook.go b/app/models/entity/webhook.gonew file mode 100644index 000000000..64a0fc6ba--- /dev/null+++ b/app/models/entity/webhook.go@@ -0,0 +1,37 @@+package entity++import (+ "database/sql/driver"+ "encoding/json"+ "github.com/getfider/fider/app/models/enum"+ "github.com/getfider/fider/app/pkg/errors"+)++// Webhook represents a webhook+type Webhook struct {+ ID int `json:"id" db:"id"`+ Name string `json:"name" db:"name"`+ Type enum.WebhookType `json:"type" db:"type"`+ Status enum.WebhookStatus `json:"status" db:"status"`+ Url string `json:"url" db:"url"`+ Content string `json:"content" db:"content"`+ HttpMethod string `json:"http_method" db:"http_method"`+ HttpHeaders HttpHeaders `json:"http_headers" db:"http_headers"`+}++type HttpHeaders map[string]string++func (h HttpHeaders) Value() (driver.Value, error) {+ return json.Marshal(h)+}++func (h *HttpHeaders) Scan(src interface{}) error {+ if src == nil {+ return nil+ }+ headers, ok := src.([]byte)+ if !ok {+ return errors.New("Invalid data stored in database")+ }+ return json.Unmarshal(headers, &h)+}diff --git a/app/models/enum/avatar.go b/app/models/enum/avatar.goindex 9286b355f..787d7cbb3 100644--- a/app/models/enum/avatar.go+++ b/app/models/enum/avatar.go@@ -24,7 +24,7 @@ var avatarTypesName = map[string]AvatarType{"custom": AvatarTypeCustom,}-// String returns the string version of the user status+// String returns the string version of the avatar typefunc (t AvatarType) String() string {return avatarTypesIDs[t]}diff --git a/app/models/enum/tenant_status.go b/app/models/enum/tenant_status.goindex 066556b45..825f6a589 100644--- a/app/models/enum/tenant_status.go+++ b/app/models/enum/tenant_status.go@@ -1,12 +1,27 @@package enum+// TenantStatus is the status of a tenant+type TenantStatus int+var (//TenantActive is the default status for most tenants- TenantActive = 1+ TenantActive TenantStatus = 1//TenantPending is used for signup via email that requires user confirmation- TenantPending = 2+ TenantPending TenantStatus = 2//TenantLocked is used to set tenant on a read-only mode- TenantLocked = 3+ TenantLocked TenantStatus = 3//TenantDisabled is used to block all access- TenantDisabled = 4+ TenantDisabled TenantStatus = 4)++var tenantStatusIDs = map[TenantStatus]string{+ TenantActive: "active",+ TenantPending: "pending",+ TenantLocked: "locked",+ TenantDisabled: "disabled",+}++// String returns the string version of the tenant status+func (status TenantStatus) String() string {+ return tenantStatusIDs[status]+}diff --git a/app/models/enum/user_role.go b/app/models/enum/user_role.goindex 7af03f64b..e0f78c929 100644--- a/app/models/enum/user_role.go+++ b/app/models/enum/user_role.go@@ -24,6 +24,11 @@ var roleNames = map[string]Role{"administrator": RoleAdministrator,}+// String returns the string version of the user role+func (role Role) String() string {+ return roleIDs[role]+}+// MarshalText returns the Text version of the user rolefunc (role Role) MarshalText() ([]byte, error) {return []byte(roleIDs[role]), nildiff --git a/app/models/enum/user_status.go b/app/models/enum/user_status.goindex e72fc31f4..0b1d8ac22 100644--- a/app/models/enum/user_status.go+++ b/app/models/enum/user_status.go@@ -24,6 +24,11 @@ var userStatusName = map[string]UserStatus{"blocked": UserBlocked,}+// String returns the string version of the user status+func (status UserStatus) String() string {+ return userStatusIDs[status]+}+// MarshalText returns the Text version of the user statusfunc (status UserStatus) MarshalText() ([]byte, error) {return []byte(userStatusIDs[status]), nildiff --git a/app/models/enum/webhook_status.go b/app/models/enum/webhook_status.gonew file mode 100644index 000000000..13857d4cd--- /dev/null+++ b/app/models/enum/webhook_status.go@@ -0,0 +1,45 @@+package enum++// WebhookStatus is the status of a webhook+type WebhookStatus int++const (+ // WebhookEnabled means the webhook can be triggered+ WebhookEnabled WebhookStatus = 1+ // WebhookDisabled means the webhook cannot be triggered+ WebhookDisabled WebhookStatus = 2+ // WebhookFailed means an error occured when the webhook was previously triggered and has been disabled+ WebhookFailed WebhookStatus = 3+)++var webhookStatusIDs = map[WebhookStatus]string{+ WebhookEnabled: "enabled",+ WebhookDisabled: "disabled",+ WebhookFailed: "failed",+}++var webhookStatusName = map[string]WebhookStatus{+ "enabled": WebhookEnabled,+ "disabled": WebhookDisabled,+ "failed": WebhookFailed,+}++// MarshalText returns the Text version of the webhook status+func (status WebhookStatus) MarshalText() ([]byte, error) {+ return []byte(webhookStatusIDs[status]), nil+}++// UnmarshalText parse string into a webhook status+func (status *WebhookStatus) UnmarshalText(text []byte) error {+ *status = webhookStatusName[string(text)]+ return nil+}++// Name returns the name of a webhook status+func (status WebhookStatus) Name() string {+ name, ok := webhookStatusIDs[status]+ if ok {+ return name+ }+ return "unknown"+}diff --git a/app/models/enum/webhook_type.go b/app/models/enum/webhook_type.gonew file mode 100644index 000000000..26abbcd01--- /dev/null+++ b/app/models/enum/webhook_type.go@@ -0,0 +1,49 @@+package enum++// WebhookType is the type of a webhook+type WebhookType int++const (+ // WebhookNewPost is triggered on new post+ WebhookNewPost WebhookType = 1+ // WebhookNewComment is triggered on new comment+ WebhookNewComment WebhookType = 2+ // WebhookChangeStatus is triggered on post status change+ WebhookChangeStatus WebhookType = 3+ // WebhookDeletePost is triggered on post deletion+ WebhookDeletePost WebhookType = 4+)++var webhookTypeIDs = map[WebhookType]string{+ WebhookNewPost: "new_post",+ WebhookNewComment: "new_comment",+ WebhookChangeStatus: "change_status",+ WebhookDeletePost: "delete_post",+}++var webhookTypeName = map[string]WebhookType{+ "new_post": WebhookNewPost,+ "new_comment": WebhookNewComment,+ "change_status": WebhookChangeStatus,+ "delete_post": WebhookDeletePost,+}++// MarshalText returns the Text version of the webhook type+func (t WebhookType) MarshalText() ([]byte, error) {+ return []byte(webhookTypeIDs[t]), nil+}++// UnmarshalText parse string into a webhook type+func (t *WebhookType) UnmarshalText(text []byte) error {+ *t = webhookTypeName[string(text)]+ return nil+}++// Name returns the name of a webhook status+func (t WebhookType) Name() string {+ name, ok := webhookTypeIDs[t]+ if ok {+ return name+ }+ return "unknown"+}diff --git a/app/models/query/webhook.go b/app/models/query/webhook.gonew file mode 100644index 000000000..0dc47ed9d--- /dev/null+++ b/app/models/query/webhook.go@@ -0,0 +1,49 @@+package query++import (+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/enum"+)++type GetWebhook struct {+ ID int++ Result *entity.Webhook+}++type ListAllWebhooks struct {+ Result []*entity.Webhook+}++type ListAllWebhooksByType struct {+ Type string++ Result []*entity.Webhook+}++type ListActiveWebhooksByType struct {+ Type enum.WebhookType++ Result []*entity.Webhook+}++type CreateEditWebhook struct {+ ID int+ Name string+ Type enum.WebhookType+ Status enum.WebhookStatus+ Url string+ Content string+ HttpMethod string+ HttpHeaders entity.HttpHeaders++ Result int+}++type DeleteWebhook struct {+ ID int+}++type MarkWebhookAsFailed struct {+ ID int+}diff --git a/app/pkg/assert/assert.go b/app/pkg/assert/assert.goindex 3f1c5b266..fe5649818 100644--- a/app/pkg/assert/assert.go+++ b/app/pkg/assert/assert.go@@ -3,6 +3,7 @@ package assertimport ("context""fmt"+ "github.com/getfider/fider/app/models/dto""os""reflect""strings"@@ -30,6 +31,14 @@ func describe(v interface{}) string {return fmt.Sprintf("[%s] %v", value.Type(), v)}+func describeProps(props dto.Props) string {+ str := ""+ for k, v := range props {+ str += "\n\t\t" + k + " = " + describe(v)+ }+ return str+}+//Fail the current test case with given messagefunc Fail(msg string, args ...interface{}) {if currentT == nil {@@ -219,3 +228,29 @@ func (a *AnyAssertions) TemporarilySimilar(other time.Time, diff time.Duration)currentT.Error(errors.StackN(err, 1))return false}++func (a AnyAssertions) ContainsProps(props map[string]interface{}) bool {+ actualValue := reflect.ValueOf(a.actual)+ actualType := actualValue.Type()+ if actualType.Kind() != reflect.Map ||+ actualType.Key().Kind() != reflect.String ||+ actualType.Elem().Kind() != reflect.Interface {+ panic("Value is not a Props")+ }++ actualProps := reflect.ValueOf(a.actual).Convert(reflect.TypeOf(map[string]interface{}{})).Interface().(map[string]interface{})+ for key, expected := range props {+ actual, ok := actualProps[key]+ if !ok {+ err := fmt.Errorf("props.Contains assertion failed.\nMissing expected key:\n\t\t%s = %s\nActual props: %s", key, describe(expected), describeProps(actualProps))+ currentT.Error(errors.StackN(err, 1))+ return false+ }+ if !reflect.DeepEqual(expected, actual) {+ err := fmt.Errorf("props.Contains assertion failed.\nFor key:\n\t\t%s\nExpected value:\n\t\t%s\nActual value:\n\t\t%s", key, describe(expected), describe(actual))+ currentT.Error(errors.StackN(err, 1))+ return false+ }+ }+ return true+}diff --git a/app/pkg/tpl/funcs.go b/app/pkg/tpl/funcs.goindex 0bfa9a6fa..32a201e41 100644--- a/app/pkg/tpl/funcs.go+++ b/app/pkg/tpl/funcs.go@@ -2,8 +2,11 @@ package tplimport ("errors"+ "fmt""html/template"+ "strconv""strings"+ "time""github.com/getfider/fider/app/pkg/crypto""github.com/getfider/fider/app/pkg/i18n"@@ -13,7 +16,7 @@ import (var strictHtmlPolicy = bluemonday.NewPolicy()-var templateFunctions = template.FuncMap{+var templateFunctions = map[string]interface{}{"stripHtml": func(input string) string {return strictHtmlPolicy.Sanitize(input)},@@ -53,4 +56,18 @@ var templateFunctions = template.FuncMap{}return dict},+ "format": func(format string, date time.Time) string {+ return date.Format(format)+ },+ "quote": func(text interface{}) string {+ return quote(text)+ },+ "escape": func(text interface{}) string {+ quoted := quote(text)+ return quoted[1 : len(quoted)-1]+ },+}++func quote(text interface{}) string {+ return strconv.Quote(fmt.Sprintf("%v", text))}diff --git a/app/pkg/tpl/text.go b/app/pkg/tpl/text.gonew file mode 100644index 000000000..51a51ca2c--- /dev/null+++ b/app/pkg/tpl/text.go@@ -0,0 +1,28 @@+package tpl++import (+ "github.com/getfider/fider/app/pkg/markdown"+ "strings"+ "text/template"+)++func GetTextTemplate(name string, rawText string) (*template.Template, error) {+ tpl, err := template.New(name).Funcs(templateFunctions).Funcs(template.FuncMap{+ "markdown": func(input string) string {+ return markdown.PlainText(input)+ },+ }).Parse(rawText)+ if err != nil {+ return nil, err+ }++ return tpl, nil+}++func Execute(tmpl *template.Template, data interface{}) (string, error) {+ builder := &strings.Builder{}+ if err := tmpl.Execute(builder, data); err != nil {+ return "", err+ }+ return builder.String(), nil+}diff --git a/app/pkg/web/testdata/home_ssr.html b/app/pkg/web/testdata/home_ssr.htmlindex 8f7c8a60e..8e9679d6b 100755--- a/app/pkg/web/testdata/home_ssr.html+++ b/app/pkg/web/testdata/home_ssr.html@@ -35,8 +35,8 @@-<div id="root"><div class="c-dev-banner">DEV</div><div id="c-header"><div class="c-menu shadow p-2 w-full flex flex flex-x flex--spacing-1 flex-items-center"><div class="container"><div class="flex flex flex-x flex--spacing-1 flex-items-center justify-between"><a href="/" class="flex flex-x flex-items-center flex--spacing-2 h-8"><h1 class="text-title"></h1></a><a href="#" class="uppercase text-sm">Sign in</a></div></div></div></div><div id="p-home" class="page container"><div class="p-home__welcome-col"><div class="flex flex flex-y flex--spacing-2"><div class="c-markdown "><p>We'd love to hear what you're thinking about.</p>-<p>What can we do better? This is the place for you to vote, discuss and share ideas.</p></div><form autoComplete="off" class="c-form"><div class="c-form-field"><div class="relative flex flex flex-x"><input type="text" class="c-input" id="input-title" tabindex="-1" maxLength="100" value="" placeholder="Enter your suggestion here..."/></div></div></form><div class="c-powered sm:hidden md:hidden lg:block"><a rel="noopener" href="https://getfider.com" target="_blank">Powered by Fider</a></div></div></div><div class="p-home__posts-col"><div class="text-center"><img style="height:120px" height="120" class="mt-6 mb-2" src="data:image/svg+xml;base64,PHN2ZyBpZD0iYjIxNjEzYzktMmJmMC00ZDM3LWJlZjAtM2IxOTNkMzRmYzVkIiBkYXRhLW5hbWU9IkxheWVyIDEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjY0Ny42MzYyNiIgaGVpZ2h0PSI2MzIuMTczODMiIHZpZXdCb3g9IjAgMCA2NDcuNjM2MjYgNjMyLjE3MzgzIj48cGF0aCBkPSJNNjg3LjMyNzksMjc2LjA4NjkxSDUxMi44MTgxM2ExNS4wMTgyOCwxNS4wMTgyOCwwLDAsMC0xNSwxNXYzODcuODVsLTIsLjYxMDA1LTQyLjgxMDA2LDEzLjExYTguMDA2NzYsOC4wMDY3NiwwLDAsMS05Ljk4OTc0LTUuMzFMMzE1LjY3OCwyNzEuMzk2OTFhOC4wMDMxMyw4LjAwMzEzLDAsMCwxLDUuMzEwMDYtOS45OWw2NS45NzAyMi0yMC4yLDE5MS4yNS01OC41NCw2NS45Njk3Mi0yMC4yYTcuOTg5MjcsNy45ODkyNywwLDAsMSw5Ljk5MDI0LDUuM2wzMi41NDk4LDEwNi4zMloiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yNzYuMTgxODcgLTEzMy45MTMwOSkiIGZpbGw9IiNmMmYyZjIiLz48cGF0aCBkPSJNNzI1LjQwOCwyNzQuMDg2OTFsLTM5LjIzLTEyOC4xNGExNi45OTM2OCwxNi45OTM2OCwwLDAsMC0yMS4yMy0xMS4yOGwtOTIuNzUsMjguMzlMMzgwLjk1ODI3LDIyMS42MDY5M2wtOTIuNzUsMjguNGExNy4wMTUyLDE3LjAxNTIsMCwwLDAtMTEuMjgwMjgsMjEuMjNsMTM0LjA4MDA4LDQzNy45M2ExNy4wMjY2MSwxNy4wMjY2MSwwLDAsMCwxNi4yNjAyNiwxMi4wMywxNi43ODkyNiwxNi43ODkyNiwwLDAsMCw0Ljk2OTcyLS43NWw2My41ODAwOC0xOS40NiwyLS42MnYtMi4wOWwtMiwuNjEtNjQuMTY5OTIsMTkuNjVhMTUuMDE0ODksMTUuMDE0ODksMCwwLDEtMTguNzMtOS45NWwtMTM0LjA2OTgzLTQzNy45NGExNC45NzkzNSwxNC45NzkzNSwwLDAsMSw5Ljk0OTcxLTE4LjczbDkyLjc1LTI4LjQsMTkxLjI0MDI0LTU4LjU0LDkyLjc1LTI4LjRhMTUuMTU1NTEsMTUuMTU1NTEsMCwwLDEsNC40MDk2Ni0uNjYsMTUuMDE0NjEsMTUuMDE0NjEsMCwwLDEsMTQuMzIwMzIsMTAuNjFsMzkuMDQ5OCwxMjcuNTYuNjIwMTIsMmgyLjA4MDA4WiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTI3Ni4xODE4NyAtMTMzLjkxMzA5KSIgZmlsbD0iIzNmM2Q1NiIvPjxwYXRoIGQ9Ik0zOTguODYyNzksMjYxLjczMzg5YTkuMDE1Nyw5LjAxNTcsMCwwLDEtOC42MTEzMy02LjM2NjdsLTEyLjg4MDM3LTQyLjA3MTc4YTguOTk4ODQsOC45OTg4NCwwLDAsMSw1Ljk3MTItMTEuMjQwMjNsMTc1LjkzOS01My44NjM3N2E5LjAwODY3LDkuMDA4NjcsMCwwLDEsMTEuMjQwNzIsNS45NzA3bDEyLjg4MDM3LDQyLjA3MjI3YTkuMDEwMjksOS4wMTAyOSwwLDAsMS01Ljk3MDcsMTEuMjQwNzJMNDAxLjQ5MjE5LDI2MS4zMzg4N0E4Ljk3Niw4Ljk3NiwwLDAsMSwzOTguODYyNzksMjYxLjczMzg5WiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTI3Ni4xODE4NyAtMTMzLjkxMzA5KSIgZmlsbD0iIzQzMzhjYSIvPjxjaXJjbGUgY3g9IjE5MC4xNTM1MSIgY3k9IjI0Ljk1NDY1IiByPSIyMCIgZmlsbD0iIzQzMzhjYSIvPjxjaXJjbGUgY3g9IjE5MC4xNTM1MSIgY3k9IjI0Ljk1NDY1IiByPSIxMi42NjQ2MiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik04NzguODE4MzYsNzE2LjA4NjkxaC0zMzhhOC41MDk4MSw4LjUwOTgxLDAsMCwxLTguNS04LjV2LTQwNWE4LjUwOTUxLDguNTA5NTEsMCwwLDEsOC41LTguNWgzMzhhOC41MDk4Miw4LjUwOTgyLDAsMCwxLDguNSw4LjV2NDA1QTguNTEwMTMsOC41MTAxMywwLDAsMSw4NzguODE4MzYsNzE2LjA4NjkxWiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTI3Ni4xODE4NyAtMTMzLjkxMzA5KSIgZmlsbD0iI2U2ZTZlNiIvPjxwYXRoIGQ9Ik03MjMuMzE4MTMsMjc0LjA4NjkxaC0yMTAuNWExNy4wMjQxMSwxNy4wMjQxMSwwLDAsMC0xNywxN3Y0MDcuOGwyLS42MXYtNDA3LjE5YTE1LjAxODI4LDE1LjAxODI4LDAsMCwxLDE1LTE1SDcyMy45MzgyNVptMTgzLjUsMGgtMzk0YTE3LjAyNDExLDE3LjAyNDExLDAsMCwwLTE3LDE3djQ1OGExNy4wMjQxLDE3LjAyNDEsMCwwLDAsMTcsMTdoMzk0YTE3LjAyNDEsMTcuMDI0MSwwLDAsMCwxNy0xN3YtNDU4QTE3LjAyNDExLDE3LjAyNDExLDAsMCwwLDkwNi44MTgxMywyNzQuMDg2OTFabTE1LDQ3NWExNS4wMTgyOCwxNS4wMTgyOCwwLDAsMS0xNSwxNWgtMzk0YTE1LjAxODI4LDE1LjAxODI4LDAsMCwxLTE1LTE1di00NThhMTUuMDE4MjgsMTUuMDE4MjgsMCwwLDEsMTUtMTVoMzk0YTE1LjAxODI4LDE1LjAxODI4LDAsMCwxLDE1LDE1WiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTI3Ni4xODE4NyAtMTMzLjkxMzA5KSIgZmlsbD0iIzNmM2Q1NiIvPjxwYXRoIGQ9Ik04MDEuODE4MzYsMzE4LjA4NjkxaC0xODRhOS4wMTAxNSw5LjAxMDE1LDAsMCwxLTktOXYtNDRhOS4wMTAxNiw5LjAxMDE2LDAsMCwxLDktOWgxODRhOS4wMTAxNiw5LjAxMDE2LDAsMCwxLDksOXY0NEE5LjAxMDE1LDkuMDEwMTUsMCwwLDEsODAxLjgxODM2LDMxOC4wODY5MVoiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yNzYuMTgxODcgLTEzMy45MTMwOSkiIGZpbGw9IiM0MzM4Y2EiLz48Y2lyY2xlIGN4PSI0MzMuNjM2MjYiIGN5PSIxMDUuMTczODMiIHI9IjIwIiBmaWxsPSIjNDMzOGNhIi8+PGNpcmNsZSBjeD0iNDMzLjYzNjI2IiBjeT0iMTA1LjE3MzgzIiByPSIxMi4xODE4NyIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg=="/><p class="text-muted">No posts have been created yet.</p></div><div class="c-powered lg:hidden xl:hidden mt-8"><a rel="noopener" href="https://getfider.com" target="_blank">Powered by Fider</a></div></div></div></div>+<div id="root"><div class="c-dev-banner">DEV</div><div id="c-header"><div class="c-menu shadow p-2 w-full flex flex-x flex--spacing-1 flex-items-center"><div class="container"><div class="flex flex-x flex--spacing-1 flex-items-center justify-between"><a href="/" class="flex flex-x flex-items-center flex--spacing-2 h-8"><h1 class="text-title"></h1></a><a href="#" class="uppercase text-sm">Sign in</a></div></div></div></div><div id="p-home" class="page container"><div class="p-home__welcome-col"><div class="flex flex-y flex--spacing-2"><div class="c-markdown "><p>We'd love to hear what you're thinking about.</p>+<p>What can we do better? This is the place for you to vote, discuss and share ideas.</p></div><form autoComplete="off" class="c-form"><div class="c-form-field"><div class="relative flex flex-x"><input type="text" class="c-input" id="input-title" tabindex="-1" maxLength="100" value="" placeholder="Enter your suggestion here..."/></div></div></form><div class="c-powered sm:hidden md:hidden lg:block"><a rel="noopener" href="https://getfider.com" target="_blank">Powered by Fider</a></div></div></div><div class="p-home__posts-col"><div class="text-center"><img style="height:120px" height="120" class="mt-6 mb-2" src="data:image/svg+xml;base64,PHN2ZyBpZD0iYjIxNjEzYzktMmJmMC00ZDM3LWJlZjAtM2IxOTNkMzRmYzVkIiBkYXRhLW5hbWU9IkxheWVyIDEiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgd2lkdGg9IjY0Ny42MzYyNiIgaGVpZ2h0PSI2MzIuMTczODMiIHZpZXdCb3g9IjAgMCA2NDcuNjM2MjYgNjMyLjE3MzgzIj48cGF0aCBkPSJNNjg3LjMyNzksMjc2LjA4NjkxSDUxMi44MTgxM2ExNS4wMTgyOCwxNS4wMTgyOCwwLDAsMC0xNSwxNXYzODcuODVsLTIsLjYxMDA1LTQyLjgxMDA2LDEzLjExYTguMDA2NzYsOC4wMDY3NiwwLDAsMS05Ljk4OTc0LTUuMzFMMzE1LjY3OCwyNzEuMzk2OTFhOC4wMDMxMyw4LjAwMzEzLDAsMCwxLDUuMzEwMDYtOS45OWw2NS45NzAyMi0yMC4yLDE5MS4yNS01OC41NCw2NS45Njk3Mi0yMC4yYTcuOTg5MjcsNy45ODkyNywwLDAsMSw5Ljk5MDI0LDUuM2wzMi41NDk4LDEwNi4zMloiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yNzYuMTgxODcgLTEzMy45MTMwOSkiIGZpbGw9IiNmMmYyZjIiLz48cGF0aCBkPSJNNzI1LjQwOCwyNzQuMDg2OTFsLTM5LjIzLTEyOC4xNGExNi45OTM2OCwxNi45OTM2OCwwLDAsMC0yMS4yMy0xMS4yOGwtOTIuNzUsMjguMzlMMzgwLjk1ODI3LDIyMS42MDY5M2wtOTIuNzUsMjguNGExNy4wMTUyLDE3LjAxNTIsMCwwLDAtMTEuMjgwMjgsMjEuMjNsMTM0LjA4MDA4LDQzNy45M2ExNy4wMjY2MSwxNy4wMjY2MSwwLDAsMCwxNi4yNjAyNiwxMi4wMywxNi43ODkyNiwxNi43ODkyNiwwLDAsMCw0Ljk2OTcyLS43NWw2My41ODAwOC0xOS40NiwyLS42MnYtMi4wOWwtMiwuNjEtNjQuMTY5OTIsMTkuNjVhMTUuMDE0ODksMTUuMDE0ODksMCwwLDEtMTguNzMtOS45NWwtMTM0LjA2OTgzLTQzNy45NGExNC45NzkzNSwxNC45NzkzNSwwLDAsMSw5Ljk0OTcxLTE4LjczbDkyLjc1LTI4LjQsMTkxLjI0MDI0LTU4LjU0LDkyLjc1LTI4LjRhMTUuMTU1NTEsMTUuMTU1NTEsMCwwLDEsNC40MDk2Ni0uNjYsMTUuMDE0NjEsMTUuMDE0NjEsMCwwLDEsMTQuMzIwMzIsMTAuNjFsMzkuMDQ5OCwxMjcuNTYuNjIwMTIsMmgyLjA4MDA4WiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTI3Ni4xODE4NyAtMTMzLjkxMzA5KSIgZmlsbD0iIzNmM2Q1NiIvPjxwYXRoIGQ9Ik0zOTguODYyNzksMjYxLjczMzg5YTkuMDE1Nyw5LjAxNTcsMCwwLDEtOC42MTEzMy02LjM2NjdsLTEyLjg4MDM3LTQyLjA3MTc4YTguOTk4ODQsOC45OTg4NCwwLDAsMSw1Ljk3MTItMTEuMjQwMjNsMTc1LjkzOS01My44NjM3N2E5LjAwODY3LDkuMDA4NjcsMCwwLDEsMTEuMjQwNzIsNS45NzA3bDEyLjg4MDM3LDQyLjA3MjI3YTkuMDEwMjksOS4wMTAyOSwwLDAsMS01Ljk3MDcsMTEuMjQwNzJMNDAxLjQ5MjE5LDI2MS4zMzg4N0E4Ljk3Niw4Ljk3NiwwLDAsMSwzOTguODYyNzksMjYxLjczMzg5WiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTI3Ni4xODE4NyAtMTMzLjkxMzA5KSIgZmlsbD0iIzQzMzhjYSIvPjxjaXJjbGUgY3g9IjE5MC4xNTM1MSIgY3k9IjI0Ljk1NDY1IiByPSIyMCIgZmlsbD0iIzQzMzhjYSIvPjxjaXJjbGUgY3g9IjE5MC4xNTM1MSIgY3k9IjI0Ljk1NDY1IiByPSIxMi42NjQ2MiIgZmlsbD0iI2ZmZiIvPjxwYXRoIGQ9Ik04NzguODE4MzYsNzE2LjA4NjkxaC0zMzhhOC41MDk4MSw4LjUwOTgxLDAsMCwxLTguNS04LjV2LTQwNWE4LjUwOTUxLDguNTA5NTEsMCwwLDEsOC41LTguNWgzMzhhOC41MDk4Miw4LjUwOTgyLDAsMCwxLDguNSw4LjV2NDA1QTguNTEwMTMsOC41MTAxMywwLDAsMSw4NzguODE4MzYsNzE2LjA4NjkxWiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTI3Ni4xODE4NyAtMTMzLjkxMzA5KSIgZmlsbD0iI2U2ZTZlNiIvPjxwYXRoIGQ9Ik03MjMuMzE4MTMsMjc0LjA4NjkxaC0yMTAuNWExNy4wMjQxMSwxNy4wMjQxMSwwLDAsMC0xNywxN3Y0MDcuOGwyLS42MXYtNDA3LjE5YTE1LjAxODI4LDE1LjAxODI4LDAsMCwxLDE1LTE1SDcyMy45MzgyNVptMTgzLjUsMGgtMzk0YTE3LjAyNDExLDE3LjAyNDExLDAsMCwwLTE3LDE3djQ1OGExNy4wMjQxLDE3LjAyNDEsMCwwLDAsMTcsMTdoMzk0YTE3LjAyNDEsMTcuMDI0MSwwLDAsMCwxNy0xN3YtNDU4QTE3LjAyNDExLDE3LjAyNDExLDAsMCwwLDkwNi44MTgxMywyNzQuMDg2OTFabTE1LDQ3NWExNS4wMTgyOCwxNS4wMTgyOCwwLDAsMS0xNSwxNWgtMzk0YTE1LjAxODI4LDE1LjAxODI4LDAsMCwxLTE1LTE1di00NThhMTUuMDE4MjgsMTUuMDE4MjgsMCwwLDEsMTUtMTVoMzk0YTE1LjAxODI4LDE1LjAxODI4LDAsMCwxLDE1LDE1WiIgdHJhbnNmb3JtPSJ0cmFuc2xhdGUoLTI3Ni4xODE4NyAtMTMzLjkxMzA5KSIgZmlsbD0iIzNmM2Q1NiIvPjxwYXRoIGQ9Ik04MDEuODE4MzYsMzE4LjA4NjkxaC0xODRhOS4wMTAxNSw5LjAxMDE1LDAsMCwxLTktOXYtNDRhOS4wMTAxNiw5LjAxMDE2LDAsMCwxLDktOWgxODRhOS4wMTAxNiw5LjAxMDE2LDAsMCwxLDksOXY0NEE5LjAxMDE1LDkuMDEwMTUsMCwwLDEsODAxLjgxODM2LDMxOC4wODY5MVoiIHRyYW5zZm9ybT0idHJhbnNsYXRlKC0yNzYuMTgxODcgLTEzMy45MTMwOSkiIGZpbGw9IiM0MzM4Y2EiLz48Y2lyY2xlIGN4PSI0MzMuNjM2MjYiIGN5PSIxMDUuMTczODMiIHI9IjIwIiBmaWxsPSIjNDMzOGNhIi8+PGNpcmNsZSBjeD0iNDMzLjYzNjI2IiBjeT0iMTA1LjE3MzgzIiByPSIxMi4xODE4NyIgZmlsbD0iI2ZmZiIvPjwvc3ZnPg=="/><p class="text-muted">No posts have been created yet.</p></div><div class="c-powered lg:hidden xl:hidden mt-8"><a rel="noopener" href="https://getfider.com" target="_blank">Powered by Fider</a></div></div></div></div><script id="server-data" type="application/json">diff --git a/app/pkg/webhook/props.go b/app/pkg/webhook/props.gonew file mode 100644index 000000000..580ce10a9--- /dev/null+++ b/app/pkg/webhook/props.go@@ -0,0 +1,79 @@+package webhook++import (+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/enum"+)++// Props is a map of key:value+type Props map[string]interface{}++// SetUser describe the user prefixed by "keyPrefix"+func (p Props) SetUser(user *entity.User, keyPrefix string) Props {+ if user != nil {+ p[keyPrefix+"_id"] = user.ID+ p[keyPrefix+"_name"] = user.Name+ p[keyPrefix+"_email"] = user.Email+ p[keyPrefix+"_role"] = user.Role.String()+ p[keyPrefix+"_avatar"] = user.AvatarURL+ }+ return p+}++// SetTenant describe the tenant prefixed by "keyPrefix"+func (p Props) SetTenant(tenant *entity.Tenant, keyPrefix, baseURL, logoURL string) Props {+ if tenant != nil {+ p[keyPrefix+"_id"] = tenant.ID+ p[keyPrefix+"_name"] = tenant.Name+ p[keyPrefix+"_subdomain"] = tenant.Subdomain+ p[keyPrefix+"_status"] = tenant.Status.String()+ p[keyPrefix+"_locale"] = tenant.Locale+ p[keyPrefix+"_url"] = baseURL+ p[keyPrefix+"_logo"] = logoURL+ }+ return p+}++// SetPost describe the post prefixed by "keyPrefix"+func (p Props) SetPost(post *entity.Post, keyPrefix, baseURL string, includeAllFields, includeAuthor bool) Props {+ if post != nil {+ p[keyPrefix+"_id"] = post.ID+ p[keyPrefix+"_number"] = post.Number+ p[keyPrefix+"_title"] = post.Title+ p[keyPrefix+"_slug"] = post.Slug+ p[keyPrefix+"_description"] = post.Description+ p[keyPrefix+"_created_at"] = post.CreatedAt+ p[keyPrefix+"_url"] = post.Url(baseURL)++ if includeAuthor {+ p.SetUser(post.User, keyPrefix+"_author")+ }++ if includeAllFields {+ postResponse := post.Response+ p[keyPrefix+"_votes"] = post.VotesCount+ p[keyPrefix+"_comments"] = post.CommentsCount+ p[keyPrefix+"_status"] = post.Status.Name()+ p[keyPrefix+"_tags"] = post.Tags+ p[keyPrefix+"_response"] = postResponse != nil++ if postResponse != nil {+ keyPrefix := keyPrefix + "_response"+ p[keyPrefix+"_text"] = postResponse.Text+ p[keyPrefix+"_responded_at"] = postResponse.RespondedAt+ p.SetUser(postResponse.User, keyPrefix+"_author")++ originalPost := postResponse.Original+ if post.Status == enum.PostDuplicate && originalPost != nil {+ keyPrefix := keyPrefix + "_original"+ p[keyPrefix+"_number"] = originalPost.Number+ p[keyPrefix+"_title"] = originalPost.Title+ p[keyPrefix+"_slug"] = originalPost.Slug+ p[keyPrefix+"_status"] = originalPost.Status.Name()+ p[keyPrefix+"_url"] = originalPost.Url(baseURL)+ }+ }+ }+ }+ return p+}diff --git a/app/services/sqlstore/postgres/postgres.go b/app/services/sqlstore/postgres/postgres.goindex 03d7fb056..47b84d4cb 100644--- a/app/services/sqlstore/postgres/postgres.go+++ b/app/services/sqlstore/postgres/postgres.go@@ -116,6 +116,14 @@ func (s Service) Init() {bus.AddHandler(listCustomOAuthConfig)bus.AddHandler(getCustomOAuthConfigByProvider)bus.AddHandler(saveCustomOAuthConfig)++ bus.AddHandler(getWebhook)+ bus.AddHandler(listAllWebhooks)+ bus.AddHandler(listAllWebhooksByType)+ bus.AddHandler(listActiveWebhooksByType)+ bus.AddHandler(createEditWebhook)+ bus.AddHandler(deleteWebhook)+ bus.AddHandler(markWebhookAsFailed)}type SqlHandler func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) errordiff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.goindex 62ed0a78b..8dab8d40a 100644--- a/app/services/sqlstore/postgres/tenant.go+++ b/app/services/sqlstore/postgres/tenant.go@@ -43,7 +43,7 @@ func (t *dbTenant) toModel() *entity.Tenant {CNAME: t.CNAME,Invitation: t.Invitation,WelcomeMessage: t.WelcomeMessage,- Status: t.Status,+ Status: enum.TenantStatus(t.Status),Locale: t.Locale,IsPrivate: t.IsPrivate,LogoBlobKey: t.LogoBlobKey,diff --git a/app/services/sqlstore/postgres/webhook.go b/app/services/sqlstore/postgres/webhook.gonew file mode 100644index 000000000..84a426b0e--- /dev/null+++ b/app/services/sqlstore/postgres/webhook.go@@ -0,0 +1,120 @@+package postgres++import (+ "context"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/enum"+ "github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/dbx"+)++func getWebhook(ctx context.Context, q *query.GetWebhook) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ webhook := &entity.Webhook{}+ err := trx.Get(webhook, `+ SELECT id, name, type, status, url, content, http_method, http_headers+ FROM webhooks+ WHERE tenant_id = $1 AND id = $2`, tenant.ID, q.ID)+ if err != nil {+ return err+ }++ q.Result = webhook+ return nil+ })+}++func listAllWebhooks(ctx context.Context, q *query.ListAllWebhooks) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ webhooks := []*entity.Webhook{}+ err := trx.Select(&webhooks, `+ SELECT id, name, type, status, url, content, http_method, http_headers+ FROM webhooks+ WHERE tenant_id = $1+ ORDER BY id`, tenant.ID)+ if err != nil {+ return err+ }++ q.Result = webhooks+ return nil+ })+}++func listAllWebhooksByType(ctx context.Context, q *query.ListAllWebhooksByType) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ webhooks := []*entity.Webhook{}+ err := trx.Select(&webhooks, `+ SELECT id, name, type, status, url, content, http_method, http_headers+ FROM webhooks+ WHERE tenant_id = $1 AND type = $2+ ORDER BY id`, tenant.ID, q.Type)+ if err != nil {+ return err+ }++ q.Result = webhooks+ return nil+ })+}++func listActiveWebhooksByType(ctx context.Context, q *query.ListActiveWebhooksByType) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ webhooks := []*entity.Webhook{}+ err := trx.Select(&webhooks, `+ SELECT id, name, type, status, url, content, http_method, http_headers+ FROM webhooks+ WHERE tenant_id = $1 AND type = $2 AND status = $3+ ORDER BY id`, tenant.ID, q.Type, enum.WebhookEnabled)+ if err != nil {+ return err+ }++ q.Result = webhooks+ return nil+ })+}++func createEditWebhook(ctx context.Context, q *query.CreateEditWebhook) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ var err error+ id := q.ID++ if q.ID == 0 {+ err = trx.Get(&id, `+ INSERT INTO webhooks (name, type, status, url, content, http_method, http_headers, tenant_id)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)+ RETURNING id`, q.Name, q.Type, q.Status, q.Url, q.Content, q.HttpMethod, q.HttpHeaders, tenant.ID)+ } else {+ _, err = trx.Execute(`+ UPDATE webhooks+ SET name = $3, type = $4, status = $5, url = $6, content = $7, http_method = $8, http_headers = $9+ WHERE tenant_id = $1 AND id = $2`, tenant.ID, q.ID, q.Name, q.Type, q.Status, q.Url, q.Content, q.HttpMethod, q.HttpHeaders)+ }++ if err != nil {+ return err+ }+ q.Result = id+ return nil+ })+}++func deleteWebhook(ctx context.Context, q *query.DeleteWebhook) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ _, err := trx.Execute(`+ DELETE FROM webhooks+ WHERE tenant_id = $1 AND id = $2`, tenant.ID, q.ID)+ return err+ })+}++func markWebhookAsFailed(ctx context.Context, q *query.MarkWebhookAsFailed) error {+ return using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {+ _, err := trx.Execute(`+ UPDATE webhooks+ SET status = $3+ WHERE tenant_id = $1 AND id = $2`, tenant.ID, q.ID, enum.WebhookFailed)+ return err+ })+}diff --git a/app/services/webhook/dummy_props.go b/app/services/webhook/dummy_props.gonew file mode 100644index 000000000..c33c4006d--- /dev/null+++ b/app/services/webhook/dummy_props.go@@ -0,0 +1,67 @@+package webhook++import (+ "context"+ "github.com/getfider/fider/app"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/enum"+ "github.com/getfider/fider/app/pkg/web"+ "github.com/getfider/fider/app/pkg/webhook"+ "time"+)++var dummyPost = &entity.Post{+ ID: 36,+ Number: 36,+ Title: "Example dummy post title",+ Slug: "example-dummy-post-title",+ Description: `*Those data are fake.*++This is an example of a post, but don't worry, nothing was created on your Fider instance:+It was just a test of a webhook trigger.++You can use ` + "`" + `{{ markdown .post_description }}` + "`" + ` to parse __Markdown__ to **HTML** in post!`,+ CreatedAt: time.Date(2021, time.May, 7, 18, 42, 27, 0, time.UTC),+ User: &entity.User{+ ID: 7,+ Name: "Fider",+ Email: "[email protected]",+ Role: 1,+ },+ HasVoted: true,+ VotesCount: 7,+ CommentsCount: 3,+ Status: enum.PostStarted,+ Response: &entity.PostResponse{+ Text: "This is a response, still in *Markdown*.",+ RespondedAt: time.Date(2021, time.July, 9, 15, 29, 57, 0, time.UTC),+ User: nil,+ },+ Tags: []string{"tag1", "tag2"},+}++func dummyTriggerProps(c context.Context, webhookType enum.WebhookType) webhook.Props {+ props := webhook.Props{}+ author := c.Value(app.UserCtxKey).(*entity.User)+ tenant := c.Value(app.TenantCtxKey).(*entity.Tenant)+ baseURL, logoURL := web.BaseURL(c), web.LogoURL(c)+ dummyPost.User.AvatarURL = logoURL+ dummyPost.Response.User = author+ props.SetUser(author, "author")+ props.SetTenant(tenant, "tenant", baseURL, logoURL)+ switch webhookType {+ case enum.WebhookNewPost:+ props.SetPost(dummyPost, "post", baseURL, false, false)+ case enum.WebhookNewComment:+ props.SetPost(dummyPost, "post", baseURL, true, true)+ props["comment"] = "An example **comment** on a post."+ case enum.WebhookChangeStatus:+ props.SetPost(dummyPost, "post", baseURL, true, true)+ props["post_old_status"] = enum.PostOpen.Name()+ case enum.WebhookDeletePost:+ props.SetPost(dummyPost, "post", baseURL, true, true)+ props["post_status"] = enum.PostDeleted.Name()+ props["post_response_text"] = "The reason _why_ this post was deleted."+ }+ return props+}diff --git a/app/services/webhook/webhook.go b/app/services/webhook/webhook.gonew file mode 100644index 000000000..b0e4c9fd8--- /dev/null+++ b/app/services/webhook/webhook.go@@ -0,0 +1,174 @@+package webhook++import (+ "context"+ "fmt"+ "github.com/getfider/fider/app/models/cmd"+ "github.com/getfider/fider/app/models/dto"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/log"+ "github.com/getfider/fider/app/pkg/tpl"+ "github.com/getfider/fider/app/pkg/webhook"+ "net/http"+ "strings"+)++func init() {+ bus.Register(Service{})+}++type Service struct{}++func (s Service) Name() string {+ return "Webhook"+}++func (s Service) Category() string {+ return "hook"+}++func (s Service) Enabled() bool {+ return true+}++func (s Service) Init() {+ bus.AddHandler(testWebhook)+ bus.AddHandler(triggerWebhooks)+ bus.AddHandler(previewWebhook)+ bus.AddHandler(getWebhookProps)+}++func testWebhook(ctx context.Context, c *cmd.TestWebhook) error {+ webhook_ := &query.GetWebhook{ID: c.ID}+ err := bus.Dispatch(ctx, webhook_)+ if err != nil {+ return err+ }++ c.Result, err = triggerWebhook(ctx, webhook_.Result, dummyTriggerProps(ctx, webhook_.Result.Type))+ if err != nil {+ return err+ }++ return nil+}++func triggerWebhooks(ctx context.Context, c *cmd.TriggerWebhooks) error {+ webhooks := &query.ListActiveWebhooksByType{Type: c.Type}+ err := bus.Dispatch(ctx, webhooks)+ if err != nil {+ return err+ }++ for _, webhook_ := range webhooks.Result {+ _, err = triggerWebhook(ctx, webhook_, c.Props)+ if err != nil {+ return err+ }+ }++ return nil+}++func triggerWebhook(ctx context.Context, webhook *entity.Webhook, props webhook.Props) (*dto.WebhookTriggerResult, error) {+ result := &dto.WebhookTriggerResult{Webhook: webhook, Props: props}+ var err error++ fullName := fmt.Sprintf("%d-%s", webhook.ID, webhook.Name)+ result.Url, err = executeTemplate(fmt.Sprintf("%s-url", fullName), webhook.Url, props)+ if err != nil {+ return resultWithError(ctx, "Could not parse webhook URL template", err.Error(), result)+ }+ result.Content, err = executeTemplate(fmt.Sprintf("%s-content", fullName), webhook.Content, props)+ if err != nil {+ return resultWithError(ctx, "Could not parse webhook content template", err.Error(), result)+ }++ httpRequest := &cmd.HTTPRequest{+ URL: result.Url,+ Body: strings.NewReader(result.Content),+ Method: webhook.HttpMethod,+ Headers: webhook.HttpHeaders,+ BasicAuth: nil,+ }+ err = bus.Dispatch(ctx, httpRequest)+ if err != nil {+ return resultWithError(ctx, "Could not execute webhook HTTP request", err.Error(), result)+ }+ result.StatusCode = httpRequest.ResponseStatusCode+ if result.StatusCode >= http.StatusBadRequest {+ fullResponse := fmt.Sprintf("%d %s:\n%s", result.StatusCode, http.StatusText(result.StatusCode), httpRequest.ResponseBody)+ return resultWithError(ctx, "Webhook HTTP request returned an error response code", fullResponse, result)+ }++ result.Success = true+ log.Infof(ctx, "Webhook #@{ID:yellow} @{Name:blue} finished with @{Code:magenta}", dto.Props{+ "ID": webhook.ID,+ "Name": webhook.Name,+ "Code": result.StatusCode,+ })+ return result, nil+}++func previewWebhook(ctx context.Context, c *cmd.PreviewWebhook) error {+ c.Result = &dto.WebhookPreviewResult{}+ var err error+ props := dummyTriggerProps(ctx, c.Type)++ c.Result.Url.Value, err = executeTemplate("preview-url", c.Url, props)+ if err != nil {+ c.Result.Url.Message = "Could not parse webhook URL template"+ c.Result.Url.Error = err.Error()+ // Do not propagate error: it's a preview+ }+ c.Result.Content.Value, err = executeTemplate("preview-content", c.Content, props)+ if err != nil {+ c.Result.Content.Message = "Could not parse webhook content template"+ c.Result.Content.Error = err.Error()+ // Do not propagate error: it's a preview+ }++ return nil+}++func executeTemplate(name, text string, props webhook.Props) (string, error) {+ tmpl, err := tpl.GetTextTemplate(name, text)+ if err != nil {+ return "", err+ }++ replacedText, err := tpl.Execute(tmpl, props)+ if err != nil {+ return "", err+ }++ return replacedText, nil+}++func resultWithError(ctx context.Context, message, error string, result *dto.WebhookTriggerResult) (*dto.WebhookTriggerResult, error) {+ result.Success = false+ result.Message = message+ result.Error = error++ log.Warnf(ctx, "@{Message} (ID: @{ID:yellow}, Name: @{Name:blue}): @{Error:red}", dto.Props{+ "Message": message,+ "ID": result.Webhook.ID,+ "Name": result.Webhook.Name,+ "Error": error,+ })++ webhooks := &query.MarkWebhookAsFailed{ID: result.Webhook.ID}+ err := bus.Dispatch(ctx, webhooks)+ if err != nil {+ return nil, err+ }++ return result, nil+}++func getWebhookProps(ctx context.Context, c *cmd.GetWebhookProps) error {+ c.Result = dummyTriggerProps(ctx, c.Type)+ return nil+}diff --git a/app/tasks/tasks.go b/app/tasks/tasks.goindex 4cf3dd361..0d28e0f31 100644--- a/app/tasks/tasks.go+++ b/app/tasks/tasks.go@@ -3,6 +3,7 @@ package tasksimport ("context""fmt"+ "github.com/getfider/fider/app/pkg/webhook""strings""time"@@ -111,10 +112,11 @@ func NotifyAboutNewPost(post *entity.Post) worker.Task {return c.Failure(err)}+ author := c.User()title := fmt.Sprintf("New post: **%s**", post.Title)link := fmt.Sprintf("/posts/%d/%s", post.Number, post.Slug)for _, user := range users {- if user.ID != c.User().ID {+ if user.ID != author.ID {err = bus.Dispatch(c, &cmd.AddNewNotification{User: user,Title: title,@@ -135,29 +137,45 @@ func NotifyAboutNewPost(post *entity.Post) worker.Task {to := make([]dto.Recipient, 0)for _, user := range users {- if user.ID != c.User().ID {+ if user.ID != author.ID {to = append(to, dto.NewRecipient(user.Name, user.Email, dto.Props{}))}}- props := dto.Props{+ tenant := c.Tenant()+ baseURL, logoURL := web.BaseURL(c), web.LogoURL(c)++ mailProps := dto.Props{"title": post.Title,- "siteName": c.Tenant().Name,- "userName": c.User().Name,+ "siteName": tenant.Name,+ "userName": author.Name,"content": markdown.Full(post.Description),- "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),- "view": linkWithText(i18n.T(c, "email.subscription.view"), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),- "change": linkWithText(i18n.T(c, "email.subscription.change"), web.BaseURL(c), "/settings"),- "logo": web.LogoURL(c),+ "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), baseURL, "/posts/%d/%s", post.Number, post.Slug),+ "view": linkWithText(i18n.T(c, "email.subscription.view"), baseURL, "/posts/%d/%s", post.Number, post.Slug),+ "change": linkWithText(i18n.T(c, "email.subscription.change"), baseURL, "/settings"),+ "logo": logoURL,}bus.Publish(c, &cmd.SendMail{- From: c.User().Name,+ From: author.Name,To: to,TemplateName: "new_post",- Props: props,+ Props: mailProps,})+ webhookProps := webhook.Props{}+ webhookProps.SetPost(post, "post", baseURL, false, false)+ webhookProps.SetUser(author, "author")+ webhookProps.SetTenant(tenant, "tenant", baseURL, logoURL)++ err = bus.Dispatch(c, &cmd.TriggerWebhooks{+ Type: enum.WebhookNewPost,+ Props: webhookProps,+ })+ if err != nil {+ return c.Failure(err)+ }+return nil})}@@ -171,10 +189,11 @@ func NotifyAboutNewComment(post *entity.Post, comment string) worker.Task {return c.Failure(err)}- title := fmt.Sprintf("**%s** left a comment on **%s**", c.User().Name, post.Title)+ author := c.User()+ title := fmt.Sprintf("**%s** left a comment on **%s**", author.Name, post.Title)link := fmt.Sprintf("/posts/%d/%s", post.Number, post.Slug)for _, user := range users {- if user.ID != c.User().ID {+ if user.ID != author.ID {err = bus.Dispatch(c, &cmd.AddNewNotification{User: user,Title: title,@@ -195,30 +214,46 @@ func NotifyAboutNewComment(post *entity.Post, comment string) worker.Task {to := make([]dto.Recipient, 0)for _, user := range users {- if user.ID != c.User().ID {+ if user.ID != author.ID {to = append(to, dto.NewRecipient(user.Name, user.Email, dto.Props{}))}}- props := dto.Props{+ tenant := c.Tenant()+ baseURL, logoURL := web.BaseURL(c), web.LogoURL(c)++ mailProps := dto.Props{"title": post.Title,- "siteName": c.Tenant().Name,- "userName": c.User().Name,+ "siteName": tenant.Name,+ "userName": author.Name,"content": markdown.Full(comment),- "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),- "view": linkWithText(i18n.T(c, "email.subscription.view"), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),- "unsubscribe": linkWithText(i18n.T(c, "email.subscription.unsubscribe"), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),- "change": linkWithText(i18n.T(c, "email.subscription.change"), web.BaseURL(c), "/settings"),- "logo": web.LogoURL(c),+ "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), baseURL, "/posts/%d/%s", post.Number, post.Slug),+ "view": linkWithText(i18n.T(c, "email.subscription.view"), baseURL, "/posts/%d/%s", post.Number, post.Slug),+ "unsubscribe": linkWithText(i18n.T(c, "email.subscription.unsubscribe"), baseURL, "/posts/%d/%s", post.Number, post.Slug),+ "change": linkWithText(i18n.T(c, "email.subscription.change"), baseURL, "/settings"),+ "logo": logoURL,}bus.Publish(c, &cmd.SendMail{- From: c.User().Name,+ From: author.Name,To: to,TemplateName: "new_comment",- Props: props,+ Props: mailProps,})+ webhookProps := webhook.Props{"comment": comment}+ webhookProps.SetPost(post, "post", baseURL, true, true)+ webhookProps.SetUser(author, "author")+ webhookProps.SetTenant(tenant, "tenant", baseURL, logoURL)++ err = bus.Dispatch(c, &cmd.TriggerWebhooks{+ Type: enum.WebhookNewComment,+ Props: webhookProps,+ })+ if err != nil {+ return c.Failure(err)+ }+return nil})}@@ -237,10 +272,11 @@ func NotifyAboutStatusChange(post *entity.Post, prevStatus enum.PostStatus) workreturn c.Failure(err)}- title := fmt.Sprintf("**%s** changed status of **%s** to **%s**", c.User().Name, post.Title, post.Status.Name())+ author := c.User()+ title := fmt.Sprintf("**%s** changed status of **%s** to **%s**", author.Name, post.Title, post.Status.Name())link := fmt.Sprintf("/posts/%d/%s", post.Number, post.Slug)for _, user := range users {- if user.ID != c.User().ID {+ if user.ID != author.ID {err = bus.Dispatch(c, &cmd.AddNewNotification{User: user,Title: title,@@ -259,38 +295,55 @@ func NotifyAboutStatusChange(post *entity.Post, prevStatus enum.PostStatus) workreturn c.Failure(err)}+ baseURL := web.BaseURL(c)var duplicate stringif post.Status == enum.PostDuplicate {- duplicate = linkWithText(post.Response.Original.Title, web.BaseURL(c), "/posts/%d/%s", post.Response.Original.Number, post.Response.Original.Slug)+ duplicate = linkWithText(post.Response.Original.Title, baseURL, "/posts/%d/%s", post.Response.Original.Number, post.Response.Original.Slug)}to := make([]dto.Recipient, 0)for _, user := range users {- if user.ID != c.User().ID {+ if user.ID != author.ID {to = append(to, dto.NewRecipient(user.Name, user.Email, dto.Props{}))}}+ tenant := c.Tenant()+ logoURL := web.LogoURL(c)+props := dto.Props{"title": post.Title,- "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),- "siteName": c.Tenant().Name,+ "postLink": linkWithText(fmt.Sprintf("#%d", post.Number), baseURL, "/posts/%d/%s", post.Number, post.Slug),+ "siteName": tenant.Name,"content": markdown.Full(post.Response.Text),"status": i18n.T(c, fmt.Sprintf("enum.poststatus.%s", post.Status.Name())),"duplicate": duplicate,- "view": linkWithText(i18n.T(c, "email.subscription.view"), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),- "unsubscribe": linkWithText(i18n.T(c, "email.subscription.unsubscribe"), web.BaseURL(c), "/posts/%d/%s", post.Number, post.Slug),- "change": linkWithText(i18n.T(c, "email.subscription.change"), web.BaseURL(c), "/settings"),- "logo": web.LogoURL(c),+ "view": linkWithText(i18n.T(c, "email.subscription.view"), baseURL, "/posts/%d/%s", post.Number, post.Slug),+ "unsubscribe": linkWithText(i18n.T(c, "email.subscription.unsubscribe"), baseURL, "/posts/%d/%s", post.Number, post.Slug),+ "change": linkWithText(i18n.T(c, "email.subscription.change"), baseURL, "/settings"),+ "logo": logoURL,}bus.Publish(c, &cmd.SendMail{- From: c.User().Name,+ From: author.Name,To: to,TemplateName: "change_status",Props: props,})+ webhookProps := webhook.Props{"post_old_status": prevStatus.Name()}+ webhookProps.SetPost(post, "post", baseURL, true, true)+ webhookProps.SetUser(author, "author")+ webhookProps.SetTenant(tenant, "tenant", baseURL, logoURL)++ err = bus.Dispatch(c, &cmd.TriggerWebhooks{+ Type: enum.WebhookChangeStatus,+ Props: webhookProps,+ })+ if err != nil {+ return c.Failure(err)+ }+return nil})}@@ -305,9 +358,10 @@ func NotifyAboutDeletedPost(post *entity.Post) worker.Task {return c.Failure(err)}- title := fmt.Sprintf("**%s** deleted **%s**", c.User().Name, post.Title)+ author := c.User()+ title := fmt.Sprintf("**%s** deleted **%s**", author.Name, post.Title)for _, user := range users {- if user.ID != c.User().ID {+ if user.ID != author.ID {err = bus.Dispatch(c, &cmd.AddNewNotification{User: user,Title: title,@@ -327,17 +381,20 @@ func NotifyAboutDeletedPost(post *entity.Post) worker.Task {to := make([]dto.Recipient, 0)for _, user := range users {- if user.ID != c.User().ID {+ if user.ID != author.ID {to = append(to, dto.NewRecipient(user.Name, user.Email, dto.Props{}))}}+ tenant := c.Tenant()+ baseURL, logoURL := web.BaseURL(c), web.LogoURL(c)+props := dto.Props{"title": post.Title,- "siteName": c.Tenant().Name,+ "siteName": tenant.Name,"content": markdown.Full(post.Response.Text),- "change": linkWithText(i18n.T(c, "email.subscription.change"), web.BaseURL(c), "/settings"),- "logo": web.LogoURL(c),+ "change": linkWithText(i18n.T(c, "email.subscription.change"), baseURL, "/settings"),+ "logo": logoURL,}bus.Publish(c, &cmd.SendMail{@@ -347,6 +404,19 @@ func NotifyAboutDeletedPost(post *entity.Post) worker.Task {Props: props,})+ webhookProps := webhook.Props{}+ webhookProps.SetPost(post, "post", baseURL, true, true)+ webhookProps.SetUser(author, "author")+ webhookProps.SetTenant(tenant, "tenant", baseURL, logoURL)++ err = bus.Dispatch(c, &cmd.TriggerWebhooks{+ Type: enum.WebhookDeletePost,+ Props: webhookProps,+ })+ if err != nil {+ return c.Failure(err)+ }+return nil})}@@ -366,7 +436,7 @@ func SendInvites(subject, message string, invitations []*actions.UserInvitation)}url := fmt.Sprintf("%s/invite/verify?k=%s", web.BaseURL(c), invite.VerificationKey)- toMessage := strings.Replace(message, app.InvitePlaceholder, string(url), -1)+ toMessage := strings.Replace(message, app.InvitePlaceholder, url, -1)to[i] = dto.NewRecipient("", invite.Email, dto.Props{"message": markdown.Full(toMessage),})diff --git a/app/tasks/tasks_test.go b/app/tasks/tasks_test.goindex 4fcd6f71f..61b7ac414 100644--- a/app/tasks/tasks_test.go+++ b/app/tasks/tasks_test.go@@ -2,6 +2,7 @@ package tasks_testimport ("context"+ "github.com/getfider/fider/app/pkg/webhook""html/template""testing""time"@@ -135,6 +136,12 @@ func TestNotifyAboutNewPostTask(t *testing.T) {return nil})+ var triggerWebhooks *cmd.TriggerWebhooks+ bus.AddHandler(func(ctx context.Context, c *cmd.TriggerWebhooks) error {+ triggerWebhooks = c+ return nil+ })+worker := mock.NewWorker()post := &entity.Post{ID: 1,@@ -178,6 +185,26 @@ func TestNotifyAboutNewPostTask(t *testing.T) {Expect(addNewNotification.Link).Equals("/posts/1/add-support-for-typescript")Expect(addNewNotification.Title).Equals("New post: **Add support for TypeScript**")Expect(addNewNotification.User).Equals(mock.AryaStark)++ Expect(triggerWebhooks).IsNotNil()+ Expect(triggerWebhooks.Type).Equals(enum.WebhookNewPost)+ Expect(triggerWebhooks.Props).ContainsProps(webhook.Props{+ "post_id": post.ID,+ "post_number": post.Number,+ "post_title": post.Title,+ "post_slug": post.Slug,+ "post_description": post.Description,+ "post_url": "http://domain.com/posts/1/add-support-for-typescript",+ "author_id": mock.JonSnow.ID,+ "author_name": mock.JonSnow.Name,+ "author_email": mock.JonSnow.Email,+ "author_role": mock.JonSnow.Role.String(),+ "tenant_id": mock.DemoTenant.ID,+ "tenant_name": mock.DemoTenant.Name,+ "tenant_subdomain": mock.DemoTenant.Subdomain,+ "tenant_status": mock.DemoTenant.Status.String(),+ "tenant_url": "http://domain.com",+ })}func TestNotifyAboutNewCommentTask(t *testing.T) {@@ -197,6 +224,12 @@ func TestNotifyAboutNewCommentTask(t *testing.T) {return nil})+ var triggerWebhooks *cmd.TriggerWebhooks+ bus.AddHandler(func(ctx context.Context, c *cmd.TriggerWebhooks) error {+ triggerWebhooks = c+ return nil+ })+worker := mock.NewWorker()post := &entity.Post{ID: 1,@@ -204,6 +237,7 @@ func TestNotifyAboutNewCommentTask(t *testing.T) {Title: "Add support for TypeScript",Slug: "add-support-for-typescript",Description: "TypeScript is great, please add support for it",+ User: mock.JonSnow,}task := tasks.NotifyAboutNewComment(post, "I agree")@@ -241,6 +275,31 @@ func TestNotifyAboutNewCommentTask(t *testing.T) {Expect(addNewNotification.Link).Equals("/posts/1/add-support-for-typescript")Expect(addNewNotification.Title).Equals("**Arya Stark** left a comment on **Add support for TypeScript**")Expect(addNewNotification.User).Equals(mock.JonSnow)++ Expect(triggerWebhooks).IsNotNil()+ Expect(triggerWebhooks.Type).Equals(enum.WebhookNewComment)+ Expect(triggerWebhooks.Props).ContainsProps(webhook.Props{+ "comment": "I agree",+ "post_id": post.ID,+ "post_number": post.Number,+ "post_title": post.Title,+ "post_slug": post.Slug,+ "post_description": post.Description,+ "post_url": "http://domain.com/posts/1/add-support-for-typescript",+ "post_author_id": mock.JonSnow.ID,+ "post_author_name": mock.JonSnow.Name,+ "post_author_email": mock.JonSnow.Email,+ "post_author_role": mock.JonSnow.Role.String(),+ "author_id": mock.AryaStark.ID,+ "author_name": mock.AryaStark.Name,+ "author_email": mock.AryaStark.Email,+ "author_role": mock.AryaStark.Role.String(),+ "tenant_id": mock.DemoTenant.ID,+ "tenant_name": mock.DemoTenant.Name,+ "tenant_subdomain": mock.DemoTenant.Subdomain,+ "tenant_status": mock.DemoTenant.Status.String(),+ "tenant_url": "http://domain.com",+ })}func TestNotifyAboutStatusChangeTask(t *testing.T) {@@ -260,6 +319,12 @@ func TestNotifyAboutStatusChangeTask(t *testing.T) {return nil})+ var triggerWebhooks *cmd.TriggerWebhooks+ bus.AddHandler(func(ctx context.Context, c *cmd.TriggerWebhooks) error {+ triggerWebhooks = c+ return nil+ })+worker := mock.NewWorker()post := &entity.Post{ID: 1,@@ -267,6 +332,7 @@ func TestNotifyAboutStatusChangeTask(t *testing.T) {Title: "Add support for TypeScript",Slug: "add-support-for-typescript",Description: "TypeScript is great, please add support for it",+ User: mock.AryaStark,Status: enum.PostPlanned,Response: &entity.PostResponse{RespondedAt: time.Now(),@@ -312,6 +378,39 @@ func TestNotifyAboutStatusChangeTask(t *testing.T) {Expect(addNewNotification.Link).Equals("/posts/1/add-support-for-typescript")Expect(addNewNotification.Title).Equals("**Jon Snow** changed status of **Add support for TypeScript** to **planned**")Expect(addNewNotification.User).Equals(mock.AryaStark)++ Expect(triggerWebhooks).IsNotNil()+ Expect(triggerWebhooks.Type).Equals(enum.WebhookChangeStatus)+ Expect(triggerWebhooks.Props).ContainsProps(webhook.Props{+ "post_old_status": enum.PostOpen.Name(),+ "post_id": post.ID,+ "post_number": post.Number,+ "post_title": post.Title,+ "post_slug": post.Slug,+ "post_description": post.Description,+ "post_status": post.Status.Name(),+ "post_url": "http://domain.com/posts/1/add-support-for-typescript",+ "post_author_id": mock.AryaStark.ID,+ "post_author_name": mock.AryaStark.Name,+ "post_author_email": mock.AryaStark.Email,+ "post_author_role": mock.AryaStark.Role.String(),+ "post_response": true,+ "post_response_text": post.Response.Text,+ "post_response_responded_at": post.Response.RespondedAt,+ "post_response_author_id": mock.JonSnow.ID,+ "post_response_author_name": mock.JonSnow.Name,+ "post_response_author_email": mock.JonSnow.Email,+ "post_response_author_role": mock.JonSnow.Role.String(),+ "author_id": mock.JonSnow.ID,+ "author_name": mock.JonSnow.Name,+ "author_email": mock.JonSnow.Email,+ "author_role": mock.JonSnow.Role.String(),+ "tenant_id": mock.DemoTenant.ID,+ "tenant_name": mock.DemoTenant.Name,+ "tenant_subdomain": mock.DemoTenant.Subdomain,+ "tenant_status": mock.DemoTenant.Status.String(),+ "tenant_url": "http://domain.com",+ })}func TestNotifyAboutDeletePostTask(t *testing.T) {@@ -331,6 +430,12 @@ func TestNotifyAboutDeletePostTask(t *testing.T) {return nil})+ var triggerWebhooks *cmd.TriggerWebhooks+ bus.AddHandler(func(ctx context.Context, c *cmd.TriggerWebhooks) error {+ triggerWebhooks = c+ return nil+ })+worker := mock.NewWorker()post := &entity.Post{ID: 1,@@ -338,6 +443,7 @@ func TestNotifyAboutDeletePostTask(t *testing.T) {Title: "Add support for TypeScript",Slug: "add-support-for-typescript",Description: "TypeScript is great, please add support for it",+ User: mock.AryaStark,Status: enum.PostDeleted,Response: &entity.PostResponse{RespondedAt: time.Now(),@@ -378,6 +484,38 @@ func TestNotifyAboutDeletePostTask(t *testing.T) {Expect(addNewNotification.Link).Equals("")Expect(addNewNotification.Title).Equals("**Jon Snow** deleted **Add support for TypeScript**")Expect(addNewNotification.User).Equals(mock.AryaStark)++ Expect(triggerWebhooks).IsNotNil()+ Expect(triggerWebhooks.Type).Equals(enum.WebhookDeletePost)+ Expect(triggerWebhooks.Props).ContainsProps(webhook.Props{+ "post_id": post.ID,+ "post_number": post.Number,+ "post_title": post.Title,+ "post_slug": post.Slug,+ "post_description": post.Description,+ "post_status": post.Status.Name(),+ "post_url": "http://domain.com/posts/1/add-support-for-typescript",+ "post_author_id": mock.AryaStark.ID,+ "post_author_name": mock.AryaStark.Name,+ "post_author_email": mock.AryaStark.Email,+ "post_author_role": mock.AryaStark.Role.String(),+ "post_response": true,+ "post_response_text": post.Response.Text,+ "post_response_responded_at": post.Response.RespondedAt,+ "post_response_author_id": mock.JonSnow.ID,+ "post_response_author_name": mock.JonSnow.Name,+ "post_response_author_email": mock.JonSnow.Email,+ "post_response_author_role": mock.JonSnow.Role.String(),+ "author_id": mock.JonSnow.ID,+ "author_name": mock.JonSnow.Name,+ "author_email": mock.JonSnow.Email,+ "author_role": mock.JonSnow.Role.String(),+ "tenant_id": mock.DemoTenant.ID,+ "tenant_name": mock.DemoTenant.Name,+ "tenant_subdomain": mock.DemoTenant.Subdomain,+ "tenant_status": mock.DemoTenant.Status.String(),+ "tenant_url": "http://domain.com",+ })}func TestNotifyAboutStatusChangeTask_Duplicate(t *testing.T) {@@ -397,12 +535,19 @@ func TestNotifyAboutStatusChangeTask_Duplicate(t *testing.T) {return nil})+ var triggerWebhooks *cmd.TriggerWebhooks+ bus.AddHandler(func(ctx context.Context, c *cmd.TriggerWebhooks) error {+ triggerWebhooks = c+ return nil+ })+worker := mock.NewWorker()post := &entity.Post{ID: 2,Number: 2,Title: "I need TypeScript",Slug: "i-need-typescript",+ User: mock.AryaStark,Status: enum.PostDuplicate,Response: &entity.PostResponse{RespondedAt: time.Now(),@@ -453,6 +598,44 @@ func TestNotifyAboutStatusChangeTask_Duplicate(t *testing.T) {Expect(addNewNotification.Link).Equals("/posts/2/i-need-typescript")Expect(addNewNotification.Title).Equals("**Jon Snow** changed status of **I need TypeScript** to **duplicate**")Expect(addNewNotification.User).Equals(mock.AryaStark)++ Expect(triggerWebhooks).IsNotNil()+ Expect(triggerWebhooks.Type).Equals(enum.WebhookChangeStatus)+ Expect(triggerWebhooks.Props).ContainsProps(webhook.Props{+ "post_old_status": enum.PostOpen.Name(),+ "post_id": post.ID,+ "post_number": post.Number,+ "post_title": post.Title,+ "post_slug": post.Slug,+ "post_description": post.Description,+ "post_status": post.Status.Name(),+ "post_url": "http://domain.com/posts/2/i-need-typescript",+ "post_author_id": mock.AryaStark.ID,+ "post_author_name": mock.AryaStark.Name,+ "post_author_email": mock.AryaStark.Email,+ "post_author_role": mock.AryaStark.Role.String(),+ "post_response": true,+ "post_response_text": post.Response.Text,+ "post_response_responded_at": post.Response.RespondedAt,+ "post_response_author_id": mock.JonSnow.ID,+ "post_response_author_name": mock.JonSnow.Name,+ "post_response_author_email": mock.JonSnow.Email,+ "post_response_author_role": mock.JonSnow.Role.String(),+ "post_response_original_number": post.Response.Original.Number,+ "post_response_original_title": post.Response.Original.Title,+ "post_response_original_slug": post.Response.Original.Slug,+ "post_response_original_status": post.Response.Original.Status.Name(),+ "post_response_original_url": "http://domain.com/posts/1/add-support-for-typescript",+ "author_id": mock.JonSnow.ID,+ "author_name": mock.JonSnow.Name,+ "author_email": mock.JonSnow.Email,+ "author_role": mock.JonSnow.Role.String(),+ "tenant_id": mock.DemoTenant.ID,+ "tenant_name": mock.DemoTenant.Name,+ "tenant_subdomain": mock.DemoTenant.Subdomain,+ "tenant_status": mock.DemoTenant.Status.String(),+ "tenant_url": "http://domain.com",+ })}func TestSendInvites(t *testing.T) {diff --git a/migrations/202108092243_create_webhooks.sql b/migrations/202108092243_create_webhooks.sqlnew file mode 100644index 000000000..2b08717e4--- /dev/null+++ b/migrations/202108092243_create_webhooks.sql@@ -0,0 +1,12 @@+CREATE TABLE IF NOT EXISTS webhooks (+ id SERIAL PRIMARY KEY,+ name VARCHAR(60) NOT NULL,+ type SMALLINT NOT NULL,+ status SMALLINT NOT NULL,+ url TEXT NOT NULL,+ content TEXT NULL,+ http_method VARCHAR(50) NOT NULL,+ http_headers JSONB NULL,+ tenant_id INT NOT NULL,+ FOREIGN KEY (tenant_id) REFERENCES tenants (id)+);\ No newline at end of filediff --git a/public/AsyncPages.tsx b/public/AsyncPages.tsxindex 89bc0318d..655a2d42c 100644--- a/public/AsyncPages.tsx+++ b/public/AsyncPages.tsx@@ -95,6 +95,14 @@ export const AsyncAdvancedSettingsPage = load())+export const AsyncManageWebhooksPage = load(+ () =>+ import(+ /* webpackChunkName: "ManageWebhooks.page" */+ "@fider/pages/Administration/pages/ManageWebhooks.page"+ )+)+export const AsyncGeneralSettingsPage = load(() =>import(diff --git a/public/assets/styles/tooltip.scss b/public/assets/styles/tooltip.scssindex dcbf761e7..7348e5032 100644--- a/public/assets/styles/tooltip.scss+++ b/public/assets/styles/tooltip.scss@@ -1,26 +1,25 @@[data-tooltip] {- cursor: pointer;position: relative;-}-[data-tooltip]::before {- background-color: get("colors.gray.700");- color: get("colors.white");- font-size: 11px;- padding: 4px 6px;- width: max-content;- border-radius: 4px;- position: absolute;- text-align: center;- bottom: 40px;- font-weight: 500;- left: 50%;- content: attr(data-tooltip);- transform: translate(-50%, 100%) scale(0);- transition: 0.1s;-}+ &::before {+ background-color: get("colors.gray.700");+ color: get("colors.white");+ font-size: 11px;+ padding: 4px 6px;+ width: max-content;+ border-radius: 4px;+ position: absolute;+ text-align: center;+ bottom: 40px;+ font-weight: 500;+ left: 50%;+ content: attr(data-tooltip);+ transform: translate(-50%, 100%) scale(0);+ transition: 0.1s;+ }-[data-tooltip]:hover:before {- display: block;- transform: translate(-50%, 100%) scale(1);+ &:hover:before {+ display: block;+ transform: translate(-50%, 100%) scale(1);+ }}diff --git a/public/assets/styles/utility/display.scss b/public/assets/styles/utility/display.scssindex 82ba22c3c..b34ab3aa2 100644--- a/public/assets/styles/utility/display.scss+++ b/public/assets/styles/utility/display.scss@@ -103,6 +103,10 @@justify-content: space-evenly;}+.justify-full > * {+ flex: 1 1 0;+}+@each $i in 0, 1, 2, 4, 6, 8 {.flex-x.flex--spacing-#{$i} > * + * {margin-left: spacing($i);diff --git a/public/components/common/Button.tsx b/public/components/common/Button.tsxindex 34806167e..fed514cf4 100644--- a/public/components/common/Button.tsx+++ b/public/components/common/Button.tsx@@ -8,6 +8,7 @@ interface ButtonProps {disabled?: booleanhref?: stringrel?: "nofollow"+ target?: "_self" | "_blank" | "_parent" | "_top"type?: "button" | "submit"variant?: "primary" | "danger" | "secondary" | "tertiary"size?: "small" | "default" | "large"@@ -81,7 +82,7 @@ export class Button extends React.Component<ButtonProps, ButtonState> {if (this.props.href) {return (- <a href={this.props.href} rel={this.props.rel} className={className}>+ <a href={this.props.href} rel={this.props.rel} target={this.props.target} className={className}>{this.props.children}</a>)diff --git a/public/components/common/HoverInfo.scss b/public/components/common/HoverInfo.scssnew file mode 100644index 000000000..503d4b9d7--- /dev/null+++ b/public/components/common/HoverInfo.scss@@ -0,0 +1,9 @@+@import "~@fider/assets/styles/variables.scss";++.c-hoverinfo {+ margin-left: spacing(1);++ &__icon {+ vertical-align: middle;+ }+}diff --git a/public/components/common/HoverInfo.tsx b/public/components/common/HoverInfo.tsxnew file mode 100644index 000000000..6a799f13f--- /dev/null+++ b/public/components/common/HoverInfo.tsx@@ -0,0 +1,27 @@+import "./HoverInfo.scss"++import React from "react"+import { Icon } from "./Icon"++import IconInformationCircle from "@fider/assets/images/heroicons-information-circle.svg"+import { classSet } from "@fider/services"++interface InfoProps {+ text: string+ onClick?: () => void+ href?: string+ target?: "_self" | "_blank" | "_parent" | "_top"+}++export const HoverInfo = (props: InfoProps) => {+ const Elem = props.href ? "a" : "span"+ const classList = classSet({+ "c-hoverinfo": true,+ clickable: props.onClick !== undefined,+ })+ return (+ <Elem className={classList} data-tooltip={props.text} onClick={props.onClick} href={props.href} target={props.target}>+ <Icon width="15" height="15" className="c-hoverinfo__icon" sprite={IconInformationCircle} />+ </Elem>+ )+}diff --git a/public/components/common/Loader.scss b/public/components/common/Loader.scssindex 97c97521f..ab71b1060 100644--- a/public/components/common/Loader.scss+++ b/public/components/common/Loader.scss@@ -1,50 +1,56 @@@import "~@fider/assets/styles/variables.scss";.c-loader {- display: block;- position: relative;- text-align: center;- z-index: 1000;- width: 30px;- height: 30px;- margin-top: 10px;- margin-bottom: 10px;- margin-left: auto;- margin-right: auto;-}+ &__spinner {+ display: block;+ position: relative;+ text-align: center;+ z-index: 1000;+ width: 30px;+ height: 30px;+ margin: 10px auto;-.c-loader:before {- position: absolute;- content: "";- top: 0%;- left: 50%;- width: 100%;- height: 100%;- border-radius: 500rem;- border: 0.2em solid get("colors.gray.300");-}+ &:before {+ position: absolute;+ content: "";+ top: 0;+ left: 50%;+ width: 100%;+ height: 100%;+ border-radius: 500rem;+ border: 0.2em solid get("colors.gray.300");+ }-.c-loader:after {- position: absolute;- content: "";- top: 0%;- left: 50%;- width: 100%;- height: 100%;- animation: loader 0.6s linear;- animation-iteration-count: infinite;- border-radius: 500rem;- border-color: get("colors.gray.700") transparent transparent;- border-style: solid;- border-width: 0.2em;- box-shadow: 0px 0px 0px 1px transparent;-}+ &:after {+ position: absolute;+ content: "";+ top: 0;+ left: 50%;+ width: 100%;+ height: 100%;+ animation: loader 0.6s linear;+ animation-iteration-count: infinite;+ border-radius: 500rem;+ border-color: get("colors.gray.700") transparent transparent;+ border-style: solid;+ border-width: 0.2em;+ box-shadow: 0 0 0 1px transparent;+ }-.c-loader:before,-.c-loader:after {- width: 30px;- height: 30px;- margin: 0 0 0 -15px;+ &:before,+ &:after {+ width: 30px;+ height: 30px;+ margin: 0 0 0 -15px;+ }+ }++ &__text {+ display: block;+ text-align: center;+ font-size: get("font.size.xs");+ color: get("colors.gray.700");+ }}@keyframes loader {diff --git a/public/components/common/Loader.tsx b/public/components/common/Loader.tsxindex a5b7ac3f4..aa71bba27 100644--- a/public/components/common/Loader.tsx+++ b/public/components/common/Loader.tsx@@ -2,13 +2,29 @@ import "./Loader.scss"import React, { useState } from "react"import { useTimeout } from "@fider/hooks"+import { classSet } from "@fider/services"-export function Loader() {+interface LoaderProps {+ text?: string+ className?: string+}++export function Loader(props: LoaderProps) {const [show, setShow] = useState(false)useTimeout(() => {setShow(true)}, 500)- return show ? <div className="c-loader" /> : null+ const className = classSet({+ "c-loader": true,+ [props.className || ""]: props.className,+ })++ return show ? (+ <div className={className}>+ <div className="c-loader__spinner" />+ {props.text && <span className="c-loader__text">{props.text}</span>}+ </div>+ ) : null}diff --git a/public/components/common/Modal.scss b/public/components/common/Modal.scssindex 48e690851..fd2d2429a 100644--- a/public/components/common/Modal.scss+++ b/public/components/common/Modal.scss@@ -1,5 +1,7 @@@import "~@fider/assets/styles/variables.scss";+$c-modal-dimmer-padding: 1em;+.c-modal-dimmer {position: fixed;top: 0;@@ -8,12 +10,12 @@height: 100%;text-align: center;vertical-align: middle;- padding: 1em;+ padding: $c-modal-dimmer-padding;z-index: 100;display: flex;justify-content: center;- align-items: center;- overflow-y: hidden;+ align-items: flex-start;+ overflow-y: auto;animation: dimmerFadeIn 0.5s;background-color: rgba(get("colors.gray.800"), 0.7);@@ -43,6 +45,12 @@}}+.c-modal-scroller {+ min-height: calc(100vh - #{2 * $c-modal-dimmer-padding});+ display: flex;+ align-items: center;+}+.c-modal-window {z-index: 101;text-align: left;diff --git a/public/components/common/Modal.tsx b/public/components/common/Modal.tsxindex 6a1342535..77e63b434 100644--- a/public/components/common/Modal.tsx+++ b/public/components/common/Modal.tsx@@ -61,8 +61,10 @@ const ModalWindow: React.FunctionComponent<ModalWindowProps> = (props) => {return ReactDOM.createPortal(<div aria-disabled={true} className="c-modal-dimmer" onClick={close}>- <div className={className} data-testid="modal" onClick={swallow}>- {props.children}+ <div className="c-modal-scroller">+ <div className={className} data-testid="modal" onClick={swallow}>+ {props.children}+ </div></div></div>,root.currentdiff --git a/public/components/common/form/Form.scss b/public/components/common/form/Form.scssindex 8f316e230..760c2d4ad 100644--- a/public/components/common/form/Form.scss+++ b/public/components/common/form/Form.scss@@ -12,5 +12,9 @@&:last-child {margin-bottom: 0;++ .flex-x > & {+ margin-bottom: spacing(2);+ }}}diff --git a/public/components/common/form/Input.scss b/public/components/common/form/Input.scssindex 78525299b..3698b3cb0 100644--- a/public/components/common/form/Input.scss+++ b/public/components/common/form/Input.scss@@ -16,7 +16,6 @@& + svg,& + img {- position: absolute;position: absolute;width: 36px;padding: spacing(2);@@ -44,9 +43,13 @@&--suffixed {border-top-right-radius: 0;border-bottom-right-radius: 0;- & + * {+ & ~ * {border-top-left-radius: 0;border-bottom-left-radius: 0;+ &:not(:last-child) {+ border-top-right-radius: 0;+ border-bottom-right-radius: 0;+ }}}}diff --git a/public/components/common/form/TextArea.tsx b/public/components/common/form/TextArea.tsxindex b4889ed81..a4675c26a 100644--- a/public/components/common/form/TextArea.tsx+++ b/public/components/common/form/TextArea.tsx@@ -13,9 +13,11 @@ interface TextAreaProps {disabled?: booleanminRows?: numberplaceholder?: string+ afterLabel?: JSX.ElementonChange?: (value: string) => voidinputRef?: React.MutableRefObject<any>onFocus?: React.FocusEventHandler<HTMLTextAreaElement>+ className?: string}export const TextArea: React.FunctionComponent<TextAreaProps> = (props) => {@@ -30,11 +32,17 @@ export const TextArea: React.FunctionComponent<TextAreaProps> = (props) => {{(ctx) => (<><div className="c-form-field">- {!!props.label && <label htmlFor={`input-${props.field}`}>{props.label}</label>}+ {!!props.label && (+ <label htmlFor={`input-${props.field}`}>+ {props.label}+ {props.afterLabel}+ </label>+ )}<TextareaclassName={classSet({"c-textarea": true,"c-textarea--error": hasError(props.field, ctx.error),+ [props.className || ""]: props.className,})}id={`input-${props.field}`}disabled={props.disabled}diff --git a/public/components/layout/Stack.tsx b/public/components/layout/Stack.tsxindex 9fe6a684f..af16c2778 100644--- a/public/components/layout/Stack.tsx+++ b/public/components/layout/Stack.tsx@@ -7,7 +7,7 @@ interface StackProps {onClick?: () => voidcenter?: booleandivide?: boolean- justify?: "between" | "evenly"+ justify?: "between" | "evenly" | "full"spacing?: 0 | 1 | 2 | 4 | 6 | 8}@@ -16,13 +16,14 @@ const Stack = (props: StackProps, dir: "x" | "y") => {const className = classSet({[`${props.className}`]: props.className,flex: true,- "flex flex-x": dir === "x",- "flex flex-y": dir === "y",+ "flex-x": dir === "x",+ "flex-y": dir === "y",[`flex--spacing-${spacing}`]: spacing > 0 && !props.divide,[`flex--divide-${spacing}`]: spacing > 0 && !!props.divide,"flex-items-center": dir === "x" && props.center !== false,"justify-between": props.justify === "between","justify-evenly": props.justify === "evenly",+ "justify-full": props.justify === "full",})return (diff --git a/public/models/index.ts b/public/models/index.tsindex bc4a3f5d9..50493048b 100644--- a/public/models/index.ts+++ b/public/models/index.ts@@ -2,3 +2,4 @@ export * from "./post"export * from "./identity"export * from "./settings"export * from "./notification"+export * from "./webhook"diff --git a/public/models/webhook.ts b/public/models/webhook.tsnew file mode 100644index 000000000..a7ca3cd5d--- /dev/null+++ b/public/models/webhook.ts@@ -0,0 +1,52 @@+import { StringObject } from "@fider/services"++export interface WebhookData {+ name: string+ type: WebhookType+ status: WebhookStatus+ url: string+ content: string+ http_method: string+ http_headers: HttpHeaders+}++export interface Webhook extends WebhookData {+ id: number+}++export enum WebhookType {+ NEW_POST = "new_post",+ NEW_COMMENT = "new_comment",+ CHANGE_STATUS = "change_status",+ DELETE_POST = "delete_post",+}++export enum WebhookStatus {+ ENABLED = "enabled",+ DISABLED = "disabled",+ FAILED = "failed",+}++export type HttpHeaders = StringObject<string>++export interface WebhookTriggerResult {+ webhook: Webhook+ props: StringObject+ success: boolean+ url: string+ content: string+ status_code: number+ message: string+ error: string+}++export interface WebhookPreviewResult {+ url: PreviewedField+ content: PreviewedField+}++export interface PreviewedField {+ value: string+ message: string+ error: string+}diff --git a/public/pages/Administration/components/SideMenu.tsx b/public/pages/Administration/components/SideMenu.tsxindex e7e14a6e8..2077368fc 100644--- a/public/pages/Administration/components/SideMenu.tsx+++ b/public/pages/Administration/components/SideMenu.tsx@@ -49,6 +49,7 @@ export const SideMenu = (props: SiteMenuProps) => {<SideMenuItem name="advanced" title="Advanced" href="/admin/advanced" isActive={activeItem === "advanced"} />{fider.session.user.isAdministrator && (<>+ <SideMenuItem name="webhooks" title="Webhooks" href="/admin/webhooks" isActive={activeItem === "webhooks"} /><SideMenuItem name="export" title="Export" href="/admin/export" isActive={activeItem === "export"} /></>)}diff --git a/public/pages/Administration/components/webhook/WebhookFailInfo.scss b/public/pages/Administration/components/webhook/WebhookFailInfo.scssnew file mode 100644index 000000000..df4571ede--- /dev/null+++ b/public/pages/Administration/components/webhook/WebhookFailInfo.scss@@ -0,0 +1,9 @@+@import "~@fider/assets/styles/variables.scss";++.c-webhook-failinfo {+ pre {+ text-align: left;+ white-space: pre-wrap;+ font-size: get("font.size.sm");+ }+}diff --git a/public/pages/Administration/components/webhook/WebhookFailInfo.tsx b/public/pages/Administration/components/webhook/WebhookFailInfo.tsxnew file mode 100644index 000000000..ba33263a5--- /dev/null+++ b/public/pages/Administration/components/webhook/WebhookFailInfo.tsx@@ -0,0 +1,71 @@+import "./WebhookFailInfo.scss"++import React from "react"+import { WebhookTriggerResult } from "@fider/models"+import { Button, Modal } from "@fider/components"++import { VStack } from "@fider/components/layout"+import { HoverInfo } from "@fider/components/common/HoverInfo"+import { WebhookProperties } from "@fider/pages/Administration/components/webhook/WebhookProperties"++interface WebhookFailInfoProps {+ result: WebhookTriggerResult+ isModalOpen: boolean+ onModalOpen: () => void+ onModalClose: () => void+}++interface InfoPropertyProps {+ value: string | number+ name: string+ info: string+ multiline?: boolean+}++const InfoProperty = (props: InfoPropertyProps) => {+ return props.value ? (+ <div>+ <h3 className="text-title mb-1">+ {props.name}+ <HoverInfo text={props.info} />+ </h3>+ {props.multiline ? <pre>{props.value}</pre> : <p>{props.value}</p>}+ </div>+ ) : (+ <div className="text-muted">+ <span className="text-bold">{props.name}</span> info not available+ </div>+ )+}++export const WebhookFailInfo = (props: WebhookFailInfoProps) => {+ return (+ <>+ <HoverInfo text="Click to show failure details" onClick={props.onModalOpen} />+ <Modal.Window isOpen={props.isModalOpen} onClose={props.onModalClose} size="large">+ <Modal.Header>Webhook trigger failure details</Modal.Header>+ <Modal.Content>+ <VStack className="c-webhook-failinfo" spacing={4} divide>+ <InfoProperty value={props.result.message} name="Message" info="Generic information about where it failed" />+ <InfoProperty value={props.result.error} name="Error" info="Detailed information about what failed" multiline />+ <InfoProperty value={props.result.url} name="URL" info="Parsed URL where the request has been made" />+ <InfoProperty value={props.result.content} name="Content" info="Parsed content that was sent as request body" multiline />+ <InfoProperty value={props.result.status_code} name="Status code" info="HTTP response status code of the request" />+ <div>+ <h3 className="text-title mb-1">+ Properties+ <HoverInfo text="Properties used when parsing URL and content" />+ </h3>+ <WebhookProperties properties={props.result.props} propsName="Property name" valueName="Resolved value" />+ </div>+ </VStack>+ </Modal.Content>+ <Modal.Footer>+ <Button variant="tertiary" onClick={props.onModalClose}>+ Close+ </Button>+ </Modal.Footer>+ </Modal.Window>+ </>+ )+}diff --git a/public/pages/Administration/components/webhook/WebhookForm.scss b/public/pages/Administration/components/webhook/WebhookForm.scssnew file mode 100644index 000000000..83df086c1--- /dev/null+++ b/public/pages/Administration/components/webhook/WebhookForm.scss@@ -0,0 +1,14 @@+@import "~@fider/assets/styles/variables.scss";++.c-webhook-form {+ &__content {+ font-family: $font-code;+ }++ &__preview {+ pre {+ white-space: pre-wrap;+ font-size: get("font.size.sm");+ }+ }+}diff --git a/public/pages/Administration/components/webhook/WebhookForm.tsx b/public/pages/Administration/components/webhook/WebhookForm.tsxnew file mode 100644index 000000000..02cf50ac5--- /dev/null+++ b/public/pages/Administration/components/webhook/WebhookForm.tsx@@ -0,0 +1,238 @@+import "./WebhookForm.scss"++import React, { useEffect, useState } from "react"+import { Button, Field, Form, Input, Loader, Message, Select, SelectOption, TextArea, Toggle } from "@fider/components"+import { actions, Failure } from "@fider/services"+import { HStack, VStack } from "@fider/components/layout"+import { Webhook, WebhookData, WebhookPreviewResult, WebhookStatus, WebhookType } from "@fider/models"+import { HoverInfo } from "@fider/components/common/HoverInfo"+import { WebhookTemplateInfoModal } from "@fider/pages/Administration/components/webhook/WebhookTemplateInfoModal"++interface WebhookFormProps {+ webhook?: Webhook+ onSave: (data: WebhookData) => Promise<Failure | undefined>+ onCancel: () => void+}++interface HttpHeaderProps {+ header?: string+ value?: string+ onEdit: (header: string, value: string) => void+ onRemove?: (header: string) => void+ allHeaders?: string[]+}++const HttpHeader = (props: HttpHeaderProps) => {+ const [header, setHeader] = useState(props.header || "")+ const [value, setValue] = useState(props.value || "")+ const [editing, setEditing] = useState(props.onRemove === undefined)++ const duplicate = props.allHeaders && props.allHeaders.includes(header)++ const suffix = editing ? (+ props.onRemove === undefined ? (+ <Button+ variant="primary"+ onClick={() => {+ props.onEdit(header, value)+ setHeader("")+ setValue("")+ }}+ disabled={duplicate || header.length === 0 || value.length === 0}+ >+ Add+ </Button>+ ) : (+ <Button+ variant="primary"+ onClick={() => {+ setEditing(false)+ props.onEdit(header, value)+ }}+ disabled={value.length === 0}+ >+ Save+ </Button>+ )+ ) : (+ <>+ <Button variant="secondary" onClick={() => setEditing(true)}>+ Edit+ </Button>+ <Button variant="danger" onClick={() => props.onRemove && props.onRemove(header)}>+ Remove+ </Button>+ </>+ )++ return (+ <HStack justify="full" spacing={4}>+ <Input+ field={`header-${header}`}+ value={header}+ onChange={setHeader}+ placeholder="Header"+ disabled={props.onRemove !== undefined}+ suffix={duplicate ? "Duplicate" : undefined}+ />+ <Input field={`value-${header}`} value={value} onChange={setValue} placeholder="Value" disabled={!editing} suffix={suffix} />+ </HStack>+ )+}++export const WebhookForm = (props: WebhookFormProps) => {+ const [name, setName] = useState(props.webhook?.name || "")+ const [type, _setType] = useState(props.webhook?.type || WebhookType.NEW_POST)+ const [status, _setStatus] = useState(props.webhook?.status || WebhookStatus.DISABLED)+ const [url, setUrl] = useState(props.webhook?.url || "")+ const [content, setContent] = useState(props.webhook?.content || "")+ const [httpMethod, setHttpMethod] = useState(props.webhook?.http_method || "POST")+ const [httpHeaders, _setHttpHeaders] = useState(props.webhook?.http_headers || {})+ const [typing, setTyping] = useState<NodeJS.Timeout | undefined>()+ const [preview, setPreview] = useState<WebhookPreviewResult | null | undefined>()+ const [isModalOpen, setIsModalOpen] = useState(false)+ const [error, setError] = useState<Failure | undefined>()++ const calculatePreview = () => {+ actions+ .previewWebhook(type, url, content)+ .then(+ (result) => (result.ok ? result.data : null),+ () => null+ )+ .then(setPreview)+ }++ useEffect(calculatePreview, [])+ useEffect(() => {+ if (typing) clearTimeout(typing)+ setPreview(undefined)+ setTyping(+ setTimeout(() => {+ calculatePreview()+ setTyping(undefined)+ }, 2_000)+ )+ }, [url, content])++ const handleSave = async () => {+ const error = await props.onSave({ name, type, status, url, content, http_method: httpMethod, http_headers: httpHeaders })+ if (error) {+ setError(error)+ }+ }+ const handleCancel = () => props.onCancel()++ const setType = (option?: SelectOption) => _setType(option?.value as WebhookType)+ const setStatus = (active: boolean) => _setStatus(active ? WebhookStatus.ENABLED : WebhookStatus.DISABLED)++ const setHttpHeader = (header: string, value: string) => {+ _setHttpHeaders((headers) => ({+ ...headers,+ [header]: value,+ }))+ }++ const removeHttpHeader = (header: string) => {+ _setHttpHeaders((headers) => {+ const { [header]: _, ...remaining } = headers+ return remaining+ })+ }++ const showModal = () => setIsModalOpen(true)+ const hideModal = () => setIsModalOpen(false)++ const allHeaders = Object.keys(httpHeaders)+ const title = props.webhook ? `Webhook #${props.webhook.id}: ${props.webhook.name}` : "New webhook"+ return (+ <>+ {status === WebhookStatus.FAILED && (+ <Message type="error" showIcon>+ This webhook has failed+ </Message>+ )}+ <h2 className="text-title mb-2">{title}</h2>+ <Form className="c-webhook-form" error={error}>+ <Input field="name" label="Name" value={name} onChange={setName} placeholder="My awesome webhook" />+ <Select+ label="Type"+ field="type"+ defaultValue={type}+ options={[+ { label: "New Post", value: WebhookType.NEW_POST },+ { label: "New Comment", value: WebhookType.NEW_COMMENT },+ { label: "Change Status", value: WebhookType.CHANGE_STATUS },+ { label: "Delete Post", value: WebhookType.DELETE_POST },+ ]}+ onChange={setType}+ />+ <Field label="Status">+ <Toggle active={status === WebhookStatus.ENABLED} onToggle={setStatus} />+ {status === WebhookStatus.FAILED && <p className="text-muted mt-1">This webhook was disabled due to a trigger failure</p>}+ </Field>+ <Input+ field="url"+ label="URL"+ afterLabel={<HoverInfo text="You can use Go template formatting with many properties here" onClick={showModal} />}+ value={url}+ onChange={setUrl}+ placeholder="https://webhook.site/..."+ />+ <TextArea+ className="c-webhook-form__content"+ field="content"+ label="Content"+ afterLabel={<HoverInfo text="You can use Go template formatting with many properties here" onClick={showModal} />}+ value={content}+ onChange={setContent}+ placeholder="Request body"+ />+ <Input field="http_method" label="HTTP Method" value={httpMethod} onChange={setHttpMethod} placeholder="POST" />+ <Field label="HTTP Headers" afterLabel={<HoverInfo text="Those headers are sent in the request when the webhook is triggered" />}>+ <VStack spacing={2}>+ {Object.entries(httpHeaders).map(([header, value]) => (+ <HttpHeader key={header} header={header} value={value} onEdit={setHttpHeader} onRemove={removeHttpHeader} />+ ))}+ <HttpHeader onEdit={setHttpHeader} allHeaders={allHeaders} />+ </VStack>+ </Field>+ {(url || content) && (+ <Field label="Preview" className="c-webhook-form__preview">+ {preview === null ? (+ <p className="text-muted">Failed to load preview</p>+ ) : preview === undefined ? (+ <Loader className="text-center" text="Loading preview" />+ ) : (+ <VStack className="bg-gray-50 rounded-md p-2" spacing={2}>+ {url && (+ <div>+ <h3 className="text-bold mb-1">URL</h3>+ <pre>{preview.url.value ? preview.url.value : preview.url.error}</pre>+ {preview.url.message && <p className="text-muted">{preview.url.message}</p>}+ </div>+ )}+ {content && (+ <div>+ <h3 className="text-bold mb-1">Content</h3>+ <pre>{preview.content.value ? preview.content.value : preview.content.error}</pre>+ {preview.content.message && <p className="text-muted">{preview.content.message}</p>}+ </div>+ )}+ </VStack>+ )}+ </Field>+ )}+ <HStack>+ <Button variant="primary" onClick={handleSave}>+ Save+ </Button>+ <Button onClick={handleCancel} variant="tertiary">+ Cancel+ </Button>+ </HStack>+ </Form>+ <WebhookTemplateInfoModal type={type} isModalOpen={isModalOpen} onModalClose={hideModal} />+ </>+ )+}diff --git a/public/pages/Administration/components/webhook/WebhookListItem.scss b/public/pages/Administration/components/webhook/WebhookListItem.scssnew file mode 100644index 000000000..f52323815--- /dev/null+++ b/public/pages/Administration/components/webhook/WebhookListItem.scss@@ -0,0 +1,19 @@+@import "~@fider/assets/styles/variables.scss";++.c-webhook-listitem {+ &__icon {+ vertical-align: middle;++ &--enabled {+ color: get("colors.green.500");+ }++ &--disabled {+ color: get("colors.yellow.500");+ }++ &--failed {+ color: get("colors.red.500");+ }+ }+}diff --git a/public/pages/Administration/components/webhook/WebhookListItem.tsx b/public/pages/Administration/components/webhook/WebhookListItem.tsxnew file mode 100644index 000000000..51d3b6776--- /dev/null+++ b/public/pages/Administration/components/webhook/WebhookListItem.tsx@@ -0,0 +1,129 @@+import "./WebhookListItem.scss"++import React, { useState } from "react"+import { Webhook, WebhookStatus, WebhookTriggerResult } from "@fider/models"+import { Button, Icon } from "@fider/components"+import { actions, notify } from "@fider/services"++import IconX from "@fider/assets/images/heroicons-x.svg"+import IconPencilAlt from "@fider/assets/images/heroicons-pencil-alt.svg"+import IconPlay from "@fider/assets/images/heroicons-play.svg"+import IconCheckCircle from "@fider/assets/images/heroicons-check-circle.svg"+import IconXCircle from "@fider/assets/images/heroicons-x-circle.svg"+import IconExclamation from "@fider/assets/images/heroicons-exclamation.svg"+import { HStack, VStack } from "@fider/components/layout"+import { WebhookFailInfo } from "./WebhookFailInfo"++interface WebhookListItemProps {+ webhook: Webhook+ editWebhook: (webhook: Webhook) => void+ onWebhookDeleted: (webhook: Webhook) => void+ onWebhookFailed: (webhook: Webhook) => void+}++interface WebhookIconProps {+ status: WebhookStatus+}++const WebhookIcon = (props: WebhookIconProps) => {+ let text, icon+ switch (props.status) {+ case WebhookStatus.ENABLED:+ text = "Enabled"+ icon = IconCheckCircle+ break+ case WebhookStatus.DISABLED:+ text = "Disabled"+ icon = IconXCircle+ break+ case WebhookStatus.FAILED:+ text = "Failed"+ icon = IconExclamation+ }+ return (+ <div data-tooltip={text}>+ <Icon width="23" height="23" className={`c-webhook-listitem__icon c-webhook-listitem__icon--${text.toLowerCase()}`} sprite={icon} />+ </div>+ )+}++export const WebhookListItem = (props: WebhookListItemProps) => {+ const [deleting, setDeleting] = useState(false)+ const [triggerResult, setTriggerResult] = useState<WebhookTriggerResult | undefined>(undefined)+ const [isFailInfoModalOpen, setIsFailInfoModalOpen] = useState(false)++ const showFailInfoModal = () => setIsFailInfoModalOpen(true)+ const hideFailInfoModal = () => setIsFailInfoModalOpen(false)++ const deleteWebhook = async () => {+ const result = await actions.deleteWebhook(props.webhook.id)+ if (result.ok) {+ setDeleting(false)+ props.onWebhookDeleted(props.webhook)+ }+ }++ const testWebhook = async () => {+ const result = await actions.testWebhook(props.webhook.id)+ setTriggerResult(result.data)+ if (result.ok && result.data.success) {+ notify.success("Successfully triggered webhook")+ } else {+ notify.error(result.data.message)+ props.onWebhookFailed(props.webhook)+ }+ }++ const renderDeleteMode = () => {+ return (+ <VStack spacing={2}>+ <div>+ <b>Are you sure?</b>{" "}+ <span>+ The webhook #{props.webhook.id} "{props.webhook.name}" will be deleted forever. Alternatively, you may want to <b>disable</b> it instead.+ </span>+ </div>+ <div>+ <Button variant="danger" onClick={deleteWebhook}>+ Delete webhook+ </Button>+ <Button onClick={() => setDeleting(false)} variant="tertiary">+ Cancel+ </Button>+ </div>+ </VStack>+ )+ }++ const renderViewMode = () => {+ return (+ <HStack justify="between">+ <HStack>+ <WebhookIcon status={props.webhook.status} />+ <h3 className="text-title">+ <span className="text-muted">#{props.webhook.id}</span> {props.webhook.name}+ </h3>+ {triggerResult?.success === false && (+ <WebhookFailInfo result={triggerResult} isModalOpen={isFailInfoModalOpen} onModalOpen={showFailInfoModal} onModalClose={hideFailInfoModal} />+ )}+ </HStack>+ <HStack>+ <Button size="small" onClick={testWebhook}>+ <Icon sprite={IconPlay} />+ <span>Test</span>+ </Button>+ <Button size="small" onClick={() => props.editWebhook(props.webhook)}>+ <Icon sprite={IconPencilAlt} />+ <span>Edit</span>+ </Button>+ <Button size="small" onClick={() => setDeleting(true)}>+ <Icon sprite={IconX} />+ <span>Delete</span>+ </Button>+ </HStack>+ </HStack>+ )+ }++ return deleting ? renderDeleteMode() : renderViewMode()+}diff --git a/public/pages/Administration/components/webhook/WebhookProperties.scss b/public/pages/Administration/components/webhook/WebhookProperties.scssnew file mode 100644index 000000000..7c328a6d8--- /dev/null+++ b/public/pages/Administration/components/webhook/WebhookProperties.scss@@ -0,0 +1,55 @@+@import "~@fider/assets/styles/variables.scss";++.c-webhook-properties {+ border-spacing: 0;++ &__header {+ font-weight: get("font.weight.semibold");+ width: 50%;+ padding: 0 spacing(1);++ @include media("sm") {+ width: 100%;++ &:last-child {+ font-weight: get("font.weight.medium");+ padding-top: spacing(2);+ }+ }+ }++ &__prop {+ font-family: get("font.family.code");+ font-size: get("font.size.sm");+ width: 50%;+ padding: 0 spacing(1);++ @include media("sm") {+ width: 100%;+ font-size: get("font.size.base");+ padding-bottom: spacing(2);+ }+ }++ &__val {+ font-size: get("font.size.sm");+ overflow-wrap: break-word;+ width: 50%;+ padding: 0 spacing(1);++ @include media("sm") {+ width: 100%;+ }++ @each $color in ("gray", "blue", "green", "red") {+ &--#{$color} {+ font-family: get("font.family.code");+ color: get("colors.#{$color}.600");+ }+ }++ &--italic {+ font-style: italic;+ }+ }+}diff --git a/public/pages/Administration/components/webhook/WebhookProperties.tsx b/public/pages/Administration/components/webhook/WebhookProperties.tsxnew file mode 100644index 000000000..06ce19469--- /dev/null+++ b/public/pages/Administration/components/webhook/WebhookProperties.tsx@@ -0,0 +1,67 @@+import "./WebhookProperties.scss"++import React from "react"++import { HStack, VStack } from "@fider/components/layout"+import { StringObject } from "@fider/services"++interface WebhookPropertiesProps {+ properties: StringObject+ propsName: string+ valueName: string+}++interface PropertyProps {+ value: any+}++const Property = (props: PropertyProps) => {+ const grayValText = (txt: string) => <span className="c-webhook-properties__val--gray c-webhook-properties__val--italic"><{txt}></span>++ if (Array.isArray(props.value))+ return (+ <VStack spacing={2} divide>+ {props.value.map((val, i) => (+ <Property key={i} value={val} />+ ))}+ </VStack>+ )++ if (props.value === "") return grayValText("empty")+ if (props.value === null) return grayValText("null")+ if (props.value === undefined) return grayValText("undefined")+ if (props.value === true) return <span className="c-webhook-properties__val--green">true</span>+ if (props.value === false) return <span className="c-webhook-properties__val--red">false</span>++ const type = typeof props.value+ switch (type) {+ case "string":+ return <span>{props.value}</span>+ case "number":+ case "bigint":+ return <span className="c-webhook-properties__val--blue">{props.value}</span>+ case "object":+ return <WebhookProperties properties={props.value} propsName="Name" valueName="Value" />+ default:+ return props.value+ }+}++export const WebhookProperties = (props: WebhookPropertiesProps) => {+ return (+ <VStack className="c-webhook-properties" spacing={2} divide>+ <HStack className="flex-wrap" spacing={0}>+ <div className="c-webhook-properties__header">{props.propsName}</div>+ <div className="c-webhook-properties__header">{props.valueName}</div>+ </HStack>+ {Object.entries(props.properties).map(([prop, val]) => (+ <HStack key={prop} className="flex-wrap" spacing={0}>+ <div className="c-webhook-properties__prop">{prop}</div>+ <div className="c-webhook-properties__val">+ <Property value={val} />+ </div>+ </HStack>+ ))}+ </VStack>+ )+}diff --git a/public/pages/Administration/components/webhook/WebhookTemplateInfoModal.scss b/public/pages/Administration/components/webhook/WebhookTemplateInfoModal.scssnew file mode 100644index 000000000..26f33df64--- /dev/null+++ b/public/pages/Administration/components/webhook/WebhookTemplateInfoModal.scss@@ -0,0 +1,102 @@+@import "~@fider/assets/styles/variables.scss";++.c-webhook-templateinfo {+ pre {+ text-align: left;+ white-space: pre-wrap;+ font-size: get("font.size.sm");+ }++ &__header {+ font-weight: get("font.weight.semibold");++ &-func {+ width: 20%;++ @include media("sm") {+ width: 100%;+ padding-bottom: spacing(2);+ }+ }++ &-desc {+ width: 30%;++ @include media("sm") {+ font-weight: get("font.weight.medium");+ width: 100%;+ padding-bottom: spacing(4);+ }+ }++ &-params {+ width: 100%;++ @include media("sm") {+ font-weight: get("font.weight.medium");+ }+ }++ &-param {+ width: 40%;++ @include media("sm") {+ font-weight: get("font.weight.medium");+ }+ }++ &-param-desc {+ width: 60%;++ @include media("sm") {+ font-weight: get("font.weight.medium");+ }+ }+ }++ &__func {+ font-family: get("font.family.code");+ font-size: get("font.size.sm");+ width: 20%;+ padding: 0 spacing(1);++ @include media("sm") {+ width: 100%;+ font-size: get("font.size.base");+ padding-bottom: spacing(2);+ }+ }++ &__desc {+ font-size: get("font.size.sm");+ width: 30%;+ padding: 0 spacing(1);++ @include media("sm") {+ width: 100%;+ padding-bottom: spacing(4);+ }+ }++ &__params {+ width: 50%;+ padding: 0 spacing(1);++ @include media("sm") {+ width: 100%;+ }+ }++ &__param {+ font-family: get("font.family.code");+ font-size: get("font.size.sm");+ width: 40%;+ padding: 0 spacing(1);+ }++ &__param-desc {+ font-size: get("font.size.sm");+ width: 60%;+ padding: 0 spacing(1);+ }+}diff --git a/public/pages/Administration/components/webhook/WebhookTemplateInfoModal.tsx b/public/pages/Administration/components/webhook/WebhookTemplateInfoModal.tsxnew file mode 100644index 000000000..448bd04b4--- /dev/null+++ b/public/pages/Administration/components/webhook/WebhookTemplateInfoModal.tsx@@ -0,0 +1,180 @@+import "./WebhookTemplateInfoModal.scss"++import { Button, Loader, Modal } from "@fider/components"+import { WebhookProperties } from "@fider/pages/Administration/components/webhook/WebhookProperties"+import React, { useEffect, useState } from "react"+import { WebhookType } from "@fider/models"+import { actions, StringObject } from "@fider/services"+import { HStack, VStack } from "@fider/components/layout"+import { HoverInfo } from "@fider/components/common/HoverInfo"++interface WebhookTemplateInfoProps {+ type: WebhookType+ isModalOpen: boolean+ onModalClose: () => void+}++interface FunctionSpecification {+ params: {+ type: string+ desc: string+ info?: string+ link?: string+ }[]+ description: string+ info?: string+ link?: string+}++const functions: StringObject<FunctionSpecification> = {+ stripHtml: {+ params: [{ type: "string", desc: "The input string containing HTML to strip" }],+ description: "Strip HTML tags from the input data",+ info: "It removes all tags to keep only content",+ },+ md5: {+ params: [{ type: "string", desc: "The input string to hash" }],+ description: "Hash text using md5 algorithm",+ info: "What is MD5?",+ link: "https://en.wikipedia.org/wiki/MD5",+ },+ lower: {+ params: [{ type: "string", desc: "The input string to lowercase" }],+ description: "Lowercase text",+ },+ upper: {+ params: [{ type: "string", desc: "The input string to uppercase" }],+ description: "Uppercase text",+ },+ markdown: {+ params: [{ type: "string", desc: "The input string containing Markdown to parse" }],+ description: "Parse Markdown to HTML from the input data",+ info: "When parsing, input is sanitized from HTML to prevent XSS attacks",+ },+ format: {+ params: [+ {+ type: "string",+ desc: "The date format according to Go specifications",+ info: "See Go time format",+ link: "https://yourbasic.org/golang/format-parse-string-time-date-example/#standard-time-and-date-formats",+ },+ { type: "time", desc: "The time to format" },+ ],+ description: "Format the given date and time",+ },+ quote: {+ params: [{ type: "string", desc: "The input string to quote" }],+ description: "Enquote a string and escape inner special characters",+ info: "You should use this function when using a value as a JSON field",+ },+ escape: {+ params: [{ type: "string", desc: "The input string to escape" }],+ description: "Escape inner special characters of a string, without enquoting it",+ info: "You should use this function when using a value within an enquoted string",+ },+ urlquery: {+ params: [{ type: "string", desc: "The input string to encode as URL query value" }],+ description: "Encode a string into a valid URL query element",+ info: "You should use this function when using a value in URL",+ },+}+const textExample = 'A new post entitled "{{ .post_title }}" has been created by {{ .author_name }}.'+const jsonExample = `{+ "title": "New post: {{ escape .post_title }}",+ "content": {{ quote .post_description }},+ "user": {{ quote .author_name }},+ "date": {{ format "2006-01-02T15:04:05-0700" .post_created_at | quote }}+}`++export const WebhookTemplateInfoModal = (props: WebhookTemplateInfoProps) => {+ const [properties, setProperties] = useState<StringObject | null>()++ useEffect(() => {+ let mounted = true+ setProperties(undefined)+ actions.getWebhookHelp(props.type).then((result) => mounted && setProperties(result.ok ? result.data : null))+ return () => {+ mounted = false+ }+ }, [props.type])++ return (+ <Modal.Window className="c-webhook-templateinfo" isOpen={props.isModalOpen} onClose={props.onModalClose} size="large">+ <Modal.Header>Webhook template formatting help</Modal.Header>+ <Modal.Content>+ <VStack spacing={4} divide>+ <div>+ <h3 className="text-title mb-1">What is a template?</h3>+ <p>+ The template engine used is the native Go <code>text/template</code> package. The simpliest way to create a template is to write your text, and+ insert the property name, prefixed by a dot, enclosed in double braces with spaces within (wierd? complete!). Example:+ </p>+ <pre className="text-left">{textExample}</pre>+ <p>+ When using a structured text format such as JSON, you may need to wrap those properties into quotes. But be careful: you must escape values by+ yourself by calling the appropriate function depending of your situation. Example:+ </p>+ <pre className="text-left">{jsonExample}</pre>+ <Button href="https://pkg.go.dev/text/template" target="_blank" variant="primary">+ Official Go templates documentation+ </Button>+ </div>+ {properties === undefined ? (+ <p className="text-muted">Failed to load help data</p>+ ) : properties === null ? (+ <Loader text="Loading help data" />+ ) : (+ <>+ <div>+ <h3 className="text-title mb-1">Properties</h3>+ <WebhookProperties properties={properties} propsName="Property name" valueName="Example value" />+ </div>+ <div>+ <h3 className="text-title mb-1">Functions</h3>+ <VStack spacing={2} divide>+ <HStack className="c-webhook-templateinfo__header flex-wrap" spacing={0}>+ <div className="c-webhook-templateinfo__header-func">Function</div>+ <div className="c-webhook-templateinfo__header-desc">Description</div>+ <VStack className="c-webhook-templateinfo__params">+ <div className="c-webhook-templateinfo__header-params">Parameters</div>+ <HStack>+ <div className="c-webhook-templateinfo__header-param">Type</div>+ <div className="c-webhook-templateinfo__header-param-desc">Description</div>+ </HStack>+ </VStack>+ </HStack>+ {Object.entries(functions).map(([func, spec]) => (+ <HStack key={func} className="flex-wrap" spacing={0}>+ <div className="c-webhook-templateinfo__func">{func}</div>+ <div className="c-webhook-templateinfo__desc">+ {spec.description}+ {spec.info && <HoverInfo text={spec.info} href={spec.link} target="_blank" />}+ </div>+ <VStack className="c-webhook-templateinfo__params" spacing={2} divide>+ {spec.params.map((param, j) => (+ <HStack key={j} className="flex-wrap" spacing={0}>+ <div className="c-webhook-templateinfo__param">{param.type}</div>+ <div className="c-webhook-templateinfo__param-desc">+ {param.desc}+ {param.info && <HoverInfo text={param.info} href={param.link} target="_blank" />}+ </div>+ </HStack>+ ))}+ </VStack>+ </HStack>+ ))}+ </VStack>+ </div>+ </>+ )}+ </VStack>+ </Modal.Content>+ <Modal.Footer>+ <Button variant="tertiary" onClick={props.onModalClose}>+ Close+ </Button>+ </Modal.Footer>+ </Modal.Window>+ )+}diff --git a/public/pages/Administration/pages/ManageWebhooks.page.tsx b/public/pages/Administration/pages/ManageWebhooks.page.tsxnew file mode 100644index 000000000..88b77dea7--- /dev/null+++ b/public/pages/Administration/pages/ManageWebhooks.page.tsx@@ -0,0 +1,149 @@+import React, { useState } from "react"+import { Button } from "@fider/components"++import { Webhook, WebhookData, WebhookStatus, WebhookType } from "@fider/models"+import { actions, Failure } from "@fider/services"+import { AdminPageContainer } from "../components/AdminBasePage"+import { WebhookForm } from "../components/webhook/WebhookForm"+import { WebhookListItem } from "../components/webhook/WebhookListItem"+import { VStack } from "@fider/components/layout"++interface ManageWebhooksPageProps {+ webhooks: Webhook[]+}++const webhookSorter = (w1: Webhook, w2: Webhook) => {+ if (w1.name < w2.name) {+ return -1+ } else if (w1.name > w2.name) {+ return 1+ }+ return 0+}++interface WebhooksListProps {+ title: string+ description: string+ list: JSX.Element[]+}++const WebhooksList = (props: WebhooksListProps) => {+ return (+ <div>+ <h2 className="text-display">{props.title}</h2>+ <p className="text-muted">These webhooks are triggered every time {props.description}.</p>+ <VStack spacing={4} divide>+ {props.list.length === 0 ? <p className="text-muted">There aren’t any "{props.title.toLowerCase()}" webhook yet.</p> : props.list}+ </VStack>+ </div>+ )+}++const ManageWebhooksPage = (props: ManageWebhooksPageProps) => {+ const [isAdding, setIsAdding] = useState(false)+ const [allWebhooks, setAllWebhooks] = useState(props.webhooks.sort(webhookSorter))+ const [editing, setEditing] = useState<Webhook>()++ const sortWebhooks = () => setAllWebhooks(allWebhooks.sort(webhookSorter))++ const addNew = () => {+ setIsAdding(true)+ setEditing(undefined)+ }+ const cancelAdd = () => setIsAdding(false)++ const saveNewWebhook = async (data: WebhookData): Promise<Failure | undefined> => {+ const result = await actions.createWebhook(data)+ if (result.ok) {+ setIsAdding(false)+ setAllWebhooks(allWebhooks.concat({ id: result.data.id, ...data }).sort(webhookSorter))+ } else {+ return result.error+ }+ }++ const startWebhookEditing = (webhook: Webhook) => {+ setIsAdding(false)+ setEditing(webhook)+ }+ const cancelEdit = () => setEditing(undefined)++ const handleWebhookDeleted = (webhook: Webhook) => {+ const idx = allWebhooks.indexOf(webhook)+ setAllWebhooks(allWebhooks.splice(idx, 1) && allWebhooks)+ }++ const handleWebhookEdited = async (data: WebhookData): Promise<Failure | undefined> => {+ const webhook = editing+ if (webhook === undefined) return // impossible+ const result = await actions.updateWebhook(webhook.id, data)+ if (result.ok) {+ webhook.name = data.name+ webhook.type = data.type+ webhook.status = data.status === WebhookStatus.FAILED ? WebhookStatus.DISABLED : data.status+ webhook.url = data.url+ webhook.content = data.content+ webhook.http_method = data.http_method+ webhook.http_headers = data.http_headers++ setEditing(undefined)+ sortWebhooks()+ } else {+ return result.error+ }+ }++ const handleWebhookFailed = (webhook: Webhook) => {+ webhook.status = WebhookStatus.FAILED+ sortWebhooks()+ }++ const getWebhookList = (filter: (webhook: Webhook) => boolean) => {+ return allWebhooks.filter(filter).map((w) => {+ return (+ <WebhookListItem+ key={w.id}+ webhook={w}+ onWebhookDeleted={handleWebhookDeleted}+ editWebhook={startWebhookEditing}+ onWebhookFailed={handleWebhookFailed}+ />+ )+ })+ }++ const render = (content: JSX.Element) => (+ <AdminPageContainer id="p-admin-webhooks" name="webhooks" title="Webhooks" subtitle="Manage your site webhooks">+ {content}+ </AdminPageContainer>+ )++ if (isAdding) {+ return render(<WebhookForm onSave={saveNewWebhook} onCancel={cancelAdd} />)+ }++ if (editing) {+ return render(<WebhookForm onSave={handleWebhookEdited} onCancel={cancelEdit} webhook={editing} />)+ }++ const newPostList = getWebhookList((w) => w.type === WebhookType.NEW_POST)+ const newCommentList = getWebhookList((w) => w.type === WebhookType.NEW_COMMENT)+ const changeStatusList = getWebhookList((w) => w.type === WebhookType.CHANGE_STATUS)+ const deletePostList = getWebhookList((w) => w.type === WebhookType.DELETE_POST)++ return render(+ <VStack spacing={8}>+ <WebhooksList title="New Post" description="a new post is created on this site" list={newPostList} />+ <WebhooksList title="New Comment" description="a new comment is created on any post" list={newCommentList} />+ <WebhooksList title="Change Status" description="the status of a post is changed" list={changeStatusList} />+ <WebhooksList title="Delete Post" description="a post is deleted on this site" list={deletePostList} />+ <div>+ <Button variant="secondary" onClick={addNew}>+ Add new+ </Button>+ </div>+ </VStack>+ )+}++export default ManageWebhooksPagediff --git a/public/pages/DesignSystem/DesignSystem.page.tsx b/public/pages/DesignSystem/DesignSystem.page.tsxindex ccc4906fd..d6ddebfb4 100644--- a/public/pages/DesignSystem/DesignSystem.page.tsx+++ b/public/pages/DesignSystem/DesignSystem.page.tsx@@ -387,6 +387,7 @@ const DesignSystemPage = () => {<h2 className="text-display2 mb-3 mt-6">11. Loader</h2><Loader />+ <Loader text="Loader with text" /><h2 className="text-display2 mb-3 mt-6">12. Message</h2>diff --git a/public/router.tsx b/public/router.tsxindex b453c2167..2c913574a 100644--- a/public/router.tsx+++ b/public/router.tsx@@ -23,6 +23,7 @@ const defaultRoutes = [route("/admin/invitations", Pages.AsyncInvitationsPage),route("/admin/authentication", Pages.AsyncManageAuthenticationPage),route("/admin/advanced", Pages.AsyncAdvancedSettingsPage),+ route("/admin/webhooks", Pages.AsyncManageWebhooksPage),route("/admin", Pages.AsyncGeneralSettingsPage),route("/terms", Pages.AsyncLegalPage, false),route("/privacy", Pages.AsyncLegalPage, false),diff --git a/public/services/actions/index.ts b/public/services/actions/index.tsindex e1229d34c..4aef473aa 100644--- a/public/services/actions/index.ts+++ b/public/services/actions/index.ts@@ -5,3 +5,4 @@ export * from "./tenant"export * from "./notification"export * from "./invite"export * from "./infra"+export * from "./webhook"diff --git a/public/services/actions/webhook.ts b/public/services/actions/webhook.tsnew file mode 100644index 000000000..930075006--- /dev/null+++ b/public/services/actions/webhook.ts@@ -0,0 +1,26 @@+import { http, Result, StringObject } from "@fider/services"+import { WebhookData, WebhookPreviewResult, WebhookTriggerResult, WebhookType } from "@fider/models"++export const createWebhook = async (data: WebhookData): Promise<Result<{ id: number }>> => {+ return await http.post(`/_api/admin/webhook`, data)+}++export const updateWebhook = async (id: number, data: WebhookData): Promise<Result> => {+ return await http.put(`/_api/admin/webhook/${id}`, data)+}++export const deleteWebhook = async (id: number): Promise<Result> => {+ return await http.delete(`/_api/admin/webhook/${id}`)+}++export const testWebhook = async (id: number): Promise<Result<WebhookTriggerResult>> => {+ return await http.get(`/_api/admin/webhook/test/${id}`)+}++export const previewWebhook = async (type: WebhookType, url: string, content: string): Promise<Result<WebhookPreviewResult>> => {+ return await http.post("/_api/admin/webhook/preview", { type, url, content })+}++export const getWebhookHelp = async (type: WebhookType): Promise<Result<StringObject>> => {+ return await http.get(`/_api/admin/webhook/props/${type}`)+}diff --git a/public/services/utils.ts b/public/services/utils.tsindex 37dac1cfc..444bcf2b8 100644--- a/public/services/utils.ts+++ b/public/services/utils.ts@@ -111,3 +111,7 @@ export const truncate = (input: string, maxLength: number): string => {}return input}++export type StringObject<T = any> = {+ [key: string]: T+}