postfreely

package module
v0.0.0-...-5a5ee98 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2023 License: AGPL-3.0 Imports: 96 Imported by: 0

README

PostFreely

PostFreely is a clean, minimalist publishing platform made for writers. Start a blog, share knowledge within your organization, or build a community around the shared act of writing.

History

PostFreely is a fork of WriteFreely. Thank you Matt Baer for creating WriteFreely and making it open-source software.

Features

Made for writing

Built on a plain, auto-saving editor, PostFreely gives you a distraction-free writing environment. Once published, your words are front and center, and easy to read.

A connected community

Start writing together, publicly or privately. Connect with other communities, whether running PostFreely, Mastodon, Firefish, Friendica, Misskey, Pixelfed, Plume, or any other ActivityPub-powered software. And bring members on board from your existing platforms, thanks to our OAuth 2.0 support.

Intuitive organization

Categorize articles with hashtags, and create static pages from normal posts by pinning them to your blog. Create draft posts and publish to multiple blogs from one account.

International

Blog elements are localized in 20+ languages, and PostFreely includes first-class support for non-Latin and right-to-left (RTL) script languages.

Private by default

PostFreely collects minimal data, and never publicizes more than a writer consents to. Writers can seamlessly create multiple blogs from a single account for different pen names or purposes without publicly revealing their association.

Building

In the main project directory, run:

% go build ./cmd/postfreely

A postfreely binary will be generated in the current directory.

The Makefile is no longer needed and will eventually be removed.

To run tests:

% go test ./...

Contributing

We gladly welcome contributions to PostFreely, whether in the form of code, bug reports, feature requests, translations, or documentation improvements.

Before contributing anything, please read our Contributing Guide. It describes the correct channels for submitting contributions and any potential requirements.

License

Copyright © 2018-2023 PostFreely contributing authors. Licensed under the AGPL.

Documentation

Overview

Package postfreely copied from https://github.com/golang/tools/blob/master/internal/semver/semver.go slight modifications made

Index

Constants

View Source
const (
	CollPublic collVisibility = 1 << iota
	CollPrivate
	CollProtected
)
View Source
const (
	UserActive = iota
	UserSilenced
)
View Source
const CollUnlisted collVisibility = 0

Visibility levels. Values are bitmasks, stored in the database as decimal numbers. If adding types, append them to this list. If removing, replace the desired visibility with a new value.

Variables

View Source
var (
	ErrBadFormData    = impart.HTTPError{http.StatusBadRequest, "Expected valid form data."}
	ErrBadJSON        = impart.HTTPError{http.StatusBadRequest, "Expected valid JSON object."}
	ErrBadJSONArray   = impart.HTTPError{http.StatusBadRequest, "Expected valid JSON array."}
	ErrBadAccessToken = impart.HTTPError{http.StatusUnauthorized, "Invalid access token."}
	ErrNoAccessToken  = impart.HTTPError{http.StatusBadRequest, "Authorization token required."}
	ErrNotLoggedIn    = impart.HTTPError{http.StatusUnauthorized, "Not logged in."}

	ErrForbiddenCollection        = impart.HTTPError{http.StatusForbidden, "You don't have permission to add to this collection."}
	ErrForbiddenEditPost          = impart.HTTPError{http.StatusForbidden, "You don't have permission to update this post."}
	ErrUnauthorizedEditPost       = impart.HTTPError{http.StatusUnauthorized, "Invalid editing credentials."}
	ErrUnauthorizedGeneral        = impart.HTTPError{http.StatusUnauthorized, "You don't have permission to do that."}
	ErrBadRequestedType           = impart.HTTPError{http.StatusNotAcceptable, "Bad requested Content-Type."}
	ErrCollectionUnauthorizedRead = impart.HTTPError{http.StatusUnauthorized, "You don't have permission to access this collection."}

	ErrNoPublishableContent = impart.HTTPError{http.StatusBadRequest, "Supply something to publish."}

	ErrInternalGeneral       = impart.HTTPError{http.StatusInternalServerError, "The humans messed something up. They've been notified."}
	ErrInternalCookieSession = impart.HTTPError{http.StatusInternalServerError, "Could not get cookie session."}

	ErrUnavailable = impart.HTTPError{http.StatusServiceUnavailable, "Service temporarily unavailable due to high load."}

	ErrCollectionNotFound     = impart.HTTPError{http.StatusNotFound, "Collection doesn't exist."}
	ErrCollectionGone         = impart.HTTPError{http.StatusGone, "This blog was unpublished."}
	ErrCollectionPageNotFound = impart.HTTPError{http.StatusNotFound, "Collection page doesn't exist."}
	ErrPostNotFound           = impart.HTTPError{Status: http.StatusNotFound, Message: "Post not found."}
	ErrPostBanned             = impart.HTTPError{Status: http.StatusGone, Message: "Post removed."}
	ErrPostUnpublished        = impart.HTTPError{Status: http.StatusGone, Message: "Post unpublished by author."}
	ErrPostFetchError         = impart.HTTPError{Status: http.StatusInternalServerError, Message: "We encountered an error getting the post. The humans have been alerted."}

	ErrUserNotFound       = impart.HTTPError{http.StatusNotFound, "User doesn't exist."}
	ErrRemoteUserNotFound = impart.HTTPError{http.StatusNotFound, "Remote user not found."}
	ErrUserNotFoundEmail  = impart.HTTPError{http.StatusNotFound, "Please enter your username instead of your email address."}

	ErrUserSilenced = impart.HTTPError{http.StatusForbidden, "Account is silenced."}

	ErrDisabledPasswordAuth = impart.HTTPError{http.StatusForbidden, "Password authentication is disabled."}
)

