Page MenuHomeMusing Studio

No OneTemporary

diff --git a/admin.go b/admin.go
index fe19ad5..4269bcc 100644
--- a/admin.go
+++ b/admin.go
@@ -1,453 +1,458 @@
/*
* Copyright © 2018-2019 A Bunch Tell LLC.
*
* This file is part of WriteFreely.
*
* WriteFreely is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, included
* in the LICENSE file in this source code package.
*/
package writefreely
import (
"database/sql"
"fmt"
"github.com/gogits/gogs/pkg/tool"
"github.com/gorilla/mux"
"github.com/writeas/impart"
"github.com/writeas/web-core/auth"
"github.com/writeas/web-core/log"
"github.com/writeas/writefreely/config"
"net/http"
"runtime"
"strconv"
"time"
)
var (
appStartTime = time.Now()
sysStatus systemStatus
)
const adminUsersPerPage = 30
type systemStatus struct {
Uptime string
NumGoroutine int
// General statistics.
MemAllocated string // bytes allocated and still in use
MemTotal string // bytes allocated (even if freed)
MemSys string // bytes obtained from system (sum of XxxSys below)
Lookups uint64 // number of pointer lookups
MemMallocs uint64 // number of mallocs
MemFrees uint64 // number of frees
// Main allocation heap statistics.
HeapAlloc string // bytes allocated and still in use
HeapSys string // bytes obtained from system
HeapIdle string // bytes in idle spans
HeapInuse string // bytes in non-idle span
HeapReleased string // bytes released to the OS
HeapObjects uint64 // total number of allocated objects
// Low-level fixed-size structure allocator statistics.
// Inuse is bytes used now.
// Sys is bytes obtained from system.
StackInuse string // bootstrap stacks
StackSys string
MSpanInuse string // mspan structures
MSpanSys string
MCacheInuse string // mcache structures
MCacheSys string
BuckHashSys string // profiling bucket hash table
GCSys string // GC metadata
OtherSys string // other system allocations
// Garbage collector statistics.
NextGC string // next run in HeapAlloc time (bytes)
LastGC string // last run in absolute time (ns)
PauseTotalNs string
PauseNs string // circular buffer of recent GC pause times, most recent at [(NumGC+255)%256]
NumGC uint32
}
type inspectedCollection struct {
CollectionObj
Followers int
LastPost string
}
type instanceContent struct {
ID string
Type string
Title sql.NullString
Content string
Updated time.Time
}
func (c instanceContent) UpdatedFriendly() string {
/*
// TODO: accept a locale in this method and use that for the format
var loc monday.Locale = monday.LocaleEnUS
return monday.Format(u.Created, monday.DateTimeFormatsByLocale[loc], loc)
*/
return c.Updated.Format("January 2, 2006, 3:04 PM")
}
func handleViewAdminDash(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
updateAppStats()
p := struct {
*UserPage
SysStatus systemStatus
Config config.AppCfg
Message, ConfigMessage string
}{
UserPage: NewUserPage(app, r, u, "Admin", nil),
SysStatus: sysStatus,
Config: app.cfg.App,
Message: r.FormValue("m"),
ConfigMessage: r.FormValue("cm"),
}
showUserPage(w, "admin", p)
return nil
}
func handleViewAdminUsers(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
p := struct {
*UserPage
Config config.AppCfg
Message string
Users *[]User
CurPage int
TotalUsers int64
TotalPages []int
}{
UserPage: NewUserPage(app, r, u, "Users", nil),
Config: app.cfg.App,
Message: r.FormValue("m"),
}
p.TotalUsers = app.db.GetAllUsersCount()
ttlPages := p.TotalUsers / adminUsersPerPage
p.TotalPages = []int{}
for i := 1; i <= int(ttlPages); i++ {
p.TotalPages = append(p.TotalPages, i)
}
var err error
p.CurPage, err = strconv.Atoi(r.FormValue("p"))
if err != nil || p.CurPage < 1 {
p.CurPage = 1
} else if p.CurPage > int(ttlPages) {
p.CurPage = int(ttlPages)
}
p.Users, err = app.db.GetAllUsers(uint(p.CurPage))
if err != nil {
return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get users: %v", err)}
}
showUserPage(w, "users", p)
return nil
}
func handleViewAdminUser(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
username := vars["username"]
if username == "" {
return impart.HTTPError{http.StatusFound, "/admin/users"}
}
p := struct {
*UserPage
Config config.AppCfg
Message string
User *User
Colls []inspectedCollection
LastPost string
TotalPosts int64
}{
Config: app.cfg.App,
Message: r.FormValue("m"),
Colls: []inspectedCollection{},
}
var err error
p.User, err = app.db.GetUserForAuth(username)
if err != nil {
return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get user: %v", err)}
}
p.UserPage = NewUserPage(app, r, u, p.User.Username, nil)
p.TotalPosts = app.db.GetUserPostsCount(p.User.ID)
lp, err := app.db.GetUserLastPostTime(p.User.ID)
if err != nil {
return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get user's last post time: %v", err)}
}
if lp != nil {
p.LastPost = lp.Format("January 2, 2006, 3:04 PM")
}
colls, err := app.db.GetCollections(p.User)
if err != nil {
return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get user's collections: %v", err)}
}
for _, c := range *colls {
ic := inspectedCollection{
CollectionObj: CollectionObj{Collection: c},
}
if app.cfg.App.Federation {
folls, err := app.db.GetAPFollowers(&c)
if err == nil {
// TODO: handle error here (at least log it)
ic.Followers = len(*folls)
}
}
app.db.GetPostsCount(&ic.CollectionObj, true)
lp, err := app.db.GetCollectionLastPostTime(c.ID)
if err != nil {
log.Error("Didn't get last post time for collection %d: %v", c.ID, err)
}
if lp != nil {
ic.LastPost = lp.Format("January 2, 2006, 3:04 PM")
}
p.Colls = append(p.Colls, ic)
}
showUserPage(w, "view-user", p)
return nil
}
func handleViewAdminPages(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
p := struct {
*UserPage
Config config.AppCfg
Message string
Pages []*instanceContent
}{
UserPage: NewUserPage(app, r, u, "Pages", nil),
Config: app.cfg.App,
Message: r.FormValue("m"),
}
var err error
p.Pages, err = app.db.GetInstancePages()
if err != nil {
return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get pages: %v", err)}
}
// Add in default pages
var hasAbout, hasPrivacy bool
for i, c := range p.Pages {
if hasAbout && hasPrivacy {
break
}
if c.ID == "about" {
hasAbout = true
if !c.Title.Valid {
p.Pages[i].Title = defaultAboutTitle(app.cfg)
}
} else if c.ID == "privacy" {
hasPrivacy = true
if !c.Title.Valid {
p.Pages[i].Title = defaultPrivacyTitle()
}
}
}
if !hasAbout {
p.Pages = append(p.Pages, &instanceContent{
ID: "about",
Title: defaultAboutTitle(app.cfg),
Content: defaultAboutPage(app.cfg),
Updated: defaultPageUpdatedTime,
})
}
if !hasPrivacy {
p.Pages = append(p.Pages, &instanceContent{
ID: "privacy",
Title: defaultPrivacyTitle(),
Content: defaultPrivacyPolicy(app.cfg),
Updated: defaultPageUpdatedTime,
})
}
showUserPage(w, "pages", p)
return nil
}
func handleViewAdminPage(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
slug := vars["slug"]
if slug == "" {
return impart.HTTPError{http.StatusFound, "/admin/pages"}
}
p := struct {
*UserPage
Config config.AppCfg
Message string
Banner *instanceContent
Content *instanceContent
}{
Config: app.cfg.App,
Message: r.FormValue("m"),
}
var err error
// Get pre-defined pages, or select slug
if slug == "about" {
p.Content, err = getAboutPage(app)
} else if slug == "privacy" {
p.Content, err = getPrivacyPage(app)
} else if slug == "landing" {
p.Banner, err = getLandingBanner(app)
if err != nil {
return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get banner: %v", err)}
}
p.Content, err = getLandingBody(app)
p.Content.ID = "landing"
+ } else if slug == "reader" {
+ p.Content, err = getReaderSection(app)
} else {
p.Content, err = app.db.GetDynamicContent(slug)
}
if err != nil {
return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not get page: %v", err)}
}
title := "New page"
if p.Content != nil {
title = "Edit " + p.Content.ID
} else {
p.Content = &instanceContent{}
}
p.UserPage = NewUserPage(app, r, u, title, nil)
showUserPage(w, "view-page", p)
return nil
}
func handleAdminUpdateSite(app *App, u *User, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
id := vars["page"]
// Validate
- if id != "about" && id != "privacy" && id != "landing" {
+ if id != "about" && id != "privacy" && id != "landing" && id != "reader" {
return impart.HTTPError{http.StatusNotFound, "No such page."}
}
var err error
m := ""
if id == "landing" {
// Handle special landing page
err = app.db.UpdateDynamicContent("landing-banner", "", r.FormValue("banner"), "section")
if err != nil {
m = "?m=" + err.Error()
return impart.HTTPError{http.StatusFound, "/admin/page/" + id + m}
}
err = app.db.UpdateDynamicContent("landing-body", "", r.FormValue("content"), "section")
+ } else if id == "reader" {
+ // Update sections with titles
+ err = app.db.UpdateDynamicContent(id, r.FormValue("title"), r.FormValue("content"), "section")
} else {
// Update page
err = app.db.UpdateDynamicContent(id, r.FormValue("title"), r.FormValue("content"), "page")
}
if err != nil {
m = "?m=" + err.Error()
}
return impart.HTTPError{http.StatusFound, "/admin/page/" + id + m}
}
func handleAdminUpdateConfig(apper Apper, u *User, w http.ResponseWriter, r *http.Request) error {
apper.App().cfg.App.SiteName = r.FormValue("site_name")
apper.App().cfg.App.SiteDesc = r.FormValue("site_desc")
apper.App().cfg.App.Landing = r.FormValue("landing")
apper.App().cfg.App.OpenRegistration = r.FormValue("open_registration") == "on"
mul, err := strconv.Atoi(r.FormValue("min_username_len"))
if err == nil {
apper.App().cfg.App.MinUsernameLen = mul
}
mb, err := strconv.Atoi(r.FormValue("max_blogs"))
if err == nil {
apper.App().cfg.App.MaxBlogs = mb
}
apper.App().cfg.App.Federation = r.FormValue("federation") == "on"
apper.App().cfg.App.PublicStats = r.FormValue("public_stats") == "on"
apper.App().cfg.App.Private = r.FormValue("private") == "on"
apper.App().cfg.App.LocalTimeline = r.FormValue("local_timeline") == "on"
if apper.App().cfg.App.LocalTimeline && apper.App().timeline == nil {
log.Info("Initializing local timeline...")
initLocalTimeline(apper.App())
}
apper.App().cfg.App.UserInvites = r.FormValue("user_invites")
if apper.App().cfg.App.UserInvites == "none" {
apper.App().cfg.App.UserInvites = ""
}
apper.App().cfg.App.DefaultVisibility = r.FormValue("default_visibility")
m := "?cm=Configuration+saved."
err = apper.SaveConfig(apper.App().cfg)
if err != nil {
m = "?cm=" + err.Error()
}
return impart.HTTPError{http.StatusFound, "/admin" + m + "#config"}
}
func updateAppStats() {
sysStatus.Uptime = tool.TimeSincePro(appStartTime)
m := new(runtime.MemStats)
runtime.ReadMemStats(m)
sysStatus.NumGoroutine = runtime.NumGoroutine()
sysStatus.MemAllocated = tool.FileSize(int64(m.Alloc))
sysStatus.MemTotal = tool.FileSize(int64(m.TotalAlloc))
sysStatus.MemSys = tool.FileSize(int64(m.Sys))
sysStatus.Lookups = m.Lookups
sysStatus.MemMallocs = m.Mallocs
sysStatus.MemFrees = m.Frees
sysStatus.HeapAlloc = tool.FileSize(int64(m.HeapAlloc))
sysStatus.HeapSys = tool.FileSize(int64(m.HeapSys))
sysStatus.HeapIdle = tool.FileSize(int64(m.HeapIdle))
sysStatus.HeapInuse = tool.FileSize(int64(m.HeapInuse))
sysStatus.HeapReleased = tool.FileSize(int64(m.HeapReleased))
sysStatus.HeapObjects = m.HeapObjects
sysStatus.StackInuse = tool.FileSize(int64(m.StackInuse))
sysStatus.StackSys = tool.FileSize(int64(m.StackSys))
sysStatus.MSpanInuse = tool.FileSize(int64(m.MSpanInuse))
sysStatus.MSpanSys = tool.FileSize(int64(m.MSpanSys))
sysStatus.MCacheInuse = tool.FileSize(int64(m.MCacheInuse))
sysStatus.MCacheSys = tool.FileSize(int64(m.MCacheSys))
sysStatus.BuckHashSys = tool.FileSize(int64(m.BuckHashSys))
sysStatus.GCSys = tool.FileSize(int64(m.GCSys))
sysStatus.OtherSys = tool.FileSize(int64(m.OtherSys))
sysStatus.NextGC = tool.FileSize(int64(m.NextGC))
sysStatus.LastGC = fmt.Sprintf("%.1fs", float64(time.Now().UnixNano()-int64(m.LastGC))/1000/1000/1000)
sysStatus.PauseTotalNs = fmt.Sprintf("%.1fs", float64(m.PauseTotalNs)/1000/1000/1000)
sysStatus.PauseNs = fmt.Sprintf("%.3fs", float64(m.PauseNs[(m.NumGC+255)%256])/1000/1000/1000)
sysStatus.NumGC = m.NumGC
}
func adminResetPassword(app *App, u *User, newPass string) error {
hashedPass, err := auth.HashPass([]byte(newPass))
if err != nil {
return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not create password hash: %v", err)}
}
err = app.db.ChangePassphrase(u.ID, true, "", hashedPass)
if err != nil {
return impart.HTTPError{http.StatusInternalServerError, fmt.Sprintf("Could not update passphrase: %v", err)}
}
return nil
}
diff --git a/pages.go b/pages.go
index 405b34f..d8f034b 100644
--- a/pages.go
+++ b/pages.go
@@ -1,137 +1,164 @@
/*
* Copyright © 2018-2019 A Bunch Tell LLC.
*
* This file is part of WriteFreely.
*
* WriteFreely is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, included
* in the LICENSE file in this source code package.
*/
package writefreely
import (
"database/sql"
"github.com/writeas/writefreely/config"
"time"
)
var defaultPageUpdatedTime = time.Date(2018, 11, 8, 12, 0, 0, 0, time.Local)
func getAboutPage(app *App) (*instanceContent, error) {
c, err := app.db.GetDynamicContent("about")
if err != nil {
return nil, err
}
if c == nil {
c = &instanceContent{
ID: "about",
Type: "page",
Content: defaultAboutPage(app.cfg),
}
}
if !c.Title.Valid {
c.Title = defaultAboutTitle(app.cfg)
}
return c, nil
}
func defaultAboutTitle(cfg *config.Config) sql.NullString {
return sql.NullString{String: "About " + cfg.App.SiteName, Valid: true}
}
func getPrivacyPage(app *App) (*instanceContent, error) {
c, err := app.db.GetDynamicContent("privacy")
if err != nil {
return nil, err
}
if c == nil {
c = &instanceContent{
ID: "privacy",
Type: "page",
Content: defaultPrivacyPolicy(app.cfg),
Updated: defaultPageUpdatedTime,
}
}
if !c.Title.Valid {
c.Title = defaultPrivacyTitle()
}
return c, nil
}
func defaultPrivacyTitle() sql.NullString {
return sql.NullString{String: "Privacy Policy", Valid: true}
}
func defaultAboutPage(cfg *config.Config) string {
if cfg.App.Federation {
return `_` + cfg.App.SiteName + `_ is an interconnected place for you to write and publish, powered by [WriteFreely](https://writefreely.org) and ActivityPub.`
}
return `_` + cfg.App.SiteName + `_ is a place for you to write and publish, powered by [WriteFreely](https://writefreely.org).`
}
func defaultPrivacyPolicy(cfg *config.Config) string {
return `[WriteFreely](https://writefreely.org), the software that powers this site, is built to enforce your right to privacy by default.
It retains as little data about you as possible, not even requiring an email address to sign up. However, if you _do_ give us your email address, it is stored encrypted in our database. We salt and hash your account's password.
We store log files, or data about what happens on our servers. We also use cookies to keep you logged in to your account.
Beyond this, it's important that you trust whoever runs **` + cfg.App.SiteName + `**. Software can only do so much to protect you -- your level of privacy protections will ultimately fall on the humans that run this particular service.`
}
func getLandingBanner(app *App) (*instanceContent, error) {
c, err := app.db.GetDynamicContent("landing-banner")
if err != nil {
return nil, err
}
if c == nil {
c = &instanceContent{
ID: "landing-banner",
Type: "section",
Content: defaultLandingBanner(app.cfg),
Updated: defaultPageUpdatedTime,
}
}
return c, nil
}
func getLandingBody(app *App) (*instanceContent, error) {
c, err := app.db.GetDynamicContent("landing-body")
if err != nil {
return nil, err
}
if c == nil {
c = &instanceContent{
ID: "landing-body",
Type: "section",
Content: defaultLandingBody(app.cfg),
Updated: defaultPageUpdatedTime,
}
}
return c, nil
}
func defaultLandingBanner(cfg *config.Config) string {
if cfg.App.Federation {
return "# Start your blog in the fediverse"
}
return "# Start your blog"
}
func defaultLandingBody(cfg *config.Config) string {
if cfg.App.Federation {
return `## Join the Fediverse
The fediverse is a large network of platforms that all speak a common language. Imagine if you could reply to Instagram posts from Twitter, or interact with your favorite Medium blogs from Facebook -- federated alternatives like [PixelFed](https://pixelfed.org), [Mastodon](https://joinmastodon.org), and WriteFreely enable you to do these types of things.
<div style="text-align:center">
<iframe style="width: 560px; height: 315px; max-width: 100%;" sandbox="allow-same-origin allow-scripts" src="https://video.writeas.org/videos/embed/cc55e615-d204-417c-9575-7b57674cc6f3" frameborder="0" allowfullscreen></iframe>
</div>
## Write More Socially
WriteFreely can communicate with other federated platforms like Mastodon, so people can follow your blogs, bookmark their favorite posts, and boost them to their followers. Sign up above to create a blog and join the fediverse.`
}
return ""
}
+
+func getReaderSection(app *App) (*instanceContent, error) {
+ c, err := app.db.GetDynamicContent("reader")
+ if err != nil {
+ return nil, err
+ }
+ if c == nil {
+ c = &instanceContent{
+ ID: "reader",
+ Type: "section",
+ Content: defaultReaderBanner(app.cfg),
+ Updated: defaultPageUpdatedTime,
+ }
+ }
+ if !c.Title.Valid {
+ c.Title = defaultReaderTitle(app.cfg)
+ }
+ return c, nil
+}
+
+func defaultReaderTitle(cfg *config.Config) sql.NullString {
+ return sql.NullString{String: "Reader", Valid: true}
+}
+
+func defaultReaderBanner(cfg *config.Config) string {
+ return "Read the latest posts from " + cfg.App.SiteName + "."
+}
diff --git a/read.go b/read.go
index 3efb89d..ec0305a 100644
--- a/read.go
+++ b/read.go
@@ -1,314 +1,324 @@
/*
* Copyright © 2018-2019 A Bunch Tell LLC.
*
* This file is part of WriteFreely.
*
* WriteFreely is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, included
* in the LICENSE file in this source code package.
*/
package writefreely
import (
"database/sql"
"fmt"
. "github.com/gorilla/feeds"
"github.com/gorilla/mux"
stripmd "github.com/writeas/go-strip-markdown"
"github.com/writeas/impart"
"github.com/writeas/web-core/log"
"github.com/writeas/web-core/memo"
"github.com/writeas/writefreely/page"
"html/template"
"math"
"net/http"
"strconv"
"time"
)
const (
tlFeedLimit = 100
tlAPIPageLimit = 10
tlMaxAuthorPosts = 5
tlPostsPerPage = 16
)
type localTimeline struct {
m *memo.Memo
posts *[]PublicPost
// Configuration values
postsPerPage int
}
type readPublication struct {
page.StaticPage
Posts *[]PublicPost
CurrentPage int
TotalPages int
SelTopic string
IsAdmin bool
CanInvite bool
+
+ // Customizable page content
+ ContentTitle string
+ Content template.HTML
}
func initLocalTimeline(app *App) {
app.timeline = &localTimeline{
postsPerPage: tlPostsPerPage,
m: memo.New(app.FetchPublicPosts, 10*time.Minute),
}
}
// satisfies memo.Func
func (app *App) FetchPublicPosts() (interface{}, error) {
// Finds all public posts and posts in a public collection published during the owner's active subscription period and within the last 3 months
rows, err := app.db.Query(`SELECT p.id, alias, c.title, p.slug, p.title, p.content, p.text_appearance, p.language, p.rtl, p.created, p.updated
FROM collections c
LEFT JOIN posts p ON p.collection_id = c.id
WHERE c.privacy = 1 AND (p.created >= ` + app.db.dateSub(3, "month") + ` AND p.created <= ` + app.db.now() + ` AND pinned_position IS NULL)
ORDER BY p.created DESC`)
if err != nil {
log.Error("Failed selecting from posts: %v", err)
return nil, impart.HTTPError{http.StatusInternalServerError, "Couldn't retrieve collection posts." + err.Error()}
}
defer rows.Close()
ap := map[string]uint{}
posts := []PublicPost{}
for rows.Next() {
p := &Post{}
c := &Collection{}
var alias, title sql.NullString
err = rows.Scan(&p.ID, &alias, &title, &p.Slug, &p.Title, &p.Content, &p.Font, &p.Language, &p.RTL, &p.Created, &p.Updated)
if err != nil {
log.Error("[READ] Unable to scan row, skipping: %v", err)
continue
}
c.hostName = app.cfg.App.Host
isCollectionPost := alias.Valid
if isCollectionPost {
c.Alias = alias.String
if c.Alias != "" && ap[c.Alias] == tlMaxAuthorPosts {
// Don't add post if we've hit the post-per-author limit
continue
}
c.Public = true
c.Title = title.String
}
p.extractData()
p.HTMLContent = template.HTML(applyMarkdown([]byte(p.Content), "", app.cfg))
fp := p.processPost()
if isCollectionPost {
fp.Collection = &CollectionObj{Collection: *c}
}
posts = append(posts, fp)
ap[c.Alias]++
}
return posts, nil
}
func viewLocalTimelineAPI(app *App, w http.ResponseWriter, r *http.Request) error {
updateTimelineCache(app.timeline)
skip, _ := strconv.Atoi(r.FormValue("skip"))
posts := []PublicPost{}
for i := skip; i < skip+tlAPIPageLimit && i < len(*app.timeline.posts); i++ {
posts = append(posts, (*app.timeline.posts)[i])
}
return impart.WriteSuccess(w, posts, http.StatusOK)
}
func viewLocalTimeline(app *App, w http.ResponseWriter, r *http.Request) error {
if !app.cfg.App.LocalTimeline {
return impart.HTTPError{http.StatusNotFound, "Page doesn't exist."}
}
vars := mux.Vars(r)
var p int
page := 1
p, _ = strconv.Atoi(vars["page"])
if p > 0 {
page = p
}
return showLocalTimeline(app, w, r, page, vars["author"], vars["tag"])
}
func updateTimelineCache(tl *localTimeline) {
// Fetch posts if enough time has passed since last cache
if tl.posts == nil || tl.m.Invalidate() {
log.Info("[READ] Updating post cache")
var err error
var postsInterfaces interface{}
postsInterfaces, err = tl.m.Get()
if err != nil {
log.Error("[READ] Unable to cache posts: %v", err)
} else {
castPosts := postsInterfaces.([]PublicPost)
tl.posts = &castPosts
}
}
}
func showLocalTimeline(app *App, w http.ResponseWriter, r *http.Request, page int, author, tag string) error {
updateTimelineCache(app.timeline)
pl := len(*(app.timeline.posts))
ttlPages := int(math.Ceil(float64(pl) / float64(app.timeline.postsPerPage)))
start := 0
if page > 1 {
start = app.timeline.postsPerPage * (page - 1)
if start > pl {
return impart.HTTPError{http.StatusFound, fmt.Sprintf("/read/p/%d", ttlPages)}
}
}
end := app.timeline.postsPerPage * page
if end > pl {
end = pl
}
var posts []PublicPost
if author != "" {
posts = []PublicPost{}
for _, p := range *app.timeline.posts {
if author == "anonymous" {
if p.Collection == nil {
posts = append(posts, p)
}
} else if p.Collection != nil && p.Collection.Alias == author {
posts = append(posts, p)
}
}
} else if tag != "" {
posts = []PublicPost{}
for _, p := range *app.timeline.posts {
if p.HasTag(tag) {
posts = append(posts, p)
}
}
} else {
posts = *app.timeline.posts
posts = posts[start:end]
}
d := &readPublication{
StaticPage: pageForReq(app, r),
Posts: &posts,
CurrentPage: page,
TotalPages: ttlPages,
SelTopic: tag,
}
if app.cfg.App.Chorus {
u := getUserSession(app, r)
d.IsAdmin = u != nil && u.IsAdmin()
d.CanInvite = canUserInvite(app.cfg, d.IsAdmin)
}
+ c, err := getReaderSection(app)
+ if err != nil {
+ return err
+ }
+ d.ContentTitle = c.Title.String
+ d.Content = template.HTML(applyMarkdown([]byte(c.Content), "", app.cfg))
- err := templates["read"].ExecuteTemplate(w, "base", d)
+ err = templates["read"].ExecuteTemplate(w, "base", d)
if err != nil {
log.Error("Unable to render reader: %v", err)
fmt.Fprintf(w, ":(")
}
return nil
}
// NextPageURL provides a full URL for the next page of collection posts
func (c *readPublication) NextPageURL(n int) string {
return fmt.Sprintf("/read/p/%d", n+1)
}
// PrevPageURL provides a full URL for the previous page of collection posts,
// returning a /page/N result for pages >1
func (c *readPublication) PrevPageURL(n int) string {
if n == 2 {
// Previous page is 1; no need for /p/ prefix
return "/read"
}
return fmt.Sprintf("/read/p/%d", n-1)
}
// handlePostIDRedirect handles a route where a post ID is given and redirects
// the user to the canonical post URL.
func handlePostIDRedirect(app *App, w http.ResponseWriter, r *http.Request) error {
vars := mux.Vars(r)
postID := vars["post"]
p, err := app.db.GetPost(postID, 0)
if err != nil {
return err
}
if !p.CollectionID.Valid {
// No collection; send to normal URL
// NOTE: not handling single user blogs here since this handler is only used for the Reader
return impart.HTTPError{http.StatusFound, app.cfg.App.Host + "/" + postID + ".md"}
}
c, err := app.db.GetCollectionBy("id = ?", fmt.Sprintf("%d", p.CollectionID.Int64))
if err != nil {
return err
}
c.hostName = app.cfg.App.Host
// Retrieve collection information and send user to canonical URL
return impart.HTTPError{http.StatusFound, c.CanonicalURL() + p.Slug.String}
}
func viewLocalTimelineFeed(app *App, w http.ResponseWriter, req *http.Request) error {
if !app.cfg.App.LocalTimeline {
return impart.HTTPError{http.StatusNotFound, "Page doesn't exist."}
}
updateTimelineCache(app.timeline)
feed := &Feed{
Title: app.cfg.App.SiteName + " Reader",
Link: &Link{Href: app.cfg.App.Host},
Description: "Read the latest posts from " + app.cfg.App.SiteName + ".",
Created: time.Now(),
}
c := 0
var title, permalink, author string
for _, p := range *app.timeline.posts {
if c == tlFeedLimit {
break
}
title = p.PlainDisplayTitle()
permalink = p.CanonicalURL()
if p.Collection != nil {
author = p.Collection.Title
} else {
author = "Anonymous"
permalink += ".md"
}
i := &Item{
Id: app.cfg.App.Host + "/read/a/" + p.ID,
Title: title,
Link: &Link{Href: permalink},
Description: "<![CDATA[" + stripmd.Strip(p.Content) + "]]>",
Content: applyMarkdown([]byte(p.Content), "", app.cfg),
Author: &Author{author, ""},
Created: p.Created,
Updated: p.Updated,
}
feed.Items = append(feed.Items, i)
c++
}
rss, err := feed.ToRss()
if err != nil {
return err
}
fmt.Fprint(w, rss)
return nil
}
diff --git a/templates/read.tmpl b/templates/read.tmpl
index 28d2fd1..9541ab5 100644
--- a/templates/read.tmpl
+++ b/templates/read.tmpl
@@ -1,132 +1,132 @@
{{define "head"}}<title>{{.SiteName}} Reader</title>
<link rel="alternate" type="application/rss+xml" title="{{.SiteName}} Reader" href="/read/feed/" />
{{if gt .CurrentPage 1}}<link rel="prev" href="{{.PrevPageURL .CurrentPage}}">{{end}}
{{if lt .CurrentPage .TotalPages}}<link rel="next" href="{{.NextPageURL .CurrentPage}}">{{end}}
<meta name="description" content="Read the latest posts from {{.SiteName}}.">
<meta itemprop="name" content="{{.SiteName}} Reader">
<meta itemprop="description" content="Read the latest posts from {{.SiteName}}.">
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="{{.SiteName}} Reader">
<meta name="twitter:description" content="Read the latest posts from {{.SiteName}}.">
<meta property="og:title" content="{{.SiteName}} Reader" />
<meta property="og:type" content="object" />
<meta property="og:description" content="Read the latest posts from {{.SiteName}}." />
<style>
.heading h1 {
font-weight: 300;
text-align: center;
margin: 3em 0 0;
}
.heading p {
text-align: center;
margin: 1.5em 0 4.5em;
font-size: 1.1em;
color: #777;
}
#wrapper {
font-size: 1.2em;
}
.preview {
max-height: 180px;
overflow: hidden;
position: relative;
}
.preview .over {
position: absolute;
top: 5em;
bottom: 0;
left: 0;
right: 0;
/* Permalink - use to edit and share this gradient: http://colorzilla.com/gradient-editor/#ffffff+0,ffffff+100&0+0,1+100 */
background: -moz-linear-gradient(top, rgba(255,255,255,0) 0%, rgba(255,255,255,1) 100%); /* FF3.6-15 */
background: -webkit-linear-gradient(top, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%); /* Chrome10-25,Safari5.1-6 */
background: linear-gradient(to bottom, rgba(255,255,255,0) 0%,rgba(255,255,255,1) 100%); /* W3C, IE10+, FF16+, Chrome26+, Opera12+, Safari7+ */
filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#00ffffff', endColorstr='#ffffff',GradientType=0 ); /* IE6-9 */
}
p.source {
font-size: 0.86em;
margin-top: 0.25em;
margin-bottom: 0;
}
.attention-box {
text-align: center;
font-size: 1.1em;
}
.attention-box hr { margin: 4rem auto; }
hr { max-width: 40rem; }
header {
padding: 0 !important;
text-align: left !important;
margin: 1em !important;
max-width: 100% !important;
}
body#collection header nav {
display: inline !important;
}
body#collection header nav:not(#full-nav):not(#user-nav) {
margin: 0 0 0 1em !important;
}
header nav#user-nav {
margin-left: 0 !important;
}
body#collection header nav.tabs a:first-child {
margin-left: 1em;
}
</style>
{{end}}
{{define "body-attrs"}}id="collection"{{end}}
{{define "content"}}
<div class="content-container snug" style="max-width: 40rem;">
- <h1 style="text-align:center">Reader</h1>
- <p{{if .SelTopic}} style="text-align:center"{{end}}>{{if .SelTopic}}#{{.SelTopic}} posts{{else}}Read the latest posts from {{.SiteName}}. {{if .Username}}To showcase your writing here, go to your <a href="/me/c/">blog</a> settings and select the <em>Public</em> option.{{end}}{{end}}</p>
+ <h1>{{.ContentTitle}}</h1>
+ <p{{if .SelTopic}} style="text-align:center"{{end}}>{{if .SelTopic}}#{{.SelTopic}} posts{{else}}{{.Content}}{{end}}</p>
</div>
<div id="wrapper">
{{ if gt (len .Posts) 0 }}
<section itemscope itemtype="http://schema.org/Blog">
{{range .Posts}}<article class="{{.Font}} h-entry" itemscope itemtype="http://schema.org/BlogPosting">
{{if .Title.String}}<h2 class="post-title" itemprop="name" class="p-name"><a href="{{if .Slug.String}}{{.Collection.CanonicalURL}}{{.Slug.String}}{{else}}{{.CanonicalURL}}.md{{end}}" itemprop="url" class="u-url">{{.PlainDisplayTitle}}</a></h2>
<time class="dt-published" datetime="{{.Created}}" pubdate itemprop="datePublished" content="{{.Created}}">{{if not .Title.String}}<a href="{{.Collection.CanonicalURL}}{{.Slug.String}}" itemprop="url">{{end}}{{.DisplayDate}}{{if not .Title.String}}</a>{{end}}</time>
{{else}}
<h2 class="post-title" itemprop="name"><time class="dt-published" datetime="{{.Created}}" pubdate itemprop="datePublished" content="{{.Created}}"><a href="{{if .Collection}}{{.Collection.CanonicalURL}}{{.Slug.String}}{{else}}{{.CanonicalURL}}.md{{end}}" itemprop="url" class="u-url">{{.DisplayDate}}</a></time></h2>
{{end}}
<p class="source">{{if .Collection}}from <a href="{{.Collection.CanonicalURL}}">{{.Collection.DisplayTitle}}</a>{{else}}<em>Anonymous</em>{{end}}</p>
{{if .Excerpt}}<div class="p-summary" {{if .Language}}lang="{{.Language.String}}"{{end}} dir="{{.Direction}}">{{.Excerpt}}</div>
<a class="read-more" href="{{if .Collection}}{{.Collection.CanonicalURL}}{{.Slug.String}}{{else}}{{.CanonicalURL}}.md{{end}}">{{localstr "Read more..." .Language.String}}</a>{{else}}<div class="e-content preview" {{if .Language}}lang="{{.Language.String}}"{{end}} dir="{{.Direction}}">{{ if not .HTMLContent }}<p id="post-body" class="e-content preview">{{.Content}}</p>{{ else }}{{.HTMLContent}}{{ end }}<div class="over">&nbsp;</div></div>
<a class="read-more maybe" href="{{if .Collection}}{{.Collection.CanonicalURL}}{{.Slug.String}}{{else}}{{.CanonicalURL}}.md{{end}}">{{localstr "Read more..." .Language.String}}</a>{{end}}</article>
{{end}}
</section>
{{ else }}
<div class="attention-box">
<p>No posts here yet!</p>
</div>
{{ end }}
{{if gt .TotalPages 1}}<nav id="paging" class="content-container clearfix">
{{if lt .CurrentPage .TotalPages}}<a href="{{.NextPageURL .CurrentPage}}">&#8672; Older</a>{{end}}
{{if gt .CurrentPage 1}}<a style="float:right;" href="{{.PrevPageURL .CurrentPage}}">Newer &#8674;</a>{{end}}
</nav>{{end}}
</div>
<script type="text/javascript">
(function() {
var $articles = document.querySelectorAll('article');
for (var i=0; i<$articles.length; i++) {
var $art = $articles[i];
var $more = $art.querySelector('.read-more.maybe');
if ($more != null) {
if ($art.querySelector('.e-content.preview').clientHeight < 180) {
$more.parentNode.removeChild($more);
var $overlay = $art.querySelector('.over');
$overlay.parentNode.removeChild($overlay);
}
}
}
})();
</script>
{{end}}
diff --git a/templates/user/admin/pages.tmpl b/templates/user/admin/pages.tmpl
index 25f7984..7a9e66a 100644
--- a/templates/user/admin/pages.tmpl
+++ b/templates/user/admin/pages.tmpl
@@ -1,34 +1,37 @@
{{define "pages"}}
{{template "header" .}}
<style>
table.classy.export .disabled, table.classy.export a {
text-transform: initial;
}
</style>
<div class="snug content-container">
{{template "admin-header" .}}
<h2 id="posts-header" style="display: flex; justify-content: space-between;">Pages</h2>
<table class="classy export" style="width:100%">
<tr>
<th>Page</th>
<th>Last Modified</th>
</tr>
<tr>
<td colspan="2"><a href="/admin/page/landing">Home</a></td>
</tr>
+ {{if .LocalTimeline}}<tr>
+ <td colspan="2"><a href="/admin/page/reader">Reader</a></td>
+ </tr>{{end}}
{{range .Pages}}
<tr>
<td><a href="/admin/page/{{.ID}}">{{if .Title.Valid}}{{.Title.String}}{{else}}{{.ID}}{{end}}</a></td>
<td style="text-align:right">{{.UpdatedFriendly}}</td>
</tr>
{{end}}
</table>
</div>
{{template "footer" .}}
{{end}}
diff --git a/templates/user/admin/view-page.tmpl b/templates/user/admin/view-page.tmpl
index 6d98b9d..161e40b 100644
--- a/templates/user/admin/view-page.tmpl
+++ b/templates/user/admin/view-page.tmpl
@@ -1,75 +1,77 @@
{{define "view-page"}}
{{template "header" .}}
<style>
label {
display: block;
margin-top: 1em;
padding: 0 0 1em;
color: #666;
}
.content-desc {
font-size: 0.95em;
}
.page-desc {
margin: 0 0 0.5em;
}
textarea + .content-desc {
margin: 0.5em 0 1em;
font-style: italic;
}
input[type=text] {
/* Match textarea color. TODO: y is it like this thooo */
border-color: #ccc;
}
</style>
<div class="snug content-container">
{{template "admin-header" .}}
<h2 id="posts-header">{{if eq .Content.ID "landing"}}Home page{{else}}{{.Content.ID}} page{{end}}</h2>
{{if eq .Content.ID "about"}}
<p class="page-desc content-desc">Describe what your instance is <a href="/about" target="page">about</a>.</p>
{{else if eq .Content.ID "privacy"}}
<p class="page-desc content-desc">Outline your <a href="/privacy" target="page">privacy policy</a>.</p>
+ {{else if eq .Content.ID "reader"}}
+ <p class="page-desc content-desc">Customize your <a href="/read" target="page">Reader</a> page.</p>
{{else if eq .Content.ID "landing"}}
<p class="page-desc content-desc">Customize your <a href="/?landing=1" target="page">home page</a>.</p>
{{end}}
{{if .Message}}<p>{{.Message}}</p>{{end}}
<form method="post" action="/admin/update/{{.Content.ID}}" onsubmit="savePage(this)">
- {{if eq .Content.Type "section"}}
+ {{if .Banner}}
<label for="banner">
Banner
</label>
<textarea id="banner" class="section codable norm edit-page" style="min-height: 5em; height: 5em;" name="banner">{{.Banner.Content}}</textarea>
<p class="content-desc">We suggest a header (e.g. <code># Welcome</code>), optionally followed by a small bit of text. Accepts Markdown and HTML.</p>
{{else}}
<label for="title">
Title
</label>
<input type="text" name="title" id="title" value="{{.Content.Title.String}}" />
{{end}}
<label for="content">
{{if .Banner}}Body{{else}}Content{{end}}
</label>
<textarea id="content" class="section codable norm edit-page" name="content">{{.Content.Content}}</textarea>
<p class="content-desc">Accepts Markdown and HTML.</p>
<input type="submit" value="Save" />
</form>
</div>
<script>
function savePage(el) {
var $btn = el.querySelector('input[type=submit]');
$btn.value = 'Saving...';
$btn.disabled = true;
}
</script>
{{template "footer" .}}
{{end}}

File Metadata

Mime Type
text/x-diff
Expires
Mon, Nov 25, 5:38 AM (1 d, 15 h)
Storage Engine
blob
Storage Format
Raw Data
Storage Handle
3105719

Event Timeline