Open platform to collect and prioritize feedback
feat: Implement ATOM feeds for posts and comments (#1287)
Alexandros Feuerstein475d76356b95
diff --git a/app/actions/tenant.go b/app/actions/tenant.goindex a1f340913..40c041d9f 100644--- a/app/actions/tenant.go+++ b/app/actions/tenant.go@@ -15,7 +15,7 @@ import ("github.com/getfider/fider/app/pkg/validate")-//CreateTenant is the input model used to create a tenant+// CreateTenant is the input model used to create a tenanttype CreateTenant struct {Token string `json:"token"`Name string `json:"name"`@@ -89,27 +89,27 @@ func (action *CreateTenant) Validate(ctx context.Context, user *entity.User) *vareturn result}-//GetEmail returns the email being verified+// GetEmail returns the email being verifiedfunc (action *CreateTenant) GetEmail() string {return action.Email}-//GetName returns the name of the email owner+// GetName returns the name of the email ownerfunc (action *CreateTenant) GetName() string {return action.Name}-//GetUser returns the current user performing this action+// GetUser returns the current user performing this actionfunc (action *CreateTenant) GetUser() *entity.User {return nil}-//GetKind returns EmailVerificationKindSignUp+// GetKind returns EmailVerificationKindSignUpfunc (action *CreateTenant) GetKind() enum.EmailVerificationKind {return enum.EmailVerificationKindSignUp}-//UpdateTenantSettings is the input model used to update tenant settings+// UpdateTenantSettings is the input model used to update tenant settingstype UpdateTenantSettings struct {Logo *dto.ImageUpload `json:"logo"`Title string `json:"title"`@@ -175,7 +175,7 @@ func (action *UpdateTenantSettings) Validate(ctx context.Context, user *entity.Ureturn result}-//UpdateTenantAdvancedSettings is the input model used to update tenant advanced settings+// UpdateTenantAdvancedSettings is the input model used to update tenant advanced settingstype UpdateTenantAdvancedSettings struct {CustomCSS string `json:"customCSS"`}@@ -190,18 +190,22 @@ func (action *UpdateTenantAdvancedSettings) Validate(ctx context.Context, user *return validate.Success()}-//UpdateTenantPrivacy is the input model used to update tenant privacy settings-type UpdateTenantPrivacy struct {- IsPrivate bool `json:"isPrivate"`+// UpdateTenantPrivacySettings is the input model used to update tenant privacy settings+type UpdateTenantPrivacySettings struct {+ IsPrivate bool `json:"isPrivate"`+ IsFeedEnabled bool `json:"isFeedEnabled"`}// IsAuthorized returns true if current user is authorized to perform this action-func (action *UpdateTenantPrivacy) IsAuthorized(ctx context.Context, user *entity.User) bool {+func (action *UpdateTenantPrivacySettings) IsAuthorized(ctx context.Context, user *entity.User) bool {return user != nil && user.Role == enum.RoleAdministrator}// Validate if current model is valid-func (action *UpdateTenantPrivacy) Validate(ctx context.Context, user *entity.User) *validate.Result {+func (action *UpdateTenantPrivacySettings) Validate(ctx context.Context, user *entity.User) *validate.Result {+ if action.IsPrivate && action.IsFeedEnabled {+ return validate.Failed("Feed can not be enabled when set to private.")+ }return validate.Success()}diff --git a/app/cmd/routes.go b/app/cmd/routes.goindex 299a2edac..d8c8e9db6 100644--- a/app/cmd/routes.go+++ b/app/cmd/routes.go@@ -44,6 +44,17 @@ func routes(r *web.Engine) *web.Engine {assets.Static("/assets/*filepath", "dist")}+ feed := r.Group()+ {+ feed.Use(middlewares.CORS())+ feed.Use(middlewares.WebSetup())+ feed.Use(middlewares.Tenant())+ feed.Use(middlewares.ClientCache(5 * time.Minute))++ feed.Get("/feed/global.atom", handlers.GlobalFeed())+ feed.Get("/feed/posts/:path", handlers.CommentFeed())+ }+r.Use(middlewares.Session())r.Get("/robots.txt", handlers.RobotsTXT())@@ -164,7 +175,7 @@ func routes(r *web.Engine) *web.Engine {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())+ ui.Post("/_api/admin/settings/privacy", handlers.UpdatePrivacySettings())ui.Post("/_api/admin/settings/emailauth", handlers.UpdateEmailAuthAllowed())ui.Post("/_api/admin/oauth", handlers.SaveOAuthConfig())ui.Post("/_api/admin/roles/:role/users", handlers.ChangeUserRole())diff --git a/app/handlers/admin.go b/app/handlers/admin.goindex 030809209..82ed74cd2 100644--- a/app/handlers/admin.go+++ b/app/handlers/admin.go@@ -92,16 +92,17 @@ func UpdateAdvancedSettings() web.HandlerFunc {}}-// UpdatePrivacy update current tenant's privacy settings-func UpdatePrivacy() web.HandlerFunc {+// UpdatePrivacySettings update current tenant's privacy settings+func UpdatePrivacySettings() web.HandlerFunc {return func(c *web.Context) error {- action := new(actions.UpdateTenantPrivacy)+ action := new(actions.UpdateTenantPrivacySettings)if result := c.BindTo(action); !result.Ok {return c.HandleValidation(result)}updateSettings := &cmd.UpdateTenantPrivacySettings{- IsPrivate: action.IsPrivate,+ IsPrivate: action.IsPrivate,+ IsFeedEnabled: action.IsFeedEnabled,}if err := bus.Dispatch(c, updateSettings); err != nil {return c.Failure(err)diff --git a/app/handlers/admin_test.go b/app/handlers/admin_test.goindex 3275da679..63adfd274 100644--- a/app/handlers/admin_test.go+++ b/app/handlers/admin_test.go@@ -134,7 +134,7 @@ func TestUpdateSettingsHandler_RemoveLogo(t *testing.T) {ExpectHandler(&cmd.UploadImage{}).CalledOnce()}-func TestUpdatePrivacyHandler(t *testing.T) {+func TestUpdatePrivacySettingsHandler(t *testing.T) {RegisterT(t)var updateCmd *cmd.UpdateTenantPrivacySettings@@ -148,12 +148,53 @@ func TestUpdatePrivacyHandler(t *testing.T) {OnTenant(mock.DemoTenant).AsUser(mock.JonSnow).ExecutePost(- handlers.UpdatePrivacy(),- `{ "isPrivate": true }`,+ handlers.UpdatePrivacySettings(),+ `{ "isPrivate": true, "isFeedEnabled": false }`,)Expect(code).Equals(http.StatusOK)Expect(updateCmd.IsPrivate).IsTrue()+ Expect(updateCmd.IsFeedEnabled).IsFalse()++ server = mock.NewServer()+ code, _ = server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(+ handlers.UpdatePrivacySettings(),+ `{ "isPrivate": false, "isFeedEnabled": false }`,+ )++ Expect(code).Equals(http.StatusOK)+ Expect(updateCmd.IsPrivate).IsFalse()+ Expect(updateCmd.IsFeedEnabled).IsFalse()++ server = mock.NewServer()+ code, _ = server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(+ handlers.UpdatePrivacySettings(),+ `{ "isPrivate": false, "isFeedEnabled": true }`,+ )++ Expect(code).Equals(http.StatusOK)+ Expect(updateCmd.IsPrivate).IsFalse()+ Expect(updateCmd.IsFeedEnabled).IsTrue()++ server = mock.NewServer()+ code, _ = server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ ExecutePost(+ handlers.UpdatePrivacySettings(),+ `{ "isPrivate": true, "isFeedEnabled": true }`,+ )++ Expect(code).Equals(http.StatusBadRequest)+ // Should be same as last request+ Expect(updateCmd.IsPrivate).IsFalse()+ Expect(updateCmd.IsFeedEnabled).IsTrue()}func TestManageMembersHandler(t *testing.T) {diff --git a/app/handlers/feed.go b/app/handlers/feed.gonew file mode 100644index 000000000..c76b10035--- /dev/null+++ b/app/handlers/feed.go@@ -0,0 +1,331 @@+package handlers++import (+ "encoding/xml"+ "fmt"+ "github.com/getfider/fider/app/models/entity"+ "github.com/getfider/fider/app/pkg/env"+ "github.com/getfider/fider/app/pkg/i18n"+ "github.com/getfider/fider/app/pkg/markdown"+ "html"+ "net/http"+ "strconv"+ "strings"+ "time"++ "github.com/getfider/fider/app/models/query"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/web"+)++type AtomFeed struct {+ XMLName xml.Name `xml:"http://www.w3.org/2005/Atom feed"`+ Title string `xml:"title"`+ Subtitle Content `xml:"subtitle"`+ Id string `xml:"id"`+ Updated string `xml:"updated"`+ Link []Link `xml:"link"`+ Author *Author `xml:"author"`+ Entries []*Entry `xml:"entry"`+}++type Entry struct {+ Title string `xml:"title,omitempty"`+ Id string `xml:"id"`+ Published string `xml:"published"`+ Updated string `xml:"updated,omitempty"`+ Link []Link `xml:"link"`+ Author *Author `xml:"author"`+ Summary *Content `xml:"summary"`+ Content *Content `xml:"content"`+ Categories []*Category `xml:"category,omitempty"`+}++type Category struct {+ Term string `xml:"term,attr"`+}++type Link struct {+ Rel string `xml:"rel,attr,omitempty"`+ Href string `xml:"href,attr"`+ Type string `xml:"type,attr,omitempty"`+ HrefLang string `xml:"hreflang,attr,omitempty"`+ Title string `xml:"title,attr,omitempty"`+ Length uint `xml:"length,attr,omitempty"`+}++type Author struct {+ Name string `xml:"name"`+ Uri string `xml:"uri,omitempty"`+ Email string `xml:"email,omitempty"`+ InnerXML string `xml:",innerxml"`+}++type Content struct {+ Type string `xml:"type,attr"`+ Body string `xml:",chardata"`+}++func formatTime(t time.Time) string {+ return t.Format("2006-01-02T15:04:05-07:00")+}++func generateXML(feed *AtomFeed) (string, error) {+ indent := ""+ if env.IsDevelopment() {+ indent = " "+ }++ feedXML, err := xml.MarshalIndent(feed, "", indent)+ if err != nil {+ return "", err+ }++ return "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" + string(feedXML), nil+}++type generatorOptions struct {+ generateTitle bool+ generateFooter bool+}++func generatePostContent(c *web.Context, post *entity.Post, options *generatorOptions) string {+ title := ""+ if options.generateTitle {+ title = i18n.T(c, "feed.post.title", i18n.Params{+ "votes": post.VotesCount,+ "comments": post.CommentsCount,+ "title": post.Title,+ })+ }++ footer := ""+ if options.generateFooter {+ responseFooter := ""+ if (post.Response != nil) && (post.Response.Text != "") {+ responseFooter = i18n.T(c, "feed.post.footer.response", i18n.Params{+ "responder": post.Response.User.Name,+ "date": post.Response.RespondedAt.Format("Jan 2, 2006"),+ "response": strings.ReplaceAll(post.Response.Text, "\n", "\n>"),+ })+ }++ footer = i18n.T(c, "feed.post.footer", i18n.Params{+ "response_footer": responseFooter,+ "votes": post.VotesCount,+ "comments": post.CommentsCount,+ "web_link": fmt.Sprintf("%s/posts/%d", web.BaseURL(c), post.Number),+ "feed_link": fmt.Sprintf("%s/feed/posts/%d.atom", web.BaseURL(c), post.Number),+ })+ }++ return string(markdown.Full(title + post.Description + footer))+}++func appendTags(c *web.Context, categories []*Category, post *entity.Post) ([]*Category, error) {+ getAssignedTags := &query.GetAssignedTags{Post: post}+ if err := bus.Dispatch(c, getAssignedTags); err != nil {+ return nil, err+ }+ tags := getAssignedTags.Result++ for _, tag := range tags {+ if tag.IsPublic {+ categories = append(categories, &Category{Term: tag.Name})+ }+ }++ return categories, nil+}++// GlobalFeed Returns the global ATOM feed with the 30 most recent posts as entries+func GlobalFeed() web.HandlerFunc {+ return func(c *web.Context) error {+ if c.Tenant().IsPrivate || !c.Tenant().IsFeedEnabled {+ return c.NotFound()+ }++ searchPosts := &query.SearchPosts{+ Query: c.QueryParam("query"),+ View: "all",+ Limit: "30",+ Tags: c.QueryParamAsArray("tags"),+ }+ if err := bus.Dispatch(c, searchPosts); err != nil {+ return c.Failure(err)+ }+ posts := searchPosts.Result++ feed := &AtomFeed{+ Title: c.Tenant().Name,+ Subtitle: Content{Body: string(markdown.Full(c.Tenant().WelcomeMessage)), Type: "html"},+ Id: web.BaseURL(c),+ Link: []Link{+ {Href: fmt.Sprintf("%s/feed/global.atom", web.BaseURL(c)), Type: "application/atom+xml", Rel: "self"},+ {Href: web.BaseURL(c), Type: "text/html", Rel: "alternate"},+ },+ Entries: []*Entry{},+ }++ lastUpdate := time.UnixMilli(0)+ for _, post := range posts {+ if post.CreatedAt.After(lastUpdate) {+ lastUpdate = post.CreatedAt+ }+ if (post.Response != nil) && post.Response.RespondedAt.After(lastUpdate) {+ lastUpdate = post.Response.RespondedAt+ }++ categories := []*Category{{Term: i18n.T(c, "enum.poststatus."+post.Status.Name())}}+ categories, err := appendTags(c, categories, post)+ if err != nil {+ return c.Failure(err)+ }++ feed.Entries = append(feed.Entries, &Entry{+ Title: i18n.T(c, "feed.global.title", i18n.Params{+ "count": post.VotesCount,+ "title": post.Title,+ }),+ Author: &Author{Name: post.User.Name},+ Published: formatTime(post.CreatedAt),+ Updated: func() string {+ if post.Response == nil {+ return formatTime(post.CreatedAt)+ }+ return formatTime(post.Response.RespondedAt)+ }(),+ Content: &Content{Type: "html", Body: generatePostContent(c, post, &generatorOptions{generateTitle: false, generateFooter: true})},+ Id: fmt.Sprintf("%s/posts/%d", web.BaseURL(c), post.Number),+ Link: []Link{+ {Href: fmt.Sprintf("%s/feed/posts/%d.atom", web.BaseURL(c), post.Number), Type: "application/atom+xml", Rel: "self"},+ {Href: fmt.Sprintf("%s/posts/%d", web.BaseURL(c), post.Number), Type: "text/html", Rel: "alternate"},+ },+ Categories: categories,+ })+ }+ feed.Updated = formatTime(lastUpdate)++ feedStr, err := generateXML(feed)+ if err != nil {+ return c.Failure(err)+ }++ return c.Blob(http.StatusOK, "application/atom+xml", []byte(feedStr))+ }+}++// CommentFeed Returns the ATOM feed for a single post, with its comments as entries+func CommentFeed() web.HandlerFunc {+ return func(c *web.Context) error {+ if c.Tenant().IsPrivate || !c.Tenant().IsFeedEnabled {+ return c.NotFound()+ }++ path := c.Param("path")+ path, found := strings.CutSuffix(path, ".atom")+ if !found {+ return c.NotFound()+ }+ number, err := strconv.Atoi(path)+ if err != nil {+ return c.NotFound()+ }++ getPost := &query.GetPostByNumber{Number: number}+ if err := bus.Dispatch(c, getPost); err != nil {+ return c.Failure(err)+ }+ getComments := &query.GetCommentsByPost{Post: getPost.Result}+ if err := bus.Dispatch(c, getComments); err != nil {+ return c.Failure(err)+ }+ post := getPost.Result+ comments := getComments.Result+ comments = comments[max(0, len(comments)-30):] // get the last 30 comments++ feed := &AtomFeed{+ Title: post.Title,+ Subtitle: Content{Body: string(markdown.Full(post.Description)), Type: "html"},+ Author: &Author{Name: post.User.Name},+ Id: fmt.Sprintf("%s/posts/%d/#comments", web.BaseURL(c), post.Number),+ Link: []Link{+ {Href: fmt.Sprintf("%s/feed/posts/%d.atom", web.BaseURL(c), post.Number), Type: "application/atom+xml", Rel: "self"},+ {Href: fmt.Sprintf("%s/posts/%d", web.BaseURL(c), post.Number), Type: "text/html", Rel: "alternate"},+ },+ Entries: []*Entry{},+ }++ categories := []*Category{{Term: i18n.T(c, "enum.poststatus."+post.Status.Name())}}+ categories, err = appendTags(c, categories, post)+ if err != nil {+ return c.Failure(err)+ }++ feed.Entries = append(feed.Entries, &Entry{+ Title: i18n.T(c, "feed.comment.op", i18n.Params{+ "author": post.User.Name,+ }),+ Author: &Author{Name: post.User.Name},+ Published: formatTime(post.CreatedAt),+ Updated: formatTime(post.CreatedAt),+ Id: fmt.Sprintf("%s/posts/%d", web.BaseURL(c), post.Number),+ Link: []Link{+ {Href: fmt.Sprintf("%s/posts/%d", web.BaseURL(c), post.Number), Type: "text/html", Rel: "alternate"},+ },+ Content: &Content{Type: "html", Body: generatePostContent(c, post, &generatorOptions{generateTitle: true, generateFooter: false})},+ Categories: categories,+ })+ if (post.Response != nil) && (post.Response.Text != "") {+ feed.Entries = append(feed.Entries, &Entry{+ Title: i18n.T(c, "feed.comment.response", i18n.Params{+ "author": post.Response.User.Name,+ }),+ Author: &Author{Name: post.Response.User.Name},+ Published: formatTime(post.Response.RespondedAt),+ Updated: formatTime(post.Response.RespondedAt), // so that it shows as "updated" on edit / new response+ Id: fmt.Sprintf("%s/posts/%d/#response", web.BaseURL(c), post.Number),+ Link: []Link{+ {Href: fmt.Sprintf("%s/posts/%d", web.BaseURL(c), post.Number), Type: "text/html", Rel: "alternate"},+ },+ Content: &Content{Type: "html", Body: string(markdown.Full(post.Response.Text))},+ Categories: []*Category{{Term: i18n.T(c, "enum.poststatus."+post.Status.Name())}},+ })+ }++ lastUpdate := time.UnixMilli(0)+ for _, comment := range comments {+ if comment.CreatedAt.After(lastUpdate) {+ lastUpdate = comment.CreatedAt+ }+ if (comment.EditedAt != nil) && comment.EditedAt.After(lastUpdate) {+ lastUpdate = *comment.EditedAt+ }++ feed.Entries = append(feed.Entries, &Entry{+ Title: i18n.T(c, "feed.comment.title", i18n.Params{+ "author": comment.User.Name,+ }),+ Author: &Author{Name: comment.User.Name},+ Published: formatTime(comment.CreatedAt),+ Updated: func() string {+ if comment.EditedAt == nil {+ return formatTime(comment.CreatedAt)+ }+ return formatTime(*comment.EditedAt)+ }(),+ Content: &Content{Type: "html", Body: string(markdown.Full(html.UnescapeString(comment.Content)))},+ Id: fmt.Sprintf("%s/posts/%d/#comment-%d", web.BaseURL(c), post.Number, comment.ID),+ Link: []Link{{Href: fmt.Sprintf("%s/posts/%d/#comment-%d", web.BaseURL(c), post.Number, comment.ID), Type: "text/html", Rel: "alternate"}},+ })+ }+ feed.Updated = formatTime(lastUpdate)++ feedStr, err := generateXML(feed)+ if err != nil {+ return c.Failure(err)+ }++ return c.Blob(http.StatusOK, "application/atom+xml", []byte(feedStr))+ }+}diff --git a/app/handlers/feed_test.go b/app/handlers/feed_test.gonew file mode 100644index 000000000..1c30082f1--- /dev/null+++ b/app/handlers/feed_test.go@@ -0,0 +1,213 @@+package handlers_test++import (+ "context"+ "github.com/getfider/fider/app/pkg/env"+ "net/http"+ "os"+ "testing"+ "time"++ "github.com/getfider/fider/app"+ "github.com/getfider/fider/app/handlers"+ "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/assert"+ "github.com/getfider/fider/app/pkg/bus"+ "github.com/getfider/fider/app/pkg/mock"+)++func compareGeneratorResponse(input string, fileName string) {+ //os.WriteFile(env.Path(fileName), []byte(input), 0744)+ bytes, err := os.ReadFile(env.Path(fileName))+ Expect(err).IsNil()+ Expect(input).Equals(string(bytes))+}++func TestGlobalFeedHandler(t *testing.T) {+ RegisterT(t)++ post1 := &entity.Post{+ ID: 1,+ Number: 1,+ Title: "First Post",+ Slug: "first-post",+ Description: "Description of first post",+ CreatedAt: time.Date(2023, 1, 1, 10, 0, 0, 0, time.UTC),+ User: &entity.User{ID: 1, Name: "Jon Snow"},+ VotesCount: 5,+ }++ post2 := &entity.Post{+ ID: 2,+ Number: 2,+ Title: "Second Post",+ Slug: "second-post",+ Description: "Description of second post",+ CreatedAt: time.Date(2023, 1, 3, 10, 0, 0, 0, time.UTC),+ User: &entity.User{ID: 2, Name: "Arya Stark"},+ VotesCount: 2,+ }++ bus.AddHandler(func(ctx context.Context, q *query.SearchPosts) error {+ q.Result = []*entity.Post{post1, post2}+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetAssignedTags) error {+ q.Result = []*entity.Tag{}+ return nil+ })++ server := mock.NewServer()+ code, response := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ Execute(handlers.GlobalFeed())++ Expect(code).Equals(http.StatusOK)+ Expect(response.Header().Get("Content-Type")).Equals("application/atom+xml")++ responseBody := response.Body.String()+ compareGeneratorResponse(responseBody, "app/handlers/testdata/global_feed.atom")+}++func TestCommentFeedHandler(t *testing.T) {+ RegisterT(t)++ post := &entity.Post{+ ID: 1,+ Number: 1,+ Title: "The Post",+ Slug: "the-post",+ Description: "Description of the post",+ CreatedAt: time.Date(2023, 1, 1, 10, 0, 0, 0, time.UTC),+ User: &entity.User{ID: 1, Name: "Jon Snow"},+ Status: enum.PostOpen,+ }++ comment1 := &entity.Comment{+ ID: 1,+ Content: "This is comment 1",+ CreatedAt: time.Date(2023, 1, 2, 10, 0, 0, 0, time.UTC),+ User: &entity.User{ID: 2, Name: "Arya Stark"},+ }++ comment2 := &entity.Comment{+ ID: 2,+ Content: "This is comment 2",+ CreatedAt: time.Date(2023, 1, 3, 10, 0, 0, 0, time.UTC),+ User: &entity.User{ID: 3, Name: "Sansa Stark"},+ }++ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {+ if q.Number == post.Number {+ q.Result = post+ return nil+ }+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetCommentsByPost) error {+ q.Result = []*entity.Comment{comment1, comment2}+ return nil+ })++ bus.AddHandler(func(ctx context.Context, q *query.GetAssignedTags) error {+ q.Result = []*entity.Tag{}+ return nil+ })++ server := mock.NewServer()+ code, response := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ AddParam("path", "1.atom").+ Execute(handlers.CommentFeed())++ Expect(code).Equals(http.StatusOK)+ Expect(response.Header().Get("Content-Type")).Equals("application/atom+xml")++ responseBody := response.Body.String()+ compareGeneratorResponse(responseBody, "app/handlers/testdata/comment_feed.atom")+}++func TestCommentFeedHandler_NotFound(t *testing.T) {+ RegisterT(t)++ bus.AddHandler(func(ctx context.Context, q *query.GetPostByNumber) error {+ // Return not found error for any post number+ return app.ErrNotFound+ })+ bus.AddHandler(func(ctx context.Context, q *query.GetCommentsByPost) error {+ q.Result = []*entity.Comment{}+ return nil+ })++ server := mock.NewServer()+ code, _ := server.+ OnTenant(mock.DemoTenant).+ AsUser(mock.JonSnow).+ AddParam("path", "999.atom").+ Execute(handlers.CommentFeed())++ Expect(code).Equals(http.StatusNotFound)+}++func TestFeedDisabled(t *testing.T) {+ RegisterT(t)++ disabledTenant := &entity.Tenant{+ ID: 998,+ Name: "Feeds Disabled",+ Subdomain: "feeds-disabled",+ Status: enum.TenantActive,+ IsFeedEnabled: false,+ }++ server := mock.NewServer()+ code, _ := server.+ OnTenant(disabledTenant).+ AsUser(mock.JonSnow).+ Execute(handlers.GlobalFeed())++ Expect(code).Equals(http.StatusNotFound)++ code, _ = server.+ OnTenant(disabledTenant).+ AsUser(mock.JonSnow).+ AddParam("path", "1.atom").+ Execute(handlers.CommentFeed())++ Expect(code).Equals(http.StatusNotFound)+}++func TestPrivacyEnabled(t *testing.T) {+ RegisterT(t)++ disabledTenant := &entity.Tenant{+ ID: 999,+ Name: "Privacy Enabled",+ Subdomain: "privacy-enabled",+ Status: enum.TenantActive,+ IsPrivate: true,+ IsFeedEnabled: true, // feed should be disabled regardless+ }++ server := mock.NewServer()+ code, _ := server.+ OnTenant(disabledTenant).+ AsUser(mock.JonSnow).+ Execute(handlers.GlobalFeed())++ Expect(code).Equals(http.StatusNotFound)++ code, _ = server.+ OnTenant(disabledTenant).+ AsUser(mock.JonSnow).+ AddParam("path", "1.atom").+ Execute(handlers.CommentFeed())++ Expect(code).Equals(http.StatusNotFound)+}diff --git a/app/handlers/testdata/comment_feed.atom b/app/handlers/testdata/comment_feed.atomnew file mode 100755index 000000000..10cca8617--- /dev/null+++ b/app/handlers/testdata/comment_feed.atom@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="utf-8"?>+<feed xmlns="http://www.w3.org/2005/Atom"><title>The Post</title><subtitle type="html"><p>Description of the post</p></subtitle><id>http:///posts/1/#comments</id><updated>2023-01-03T10:00:00+00:00</updated><link rel="self" href="http:///feed/posts/1.atom" type="application/atom+xml"></link><link rel="alternate" href="http:///posts/1" type="text/html"></link><author><name>Jon Snow</name></author><entry><title>Original Post by Jon Snow</title><id>http:///posts/1</id><published>2023-01-01T10:00:00+00:00</published><updated>2023-01-01T10:00:00+00:00</updated><link rel="alternate" href="http:///posts/1" type="text/html"></link><author><name>Jon Snow</name></author><content type="html"><h1>The Post</h1>

<p>0 votes, 0 comments</p>

<hr />

<p>Description of the post</p></content><category term="Open"></category></entry><entry><title>Comment by Arya Stark</title><id>http:///posts/1/#comment-1</id><published>2023-01-02T10:00:00+00:00</published><updated>2023-01-02T10:00:00+00:00</updated><link rel="alternate" href="http:///posts/1/#comment-1" type="text/html"></link><author><name>Arya Stark</name></author><content type="html"><p>This is comment 1</p></content></entry><entry><title>Comment by Sansa Stark</title><id>http:///posts/1/#comment-2</id><published>2023-01-03T10:00:00+00:00</published><updated>2023-01-03T10:00:00+00:00</updated><link rel="alternate" href="http:///posts/1/#comment-2" type="text/html"></link><author><name>Sansa Stark</name></author><content type="html"><p>This is comment 2</p></content></entry></feed>\ No newline at end of filediff --git a/app/handlers/testdata/global_feed.atom b/app/handlers/testdata/global_feed.atomnew file mode 100755index 000000000..735b2dbad--- /dev/null+++ b/app/handlers/testdata/global_feed.atom@@ -0,0 +1,2 @@+<?xml version="1.0" encoding="utf-8"?>+<feed xmlns="http://www.w3.org/2005/Atom"><title>Demonstration</title><subtitle type="html"></subtitle><id>http://</id><updated>2023-01-03T10:00:00+00:00</updated><link rel="self" href="http:///feed/global.atom" type="application/atom+xml"></link><link rel="alternate" href="http://" type="text/html"></link><entry><title>(5 Votes) First Post</title><id>http:///posts/1</id><published>2023-01-01T10:00:00+00:00</published><updated>2023-01-01T10:00:00+00:00</updated><link rel="self" href="http:///feed/posts/1.atom" type="application/atom+xml"></link><link rel="alternate" href="http:///posts/1" type="text/html"></link><author><name>Jon Snow</name></author><content type="html"><p>Description of first post</p>

<hr />

<p>5 votes, 0 comments - view <a href="http:///posts/1" rel="nofollow noreferrer">in the web</a> or <a href="http:///feed/posts/1.atom" rel="nofollow noreferrer">as a feed</a></p></content><category term="Open"></category></entry><entry><title>(2 Votes) Second Post</title><id>http:///posts/2</id><published>2023-01-03T10:00:00+00:00</published><updated>2023-01-03T10:00:00+00:00</updated><link rel="self" href="http:///feed/posts/2.atom" type="application/atom+xml"></link><link rel="alternate" href="http:///posts/2" type="text/html"></link><author><name>Arya Stark</name></author><content type="html"><p>Description of second post</p>

<hr />

<p>2 votes, 0 comments - view <a href="http:///posts/2" rel="nofollow noreferrer">in the web</a> or <a href="http:///feed/posts/2.atom" rel="nofollow noreferrer">as a feed</a></p></content><category term="Open"></category></entry></feed>\ No newline at end of filediff --git a/app/models/cmd/tenant.go b/app/models/cmd/tenant.goindex f4fc9eedb..a95a5fef3 100644--- a/app/models/cmd/tenant.go+++ b/app/models/cmd/tenant.go@@ -17,7 +17,8 @@ type CreateTenant struct {}type UpdateTenantPrivacySettings struct {- IsPrivate bool+ IsPrivate bool+ IsFeedEnabled bool}type UpdateTenantEmailAuthAllowedSettings struct {@@ -47,7 +48,7 @@ type SaveVerificationKey struct {Request NewEmailVerification}-//NewEmailVerification is used to define an email verification process+// NewEmailVerification is used to define an email verification processtype NewEmailVerification interface {GetEmail() stringGetName() stringdiff --git a/app/models/entity/tenant.go b/app/models/entity/tenant.goindex 09a9e9883..d05263d59 100644--- a/app/models/entity/tenant.go+++ b/app/models/entity/tenant.go@@ -16,6 +16,7 @@ type Tenant struct {LogoBlobKey string `json:"logoBlobKey"`CustomCSS string `json:"-"`IsEmailAuthAllowed bool `json:"isEmailAuthAllowed"`+ IsFeedEnabled bool `json:"isFeedEnabled"`}func (t *Tenant) IsDisabled() bool {diff --git a/app/pkg/dbx/setup.sql b/app/pkg/dbx/setup.sqlindex d10a8ed7c..d249935a1 100644--- a/app/pkg/dbx/setup.sql+++ b/app/pkg/dbx/setup.sql@@ -2,8 +2,8 @@ TRUNCATE TABLE blobs RESTART IDENTITY CASCADE;TRUNCATE TABLE logs RESTART IDENTITY CASCADE;TRUNCATE TABLE tenants RESTART IDENTITY CASCADE;-INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed)-VALUES ('Demonstration', 'demo', now(), '', '', '', 1, false, '', '', 'en', true);+INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed, is_feed_enabled)+VALUES ('Demonstration', 'demo', now(), '', '', '', 1, false, '', '', 'en', true, true);INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)VALUES ('Jon Snow', '[email protected]', 1, now(), 3, 1, 2, '');@@ -18,8 +18,8 @@ VALUES (2, 1, 'google', 'GO5678', now());INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)VALUES ('Sansa Stark', '[email protected]', 1, now(), 1, 1, 2, '');-INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed)-VALUES ('Avengers', 'avengers', now(), 'feedback.avengers.com', '', '', 1, false, '', '', 'en', true);+INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed, is_feed_enabled)+VALUES ('Avengers', 'avengers', now(), 'feedback.avengers.com', '', '', 1, false, '', '', 'en', true, true);INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)VALUES ('Tony Stark', '[email protected]', 2, now(), 3, 1, 2, '');@@ -32,8 +32,8 @@ INSERT INTO user_providers (user_id, tenant_id, provider, provider_uid, created_VALUES (5, 2, 'google', 'GO1111', now());-- Create a tenant that has reached the end of it's trial period-INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed)-VALUES ('Trial Expired', 'trial-expired', now(), 'feedback.trial-expired.com', '', '', 1, false, '', '', 'en', true);+INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed, is_feed_enabled)+VALUES ('Trial Expired', 'trial-expired', now(), 'feedback.trial-expired.com', '', '', 1, false, '', '', 'en', true, true);INSERT INTO tenants_billing (tenant_id, paddle_plan_id, paddle_subscription_id, status, subscription_ends_at, trial_ends_at)VALUES (3, 1, 1,1, now(), CURRENT_DATE - INTERVAL '10 days');INSERT INTO users (name, email, tenant_id, created_at, role, status, avatar_type, avatar_bkey)diff --git a/app/pkg/mock/setup.go b/app/pkg/mock/setup.goindex cd05bcd6c..06adc2d30 100644--- a/app/pkg/mock/setup.go+++ b/app/pkg/mock/setup.go@@ -52,6 +52,7 @@ func seed() {Subdomain: "demo",Status: enum.TenantActive,IsEmailAuthAllowed: true,+ IsFeedEnabled: true,}AvengersTenant = &entity.Tenant{ID: 2,diff --git a/app/pkg/web/testdata/basic.html b/app/pkg/web/testdata/basic.htmlindex c05ccf408..00dab5f09 100755--- a/app/pkg/web/testdata/basic.html+++ b/app/pkg/web/testdata/basic.html@@ -14,6 +14,7 @@+<link rel="preload" href="https://demo.test.fider.io:3000/assets/locale-en.js" as="script" />diff --git a/app/pkg/web/testdata/canonical.html b/app/pkg/web/testdata/canonical.htmlindex 4061b5129..fd2d20b80 100755--- a/app/pkg/web/testdata/canonical.html+++ b/app/pkg/web/testdata/canonical.html@@ -16,6 +16,7 @@+<link rel="preload" href="https://demo.test.fider.io:3000/assets/locale-en.js" as="script" />diff --git a/app/pkg/web/testdata/chunk.html b/app/pkg/web/testdata/chunk.htmlindex 5d496dac0..510685805 100644--- a/app/pkg/web/testdata/chunk.html+++ b/app/pkg/web/testdata/chunk.html@@ -14,6 +14,7 @@+<link rel="preload" href="https://demo.test.fider.io:3000/assets/locale-en.js" as="script" />diff --git a/app/pkg/web/testdata/home.html b/app/pkg/web/testdata/home.htmlindex 9af79e4fb..9a7a61308 100755--- a/app/pkg/web/testdata/home.html+++ b/app/pkg/web/testdata/home.html@@ -14,6 +14,7 @@+<link rel="preload" href="https://demo.test.fider.io:3000/assets/locale-en.js" as="script" />diff --git a/app/pkg/web/testdata/home_ssr.html b/app/pkg/web/testdata/home_ssr.htmlindex 3570269df..64aeb9d3d 100755--- a/app/pkg/web/testdata/home_ssr.html+++ b/app/pkg/web/testdata/home_ssr.html@@ -14,6 +14,7 @@+<link rel="preload" href="https://demo.test.fider.io:3000/assets/locale-en.js" as="script" />@@ -44,7 +45,7 @@<script id="server-data" type="application/json">- {"contextID":"CONTEXT_ID","description":"My Page Description","page":"Test.page","props":{"countPerStatus":{},"posts":[],"tags":[]},"sessionID":"","settings":{"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":{"id":0,"name":"","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"locale":"en","isPrivate":false,"logoBlobKey":"","isEmailAuthAllowed":false},"title":"My Page Title · "}+ {"contextID":"CONTEXT_ID","description":"My Page Description","page":"Test.page","props":{"countPerStatus":{},"posts":[],"tags":[]},"sessionID":"","settings":{"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":{"id":0,"name":"","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"locale":"en","isPrivate":false,"logoBlobKey":"","isEmailAuthAllowed":false,"isFeedEnabled":false},"title":"My Page Title · "}</script>diff --git a/app/pkg/web/testdata/oauth.html b/app/pkg/web/testdata/oauth.htmlindex 81361adc5..321f304e5 100755--- a/app/pkg/web/testdata/oauth.html+++ b/app/pkg/web/testdata/oauth.html@@ -14,6 +14,7 @@+<link rel="preload" href="https://demo.test.fider.io:3000/assets/locale-en.js" as="script" />diff --git a/app/pkg/web/testdata/tenant.html b/app/pkg/web/testdata/tenant.htmlindex 71410bd00..24917cd8b 100755--- a/app/pkg/web/testdata/tenant.html+++ b/app/pkg/web/testdata/tenant.html@@ -14,6 +14,7 @@+<link rel="preload" href="https://demo.test.fider.io:3000/assets/locale-en.js" as="script" />@@ -44,7 +45,7 @@<script id="server-data" type="application/json">- {"contextID":"CONTEXT_ID","page":"","props":{},"sessionID":"","settings":{"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":"","isEmailAuthAllowed":false},"title":"Game of Thrones"}+ {"contextID":"CONTEXT_ID","page":"","props":{},"sessionID":"","settings":{"assetsURL":"https://demo.test.fider.io:3000","baseURL":"https://demo.test.fider.io:3000","domain":".test.fider.io","environment":"test","googleAnalytics":"","hasLegal":true,"isBillingEnabled":false,"locale":"en","localeDirection":"ltr","mode":"multi","oauth":[],"postWithTags":true},"tenant":{"id":0,"name":"Game of Thrones","subdomain":"","invitation":"","welcomeMessage":"","cname":"","status":0,"locale":"","isPrivate":false,"logoBlobKey":"","isEmailAuthAllowed":false,"isFeedEnabled":false},"title":"Game of Thrones"}</script>diff --git a/app/pkg/web/testdata/user.html b/app/pkg/web/testdata/user.htmlindex efe50ceb5..1d248d090 100755--- a/app/pkg/web/testdata/user.html+++ b/app/pkg/web/testdata/user.html@@ -14,6 +14,7 @@+<link rel="preload" href="https://demo.test.fider.io:3000/assets/locale-en.js" as="script" />diff --git a/app/services/sqlstore/postgres/tenant.go b/app/services/sqlstore/postgres/tenant.goindex a1691be51..92cad0717 100644--- a/app/services/sqlstore/postgres/tenant.go+++ b/app/services/sqlstore/postgres/tenant.go@@ -29,6 +29,7 @@ type dbTenant struct {LogoBlobKey string `db:"logo_bkey"`CustomCSS string `db:"custom_css"`IsEmailAuthAllowed bool `db:"is_email_auth_allowed"`+ IsFeedEnabled bool `db:"is_feed_enabled"`}func (t *dbTenant) toModel() *entity.Tenant {@@ -49,6 +50,7 @@ func (t *dbTenant) toModel() *entity.Tenant {LogoBlobKey: t.LogoBlobKey,CustomCSS: t.CustomCSS,IsEmailAuthAllowed: t.IsEmailAuthAllowed,+ IsFeedEnabled: t.IsFeedEnabled,}return tenant@@ -121,7 +123,11 @@ func updateTenantPrivacySettings(ctx context.Context, c *cmd.UpdateTenantPrivacyreturn using(ctx, func(trx *dbx.Trx, tenant *entity.Tenant, user *entity.User) error {_, err := trx.Execute("UPDATE tenants SET is_private = $1 WHERE id = $2", c.IsPrivate, tenant.ID)if err != nil {- return errors.Wrap(err, "failed update tenant privacy settings")+ return errors.Wrap(err, "failed update tenant privacy setting")+ }+ _, err = trx.Execute("UPDATE tenants SET is_feed_enabled = $1 WHERE id = $2", c.IsFeedEnabled, tenant.ID)+ if err != nil {+ return errors.Wrap(err, "failed update tenant feed setting")}return nil})@@ -230,8 +236,8 @@ func createTenant(ctx context.Context, c *cmd.CreateTenant) error {var id interr := trx.Get(&id,- `INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed)- VALUES ($1, $2, $3, '', '', '', $4, false, '', '', $5, true)+ `INSERT INTO tenants (name, subdomain, created_at, cname, invitation, welcome_message, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed, is_feed_enabled)+ VALUES ($1, $2, $3, '', '', '', $4, false, '', '', $5, true, true)RETURNING id`, c.Name, c.Subdomain, now, c.Status, env.Config.Locale)if err != nil {return err@@ -259,7 +265,7 @@ func getFirstTenant(ctx context.Context, q *query.GetFirstTenant) error {tenant := dbTenant{}err := trx.Get(&tenant, `- SELECT id, name, subdomain, cname, invitation, locale, welcome_message, status, is_private, logo_bkey, custom_css, is_email_auth_allowed+ SELECT id, name, subdomain, cname, invitation, locale, welcome_message, status, is_private, logo_bkey, custom_css, is_email_auth_allowed, is_feed_enabledFROM tenantsORDER BY id LIMIT 1`)@@ -278,7 +284,7 @@ func getTenantByDomain(ctx context.Context, q *query.GetTenantByDomain) error {tenant := dbTenant{}err := trx.Get(&tenant, `- SELECT id, name, subdomain, cname, invitation, locale, welcome_message, status, is_private, logo_bkey, custom_css, is_email_auth_allowed+ SELECT id, name, subdomain, cname, invitation, locale, welcome_message, status, is_private, logo_bkey, custom_css, is_email_auth_allowed, is_feed_enabledFROM tenants tWHERE subdomain = $1 OR subdomain = $2 OR cname = $3ORDER BY cname DESCdiff --git a/app/services/sqlstore/postgres/user_test.go b/app/services/sqlstore/postgres/user_test.goindex c825640f3..a4253b83a 100644--- a/app/services/sqlstore/postgres/user_test.go+++ b/app/services/sqlstore/postgres/user_test.go@@ -159,8 +159,8 @@ func TestUserStorage_Register_MultipleProviders(t *testing.T) {var tenantID interr := trx.Get(&tenantID, `- INSERT INTO tenants (name, subdomain, created_at, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed)- VALUES ('My Domain Inc.','mydomain', now(), 1, false, '', '', 'en', true)+ INSERT INTO tenants (name, subdomain, created_at, status, is_private, custom_css, logo_bkey, locale, is_email_auth_allowed, is_feed_enabled)+ VALUES ('My Domain Inc.','mydomain', now(), 1, false, '', '', 'en', true, true)RETURNING id`)Expect(err).IsNil()diff --git a/locale/en/server.json b/locale/en/server.jsonindex 9c4c06347..885983422 100644--- a/locale/en/server.json+++ b/locale/en/server.json@@ -60,5 +60,12 @@"email.signup_email.confirmation": "Through the link below you can verify your email address and complete the activation process.","email.footer.subscription_notice": "You are receiving this email because you are subscribed to this post. You can {view}, {unsubscribe} or {change}.","email.footer.subscription_notice2": "You are receiving this email because you are subscribed to this post. You can {change}.",- "email.footer.subscription_notice3": "You are receiving this email because you are subscribed to this post. You can {view} or {change}."+ "email.footer.subscription_notice3": "You are receiving this email because you are subscribed to this post. You can {view} or {change}.",+ "feed.global.title": "{count, plural, one {({count} Vote) {title}} other {({count} Votes) {title}}}",+ "feed.comment.title": "Comment by {author}",+ "feed.comment.op": "Original Post by {author}",+ "feed.comment.response": "Response by {author}",+ "feed.post.title": "# {title}\n{votes, plural, one {# vote} other {# votes}}, {comments, plural, one {# comment} other {# comments}}\n\n---\n",+ "feed.post.footer.response": "Response by {responder} on {date}:\n\n>{response}\n",+ "feed.post.footer": "\n\n---\n{response_footer}\n{votes, plural, one {# vote} other {# votes}}, {comments, plural, one {# comment} other {# comments}} - view [in the web]({web_link}) or [as a feed]({feed_link})"}diff --git a/migrations/202504252031_add_is_feed_enabled.sql b/migrations/202504252031_add_is_feed_enabled.sqlnew file mode 100644index 000000000..460cc665b--- /dev/null+++ b/migrations/202504252031_add_is_feed_enabled.sql@@ -0,0 +1,9 @@+ALTER TABLE tenants ADD is_feed_enabled BOOLEAN NULL;++UPDATE tenants+SET is_feed_enabled = CASE+ WHEN is_private = true THEN false+ ELSE true+END;++ALTER TABLE tenants ALTER COLUMN is_feed_enabled SET NOT NULL;\ No newline at end of filediff --git a/public/assets/images/heroicons-rss.svg b/public/assets/images/heroicons-rss.svgnew file mode 100644index 000000000..854fd81b0--- /dev/null+++ b/public/assets/images/heroicons-rss.svg@@ -0,0 +1,3 @@+<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-6">+ <path stroke-linecap="round" stroke-linejoin="round" d="M12.75 19.5v-.75a7.5 7.5 0 0 0-7.5-7.5H4.5m0-6.75h.75c7.87 0 14.25 6.38 14.25 14.25v.75M6 18.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0Z" />+</svg>diff --git a/public/components/Header.tsx b/public/components/Header.tsxindex 358dc9281..37d4c0020 100644--- a/public/components/Header.tsx+++ b/public/components/Header.tsx@@ -1,8 +1,9 @@import React, { useState } from "react"-import { SignInModal, TenantLogo, NotificationIndicator, UserMenu, ThemeSwitcher } from "@fider/components"+import { SignInModal, TenantLogo, NotificationIndicator, UserMenu, ThemeSwitcher, Icon } from "@fider/components"import { useFider } from "@fider/hooks"import { HStack } from "./layout"import { Trans } from "@lingui/react/macro"+import IconRss from "@fider/assets/images/heroicons-rss.svg"export const Header = () => {const fider = useFider()@@ -27,6 +28,11 @@ export const Header = () => {</a>{fider.session.isAuthenticated && (<HStack spacing={2}>+ {fider.session.tenant.isFeedEnabled && (+ <a title="ATOM Feed (All Posts)" type="application/atom+xml" className="c-themeswitcher" href="/feed/global.atom">+ <Icon sprite={IconRss} className="h-6" />+ </a>+ )}<ThemeSwitcher /><NotificationIndicator /><UserMenu />@@ -34,6 +40,11 @@ export const Header = () => {)}{!fider.session.isAuthenticated && (<HStack spacing={2}>+ {fider.session.tenant.isFeedEnabled && (+ <a title="ATOM Feed (All Posts)" type="application/atom+xml" className="c-themeswitcher" href="/feed/global.atom">+ <Icon sprite={IconRss} className="h-6" />+ </a>+ )}<ThemeSwitcher /><a href="#" className="uppercase text-sm" onClick={showModal}><Trans id="action.signin">Sign in</Trans>diff --git a/public/components/common/Toggle.tsx b/public/components/common/Toggle.tsxindex f6e388a50..30e3760de 100644--- a/public/components/common/Toggle.tsx+++ b/public/components/common/Toggle.tsx@@ -1,6 +1,6 @@import "./Toggle.scss"-import React, { useState } from "react"+import React, { useState, useEffect } from "react"import { classSet } from "@fider/services"import { HStack } from "../layout"import { DisplayError, ValidationContext } from "@fider/components"@@ -16,6 +16,10 @@ interface ToggleProps {export const Toggle: React.FC<ToggleProps> = (props) => {const [active, setActive] = useState(props.active)+ useEffect(() => {+ setActive(props.active)+ }, [props.active])+const toggle = () => {if (props.disabled) {returndiff --git a/public/models/identity.ts b/public/models/identity.tsindex d63dd2a5d..acb686cd1 100644--- a/public/models/identity.ts+++ b/public/models/identity.ts@@ -10,6 +10,7 @@ export interface Tenant {isPrivate: booleanlogoBlobKey: stringisEmailAuthAllowed: boolean+ isFeedEnabled: boolean}export enum TenantStatus {diff --git a/public/pages/Administration/pages/PrivacySettings.page.tsx b/public/pages/Administration/pages/PrivacySettings.page.tsxindex 753f2c61a..d10715f4f 100644--- a/public/pages/Administration/pages/PrivacySettings.page.tsx+++ b/public/pages/Administration/pages/PrivacySettings.page.tsx@@ -3,31 +3,34 @@ import { Toggle, Form, Field } from "@fider/components"import { actions, notify, Fider } from "@fider/services"import { AdminBasePage } from "@fider/pages/Administration/components/AdminBasePage"-interface PrivacySettingsPageState {+export interface PrivacySettingsPageState {isPrivate: boolean+ isFeedEnabled: boolean}export default class PrivacySettingsPage extends AdminBasePage<any, PrivacySettingsPageState> {public id = "p-admin-privacy"public name = "privacy"public title = "Privacy"- public subtitle = "Manage your site privacy"+ public subtitle = "Manage your site's privacy"constructor(props: any) {super(props)this.state = {isPrivate: Fider.session.tenant.isPrivate,+ isFeedEnabled: Fider.session.tenant.isFeedEnabled,}}- private toggle = async (active: boolean) => {+ private updatePrivacySettings = async (isPrivate: boolean, isFeedEnabled: boolean) => {this.setState(- () => ({- isPrivate: active,- }),+ {+ isPrivate,+ isFeedEnabled: isPrivate ? false : isFeedEnabled, // Disable feed if site is private+ },async () => {- const response = await actions.updateTenantPrivacy(this.state.isPrivate)+ const response = await actions.updateTenantPrivacy(this.state)if (response.ok) {notify.success("Your privacy settings have been saved.")}@@ -35,14 +38,29 @@ export default class PrivacySettingsPage extends AdminBasePage<any, PrivacySetti)}+ private privacyToggle = async (active: boolean) => {+ this.updatePrivacySettings(active, this.state.isFeedEnabled)+ }++ private atomFeedToggle = async (enabled: boolean) => {+ this.updatePrivacySettings(this.state.isPrivate, enabled)+ }+public content() {return (<Form><Field label="Private Site">- <Toggle disabled={!Fider.session.user.isAdministrator} active={this.state.isPrivate} onToggle={this.toggle} />+ <Toggle disabled={!Fider.session.user.isAdministrator} active={this.state.isPrivate} onToggle={this.privacyToggle} /><p className="text-muted mt-1">A private site prevents unauthenticated users from viewing or interacting with its content. <br /> When enabled, only already registered users,- invited users and users from trusted OAuth providers will have access to this site.+ invited users and users from trusted OAuth providers will have access to this site. Disables the feed feature.+ </p>+ </Field>+ <Field label="ATOM Feed">+ <Toggle disabled={!Fider.session.user.isAdministrator || this.state.isPrivate} active={this.state.isFeedEnabled} onToggle={this.atomFeedToggle} />+ <p className="text-muted mt-1">+ This feature lets users access this site via a feed reader. <br /> When enabled, the site makes its posts and comments available using the ATOM+ format. Links to feeds and autodiscovery metadata are shown on the site.</p></Field></Form>diff --git a/public/pages/ShowPost/ShowPost.page.tsx b/public/pages/ShowPost/ShowPost.page.tsxindex 31ea3ff21..4fc7041f6 100644--- a/public/pages/ShowPost/ShowPost.page.tsx+++ b/public/pages/ShowPost/ShowPost.page.tsx@@ -5,6 +5,7 @@ import React, { useState, useEffect, useCallback } from "react"import { Comment, Post, Tag, Vote, ImageUpload, CurrentUser, PostStatus } from "@fider/models"import { actions, clearUrlHash, Failure, Fider, notify, timeAgo } from "@fider/services"import IconDotsHorizontal from "@fider/assets/images/heroicons-dots-horizontal.svg"+import IconRss from "@fider/assets/images/heroicons-rss.svg"import {ResponseDetails,@@ -163,28 +164,35 @@ export default function ShowPostPage(props: ShowPostPageProps) {</VStack>{!editMode && (- <Dropdown position="left" renderHandle={<Icon sprite={IconDotsHorizontal} width="24" height="24" />}>- <Dropdown.ListItem onClick={onActionSelected("copy")}>- <Trans id="action.copylink">Copy link</Trans>- </Dropdown.ListItem>- {Fider.session.isAuthenticated && canEditPost(Fider.session.user, props.post) && (- <>- <Dropdown.ListItem onClick={onActionSelected("edit")}>- <Trans id="action.edit">Edit</Trans>- </Dropdown.ListItem>- {Fider.session.user.isCollaborator && (- <Dropdown.ListItem onClick={onActionSelected("status")}>- <Trans id="action.respond">Respond</Trans>- </Dropdown.ListItem>- )}- </>+ <HStack>+ {Fider.session.tenant.isFeedEnabled && (+ <a title="ATOM Feed (Comments)" type="application/atom+xml" href={`/feed/posts/${props.post.id}.atom`}>+ <Icon sprite={IconRss} width="24" height="24" />+ </a>)}- {canDeletePost() && (- <Dropdown.ListItem onClick={onActionSelected("delete")} className="text-red-700">- <Trans id="action.delete">Delete</Trans>+ <Dropdown position="left" renderHandle={<Icon sprite={IconDotsHorizontal} width="24" height="24" />}>+ <Dropdown.ListItem onClick={onActionSelected("copy")}>+ <Trans id="action.copylink">Copy link</Trans></Dropdown.ListItem>- )}- </Dropdown>+ {Fider.session.isAuthenticated && canEditPost(Fider.session.user, props.post) && (+ <>+ <Dropdown.ListItem onClick={onActionSelected("edit")}>+ <Trans id="action.edit">Edit</Trans>+ </Dropdown.ListItem>+ {Fider.session.user.isCollaborator && (+ <Dropdown.ListItem onClick={onActionSelected("status")}>+ <Trans id="action.respond">Respond</Trans>+ </Dropdown.ListItem>+ )}+ </>+ )}+ {canDeletePost() && (+ <Dropdown.ListItem onClick={onActionSelected("delete")} className="text-red-700">+ <Trans id="action.delete">Delete</Trans>+ </Dropdown.ListItem>+ )}+ </Dropdown>+ </HStack>)}</HStack>diff --git a/public/services/actions/tenant.ts b/public/services/actions/tenant.tsindex 43cb2703d..e0eb24f07 100644--- a/public/services/actions/tenant.ts+++ b/public/services/actions/tenant.ts@@ -1,5 +1,6 @@import { http, Result } from "@fider/services/http"import { UserRole, OAuthConfig, ImageUpload, EmailVerificationKind } from "@fider/models"+import { PrivacySettingsPageState } from "@fider/pages/Administration/pages/PrivacySettings.page"export interface CheckAvailabilityResponse {message: string@@ -39,10 +40,8 @@ export const updateTenantAdvancedSettings = async (customCSS: string): Promise<Rreturn await http.post("/_api/admin/settings/advanced", { customCSS })}-export const updateTenantPrivacy = async (isPrivate: boolean): Promise<Result> => {- return await http.post("/_api/admin/settings/privacy", {- isPrivate,- })+export const updateTenantPrivacy = async (request: PrivacySettingsPageState): Promise<Result> => {+ return await http.post("/_api/admin/settings/privacy", request)}export const updateTenantEmailAuthAllowed = async (isEmailAuthAllowed: boolean): Promise<Result> => {diff --git a/views/index.html b/views/index.htmlindex ac0239cae..12d1b16fd 100644--- a/views/index.html+++ b/views/index.html@@ -1,4 +1,10 @@{{define "head"}}+ {{if (and .public.tenant .public.tenant.IsFeedEnabled)}}+ <link rel=alternate title="{{ $.public.tenant.Name }}: All Posts" type=application/atom+xml href="/feed/global.atom">+ {{if (eq .public.page "ShowPost/ShowPost.page")}}+ <link rel=alternate title="{{ $.public.props.post.Title }}: Comments" type=application/atom+xml href="/feed/posts/{{ $.public.props.post.ID }}.atom">+ {{end}}+ {{end}}{{range $asset := .private.preloadAssets}}{{if $asset}}{{range $asset.CSS}}<link rel="preload" href="{{ $.public.settings.assetsURL }}{{ . }}" as="style" />{{end}}