madon

package module
v2.3.0+incompatible Latest Latest
Warning

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

Go to latest
Published: Mar 21, 2018 License: MIT Imports: 19 Imported by: 11

README

madon

Golang library for the Mastodon API

godoc license build Go Report Card

madon is a Go library to access the Mastondon REST API.

This implementation covers 100% of the current API, including the streaming API.

The madonctl console client uses this library exhaustively.

Installation

To install the library (Go >= v1.5 required):

go get github.com/McKael/madon

You can test it with my CLI tool:

go get github.com/McKael/madonctl

Usage

This section has not been written yet (PR welcome).

For now please check godoc and check the madonctl project implementation.

History

This API implementation was initially submitted as a PR for gondole.

The repository is actually a fork of my gondole branch so that history and credits are preserved.

References

Documentation

Index

Constants

View Source
const (
	// MadonVersion contains the version of the Madon library
	MadonVersion = "2.3.0"

	// NoRedirect is the URI for no redirection in the App registration
	NoRedirect = "urn:ietf:wg:oauth:2.0:oob"
)

Variables

View Source
var (
	ErrUninitializedClient = errors.New("use of uninitialized madon client")
	ErrAlreadyRegistered   = errors.New("app already registered")
	ErrEntityNotFound      = errors.New("entity not found")
	ErrInvalidParameter    = errors.New("incorrect parameter")
	ErrInvalidID           = errors.New("incorrect entity ID")
)

Error codes

Functions

This section is empty.

Types

type Account

type Account struct {
	ID             int64     `json:"id,string"`
	Username       string    `json:"username"`
	Acct           string    `json:"acct"`
	DisplayName    string    `json:"display_name"`
	Note           string    `json:"note"`
	URL            string    `json:"url"`
	Avatar         string    `json:"avatar"`
	AvatarStatic   string    `json:"avatar_static"`
	Header         string    `json:"header"`
	HeaderStatic   string    `json:"header_static"`
	Locked         bool      `json:"locked"`
	CreatedAt      time.Time `json:"created_at"`
	FollowersCount int64     `json:"followers_count"`
	FollowingCount int64     `json:"following_count"`
	StatusesCount  int64     `json:"statuses_count"`
	Moved          *Account  `json:"moved"`
	Source         *struct {
		Privacy   string `json:"privacy"`
		Sensitive bool   `json:"sensitive"`
		Note      string `json:"note"`
	} `json:"source"`
}

Account represents a Mastodon account entity

type ActivityTime

type ActivityTime struct {
	time.Time
}

ActivityTime is a custom type for the time returned by instance/activity

func (*ActivityTime) MarshalJSON

func (act *ActivityTime) MarshalJSON() ([]byte, error)

MarshalJSON handles serialization for custom ActivityTime type

func (*ActivityTime) UnmarshalJSON

func (act *ActivityTime) UnmarshalJSON(b []byte) error

UnmarshalJSON handles deserialization for custom ActivityTime type

type Application

type Application struct {
	Name    string `json:"name"`
	Website string `json:"website"`
}

Application represents a Mastodon application entity

type Attachment

type Attachment struct {
	ID         int64   `json:"id,string"`
	Type       string  `json:"type"`
	URL        string  `json:"url"`
	RemoteURL  *string `json:"remote_url"`
	PreviewURL string  `json:"preview_url"`
	TextURL    *string `json:"text_url"`
	Meta       *struct {
		Original struct {
			Size   string  `json:"size"`
			Aspect float64 `json:"aspect"`
			Width  int     `json:"width"`
			Height int     `json:"height"`
		} `json:"original"`
		Small struct {
			Size   string  `json:"size"`
			Aspect float64 `json:"aspect"`
			Width  int     `json:"width"`
			Height int     `json:"height"`
		} `json:"small"`
	} `json:"meta"`
	Description *string `json:"description"`
}

Attachment represents a Mastodon media attachment entity

type Card

