db

package
v0.0.0-...-1a9902f Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2020 License: AGPL-3.0, AGPL-3.0-or-later Imports: 32 Imported by: 0

Documentation

Overview

Package db handles all core database interactions of the server

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidToken occurs, when trying to retrieve an image with an
	// non-existent token. The token might have expired (60 to 119 seconds) or
	// the client could have provided an invalid token to begin with.
	ErrInvalidToken = common.ErrInvalidInput("invalid image token")
)
View Source
var (
	ErrUserNameTaken = errors.New("user name already taken")
)

Common errors

Functions

func AllBoardCounter

func AllBoardCounter() (uint64, error)

AllBoardCounter retrieves the progress counter of the /all/ board

func AllocateImage

func AllocateImage(tx *sql.Tx, src, thumb io.ReadSeeker, img common.ImageCommon,
) (
	err error,
)

AllocateImage allocates an image's file resources to their respective served directories and write its data to the database

func AssertNotSpammer

func AssertNotSpammer(session auth.Base64Token, ip string) (err error)

Check if IP is spammer

func Ban

func Ban(board, reason, by string, length time.Duration, id uint64,
) (err error)

Ban IPs from accessing a specific board. Need to target posts. Returns all banned IPs.

func BoardCounter

func BoardCounter(board string) (uint64, error)

BoardCounter retrieves the progress counter of a board

func CanPerform

func CanPerform(account, board string, action common.ModerationLevel) (
	can bool, err error,
)

CanPerform returns, if the account can perform an action of ModerationLevel 'action' on the target board

func ChangePassword

func ChangePassword(account string, hash []byte) error

ChangePassword changes an existing user's login password

func CheckThreadLocked

func CheckThreadLocked(id uint64) (locked bool, err error)

CheckThreadLocked checks, if a thread has been locked by a moderator

func ClearLoginAttempts

func ClearLoginAttempts(ip, account string) error

ClearLoginAttempts clears login attempts for account for IP

func ClearTables

func ClearTables(tables ...string) error

ClearTables deletes the contents of specified DB tables. Only used for tests.

func Close

func Close() (err error)

Close DB and release resources

func ClosePost

func ClosePost(id, op uint64, body string, links []common.Link,
	com []common.Command,
) (err error)

ClosePost closes an open post and commits any links and hash commands

func CreateAdminAccount

func CreateAdminAccount(tx *sql.Tx) (err error)

CreateAdminAccount writes a fresh admin account with the default password to the database

func CreateSystemAccount

func CreateSystemAccount(tx *sql.Tx) (err error)

CreateSystemAccount create an inaccessible account used for automatic internal purposes

func DecrementPyuLimit

func DecrementPyuLimit(tx *sql.Tx, ip string, b string) (err error)

DecrementPyuLimit decrements the pyu limit counter by one and returns the new counter

func DeleteBoard

func DeleteBoard(board, by string) error

DeleteBoard deletes a board and all of its contained threads and posts

func DeleteImages

func DeleteImages(ids []uint64, by string) (err error)

DeleteImage permanently deletes an image from a post

func DeletePosts

func DeletePosts(ids []uint64, by string) (err error)

DeletePost marks the target post as deleted

func DeletePostsByIP

func DeletePostsByIP(id uint64, account string, keepDeleting time.Duration,
	reason string,
) (err error)

Delete posts of the same IP as target post on board and optionally keep deleting posts by this IP

func FindPosition

func FindPosition(board, userID string) (pos common.ModerationLevel, err error)

FindPosition returns the highest matching position of a user on a certain board. As a special case the admin user will always return "admin".

func FreePyuLimit

func FreePyuLimit() error

FreePyuLimit resets the restricted status and pcount so sluts can #pyu again.

func GetAllBoardCatalog

func GetAllBoardCatalog() (board common.Board, err error)

GetAllBoardCatalog retrieves all threads for the "/all/" meta-board

func GetAllThreadsIDs

func GetAllThreadsIDs() ([]uint64, error)

GetAllThreadsIDs retrieves all threads IDs in bump order

func GetBanInfo

func GetBanInfo(ip, board string) (b auth.BanRecord, err error)

GetBanInfo retrieves information about a specific ban

func GetBitChuteTitle

func GetBitChuteTitle(id string) (title string, err error)

GetBitChuteTitle retrieves the bitchute video title by ID

func GetBoardBans

func GetBoardBans(board string) (b []auth.BanRecord, err error)