Commonly returned HTTP errors

View Source
var (
	ErrPostNoUpdatableVals = impart.HTTPError{http.StatusBadRequest, "Supply some properties to update."}
)

Post operation errors

View Source
var (
	SQLiteEnabled bool
)

Functions

func AuthenticateUser

func AuthenticateUser(db writestore, accessToken string) (int64, error)

AuthenticateUser ensures a user with the given accessToken is valid. Call it before any operations that require authentication or optionally associate data with a user account. Returns an error if the given accessToken is invalid. Otherwise the associated user ID is returned.

func CachePosts

func CachePosts(userID int64, p *[]PublicPost)

func CompareSemver

func CompareSemver(v, w string) int

CompareSemver returns an integer comparing two versions according to according to semantic version precedence. The result will be 0 if v == w, -1 if v < w, or +1 if v > w.

An invalid semantic version string is considered less than a valid one. All invalid semantic version strings compare equal to each other.

func ConnectToDatabase

func ConnectToDatabase(app *App) error

ConnectToDatabase validates and connects to the configured database, then tests the connection.

func CreateConfig

func CreateConfig(app *App) error

CreateConfig creates a default configuration and saves it to the app's cfgFile.

func CreateSchema

func CreateSchema(apper Apper) error

CreateSchema creates all database tables needed for the application.

func CreateUser

func CreateUser(apper Apper, username, password string, isAdmin bool) error

CreateUser creates a new admin or normal user from the given credentials.

func DoConfig

func DoConfig(app *App, configSections string)

DoConfig runs the interactive configuration process.

func DoDeleteAccount

func DoDeleteAccount(apper Apper, username string) error

DoDeleteAccount runs the confirmation and account delete process.

func FormatVersion

func FormatVersion() string

FormatVersion constructs the version string for the application

func GenerateKeyFiles

func GenerateKeyFiles(app *App) error

GenerateKeyFiles creates app encryption keys and saves them into the configured KeysParentDir.

func GetPostsCache

func GetPostsCache(userID int64) *[]PublicPost

func GetProfileURLFromHandle

func GetProfileURLFromHandle(app *App, handle string) (string, error)

func InitKeys

func InitKeys(apper Apper) error

InitKeys loads encryption keys into memory via the given Apper interface

func InitRoutes

func InitRoutes(apper Apper, r *mux.Router) *mux.Router

InitRoutes adds dynamic routes for the given mux.Router.

func InitTemplates

func InitTemplates(cfg *config.Config) error

InitTemplates loads all template files from the configured parent dir.

func IsActivityPubRequest

func IsActivityPubRequest(r *http.Request) bool

func IsJSON

func IsJSON(r *http.Request) bool

func IsValid

func IsValid(v string) bool

IsValid reports whether v is a valid semantic version string.

func Migrate

func Migrate(apper Apper) error

Migrate runs all necessary database migrations.

func OutputVersion

func OutputVersion()

OutputVersion prints out the version of the application.

func PostsContains

func PostsContains(sl *[]PublicPost, s *PublicPost) bool

TODO: move this to utils after making it more generic

func RemoteLookup

func RemoteLookup(handle string) string

RemoteLookup looks up a user by handle at a remote server and returns the actor URL

func ResetPassword

func ResetPassword(apper Apper, username string) error

ResetPassword runs the interactive password reset process.

func RouteCollections

func RouteCollections(handler *Handler, r *mux.Router)

func RouteRead

func RouteRead(handler *Handler, readPerm UserLevelFunc, r *mux.Router)

func Serve

func Serve(app *App, r *mux.Router)

func ServerUserAgent

func ServerUserAgent(hostName string) string

ServerUserAgent returns a User-Agent string to use in external requests. The hostName parameter may be left empty.

func UnpackTemplates