type Card struct {
	URL          string  `json:"url"`
	Title        string  `json:"title"`
	Description  string  `json:"description"`
	Image        string  `json:"image"`
	Type         *string `json:"type"`
	AuthorName   *string `json:"author_name"`
	AuthorURL    *string `json:"author_url"`
	ProviderName *string `json:"provider_name"`
	ProviderURL  *string `json:"provider_url"`
	EmbedURL     *string `json:"embed_url"`
	HTML         *string `json:"html"`
	Width        *int    `json:"width"`
	Height       *int    `json:"height"`
}

Card represents a Mastodon preview card entity

type Client

type Client struct {
	Name        string // Name of the client
	ID          string // Application ID
	Secret      string // Application secret
	APIBase     string // API prefix URL
	InstanceURL string // Instance base URL

	UserToken *UserToken // User token
}

Client contains data for a madon client application

func NewApp

func NewApp(name, website string, scopes []string, redirectURI, instanceName string) (mc *Client, err error)

NewApp registers a new application with a given instance

func RestoreApp

func RestoreApp(name, instanceName, appID, appSecret string, userToken *UserToken) (mc *Client, err error)

RestoreApp recreates an application client with existing secrets

func (*Client) AddListAccounts

func (mc *Client) AddListAccounts(listID int64, accountIDs []int64) error

AddListAccounts adds the accounts to a given list

func (*Client) BlockAccount

func (mc *Client) BlockAccount(accountID int64) (*Relationship, error)

BlockAccount blocks an account

func (*Client) BlockDomain added in v1.6.0

func (mc *Client) BlockDomain(domain DomainName) error

BlockDomain blocks the specified domain

func (*Client) ClearNotifications

func (mc *Client) ClearNotifications() error

ClearNotifications deletes all notifications from the Mastodon server for the authenticated user

func (*Client) CreateList

func (mc *Client) CreateList(title string) (*List, error)

CreateList creates a List

func (*Client) DeleteList

func (mc *Client) DeleteList(listID int64) error

DeleteList deletes a list

func (*Client) DeleteStatus

func (mc *Client) DeleteStatus(statusID int64) error

DeleteStatus deletes a status

func (*Client) DismissNotification

func (mc *Client) DismissNotification(notificationID int64) error

DismissNotification deletes a notification

func (*Client) FavouriteStatus

func (mc *Client) FavouriteStatus(statusID int64) error

FavouriteStatus favourites a status

func (*Client) FollowAccount

func (mc *Client) FollowAccount(accountID int64, reblogs *bool) (*Relationship, error)

FollowAccount follows an account 'reblogs' can be used to specify if boots should be displayed or hidden.

func (*Client) FollowRemoteAccount

func (mc *Client) FollowRemoteAccount(uri string) (*Account, error)

FollowRemoteAccount follows a remote account The parameter 'uri' is a URI (e.g. "username@domain").

func (*Client) FollowRequestAuthorize

func (mc *Client) FollowRequestAuthorize(accountID int64, authorize bool) error

FollowRequestAuthorize authorizes or rejects an account follow-request

func (*Client) GetAccount

func (mc *Client) GetAccount(accountID int64) (*Account, error)

GetAccount returns an account entity The returned value can be nil if there is an error or if the requested ID does not exist.

func (*Client) GetAccountFollowRequests

func (mc *Client) GetAccountFollowRequests(lopt *LimitParams) ([]Account, error)

GetAccountFollowRequests returns the list of follow requests accounts The lopt parameter is optional (can be nil).

func (*Client) GetAccountFollowers

func (mc *Client) GetAccountFollowers(accountID int64, lopt *LimitParams) ([]Account, error)

GetAccountFollowers returns the list of accounts following a given account

func (*Client) GetAccountFollowing

func (mc *Client) GetAccountFollowing(accountID int64, lopt *LimitParams) ([]Account, error)

GetAccountFollowing returns the list of accounts a given account is following

func (*Client) GetAccountRelationships

func (mc *Client) GetAccountRelationships(accountIDs []int64) ([]Relationship, error)

GetAccountRelationships returns a list of relationship entities for the given accounts

func (*Client) GetAccountStatuses