GetBoardBans gets all bans on a specific board. "all" counts as a valid board value.

func GetBoardCatalog

func GetBoardCatalog(board string) (b common.Board, err error)

GetBoardCatalog retrieves all OPs of a single board

func GetBoardConfigs

func GetBoardConfigs(board string) (config.BoardConfigs, error)

GetBoardConfigs retrives the configurations of a specific board

func GetConfigs

func GetConfigs() (c config.Configs, err error)

GetConfigs retrieves global configurations. Only used in tests.

func GetIP

func GetIP(id uint64) (string, error)

GetIP returns an IP of the poster that created a post. Posts older than 7 days will not have this information.

func GetImage

func GetImage(sha1 string) (img common.ImageCommon, err error)

GetImage retrieves a thumbnailed image record from the DB.

Only used in tests.

func GetModLog

func GetModLog(board string) (log []auth.ModLogEntry, err error)

GetModLog retrieves the moderation log for a specific board

func GetModLogEntry

func GetModLogEntry(id uint64) (e auth.ModLogEntry, err error)

GetModLog retrieves the moderation log entry by ID

func GetOpenBody

func GetOpenBody(id uint64) (body string, err error)

GetOpenBody retrieves an open body of a post

func GetOwnedBoards

func GetOwnedBoards(account string) (boards []string, err error)

GetOwnedBoards returns boards the account holder owns

func GetPassword

func GetPassword(id string) (hash []byte, err error)

GetPassword retrieves the login password hash of the registered user account

func GetPcount

func GetPcount(b string) (c uint64, err error)

GetPcount retrieves the board's pyu counter

func GetPcountA

func GetPcountA(tx *sql.Tx, b string) (c uint64, err error)

GetPcountA retrieves the board's pyu counter atomically

func GetPost

func GetPost(id uint64) (res common.StandalonePost, err error)

GetPost reads a single post from the database

func GetPostBoard

func GetPostBoard(id uint64) (board string, err error)

GetPostBoard retrieves the board of a post by ID

func GetPostParenthood

func GetPostParenthood(id uint64) (board string, op uint64, err error)

GetPostParenthood retrieves the board and OP of a post

func GetPostPassword

func GetPostPassword(id uint64) (p []byte, err error)

GetPostPassword retrieves a post's modification password

func GetPyuLimit

func GetPyuLimit(tx *sql.Tx, ip string, b string) (c uint8, err error)

GetPyuLimit retrieves the IP and respective board's pyu limit counter

func GetPyuLimitRestricted

func GetPyuLimitRestricted(tx *sql.Tx, ip string, b string,
) (restricted bool, err error)

GetPyuLimitRestricted retrieves the IP and respective board's pyu limit restricted status

func GetReports

func GetReports(board string) (rep []auth.Report, err error)

GetReports reads reports for a specific board. Pass "all" for global reports.

func GetSameIPPosts

func GetSameIPPosts(id uint64, board string, by string) (
	posts []common.StandalonePost, err error,
)

GetSameIPPosts returns posts with the same IP and on the same board as the target post

func GetStaff

func GetStaff(board string,
) (staff map[common.ModerationLevel][]string, err error)

GetStaff retrieves all staff positions of a specific board

func GetThread

func GetThread(id uint64, lastN int) (t common.Thread, err error)

GetThread retrieves public thread data from the database

func GetThreadIDs

func GetThreadIDs(board string) ([]uint64, error)

GetThreadIDs retrieves all threads IDs on the board in bump order with stickies first

func HasImage

func HasImage(id uint64) (has bool, err error)

HasImage returns, if the post has an image allocated. Only used in tests.

func ImageExists

func ImageExists(tx *sql.Tx, sha1 string) (exists bool, err error)

ImageExists returns, if image exists

func ImageVisible

func ImageVisible(sha1, board string) (visible bool, err error)

ImageVisible returns if the image is attached to any non-deleted and unspoilered posts on the board

func InTransaction

func InTransaction(readOnly bool, fn func(*sql.Tx) error) (err error)

InTransaction runs a function inside a transaction and handles comminting and rollback on error. readOnly: the DBMS can optimise read-only transactions for better concurrency

TODO: Get rid off readOnly param, once reader ported to output JSON

func IncrementLoginAttempts

func IncrementLoginAttempts(ip, account string) (attempts uint8, err error)

IncrementLoginAttempts increments or creates the login attempt counter for user

func IncrementPcount