func UnpackTemplates() error

func ViewFeed

func ViewFeed(app *App, w http.ResponseWriter, req *http.Request) error

Types

type AdminPage

type AdminPage struct {
	UpdateAvailable bool
}

func NewAdminPage

func NewAdminPage(app *App) *AdminPage

type AnonymousAuthPost

type AnonymousAuthPost struct {
	ID    string `json:"id"`
	Token string `json:"token"`
}

type AnonymousPost

type AnonymousPost struct {
	ID          string
	Content     string
	HTMLContent template.HTML
	Font        string
	Language    string
	Direction   string
	Title       string
	GenTitle    string
	Description string
	Author      string
	Views       int64
	Images      []string
	IsPlainText bool
	IsCode      bool
	IsLinkable  bool
}

type App

type App struct {
	// contains filtered or unexported fields
}

App holds data and configuration for an individual WriteFreely instance.

func Initialize

func Initialize(apper Apper, debug bool) (*App, error)

Initialize loads the app configuration and initializes templates, keys, session, route handlers, and the database connection.

func NewApp

func NewApp(cfgFile string) *App

NewApp creates a new app instance.

func (*App) App

func (app *App) App() *App

App returns the App

func (*App) Config

func (app *App) Config() *config.Config

Config returns the App's current configuration.

func (*App) DB

func (app *App) DB() *datastore

DB returns the App's datastore

func (*App) FetchPublicPosts

func (app *App) FetchPublicPosts() (interface{}, error)

satisfies memo.Func

func (*App) InitDecoder

func (app *App) InitDecoder()

func (*App) InitSession

func (app *App) InitSession()

InitSession creates the cookie store. It depends on the keychain already being loaded.

func (*App) InitStaticRoutes

func (app *App) InitStaticRoutes(r *mux.Router)

InitStaticRoutes adds routes for serving static files. TODO: this should just be a func, not method

func (*App) InitUpdates

func (app *App) InitUpdates()

InitUpdates initializes the updates cache, if the config value is set It uses the defaultUpdatesCacheTime for the cache expiry

func (*App) LoadConfig

func (app *App) LoadConfig() error

LoadConfig loads and parses a config file.

func (*App) LoadKeys

func (app *App) LoadKeys() error

LoadKeys reads all needed keys from disk into the App. In order to use the configured `Server.KeysParentDir`, you must call initKeyPaths(App) before this.

func (*App) ReqLog

func (app *App) ReqLog(r *http.Request, status int, timeSince time.Duration) string

func (*App) Router

func (app *App) Router() *mux.Router

Router returns the App's router

func (*App) SaveConfig

func (app *App) SaveConfig(c *config.Config) error

SaveConfig saves the given Config to disk -- namely, to the App's cfgFile.

func (*App) SessionStore

func (app *App) SessionStore() sessions.Store

func (*App) SetConfig

func (app *App) SetConfig(cfg *config.Config)

SetConfig updates the App's Config to the given value.

func (*App) SetKeys

func (app *App) SetKeys(k *key.Keychain)

SetKeys updates the App's Keychain to the given value.

func (*App) SetSessionStore

func (app *App) SetSessionStore(s sessions.Store)

type Apper

type Apper interface {
	App() *App

	LoadConfig() error
	SaveConfig(*config.Config) error

	LoadKeys() error

	ReqLog(r *http.Request, status int, timeSince time.Duration) string
}

Apper is the interface for getting data into and out of a WriteFreely instance (or "App").

App returns the App for the current instance.

LoadConfig reads an app configuration into the App, returning any error encountered.

SaveConfig persists the current App configuration.

LoadKeys reads the App's encryption keys and loads them into its key.Keychain.

type AuthCache

type AuthCache struct {
	Alias, Pass, Token string
	BadPasses          map[string]bool
	// contains filtered or unexported fields
}

type AuthUser

type AuthUser struct {
	AccessToken string `json:"access_token,omitempty"`
	Password    string `json:"password,omitempty"`
	User        *User  `json:"user"`

	// Verbose user data
	Posts       *[]PublicPost `json:"posts,omitempty"`
	Collections *[]Collection `json:"collections,omitempty"`
}

AuthUser contains information for a newly authenticated user (either from signing up or logging in).

type AuthenticatedPost

type AuthenticatedPost struct {
	ID  string `json:"id" schema:"id"`
	Web bool   `json:"web" schema:"web"`
	*SubmittedPost
}

type ClaimPostRequest

type ClaimPostRequest struct {
	*AnonymousAuthPost
	CollectionAlias  string `json:"collection"`
	CreateCollection bool   `json:"create_collection"`

	// Generated properties
	Slug string `json:"-"`
}

type ClaimPostResult