func (mc *Client) GetAccountStatuses(accountID int64, onlyPinned, onlyMedia, excludeReplies bool, lopt *LimitParams) ([]Status, error)

GetAccountStatuses returns a list of status entities for the given account If onlyMedia is true, returns only statuses that have media attachments. If onlyPinned is true, returns only statuses that have been pinned. If excludeReplies is true, skip statuses that reply to other statuses. If lopt.All is true, several requests will be made until the API server has nothing to return. If lopt.Limit is set (and not All), several queries can be made until the limit is reached.

func (*Client) GetBlockedAccounts

func (mc *Client) GetBlockedAccounts(lopt *LimitParams) ([]Account, error)

GetBlockedAccounts returns the list of blocked accounts The lopt parameter is optional (can be nil).

func (*Client) GetBlockedDomains added in v1.6.0

func (mc *Client) GetBlockedDomains(lopt *LimitParams) ([]DomainName, error)

GetBlockedDomains returns the current user blocked domains If lopt.All is true, several requests will be made until the API server has nothing to return.

func (*Client) GetCurrentAccount

func (mc *Client) GetCurrentAccount() (*Account, error)

GetCurrentAccount returns the current user account

func (*Client) GetCurrentInstance

func (mc *Client) GetCurrentInstance() (*Instance, error)

GetCurrentInstance returns current instance information

func (*Client) GetCustomEmojis

func (mc *Client) GetCustomEmojis(lopt *LimitParams) ([]Emoji, error)

GetCustomEmojis returns a list with the server custom emojis

func (*Client) GetFavourites

func (mc *Client) GetFavourites(lopt *LimitParams) ([]Status, error)

GetFavourites returns the list of the user's favourites If lopt.All is true, several requests will be made until the API server has nothing to return. If lopt.Limit is set (and not All), several queries can be made until the limit is reached.

func (*Client) GetInstanceActivity

func (mc *Client) GetInstanceActivity() ([]WeekActivity, error)

GetInstanceActivity returns current instance activity

func (*Client) GetInstancePeers

func (mc *Client) GetInstancePeers() ([]InstancePeer, error)

GetInstancePeers returns current instance peers The peers are defined as the domains of users the instance has previously resolved.

func (*Client) GetList

func (mc *Client) GetList(listID int64) (*List, error)

GetList returns a List entity

func (*Client) GetListAccounts

func (mc *Client) GetListAccounts(listID int64, lopt *LimitParams) ([]Account, error)

GetListAccounts returns the accounts belonging to a given list

func (*Client) GetLists

func (mc *Client) GetLists(accountID int64, lopt *LimitParams) ([]List, error)

GetLists returns a list of List entities If accountID is > 0, this will return the lists containing this account. If lopt.All is true, several requests will be made until the API server has nothing to return.

func (*Client) GetMutedAccounts

func (mc *Client) GetMutedAccounts(lopt *LimitParams) ([]Account, error)

GetMutedAccounts returns the list of muted accounts The lopt parameter is optional (can be nil).

func (*Client) GetNotification

func (mc *Client) GetNotification(notificationID int64) (*Notification, error)

GetNotification returns a notification The returned notification can be nil if there is an error or if the requested notification does not exist.

func (*Client) GetNotifications

func (mc *Client) GetNotifications(excludeTypes []string, lopt *LimitParams) ([]Notification, error)

GetNotifications returns the list of the user's notifications excludeTypes is an array of notifications to exclude ("follow", "favourite", "reblog", "mention"). It can be nil. If lopt.All is true, several requests will be made until the API server has nothing to return. If lopt.Limit is set (and not All), several queries can be made until the limit is reached.

func (*Client) GetReports

func (mc *Client) GetReports(lopt *LimitParams) ([]Report, error)

GetReports returns the current user's reports (I don't know if the limit options are used by the API server.)

func (*Client) GetStatus

func (mc *Client) GetStatus(statusID int64) (*Status, error)

GetStatus returns a status The returned status can be nil if there is an error or if the requested ID does not exist.

func (*Client) GetStatusCard

func (mc *Client) GetStatusCard(statusID int64) (*Card, error)