func IncrementPcount(tx *sql.Tx, b string) (c uint64, err error)

IncrementPcount increments the board's pyu counter by one and returns the new counter

func IncrementSpamScore

func IncrementSpamScore(session auth.Base64Token, ip string, increment uint)

IncrementSpamScore increments spam detection score of a captcha session and sends captcha requests, if score exceeded.

session: token identifying captcha session ip: IP of client increment: increment amount in milliseconds

func InsertImage

func InsertImage(tx *sql.Tx, postID uint64, token, name string, spoiler bool,
) (
	json []byte, err error,
)

InsertImage insert and image into and existing open post and return image JSON

func InsertPost

func InsertPost(tx *sql.Tx, p *Post) (err error)

Insert Post into thread and set its ID and creation time and moderation status. Thread OPs must have their post ID set to the thread ID. Any images are to be inserted in a separate call.

func InsertThread

func InsertThread(tx *sql.Tx, subject string, p *Post) (err error)

InsertThread inserts a new thread into the database. Sets ID, OP and time on inserted post.

func IsBanned

func IsBanned(board, ip string) error

IsBanned checks if the IP is banned on the target board or globally

func IsConflictError

func IsConflictError(err error) bool

IsConflictError returns if an error is a unique key conflict error

func IsLoggedIn

func IsLoggedIn(user, session string) (loggedIn bool, err error)

IsLoggedIn check if the user is logged in with the specified session

func Listen

func Listen(event string, fn func(msg string) error) (err error)

Listen assigns a function to listen to Postgres notifications on a channel. Can't be used in tests.

func ListenCancelable

func ListenCancelable(event string, canceller <-chan struct{},
	fn func(msg string) error,
) (err error)

Like listen, but is cancelable. Can be used in tests.

func LoadDB

func LoadDB() error

Connects to PostgreSQL database and performs schema upgrades

func LoadTestDB

func LoadTestDB(suffix string) (close func() error, err error)

Create and load testing database. Call close() to clean up temporary resources.

func LogOut

func LogOut(account, token string) error

LogOut logs the account out of one specific session

func LogOutAll

func LogOutAll(account string) error

LogOutAll logs an account out of all user sessions

func ModSpoilerImages

func ModSpoilerImages(ids []uint64, by string) (err error)

ModSpoilerImage spoilers image as a moderator

func NeedCaptcha

func NeedCaptcha(session auth.Base64Token, ip string) (need bool, err error)

NeedCaptcha returns, if the user needs a captcha to proceed with usage of server resources

func NewImageToken

func NewImageToken(tx *sql.Tx, SHA1 string) (token string, err error)

NewImageToken inserts a new image allocation token into the DB and returns it's ID

func PurgePost

func PurgePost(id uint64, by, reason string) (err error)

Clear post contents and remove any uploaded image from the server

func PyuLimitExists

func PyuLimitExists(tx *sql.Tx, ip string, b string) (e bool, err error)

PyuLimitExists checks whether an IP has a pyu limit counter

func Read

func Read()

func RefreshBanCache

func RefreshBanCache() (err error)

RefreshBanCache loads up to date bans from the database and caches them in memory

func RegisterAccount

func RegisterAccount(tx *sql.Tx, id string, hash []byte) error

RegisterAccount writes the ID and password hash of a new user account to the database

func Report

func Report(id uint64, board, reason, ip string, illegal bool) error

Report a post for rule violations

func SetBanners

func SetBanners(board string, banners []assets.File) error

SetBanners overwrites the list of banners in the DB, for a specific board

func SetLoadingAnimation

func SetLoadingAnimation(board string, file assets.File) error

SetLoadingAnimation sets the loading animation for a specific board. Nil file.Data means the default animation should be used.

func SetOpenBody

func SetOpenBody(id uint64, body []byte) (err error)

SetOpenBody sets the open body of a post

func SetPostCounter

func SetPostCounter(c uint64) error

SetPostCounter sets the post counter. Should only be used in tests.

func SetPyuLimitRestricted

func SetPyuLimitRestricted(tx *sql.Tx, ip string, b string) (err error)

SetPyuLimitRestricted sets the IP and respective board's pyu limit restricted status

func SetThreadLock

func SetThreadLock(id uint64, locked bool, by string) error

SetThreadLock sets the ability of users to post in a specific thread

func SetThreadSticky

func SetThreadSticky(id uint64, sticky bool) error

SetThreadSticky sets the sticky field on a thread

func SolvedCaptchaRecently