type ClaimPostResult struct {
	ID           string      `json:"id,omitempty"`
	Code         int         `json:"code,omitempty"`
	ErrorMessage string      `json:"error_msg,omitempty"`
	Post         *PublicPost `json:"post,omitempty"`
}

type Collection

type Collection struct {
	ID          int64          `datastore:"id" json:"-"`
	Alias       string         `datastore:"alias" schema:"alias" json:"alias"`
	Title       string         `datastore:"title" schema:"title" json:"title"`
	Description string         `datastore:"description" schema:"description" json:"description"`
	Direction   string         `schema:"dir" json:"dir,omitempty"`
	Language    string         `schema:"lang" json:"lang,omitempty"`
	StyleSheet  string         `datastore:"style_sheet" schema:"style_sheet" json:"style_sheet"`
	Script      string         `datastore:"script" schema:"script" json:"script,omitempty"`
	Signature   string         `datastore:"post_signature" schema:"signature" json:"-"`
	Public      bool           `datastore:"public" json:"public"`
	Visibility  collVisibility `datastore:"private" json:"-"`
	Format      string         `datastore:"format" json:"format,omitempty"`
	Views       int64          `json:"views"`
	OwnerID     int64          `datastore:"owner_id" json:"-"`
	PublicOwner bool           `datastore:"public_owner" json:"-"`
	URL         string         `json:"url,omitempty"`

	Monetization string `json:"monetization_pointer,omitempty"`
	Verification string `json:"verification_link"`
	// contains filtered or unexported fields
}

TODO: add Direction to db TODO: add Language to db

func (*Collection) AvatarURL

func (c *Collection) AvatarURL() string

func (*Collection) CanonicalURL

func (c *Collection) CanonicalURL() string

CanonicalURL returns a fully-qualified URL to the collection.

func (*Collection) DisplayCanonicalURL

func (c *Collection) DisplayCanonicalURL() string

func (*Collection) DisplayDescription

func (c *Collection) DisplayDescription() *template.HTML

DisplayDescription returns the description with rendered Markdown and HTML.

func (*Collection) DisplayTitle

func (c *Collection) DisplayTitle() string

func (*Collection) FederatedAPIBase

func (c *Collection) FederatedAPIBase() string

func (*Collection) FederatedAccount

func (c *Collection) FederatedAccount() string

func (*Collection) ForPublic

func (c *Collection) ForPublic()

ForPublic modifies the Collection for public consumption, such as via the API.

func (*Collection) FriendlyVisibility

func (c *Collection) FriendlyVisibility() string

func (*Collection) IsInstanceColl

func (c *Collection) IsInstanceColl() bool

func (*Collection) IsPrivate

func (c *Collection) IsPrivate() bool

func (*Collection) IsProtected

func (c *Collection) IsProtected() bool

func (*Collection) IsPublic

func (c *Collection) IsPublic() bool

func (*Collection) IsUnlisted

func (c *Collection) IsUnlisted() bool

func (*Collection) MonetizationURL

func (c *Collection) MonetizationURL() string

func (*Collection) NewFormat

func (c *Collection) NewFormat() *CollectionFormat

NewFormat creates a new CollectionFormat object from the Collection.

func (*Collection) NextPageURL

func (c *Collection) NextPageURL(prefix, navSuffix string, n int, tl bool) string

NextPageURL provides a full URL for the next page of collection posts

func (*Collection) PersonObject

func (c *Collection) PersonObject(ids ...int64) *activitystreams.Person

func (*Collection) PlainDescription

func (c *Collection) PlainDescription() string

PlainDescription returns the description with all Markdown and HTML removed.

func (*Collection) PrevPageURL

func (c *Collection) PrevPageURL(prefix, navSuffix string, n int, tl bool) string

PrevPageURL provides a full URL for the previous page of collection posts, returning a /page/N result for pages >1

func (*Collection) RedirectingCanonicalURL

func (c *Collection) RedirectingCanonicalURL(isRedir bool) string

RedirectingCanonicalURL returns the fully-qualified canonical URL for the Collection, with a trailing slash. The hostName field needs to be populated for this to work correctly.

func (*Collection) RenderMathJax

func (c *Collection) RenderMathJax() bool

func (*Collection) ShowFooterBranding

func (c *Collection) ShowFooterBranding() bool

func (*Collection) StyleSheetDisplay

func (c *Collection) StyleSheetDisplay() template.CSS

type CollectionFormat

type CollectionFormat struct {
	Format string
}

func (*CollectionFormat) Ascending

func (cf *CollectionFormat) Ascending() bool

func (*CollectionFormat) PostsPerPage

func (cf *CollectionFormat) PostsPerPage() int

func (*CollectionFormat) ShowDates

func (cf *CollectionFormat) ShowDates() bool