GetStatusCard returns a status card

func (*Client) GetStatusContext

func (mc *Client) GetStatusContext(statusID int64) (*Context, error)

GetStatusContext returns a status context

func (*Client) GetStatusFavouritedBy

func (mc *Client) GetStatusFavouritedBy(statusID int64, lopt *LimitParams) ([]Account, error)

GetStatusFavouritedBy returns a list of the accounts who favourited a status

func (*Client) GetStatusRebloggedBy

func (mc *Client) GetStatusRebloggedBy(statusID int64, lopt *LimitParams) ([]Account, error)

GetStatusRebloggedBy returns a list of the accounts who reblogged a status

func (*Client) GetTimelines

func (mc *Client) GetTimelines(timeline string, local, onlyMedia bool, lopt *LimitParams) ([]Status, error)

GetTimelines returns a timeline (a list of statuses timeline can be "home", "public", a hashtag (use ":hashtag" or "#hashtag") or a list (use "!N", e.g. "!42" for list ID #42). For the public timelines, you can set 'local' to true to get only the local instance. Set 'onlyMedia' to true to only get statuses that have media attachments. If lopt.All is true, several requests will be made until the API server has nothing to return. If lopt.Limit is set (and not All), several queries can be made until the limit is reached.

func (*Client) LoginBasic

func (mc *Client) LoginBasic(username, password string, scopes []string) error

LoginBasic does basic user authentication

func (*Client) LoginOAuth2 added in v1.5.0

func (mc *Client) LoginOAuth2(code string, scopes []string) (string, error)

LoginOAuth2 handles OAuth2 authentication If code is empty, the URL to the server consent page will be returned; if not, the user token is set.

func (*Client) MuteAccount

func (mc *Client) MuteAccount(accountID int64, muteNotifications *bool) (*Relationship, error)

MuteAccount mutes an account Note that with current Mastodon API, muteNotifications defaults to true when it is not provided.

func (*Client) MuteConversation added in v1.6.0

func (mc *Client) MuteConversation(statusID int64) (*Status, error)

MuteConversation mutes the conversation containing a status

func (*Client) PinStatus

func (mc *Client) PinStatus(statusID int64) error

PinStatus pins a status

func (*Client) PostStatus

func (mc *Client) PostStatus(text string, inReplyTo int64, mediaIDs []int64, sensitive bool, spoilerText string, visibility string) (*Status, error)

PostStatus posts a new "toot" All parameters but "text" can be empty. Visibility must be empty, or one of "direct", "private", "unlisted" and "public".

func (*Client) ReblogStatus

func (mc *Client) ReblogStatus(statusID int64) error

ReblogStatus reblogs a status

func (*Client) RemoveListAccounts

func (mc *Client) RemoveListAccounts(listID int64, accountIDs []int64) error

RemoveListAccounts removes the accounts from the given list

func (*Client) ReportUser

func (mc *Client) ReportUser(accountID int64, statusIDs []int64, comment string) (*Report, error)

ReportUser reports the user account

func (*Client) Search

func (mc *Client) Search(query string, resolve bool) (*Results, error)

Search search for contents (accounts or statuses) and returns a Results

func (*Client) SearchAccounts

func (mc *Client) SearchAccounts(query string, following bool, lopt *LimitParams) ([]Account, error)

SearchAccounts returns a list of accounts matching the query string The lopt parameter is optional (can be nil) or can be used to set a limit.

func (*Client) SetUserToken

func (mc *Client) SetUserToken(token, username, password string, scopes []string) error

SetUserToken sets an existing user credentials No verification of the arguments is made.

func (*Client) StreamListener

func (mc *Client) StreamListener(name, hashTag string, events chan<- StreamEvent, stopCh <-chan bool, doneCh chan bool) error

StreamListener listens to a stream from the Mastodon server The stream 'name' can be "user", "local", "public" or "hashtag". For 'hashtag', the hashTag argument cannot be empty. The events are sent to the events channel (the errors as well). The streaming is terminated if the 'stopCh' channel is closed. The 'doneCh' channel is closed if the connection is closed by the server. Please note that this method launches a goroutine to listen to the events.

func (*Client) UnblockAccount

func (mc *Client) UnblockAccount(accountID int64) (*Relationship, error)

UnblockAccount unblocks an account

func (*Client) UnblockDomain added in v1.6.0

func (mc *Client) UnblockDomain(domain DomainName) error

UnblockDomain unblocks the specified domain

func (*Client) UnfavouriteStatus

func (mc *Client) UnfavouriteStatus(statusID int64) error

UnfavouriteStatus unfavourites a status

func (*Client) UnfollowAccount

func (mc *Client) UnfollowAccount(accountID int64) (*Relationship, error)

UnfollowAccount unfollows an account

func (*Client) UnmuteAccount

func (mc *Client) UnmuteAccount(accountID int64) (*Relationship, error)

UnmuteAccount unmutes an account

func (*Client) UnmuteConversation added in v1.6.0

func (mc *Client) UnmuteConversation(statusID int64) (*Status, error)

UnmuteConversation unmutes the conversation containing a status

func (*Client) UnpinStatus

func (mc *Client) UnpinStatus(statusID int64) error

UnpinStatus unpins a status

func (*Client) UnreblogStatus

func (mc *Client) UnreblogStatus(statusID int64) error

UnreblogStatus unreblogs a status

func (*Client) UpdateAccount

func (mc *Client) UpdateAccount(displayName, note, avatar, headerImage *string, locked *bool) (*Account, error)

UpdateAccount updates the connected user's account data The fields avatar & headerImage can contain base64-encoded images; if they do not (that is; if they don't contain ";base64,"), they are considered as file paths and their content will be encoded. Setting 'locked' to true means all followers should be approved. All fields can be nil, in which case they are not updated. displayName and note can be set to "" to delete previous values; I'm not sure images can be deleted -- only replaced AFAICS.

func (*Client) UpdateList

func (mc *Client) UpdateList(listID int64, title string) (*List, error)

UpdateList updates an existing List

func (*Client) UpdateMedia

func (mc *Client) UpdateMedia(mediaID int64, description, focus *string) (*Attachment, error)

UpdateMedia updates the description and focal point of a media One of the description and focus arguments can be nil to not be updated.

func (*Client) UploadMedia

func (mc *Client) UploadMedia(filePath, description, focus string) (*Attachment, error)

UploadMedia uploads the given file and returns an attachment The description and focus arguments can be empty strings. 'focus' is the "focal point", written as two comma-delimited floating points.

type Context

type Context struct {
	Ancestors   []Status `json:"ancestors"`
	Descendants []Status `json:"descendants"`
}

Context represents a Mastodon context entity

type DomainName added in v1.6.0

type DomainName string

DomainName is a domain name string, as returned by the domain_blocks API

type Emoji

type Emoji struct {
	ShortCode       string `json:"shortcode"`
	URL             string `json:"url"`
	StaticURL       string `json:"static_url"`
	VisibleInPicker bool   `json:"visible_in_picker"`
}

Emoji represents a Mastodon emoji entity

type Error

type Error struct {
	Text string `json:"error"`
}

Error represents a Mastodon error entity

type Instance

type Instance struct {
	URI         string `json:"uri"`
	Title       string `json:"title"`
	Description string `json:"description"`
	Email       string `json:"email"`
	Version     string `json:"version"`

	URLs struct {
		SteamingAPI string `json:"streaming_api"`
	} `json:"urls"`
	Stats struct {
		UserCount   int64 `json:"user_count"`
		StatusCount int64 `json:"status_count"`
		DomainCount int64 `json:"domain_count"`
	} `json:"stats"`
	Thumbnail      *string  `json:"thumbnail"`
	Languages      []string `json:"languages"`
	ContactAccount *Account `json:"contact_account"`
}

Instance represents a Mastodon instance entity

type InstancePeer

type InstancePeer string

InstancePeer is a peer name, as returned by the instance/peers API

type LimitParams

type LimitParams struct {
	Limit          int   // Number of items per query
	SinceID, MaxID int64 // Boundaries
	All            bool  // Get as many items as possible
}

LimitParams contains common limit/paging options for the Mastodon REST API

type List

type List struct {
	ID    int64  `json:"id,string"`
	Title string `json:"title"`
}

List represents a Mastodon list entity

type Mention

type Mention struct {
	ID       int64  `json:"id,string"`
	URL      string `json:"url"`
	Username string `json:"username"`
	Acct     string `json:"acct"`
}

Mention represents a Mastodon mention entity

type Notification

type Notification struct {
	ID        int64     `json:"id,string"`
	Type      string    `json:"type"`
	CreatedAt time.Time `json:"created_at"`
	Account   *Account  `json:"account"`
	Status    *Status   `json:"status"`
}

Notification represents a Mastodon notification entity

type Relationship

type Relationship struct {
	ID        int64 `json:"id,string"`
	Following bool  `json:"following"`
	//ShowingReblogs      bool  `json:"showing_reblogs"` // Incoherent type
	FollowedBy          bool `json:"followed_by"`
	Blocking            bool `json:"blocking"`
	Muting              bool `json:"muting"`
	Requested           bool `json:"requested"`
	DomainBlocking      bool `jsin:"domain_blocking"`
	MutingNotifications bool `json:"muting_notifications"`
}

Relationship represents a Mastodon relationship entity

type Report

type Report struct {
	ID          int64  `json:"id,string"`
	ActionTaken string `json:"action_taken"`
}

Report represents a Mastodon report entity

type Results

type Results struct {
	Accounts []Account `json:"accounts"`
	Statuses []Status  `json:"statuses"`
	Hashtags []string  `json:"hashtags"`
}

Results represents a Mastodon search results entity

type Status

type Status struct {
	ID                 int64        `json:"id,string"`
	URI                string       `json:"uri"`
	URL                string       `json:"url"`
	Account            *Account     `json:"account"`
	InReplyToID        *int64       `json:"in_reply_to_id,string"`
	InReplyToAccountID *int64       `json:"in_reply_to_account_id,string"`
	Reblog             *Status      `json:"reblog"`
	Content            string       `json:"content"`
	CreatedAt          time.Time    `json:"created_at"`
	ReblogsCount       int64        `json:"reblogs_count"`
	FavouritesCount    int64        `json:"favourites_count"`
	Reblogged          bool         `json:"reblogged"`
	Favourited         bool         `json:"favourited"`
	Muted              bool         `json:"muted"`
	Pinned             bool         `json:"pinned"`
	Sensitive          bool         `json:"sensitive"`
	SpoilerText        string       `json:"spoiler_text"`
	Visibility         string       `json:"visibility"`
	MediaAttachments   []Attachment `json:"media_attachments"`
	Mentions           []Mention    `json:"mentions"`
	Tags               []Tag        `json:"tags"`
	Emojis             []Emoji      `json:"emojis"`
	Application        *Application `json:"application"`
	Language           *string      `json:"language"`
}

Status represents a Mastodon status entity

type StreamEvent

type StreamEvent struct {
	Event string      // Name of the event (error, update, notification or delete)
	Data  interface{} // Status, Notification or status ID
	Error error       // Error message from the StreamListener
}

StreamEvent contains a single event from the streaming API

type Tag

type Tag struct {
	Name string `json:"name"`
	URL  string `json:"url"`
}

Tag represents a Mastodon tag entity

type UserToken

type UserToken struct {
	AccessToken string `json:"access_token"`
	CreatedAt   int64  `json:"created_at"`
	Scope       string `json:"scope"`
	TokenType   string `json:"token_type"`
}

UserToken represents a user token as returned by the Mastodon API

type WeekActivity

type WeekActivity struct {
	Week          ActivityTime `json:"week"`
	Statuses      int64        `json:"statuses,string"`
	Logins        int64        `json:"logins,string"`
	Registrations int64        `json:"registrations,string"`
}

WeekActivity represents a Mastodon instance activity "week" entity

Jump to

Keyboard shortcuts

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