func SolvedCaptchaRecently(
	session auth.Base64Token,
	dur time.Duration,
) (
	has bool,
	err error,
)

Returns, if IP has solved a captcha within the last dur

func SplitBoardAndID

func SplitBoardAndID(msg string) (board string, id uint64, err error)

Split message containing a board and post/thread ID

func SplitUint64s

func SplitUint64s(msg string, n int) (arr []uint64, err error)

Split message containing a list of uint64 numbers. Returns error, if message did not contain n integers.

func SpoilerImage

func SpoilerImage(id, op uint64) error

SpoilerImage spoilers an already allocated image

func SystemBan

func SystemBan(ip, reason string, length time.Duration) (err error)

Automatically bans an IP

func ThreadCounter

func ThreadCounter(id uint64) (uint64, error)

ThreadCounter retrieves the progress counter of a thread

func Unban

func Unban(board string, id uint64, by string) error

Unban lifts a ban from a specific post on a specific board

func UpdateBoard

func UpdateBoard(c config.BoardConfigs) (err error)

UpdateBoard updates board configurations

func ValidateCaptcha

func ValidateCaptcha(
	req auth.Captcha,
	session auth.Base64Token,
	ip string,
) (err error)

ValidateCaptcha with captcha backend

func ValidateOP

func ValidateOP(id uint64, board string) (valid bool, err error)

ValidateOP confirms the specified thread exists on specific board

func WriteBitChuteTitle

func WriteBitChuteTitle(id string, title string) error

WriteBitChuteTitle creates a new bitchute title row.

func WriteBoard

func WriteBoard(tx *sql.Tx, c BoardConfigs) error

WriteBoard writes a board complete with configurations to the database

func WriteConfigs

func WriteConfigs(c config.Configs) (err error)

WriteConfigs writes new global configurations to the database

func WriteImage

func WriteImage(i common.ImageCommon) error

WriteImage writes a processed image record to the DB. Only used in tests.

func WriteLoginSession

func WriteLoginSession(account, token string) error

WriteLoginSession writes a new user login session to the DB

func WritePost

func WritePost(tx *sql.Tx, p Post) (err error)

WritePost writes a post struct to the database. Only used in tests and migrations.

func WritePyuLimit

func WritePyuLimit(tx *sql.Tx, ip string, b string) error

WritePyuLimit creates a new pyu limit row. Only used on the first post of a new IP.

func WriteStaff

func WriteStaff(tx *sql.Tx, board string,
	staff map[common.ModerationLevel][]string,
) (err error)

WriteStaff writes staff positions of a specific board. Old rows are overwritten.

func WriteThread

func WriteThread(t Thread, p Post) (err error)

WriteThread writes a thread and it's OP to the database. Only used for tests.

Types

type BoardConfigs

type BoardConfigs struct {
	config.BoardConfigs
	Created time.Time
}

BoardConfigs contains extra fields not exposed on database reads

type ErrMsgParse

type ErrMsgParse string

PostgreSQL notification message parse error

func (ErrMsgParse) Error

func (e ErrMsgParse) Error() string

type Post

type Post struct {
	common.StandalonePost
	Password []byte
	IP       string
}

Post is for writing new posts to a database. It contains the Password field, which is never exposed publically through Post.

type PostStats

type PostStats struct {
	Editing, HasImage, Spoilered bool
	ID                           uint64
	Time                         int64
	Body                         []byte
}

PostStats contains post open status, body and creation time

type Thread

type Thread struct {
	ID                   uint64
	PostCtr, ImageCtr    uint32
	UpdateTime, BumpTime int64
	Subject, Board       string
}

Thread is a template for writing new threads to the database

type ThreadPostCountDiff

type ThreadPostCountDiff struct {
	Changed map[uint64]uint64 `json:"changed"`
	Deleted []uint64          `json:"deleted"`
}

Diff of passed and actual thread posts counts

func DiffThreadPostCounts

func DiffThreadPostCounts(old map[uint64]uint64) (
	diff ThreadPostCountDiff, err error,
)

Return diff of passed and actual thread post counts

type Video

type Video struct {
	FileType uint8         `json:"file_type"`
	Duration time.Duration `json:"-"`
	SHA1     string        `json:"sha1"`
}

Video structure

func VideoPlaylist

func VideoPlaylist(board string) (videos []Video, err error)

VideoPlaylist returns a video playlist for a board

Jump to

Keyboard shortcuts

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