func (*CollectionFormat) Valid

func (cf *CollectionFormat) Valid() bool

Valid returns whether or not a format value is valid.

type CollectionObj

type CollectionObj struct {
	Collection
	TotalPosts int           `json:"total_posts"`
	Owner      *User         `json:"owner,omitempty"`
	Posts      *[]PublicPost `json:"posts,omitempty"`
	Format     *CollectionFormat
}

func NewCollectionObj

func NewCollectionObj(c *Collection) *CollectionObj

func (*CollectionObj) CanShowScript

func (c *CollectionObj) CanShowScript() bool

func (*CollectionObj) ExternalScripts

func (c *CollectionObj) ExternalScripts() []template.URL

func (*CollectionObj) ScriptDisplay

func (c *CollectionObj) ScriptDisplay() template.JS

type CollectionPage

type CollectionPage struct {
	page.StaticPage
	*DisplayCollection
	IsCustomDomain bool
	IsWelcome      bool
	IsOwner        bool
	IsCollLoggedIn bool
	CanPin         bool
	Username       string
	Monetization   string
	Collections    *[]Collection
	PinnedPosts    *[]PublicPost
	IsAdmin        bool
	CanInvite      bool

	// Helper field for Chorus mode
	CollAlias string
}

func (CollectionPage) DisplayMonetization

func (c CollectionPage) DisplayMonetization() string

type CollectionPostPage

type CollectionPostPage struct {
	*PublicPost
	page.StaticPage
	IsOwner        bool
	IsPinned       bool
	IsCustomDomain bool
	Monetization   string
	Verification   string
	PinnedPosts    *[]PublicPost
	IsFound        bool
	IsAdmin        bool
	CanInvite      bool
	Silenced       bool

	// Helper field for Chorus mode
	CollAlias string
}

func (CollectionPostPage) DisplayMonetization

func (c CollectionPostPage) DisplayMonetization() string

type DisplayCollection

type DisplayCollection struct {
	*CollectionObj
	Prefix      string
	NavSuffix   string
	IsTopLevel  bool
	CurrentPage int
	TotalPages  int
	Silenced    bool
}

func (*DisplayCollection) Direction

func (c *DisplayCollection) Direction() string

type ErrorPages

type ErrorPages struct {
	NotFound            *template.Template
	Gone                *template.Template
	InternalServerError *template.Template
	UnavailableError    *template.Template
	Blank               *template.Template
}

ErrorPages hold template HTML error pages for displaying errors to the user. In each, there should be a defined template named "base".

type ExportUser

type ExportUser struct {
	*User
	Collections    *[]CollectionObj `json:"collections"`
	AnonymousPosts []PublicPost     `json:"posts"`
}

type Handler

type Handler struct {
	// contains filtered or unexported fields
}

func NewHandler

func NewHandler(apper Apper) *Handler

NewHandler returns a new Handler instance, using the given StaticPage data, and saving alias to the application's CookieStore.

func NewWFHandler

func NewWFHandler(apper Apper) *Handler

NewWFHandler returns a new Handler instance, using WriteFreely template files. You MUST call writefreely.InitTemplates() before this.

func (*Handler) Admin

func (h *Handler) Admin(f userHandlerFunc) http.HandlerFunc

Admin handles requests on /admin routes

func (*Handler) AdminApper

func (h *Handler) AdminApper(f userApperHandlerFunc) http.HandlerFunc

AdminApper handles requests on /admin routes that require an Apper.

func (*Handler) All

func (h *Handler) All(f handlerFunc) http.HandlerFunc

func (*Handler) AllReader

func (h *Handler) AllReader(f handlerFunc) http.HandlerFunc

func (*Handler) CollectionPostOrStatic

func (h *Handler) CollectionPostOrStatic(w http.ResponseWriter, r *http.Request)

func (*Handler) Download

func (h *Handler) Download(f dataHandlerFunc, ul UserLevelFunc) http.HandlerFunc

func (*Handler) Gopher

func (h *Handler) Gopher(f gopherFunc) gopher.HandlerFunc

func (*Handler) LogHandlerFunc

func (h *Handler) LogHandlerFunc(f http.HandlerFunc) http.HandlerFunc

func (*Handler) OAuth

func (h *Handler) OAuth(f handlerFunc) http.HandlerFunc

func (*Handler) Page

func (h *Handler) Page(n string) http.HandlerFunc

func (*Handler) PlainTextAPI

func (h *Handler) PlainTextAPI(f handlerFunc) http.HandlerFunc

func (*Handler) Redirect

func (h *Handler) Redirect(url string, ul UserLevelFunc) http.HandlerFunc

func (*Handler) RedirectOnErr

func (h *Handler) RedirectOnErr(f handlerFunc, loc string) handlerFunc

func (*Handler) SetErrorPages

func (h *Handler) SetErrorPages(e *ErrorPages)

SetErrorPages sets the given set of ErrorPages as templates for any errors that come up.

func (*Handler) User

func (h *Handler) User(f userHandlerFunc) http.HandlerFunc

User handles requests made in the web application by the authenticated user. This provides user-friendly HTML pages and actions that work in the browser.

func (*Handler) UserAPI

func (h *Handler) UserAPI(f userHandlerFunc) http.HandlerFunc

UserAPI handles requests made in the API by the authenticated user. This provides user-friendly HTML pages and actions that work in the browser.

func (*Handler) UserAll

func (h *Handler) UserAll(web bool, f userHandlerFunc, a authFunc) http.HandlerFunc

func (*Handler) UserWebAPI

func (h *Handler) UserWebAPI(f userHandlerFunc) http.HandlerFunc

UserWebAPI handles endpoints that accept a user authorized either via the web (cookies) or an Authorization header.

func (*Handler) Web

func (h *Handler) Web(f handlerFunc, ul UserLevelFunc) http.HandlerFunc

Web handles requests made in the web application. This provides user- friendly HTML pages and actions that work in the browser.

func (*Handler) WebErrors

func (h *Handler) WebErrors(f handlerFunc, ul UserLevelFunc) http.HandlerFunc

type HttpClient

type HttpClient interface {
	Do(req *http.Request) (*http.Response, error)
}

type InspectResponse

type InspectResponse struct {
	ClientID    string    `json:"client_id"`
	UserID      string    `json:"user_id"`
	ExpiresAt   time.Time `json:"expires_at"`
	Username    string    `json:"username"`
	DisplayName string    `json:"-"`
	Email       string    `json:"email"`
	Error       string    `json:"error"`
}

InspectResponse contains data returned when an access token is inspected.

type InstanceStats

type InstanceStats struct {
	NumPosts int64
	NumBlogs int64
}

type Invite

type Invite struct {
	ID       string
	MaxUses  sql.NullInt64
	Created  time.Time
	Expires  *time.Time
	Inactive bool
	// contains filtered or unexported fields
}

func (Invite) Active

func (i Invite) Active(db *datastore) bool

func (Invite) Expired

func (i Invite) Expired() bool

func (Invite) ExpiresFriendly

func (i Invite) ExpiresFriendly() string

func (Invite) Uses

func (i Invite) Uses() int64

type OAuthButtons

type OAuthButtons struct {
	SlackEnabled       bool
	WriteAsEnabled     bool
	GitLabEnabled      bool
	GitLabDisplayName  string
	GiteaEnabled       bool
	GiteaDisplayName   string
	GenericEnabled     bool
	GenericDisplayName string
}

OAuthButtons holds display information for different OAuth providers we support.

func NewOAuthButtons

func NewOAuthButtons(cfg *config.Config) *OAuthButtons

NewOAuthButtons creates a new OAuthButtons struct based on our app configuration.

type OAuthDatastore

type OAuthDatastore interface {
	GetIDForRemoteUser(context.Context, string, string, string) (int64, error)
	RecordRemoteUserID(context.Context, int64, string, string, string, string) error
	ValidateOAuthState(context.Context, string) (string, string, int64, string, error)
	GenerateOAuthState(context.Context, string, string, int64, string) (string, error)

	CreateUser(*config.Config, *User, string, string) error
	GetUserByID(int64) (*User, error)
}

OAuthDatastore provides a minimal interface of data store methods used in oauth functionality.

type OAuthDatastoreProvider

type OAuthDatastoreProvider interface {
	DB() OAuthDatastore
	Config() *config.Config
	SessionStore() sessions.Store
}

OAuthDatastoreProvider provides a minimal interface of data store, config, and session store for use with the oauth handlers.

type PinPostResult

type PinPostResult struct {
	ID           string `json:"id,omitempty"`
	Code         int    `json:"code,omitempty"`
	ErrorMessage string `json:"error_msg,omitempty"`
}

type Post

type Post struct {
	ID             string        `db:"id" json:"id"`
	Slug           null.String   `db:"slug" json:"slug,omitempty"`
	Font           string        `db:"text_appearance" json:"appearance"`
	Language       zero.String   `db:"language" json:"language"`
	RTL            zero.Bool     `db:"rtl" json:"rtl"`
	Privacy        int64         `db:"privacy" json:"-"`
	OwnerID        null.Int      `db:"owner_id" json:"-"`
	CollectionID   null.Int      `db:"collection_id" json:"-"`
	PinnedPosition null.Int      `db:"pinned_position" json:"-"`
	Created        time.Time     `db:"created" json:"created"`
	Updated        time.Time     `db:"updated" json:"updated"`
	ViewCount      int64         `db:"view_count" json:"-"`
	Title          zero.String   `db:"title" json:"title"`
	HTMLTitle      template.HTML `db:"title" json:"-"`
	Content        string        `db:"content" json:"body"`
	HTMLContent    template.HTML `db:"content" json:"-"`
	HTMLExcerpt    template.HTML `db:"content" json:"-"`
	Tags           []string      `json:"tags"`
	Images         []string      `json:"images,omitempty"`
	IsPaid         bool          `json:"paid"`

	OwnerName string `json:"owner,omitempty"`
}

Post represents a post as found in the database.

func (*Post) Created8601

func (p *Post) Created8601() string

func (*Post) CreatedDate

func (p *Post) CreatedDate() string

func (*Post) Direction

func (p *Post) Direction() string

func (*Post) DisplayTitle

func (p *Post) DisplayTitle() string

DisplayTitle dynamically generates a title from the Post's contents if it doesn't already have an explicit title.

func (*Post) Excerpt

func (p *Post) Excerpt() template.HTML

Excerpt shows any text that comes before a (more) tag. TODO: use HTMLExcerpt in templates instead of this method

func (*Post) FormattedDisplayTitle

func (p *Post) FormattedDisplayTitle() template.HTML

FormattedDisplayTitle dynamically generates a title from the Post's contents if it doesn't already have an explicit title.

func (*Post) HasTag

func (p *Post) HasTag(tag string) bool
func (p *Post) HasTitleLink() bool

func (*Post) IsScheduled

func (p *Post) IsScheduled() bool

func (*Post) PlainDisplayTitle

func (p *Post) PlainDisplayTitle() string

PlainDisplayTitle dynamically generates a title from the Post's contents if it doesn't already have an explicit title.

func (Post) Summary

func (p Post) Summary() string

Summary gives a shortened summary of the post based on the post's title, especially for display in a longer list of posts. It extracts a summary for posts in the Title\n\nBody format, returning nothing if the entire was short enough that the extracted title == extracted summary.

func (Post) SummaryHTML

func (p Post) SummaryHTML() template.HTML

type PublicPost

type PublicPost struct {
	*Post
	IsSubdomain bool           `json:"-"`
	IsTopLevel  bool           `json:"-"`
	DisplayDate string         `json:"-"`
	Views       int64          `json:"views"`
	Owner       *PublicUser    `json:"-"`
	IsOwner     bool           `json:"-"`
	URL         string         `json:"url,omitempty"`
	Collection  *CollectionObj `json:"collection,omitempty"`
}

PublicPost holds properties for a publicly returned post, i.e. a post in a context where the viewer may not be the owner. As such, sensitive metadata for the post is hidden and properties supporting the display of the post are added.

func (*PublicPost) ActivityObject

func (p *PublicPost) ActivityObject(app *App) *activitystreams.Object

func (*PublicPost) CanonicalURL

func (p *PublicPost) CanonicalURL(hostName string) string

type PublicUser

type PublicUser struct {
	Username string `json:"username"`
}

type RawPost

type RawPost struct {
	Id, Slug     string
	Title        string
	Content      string
	Views        int64
	Font         string
	Created      time.Time
	Updated      time.Time
	IsRTL        sql.NullBool
	Language     sql.NullString
	OwnerID      int64
	CollectionID sql.NullInt64

	Found bool
	Gone  bool
}

func (*RawPost) Created8601

func (rp *RawPost) Created8601() string

func (*RawPost) Updated8601

func (rp *RawPost) Updated8601() string

func (*RawPost) UserFacingCreated

func (rp *RawPost) UserFacingCreated() string

type RemoteUser

type RemoteUser struct {
	ID          int64
	ActorID     string
	Inbox       string
	SharedInbox string
	URL         string
	Handle      string
}

func (*RemoteUser) AsPerson

func (ru *RemoteUser) AsPerson() *activitystreams.Person

type SubmittedCollection

type SubmittedCollection struct {
	// Data used for updating a given collection
	ID      int64
	OwnerID uint64

	// Form helpers
	PreferURL string `schema:"prefer_url" json:"prefer_url"`
	Privacy   int    `schema:"privacy" json:"privacy"`
	Pass      string `schema:"password" json:"password"`
	MathJax   bool   `schema:"mathjax" json:"mathjax"`
	Handle    string `schema:"handle" json:"handle"`

	// Actual collection values updated in the DB
	Alias        *string         `schema:"alias" json:"alias"`
	Title        *string         `schema:"title" json:"title"`
	Description  *string         `schema:"description" json:"description"`
	StyleSheet   *sql.NullString `schema:"style_sheet" json:"style_sheet"`
	Script       *sql.NullString `schema:"script" json:"script"`
	Signature    *sql.NullString `schema:"signature" json:"signature"`
	Monetization *string         `schema:"monetization_pointer" json:"monetization_pointer"`
	Verification *string         `schema:"verification_link" json:"verification_link"`
	Visibility   *int            `schema:"visibility" json:"public"`
	Format       *sql.NullString `schema:"format" json:"format"`
}

func (*SubmittedCollection) FediverseHandle

func (sc *SubmittedCollection) FediverseHandle() string

type SubmittedPost

type SubmittedPost struct {
	Slug     *string                  `json:"slug" schema:"slug"`
	Title    *string                  `json:"title" schema:"title"`
	Content  *string                  `json:"body" schema:"body"`
	Font     string                   `json:"font" schema:"font"`
	IsRTL    converter.NullJSONBool   `json:"rtl" schema:"rtl"`
	Language converter.NullJSONString `json:"lang" schema:"lang"`
	Created  *string                  `json:"created" schema:"created"`
}

SubmittedPost represents a post supplied by a client for publishing or updating. Since Title and Content can be updated to "", they are pointers that can be easily tested to detect changes.

type TagCollectionPage

type TagCollectionPage struct {
	CollectionPage
	Tag string
}

func (TagCollectionPage) NextPageURL

func (tcp TagCollectionPage) NextPageURL(prefix string, n int, tl bool) string

func (TagCollectionPage) PrevPageURL

func (tcp TagCollectionPage) PrevPageURL(prefix string, n int, tl bool) string

type TokenResponse

type TokenResponse struct {
	AccessToken  string `json:"access_token"`
	ExpiresIn    int    `json:"expires_in"`
	RefreshToken string `json:"refresh_token"`
	TokenType    string `json:"token_type"`
	Error        string `json:"error"`
}

TokenResponse contains data returned when a token is created either through a code exchange or using a refresh token.

type User

type User struct {
	ID         int64       `json:"-"`
	Username   string      `json:"username"`
	HashedPass []byte      `json:"-"`
	HasPass    bool        `json:"has_pass"`
	Email      zero.String `json:"email"`
	Created    time.Time   `json:"created"`
	Status     UserStatus  `json:"status"`
	// contains filtered or unexported fields
}

User is a consistent user object in the database and all contexts (auth and non-auth) in the API.

func (User) Cookie

func (u User) Cookie() *User

Cookie strips down an AuthUser to contain only information necessary for cookies.

func (User) CreatedFriendly

func (u User) CreatedFriendly() string

func (*User) EmailClear

func (u *User) EmailClear(keys *key.Keychain) string

EmailClear decrypts and returns the user's email, caching it in the user object.

func (*User) IsAdmin

func (u *User) IsAdmin() bool

func (*User) IsSilenced

func (u *User) IsSilenced() bool

type UserLevel

type UserLevel int

UserLevel represents the required user level for accessing an endpoint

const (
	UserLevelNoneType         UserLevel = iota // user or not -- ignored
	UserLevelOptionalType                      // user or not -- object fetched if user
	UserLevelNoneRequiredType                  // non-user (required)
	UserLevelUserType                          // user (required)
)

func UserLevelNone

func UserLevelNone(cfg *config.Config) UserLevel

func UserLevelNoneRequired

func UserLevelNoneRequired(cfg *config.Config) UserLevel

func UserLevelOptional

func UserLevelOptional(cfg *config.Config) UserLevel

func UserLevelReader

func UserLevelReader(cfg *config.Config) UserLevel

UserLevelReader returns the permission level required for any route where users can read published content.

func UserLevelUser

func UserLevelUser(cfg *config.Config) UserLevel

type UserLevelFunc

type UserLevelFunc func(cfg *config.Config) UserLevel

type UserPage

type UserPage struct {
	page.StaticPage

	PageTitle string
	Separator template.HTML
	IsAdmin   bool
	CanInvite bool
	CollAlias string
}

func NewUserPage

func NewUserPage(app *App, r *http.Request, u *User, title string, flashes []string) *UserPage

func (*UserPage) SetMessaging

func (up *UserPage) SetMessaging(u *User)

type UserStatus

type UserStatus int

Directories

Path Synopsis
cmd
Package config holds and assists in the configuration of a writefreely instance.
Package config holds and assists in the configuration of a writefreely instance.
Package key holds application keys and utilities around generating them.
Package key holds application keys and utilities around generating them.
Package migrations contains database migrations for WriteFreely
Package migrations contains database migrations for WriteFreely
package page provides mechanisms and data for generating a WriteFreely page.
package page provides mechanisms and data for generating a WriteFreely page.
Package parse assists in the parsing of plain text posts
Package parse assists in the parsing of plain text posts

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL