pmapi

package
v1.6.3 Latest Latest
Warning

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

Go to latest
Published: Feb 10, 2021 License: GPL-3.0 Imports: 44 Imported by: 8

Documentation

Index

Constants

View Source
const (
	DisabledAddress = iota
	EnabledAddress
)

Address statuses.

View Source
const (
	CannotReceive = iota
	CanReceive
)

Address receive values.

View Source
const (
	MissingKeys = iota
	KeysPresent
)

Address HasKeys values.

View Source
const (
	OriginalAddress
	AliasAddress
	CustomAddress
	PremiumAddress
)

Address types.

View Source
const (
	NoSendAddress = iota
	MainSendAddress
	SecondarySendAddress
)

Address Send values.

View Source
const (
	EmailClientType = iota + 1
	VPNClientType
)

ClientType is required by API.

View Source
const (
	ForceUpgradeBadAppVersion = 5003
	APIOffline                = 7001
	ImportMessageTooLong      = 36022
	BansRequests              = 85131
)

API return codes.

View Source
const (
	CardEncrypted = 1
	CardSigned    = 2
)
View Source
const (
	EventRefreshMail    = 1
	EventRefreshContact = 2
	EventRefreshAll     = 255
)

Flags for event refresh.

View Source
const (
	UseToVerifyFlag = 1 << iota
	UseToEncryptFlag
)

Flags

View Source
const (
	RecipientInternal = 1
	RecipientExternal = 2
)
View Source
const (
	InboxLabel     = "0"
	AllDraftsLabel = "1"
	AllSentLabel   = "2"
	TrashLabel     = "3"
	SpamLabel      = "4"
	AllMailLabel   = "5"
	ArchiveLabel   = "6"
	SentLabel      = "7"
	DraftLabel     = "8"
	StarredLabel   = "10"

	LabelTypeMailbox      = 1
	LabelTypeContactGroup = 2
)

System labels

View Source
const (
	DraftActionReply    = 0
	DraftActionReplyAll = 1
	DraftActionForward  = 2
)

Draft actions

View Source
const (
	InternalPackage         = PackageFlag(1)
	EncryptedOutsidePackage = PackageFlag(2)
	ClearPackage            = PackageFlag(4)
	PGPInlinePackage        = PackageFlag(8)
	PGPMIMEPackage          = PackageFlag(16)
	ClearMIMEPackage        = PackageFlag(32)
)

Send message package types.

View Source
const (
	SignatureNone            = SignatureFlag(0)
	SignatureDetached        = SignatureFlag(1)
	SignatureAttachedArmored = SignatureFlag(2)
)

Send signature types.

View Source
const (
	MessageHeader       = "-----BEGIN PGP MESSAGE-----"
	MessageTail         = "-----END PGP MESSAGE-----"
	MessageHeaderLegacy = "---BEGIN ENCRYPTED MESSAGE---"
	MessageTailLegacy   = "---END ENCRYPTED MESSAGE---"
	RandomKeyHeader     = "---BEGIN ENCRYPTED RANDOM KEY---"
	RandomKeyTail       = "---END ENCRYPTED RANDOM KEY---"
)

Header types.

View Source
const (
	SortByTo      = "To"
	SortByFrom    = "From"
	SortBySubject = "Subject"
	SortBySize    = "Size"
	SortByTime    = "Time"
	SortByID      = "ID"
	SortDesc      = true
	SortAsc       = false
)

Sort types.

View Source
const (
	ActionReply    = 0
	ActionReplyAll = 1
	ActionForward  = 2
)

Message actions.

View Source
const (
	FlagReceived   = 1
	FlagSent       = 2
	FlagInternal   = 4
	FlagE2E        = 8
	FlagAuto       = 16
	FlagReplied    = 32
	FlagRepliedAll = 64
	FlagForwarded  = 128

	FlagAutoreplied = 256
	FlagImported    = 512
	FlagOpened      = 1024
	FlagReceiptSent = 2048
)

Message flag definitions.

View Source
const (
	FlagReceiptRequest = 1 << 16
	FlagPublicKey      = 1 << 17
	FlagSign           = 1 << 18
)

Draft flags.

View Source
const (
	FlagSpfFail        = 1 << 24
	FlagDkimFail       = 1 << 25
	FlagDmarcFail      = 1 << 26
	FlagHamManual      = 1 << 27
	FlagSpamAuto       = 1 << 28
	FlagSpamManual     = 1 << 29
	FlagPhishingAuto   = 1 << 30
	FlagPhishingManual = 1 << 31
)

Spam flags.

View Source
const (
	FlagMaskGeneral = 4095
	FlagMaskDraft   = FlagReceiptRequest * 7
	FlagMaskSpam    = FlagSpfFail * 255
	FlagMask        = FlagMaskGeneral | FlagMaskDraft | FlagMaskSpam
)

Message flag masks.

View Source
const (
	ContentTypeMultipartMixed     = "multipart/mixed"
	ContentTypeMultipartEncrypted = "multipart/encrypted"
	ContentTypePlainText          = "text/plain"
	ContentTypeHTML               = "text/html"
)

Content types.

View Source
const (
	MessageTypeInbox int = iota
	MessageTypeDraft
	MessageTypeSent
	MessageTypeInboxAndSent
)
View Source
const (
	FreeUserRole = iota
	PaidMemberRole
	PaidAdminRole
)

Role values.

View Source
const (
	DeletedUser  = 0
	DisabledUser = 1
	ActiveUser   = 2
	VPNAdminUser = 3
	AdminUser    = 4
	SuperUser    = 5
)

User status

View Source
const (
	CurrentUser = iota
	AvailableUser
	OverdueUser
	DelinquentUser
	NoReceiveUser
)

Delinquent values.

View Source
const (
	PMSignatureDisabled = iota
	PMSignatureEnabled
	PMSignatureLocked
)

PMSignature values.

View Source
const (
	CodeOk = 1000
)

Common response codes.

View Source
const ConversationIDDomain = `protonmail.conversationid`

ConversationIDDomain is used as a placeholder for conversation reference headers to improve compatibility with various clients.

View Source
const (
	FlagMaskAdd = 4067 + (16777216 * 168)
)

INTERNAL, AUTO are immutable. E2E is immutable except for drafts on send.

View Source
const (
	ImportMessageTooLarge = 36022
)

Import errors.

View Source
const InternalIDDomain = `protonmail.internalid`

InternalIDDomain is used as a placeholder for reference/message ID headers to improve compatibility with various clients.

View Source
const TLSReportURI = "https://reports.protonmail.ch/reports/tls"

TLSReportURI is the address where TLS reports should be sent.

View Source
const Version = 3

Version of the API.

Variables

View Source
var (
	ErrInvalidToken       = errors.New("refresh token invalid")
	ErrAPINotReachable    = errors.New("cannot reach the server")
	ErrUpgradeApplication = errors.New("application upgrade required")
	ErrConnectionSlow     = errors.New("request canceled because connection speed was too slow")
)

The output errors.

View Source
var ErrBad2FACode = errors.New("incorrect 2FA code")
View Source
var ErrBad2FACodeTryAgain = errors.New("incorrect 2FA code: please try again")
View Source
var ErrNoInternetConnection = errors.New("no internet connection")

ErrNoInternetConnection indicates that both protonstatus and the API are unreachable.

View Source
var ErrNoKeyringAvailable = errors.New("no keyring available")

ErrNoKeyringAvailable represents an error caused by a keyring being nil or having no entities.

View Source
var ErrTLSMismatch = errors.New("no TLS fingerprint match found")

ErrTLSMismatch indicates that no TLS fingerprint match could be found.

View Source
var LabelColors = []string{
	"#7272a7",
	"#cf5858",
	"#c26cc7",
	"#7569d1",
	"#69a9d1",
	"#5ec7b7",
	"#72bb75",
	"#c3d261",
	"#e6c04c",
	"#e6984c",
	"#8989ac",
	"#cf7e7e",
	"#c793ca",
	"#9b94d1",
	"#a8c4d5",
	"#97c9c1",
	"#9db99f",
	"#c6cd97",
	"#e7d292",
	"#dfb286",
}

LabelColors provides the RGB values of the available label colors.

View Source
var RxInternalReferenceFormat = regexp.MustCompile(`(?U)<(.+)@` + regexp.QuoteMeta(InternalIDDomain) + `>`) //nolint[gochecknoglobals]

RxInternalReferenceFormat is compiled regexp which describes the match for a message ID used in reference headers.

View Source
var TrustedAPIPins = []string{

	`pin-sha256="drtmcR2kFkM8qJClsuWgUzxgBkePfRCkRpqUesyDmeE="`,
	`pin-sha256="YRGlaY0jyJ4Jw2/4M8FIftwbDIQfh8Sdro96CeEel54="`,
	`pin-sha256="AfMENBVvOS8MnISprtvyPsjKlPooqh8nMB/pvCrpJpw="`,

	`pin-sha256="8joiNBdqaYiQpKskgtkJsqRxF7zN0C0aqfi8DacknnI="`,
	`pin-sha256="JMI8yrbc6jB1FYGyyWRLFTmDNgIszrNEMGlgy972e7w="`,
	`pin-sha256="Iu44zU84EOCZ9vx/vz67/MRVrxF1IO4i4NIa8ETwiIY="`,

	`pin-sha256="EU6TS9MO0L/GsDHvVc9D5fChYLNy5JdGYpJw0ccgetM="`,
	`pin-sha256="iKPIHPnDNqdkvOnTClQ8zQAIKG0XavaPkcEo0LBAABA="`,
	`pin-sha256="MSlVrBCdL0hKyczvgYVSRNm88RicyY04Q2y5qrBt0xA="`,
	`pin-sha256="C2UxW0T1Ckl9s+8cXfjXxlEqwAfPM4HiW2y3UdtBeCw="`,
}

TrustedAPIPins contains trusted public keys of the protonmail API and proxies. NOTE: the proxy pins are the same for all proxy servers, guaranteed by infra team ;)

Functions

func CheckConnection

func CheckConnection() error

CheckConnection returns an error if there is no internet connection.

func ComputeMessageFlagsByLabels

func ComputeMessageFlagsByLabels(labels []string) (flag int64)

ComputeMessageFlagsByLabels returns flags based on labels.

func ConstructAddress

func ConstructAddress(headerEmail string, addressEmail string) string

func CreateTransportWithDialer

func CreateTransportWithDialer(dialer TLSDialer) *http.Transport

CreateTransportWithDialer creates an http.Transport that uses the given dialer to make TLS connections.

func GetRoundTripper added in v1.6.3

func GetRoundTripper(cm *ClientManager, listener listener.Listener) http.RoundTripper

func HashMailboxPassword

func HashMailboxPassword(password, salt string) (hashedPassword string, err error)

func IsSystemLabel

func IsSystemLabel(label string) bool

IsSystemLabel checks if a label is a pre-defined system label.

func LeastUsedColor

func LeastUsedColor(colors []string) (color string)

LeastUsedColor is intended to return color for creating a new inbox or label

func SanitizeEmail

func SanitizeEmail(email string) string

Types

type AddContactsReq

type AddContactsReq struct {
	ContactsCards
	Overwrite int
	Groups    int
	Labels    int
}

type AddContactsResponse

type AddContactsResponse struct {
	Res
	Responses []IndexedContactResponse
}

type Address

type Address struct {
	ID          string
	DomainID    string
	Email       string
	Send        int
	Receive     int
	Status      int
	Order       int `json:",omitempty"`
	Type        int
	DisplayName string
	Signature   string
	MemberID    string `json:",omitempty"`
	MemberName  string `json:",omitempty"`

	HasKeys int
	Keys    PMKeys
}

Address represents a user's address.

type AddressList

type AddressList []*Address

AddressList is a list of addresses.

func (AddressList) ActiveEmails

func (l AddressList) ActiveEmails() (addresses []string)

ActiveEmails returns only active emails.

func (AddressList) AllEmails

func (l AddressList) AllEmails() (addresses []string)

AllEmails returns all emails.

func (AddressList) ByEmail

func (l AddressList) ByEmail(email string) *Address

ByEmail gets an address by email. Returns nil if no address is found.

func (AddressList) ByID

func (l AddressList) ByID(id string) *Address

ByID returns an address by id. Returns nil if no address is found.

func (AddressList) Main

func (l AddressList) Main() *Address

Main gets the main address.

type AddressesRes

type AddressesRes struct {
	Res
	Addresses AddressList
}

type AlgoKey

type AlgoKey struct {
	Key       string
	Algorithm string
}

type Attachment

type Attachment struct {
	ID         string `json:",omitempty"`
	MessageID  string `json:",omitempty"` // msg v3 ???
	Name       string `json:",omitempty"`
	Size       int64  `json:",omitempty"`
	MIMEType   string `json:",omitempty"`
	ContentID  string `json:",omitempty"`
	KeyPackets string `json:",omitempty"`
	Signature  string `json:",omitempty"`

	Header textproto.MIMEHeader `json:"-"`
}

Attachment represents a message attachment.

func (*Attachment) Decrypt

func (a *Attachment) Decrypt(r io.Reader, kr *crypto.KeyRing) (decrypted io.Reader, err error)

Decrypt decrypts this attachment's data from r using the keys from kr.

func (*Attachment) DetachedSign

func (a *Attachment) DetachedSign(kr *crypto.KeyRing, att io.Reader) (signed io.Reader, err error)

func (*Attachment) Encrypt

func (a *Attachment) Encrypt(kr *crypto.KeyRing, att io.Reader) (encrypted io.Reader, err error)

Encrypt encrypts an attachment.

func (*Attachment) MarshalJSON

func (a *Attachment) MarshalJSON() ([]byte, error)

func (*Attachment) UnmarshalJSON

func (a *Attachment) UnmarshalJSON(b []byte) error

type Auth

type Auth struct {
	ExpiresIn int

	RefreshToken string
	EventID      string
	PasswordMode int
	TwoFA        *TwoFactorInfo `json:"2FA,omitempty"`
	// contains filtered or unexported fields
}

Auth contains data after a successful authentication. It should be provided to Client.Unlock().

func (*Auth) DANGEROUSLYSetUID

func (s *Auth) DANGEROUSLYSetUID(uid string)

DANGEROUSLYSetUID SHOULD NOT be used!!! This is only for testing purposes.

func (*Auth) GenToken

func (s *Auth) GenToken() string

GenToken generates a string token containing the session UID and refresh token.

func (*Auth) HasMailboxPassword

func (s *Auth) HasMailboxPassword() bool

func (*Auth) HasTwoFactor

func (s *Auth) HasTwoFactor() bool

func (*Auth) UID

func (s *Auth) UID() string

UID returns the session UID from the Auth. Only Auths generated from the /auth route will have the UID. Auths generated from /auth/refresh are not required to.

type Auth2FAReq

type Auth2FAReq struct {
	TwoFactorCode string
}

type Auth2FARes

type Auth2FARes struct {
	Res
}

type AuthInfo

type AuthInfo struct {
	TwoFA *TwoFactorInfo `json:"2FA,omitempty"`
	// contains filtered or unexported fields
}

AuthInfo contains data used when authenticating a user. It should be provided to Client.Auth(). Each AuthInfo can be used for only one login attempt.

func (*AuthInfo) HasTwoFactor

func (a *AuthInfo) HasTwoFactor() bool

type AuthInfoReq

type AuthInfoReq struct {
	Username string
}

type AuthInfoRes

type AuthInfoRes struct {
	Res
	AuthInfo

	Modulus         string
	ServerEphemeral string
	Version         int
	Salt            string
	SRPSession      string
}

type AuthRefreshReq

type AuthRefreshReq struct {
	ResponseType string
	GrantType    string
	RefreshToken string
	UID          string
	RedirectURI  string
	State        string
}

type AuthReq

type AuthReq struct {
	Username        string
	ClientProof     string
	ClientEphemeral string
	SRPSession      string
}

type AuthRes

type AuthRes struct {
	Res
	Auth

	AccessToken string
	TokenType   string

	// UID is the session UID. This is only present in an initial Auth (/auth), not in a refreshed Auth (/auth/refresh).
	UID string

	ServerProof string
}

type BasicTLSDialer

type BasicTLSDialer struct{}

BasicTLSDialer implements TLSDialer.

func NewBasicTLSDialer

func NewBasicTLSDialer() *BasicTLSDialer

NewBasicTLSDialer returns a new BasicTLSDialer.

func (*BasicTLSDialer) DialTLS

func (b *BasicTLSDialer) DialTLS(network, address string) (conn net.Conn, err error)

DialTLS returns a connection to the given address using the given network.

type Card

type Card struct {
	Type      int
	Data      string
	Signature string
}

type CardsList

type CardsList struct {
	Cards []Card
}

type Client

type Client interface {
	Auth(username, password string, info *AuthInfo) (*Auth, error)
	AuthInfo(username string) (*AuthInfo, error)
	AuthRefresh(token string) (*Auth, error)
	Auth2FA(twoFactorCode string, auth *Auth) error
	AuthSalt() (salt string, err error)
	Logout()
	DeleteAuth() error
	IsConnected() bool
	CloseConnections()
	ClearData()

	CurrentUser() (*User, error)
	UpdateUser() (*User, error)
	Unlock(passphrase []byte) (err error)
	ReloadKeys(passphrase []byte) (err error)
	IsUnlocked() bool

	GetAddresses() (addresses AddressList, err error)
	Addresses() AddressList
	ReorderAddresses(addressIDs []string) error

	GetEvent(eventID string) (*Event, error)

	SendMessage(string, *SendMessageReq) (sent, parent *Message, err error)
	CreateDraft(m *Message, parent string, action int) (created *Message, err error)
	Import([]*ImportMsgReq) ([]*ImportMsgRes, error)

	CountMessages(addressID string) ([]*MessagesCount, error)
	ListMessages(filter *MessagesFilter) ([]*Message, int, error)
	GetMessage(apiID string) (*Message, error)
	DeleteMessages(apiIDs []string) error
	LabelMessages(apiIDs []string, labelID string) error
	UnlabelMessages(apiIDs []string, labelID string) error
	MarkMessagesRead(apiIDs []string) error
	MarkMessagesUnread(apiIDs []string) error

	ListLabels() ([]*Label, error)
	CreateLabel(label *Label) (*Label, error)
	UpdateLabel(label *Label) (*Label, error)
	DeleteLabel(labelID string) error
	EmptyFolder(labelID string, addressID string) error

	Report(report ReportReq) error
	SendSimpleMetric(category, action, label string) error

	GetMailSettings() (MailSettings, error)
	GetContactEmailByEmail(string, int, int) ([]ContactEmail, error)
	GetContactByID(string) (Contact, error)
	DecryptAndVerifyCards([]Card) ([]Card, error)

	GetAttachment(id string) (att io.ReadCloser, err error)
	CreateAttachment(att *Attachment, r io.Reader, sig io.Reader) (created *Attachment, err error)
	DeleteAttachment(attID string) (err error)

	KeyRingForAddressID(string) (kr *crypto.KeyRing, err error)
	GetPublicKeysForEmail(string) ([]PublicKey, bool, error)

	DownloadAndVerify(string, string, *crypto.KeyRing) (io.Reader, error)
}

Client defines the interface of a PMAPI client.

type ClientAuth

type ClientAuth struct {
	UserID string
	Auth   *Auth
}

ClientAuth holds an API auth produced by a Client for a specific user.

type ClientConfig

type ClientConfig struct {
	// The client application name and version.
	AppVersion string

	// The client application user agent in format `client name/client version (os)`, e.g.:
	// (Intel Mac OS X 10_15_3)
	// Mac OS X Mail/13.0 (3608.60.0.2.5) (Intel Mac OS X 10_15_3)
	// Thunderbird/1.5.0 (Ubuntu 18.04.4 LTS)
	// MSOffice 12 (Windows 10 (10.0))
	UserAgent string

	// The client ID.
	ClientID string

	// Timeout is the timeout of the full request. It is passed to http.Client.
	// If it is left unset, it means no timeout is applied.
	Timeout time.Duration

	// FirstReadTimeout specifies the timeout from getting response to the first read of body response.
	// This timeout is applied only when MinBytesPerSecond is used.
	// Default is 5 minutes.
	FirstReadTimeout time.Duration

	// MinBytesPerSecond specifies minimum Bytes per second or the request will be canceled.
	// Zero means no limitation.
	MinBytesPerSecond int64

	ConnectionOnHandler       func()
	ConnectionOffHandler      func()
	UpgradeApplicationHandler func()
}

ClientConfig contains Client configuration.

func GetAPIConfig added in v1.6.3

func GetAPIConfig(configName, appVersion string) *ClientConfig

type ClientManager

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

ClientManager is a manager of clients.

func NewClientManager

func NewClientManager(config *ClientConfig) (cm *ClientManager)

NewClientManager creates a new ClientMan which manages clients configured with the given client config.

func (*ClientManager) AllowProxy

func (cm *ClientManager) AllowProxy()

AllowProxy allows the client manager to switch clients over to a proxy if need be.

func (*ClientManager) CheckConnection

func (cm *ClientManager) CheckConnection() error

CheckConnection returns an error if there is no internet connection. This should be moved to the ConnectionManager when it is implemented.

func (*ClientManager) DisallowProxy

func (cm *ClientManager) DisallowProxy()

DisallowProxy prevents the client manager from switching clients over to a proxy if need be.

func (*ClientManager) GetAnonymousClient

func (cm *ClientManager) GetAnonymousClient() Client

GetAnonymousClient returns an anonymous client.

func (*ClientManager) GetAuthUpdateChannel

func (cm *ClientManager) GetAuthUpdateChannel() chan ClientAuth

GetAuthUpdateChannel returns a channel on which client auths can be received.

func (*ClientManager) GetClient

func (cm *ClientManager) GetClient(userID string) Client

GetClient returns a client for the given userID. If the client does not exist already, it is created.

func (*ClientManager) GetClientConfig added in v1.6.3

func (cm *ClientManager) GetClientConfig() *ClientConfig

func (*ClientManager) GetRootURL

func (cm *ClientManager) GetRootURL() string

GetRootURL returns the full root URL (scheme+host).

func (*ClientManager) GetToken

func (cm *ClientManager) GetToken(userID string) string

GetToken returns the token for the given userID.

func (*ClientManager) GetUserAgent added in v1.6.3

func (cm *ClientManager) GetUserAgent() string

func (*ClientManager) HandleAuth

func (cm *ClientManager) HandleAuth(ca ClientAuth)

HandleAuth updates or clears client authorisation based on auths received and then forwards the auth onwards.

func (*ClientManager) IsProxyAllowed

func (cm *ClientManager) IsProxyAllowed() bool

IsProxyAllowed returns whether the user has allowed us to switch to a proxy if need be.

func (*ClientManager) IsProxyEnabled

func (cm *ClientManager) IsProxyEnabled() bool

IsProxyEnabled returns whether we are currently proxying requests.

func (*ClientManager) LogoutClient

func (cm *ClientManager) LogoutClient(userID string)

LogoutClient logs out the client with the given userID and ensures its sensitive data is successfully cleared.

func (*ClientManager) SetClientConstructor

func (cm *ClientManager) SetClientConstructor(f func(userID string) Client)

SetClientConstructor sets the method used to construct clients. By default this is `pmapi.newClient` but can be overridden with this method.

func (*ClientManager) SetCookieJar

func (cm *ClientManager) SetCookieJar(jar http.CookieJar)

SetCookieJar sets the cookie jar given to clients.

func (*ClientManager) SetRoundTripper

func (cm *ClientManager) SetRoundTripper(rt http.RoundTripper)

SetRoundTripper sets the roundtripper used by clients created by this client manager.

func (*ClientManager) SetUserAgent

func (cm *ClientManager) SetUserAgent(clientName, clientVersion, os string)

type ConnectionReporter

type ConnectionReporter interface {
	NotifyConnectionLost() error
}

ConnectionReporter provides a way to report when internet connection is lost.

type Contact

type Contact struct {
	ID         string
	Name       string
	UID        string
	Size       int64
	CreateTime int64
	ModifyTime int64
	LabelIDs   []string

	ContactEmails []ContactEmail
	Cards         []Card
}

type ContactEmail

type ContactEmail struct {
	ID        string
	Name      string
	Email     string
	Type      []string
	Defaults  int
	Order     int
	ContactID string
	LabelIDs  []string
}

type ContactsCards

type ContactsCards struct {
	Contacts []CardsList
}

type ContactsEmailsRes

type ContactsEmailsRes struct {
	Res
	ContactEmails []ContactEmail
	Total         int
}

type ContactsListRes

type ContactsListRes struct {
	Res
	Contacts []*Contact
}

type Conversation

type Conversation struct{}

Conversation contains one body and multiple metadata.

type ConversationsCount

type ConversationsCount MessagesCount

ConversationsCount have same structure as MessagesCount.

type ConversationsCountsRes

type ConversationsCountsRes struct {
	Res

	Counts []*ConversationsCount
}

ConversationsCountsRes holds response from server.

type CreateAttachmentRes

type CreateAttachmentRes struct {
	Res

	Attachment *Attachment
}

type DeleteReq

type DeleteReq struct {
	IDs []string
}

type DraftReq

type DraftReq struct {
	Message              *Message
	ParentID             string `json:",omitempty"`
	Action               int
	AttachmentKeyPackets []string
}

DraftReq defines paylod for creating drafts

type ErrUnauthorized

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

func (*ErrUnauthorized) Error

func (err *ErrUnauthorized) Error() string

type ErrUnprocessableEntity

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

func (*ErrUnprocessableEntity) Error

func (err *ErrUnprocessableEntity) Error() string

type Error

type Error struct {
	// The error code.
	Code int
	// The error message.
	ErrorMessage string `json:"Error"`
}

Error is an API error.

func (Error) Error

func (err Error) Error() string

type Event

type Event struct {
	// The current event ID.
	EventID string
	// If set to one, all cached data must be fetched again.
	Refresh int
	// If set to one, fetch more events.
	More int
	// Changes applied to messages.
	Messages []*EventMessage
	// Counts of messages per labels.
	MessageCounts []*MessagesCount
	// Changes applied to labels.
	Labels []*EventLabel
	// Current user status.
	User User
	// Changes to addresses.
	Addresses []*EventAddress
	// Messages to show to the user.
	Notices []string
}

Event represents changes since the last check.

type EventAction

type EventAction int

EventAction is the action that created a change.

const (
	EventDelete      EventAction = iota // Item has been deleted.
	EventCreate                         // Item has been created.
	EventUpdate                         // Item has been updated.
	EventUpdateFlags                    // For messages: flags have been updated.
)

type EventAddress

type EventAddress struct {
	EventItem
	Address *Address
}

EventAddress is an address that has changed.

type EventItem

type EventItem struct {
	ID     string
	Action EventAction
}

EventItem is an item that has changed.

type EventLabel

type EventLabel struct {
	EventItem
	Label *Label
}

EventLabel is a label that has changed.

type EventMessage

type EventMessage struct {
	EventItem

	// If the message has been created, the new message.
	Created *Message `json:"-"`
	// If the message has been updated, the updated fields.
	Updated *EventMessageUpdated `json:"-"`
}

EventMessage is a message that has changed.

func (*EventMessage) MarshalJSON

func (em *EventMessage) MarshalJSON() ([]byte, error)

func (*EventMessage) UnmarshalJSON

func (em *EventMessage) UnmarshalJSON(b []byte) (err error)

type EventMessageUpdated

type EventMessageUpdated struct {
	ID string

	Subject *string
	Unread  *int
	Flags   *int64
	Sender  *mail.Address
	ToList  *[]*mail.Address
	CCList  *[]*mail.Address
	BCCList *[]*mail.Address
	Time    int64

	// Fields only present for EventUpdateFlags.
	LabelIDs        []string
	LabelIDsAdded   []string
	LabelIDsRemoved []string
}

EventMessageUpdated contains changed fields for an updated message.

type EventRes

type EventRes struct {
	Res
	*Event
}

type ImportMsgReq

type ImportMsgReq struct {
	// The address where the message will be imported.
	AddressID string
	// The full MIME message.
	Body []byte `json:"-"`

	// 0: read, 1: unread.
	Unread int
	// 1 if the message has been replied.
	IsReplied int
	// 1 if the message has been replied to all.
	IsRepliedAll int
	// 1 if the message has been forwarded.
	IsForwarded int
	// The time when the message was received as a Unix time.
	Time int64
	// The type of the imported message.
	Flags int64
	// The labels to apply to the imported message. Must contain at least one system label.
	LabelIDs []string
}

ImportMsgReq is a request to import a message. All fields are optional except AddressID and Body.

func (ImportMsgReq) String

func (req ImportMsgReq) String() string

type ImportMsgRes

type ImportMsgRes struct {
	// The error encountered while importing the message, if any.
	Error error
	// The newly created message ID.
	MessageID string
}

ImportMsgRes is a response to a single message import request.

type ImportReq

type ImportReq struct {
	// A list of messages that will be imported.
	Messages []*ImportMsgReq
}

ImportReq is an import request.

func (*ImportReq) WriteTo

func (req *ImportReq) WriteTo(w *multipart.Writer) (err error)

WriteTo writes the import request to a multipart writer.

type ImportRes

type ImportRes struct {
	Res

	Responses []struct {
		Name     string
		Response struct {
			Res
			MessageID string
		}
	}
}

ImportRes is a response to an import request.

type IndexedContactResponse

type IndexedContactResponse struct {
	Index    int
	Response SingleContactResponse
}

type KeySalt

type KeySalt struct {
	ID, KeySalt string
}

KeySalt contains id and salt for key.

type KeySaltRes

type KeySaltRes struct {
	Res
	KeySalts []KeySalt
}

KeySaltRes is used to unmarshal API response.

type Label

type Label struct {
	ID        string
	Name      string
	Path      string
	Color     string
	Order     int `json:",omitempty"`
	Display   int // Not used for now, leave it empty.
	Exclusive int
	Type      int
	Notify    int
}

Label for message.

type LabelAction

type LabelAction int
const (
	RemoveLabel LabelAction = iota
	AddLabel
)

type LabelListRes

type LabelListRes struct {
	Res
	Labels []*Label
}

type LabelMessagesReq

type LabelMessagesReq struct {
	LabelID string
	IDs     []string
}

type LabelReq

type LabelReq struct {
	*Label
}

type LabelRes

type LabelRes struct {
	Res
	Label *Label
}

type LabelsOperation

type LabelsOperation int

LabelsOperation is the operation to apply to labels.

const (
	KeepLabels    LabelsOperation = iota // Do nothing.
	ReplaceLabels                        // Replace current labels with new ones.
	AddLabels                            // Add new labels to current ones.
	RemoveLabels                         // Remove specified labels from current ones.
)

type LatestEventRes

type LatestEventRes struct {
	Res
	*Event
}

type MailSettings

type MailSettings struct {
	DisplayName        string
	Signature          string `json:",omitempty"`
	Theme              string `json:",omitempty"`
	AutoSaveContacts   int
	AutoWildcardSearch int
	ComposerMode       int
	MessageButtons     int
	ShowImages         int
	ShowMoved          int
	ViewMode           int
	ViewLayout         int
	SwipeLeft          int
	SwipeRight         int
	AlsoArchive        int
	Hotkeys            int
	PMSignature        int
	ImageProxy         int
	TLS                int
	RightToLeft        int
	AttachPublicKey    int
	Sign               int
	PGPScheme          PackageFlag
	PromptPin          int
	Autocrypt          int
	NumMessagePerPage  int
	DraftMIMEType      string
	ReceiveMIMEType    string
	ShowMIMEType       string
}

type Message

type Message struct {
	ID             string `json:",omitempty"`
	Order          int64  `json:",omitempty"`
	ConversationID string `json:",omitempty"` // only filter
	Subject        string
	Unread         int
	Type           int
	Flags          int64
	Sender         *mail.Address
	ReplyTo        *mail.Address   `json:",omitempty"`
	ReplyTos       []*mail.Address `json:",omitempty"`
	ToList         []*mail.Address
	CCList         []*mail.Address
	BCCList        []*mail.Address
	Time           int64 // Unix time
	Size           int64
	NumAttachments int
	ExpirationTime int64 // Unix time
	SpamScore      int
	AddressID      string
	Body           string `json:",omitempty"`
	Attachments    []*Attachment
	LabelIDs       []string
	ExternalID     string
	Header         mail.Header
	MIMEType       string
}

Message structure.

func NewMessage

func NewMessage() *Message

NewMessage initializes a new message.

func (*Message) Decrypt

func (m *Message) Decrypt(kr *crypto.KeyRing) (err error)

func (*Message) DecryptLegacy

func (m *Message) DecryptLegacy(kr *crypto.KeyRing) (err error)

func (*Message) Encrypt

func (m *Message) Encrypt(encrypter, signer *crypto.KeyRing) (err error)

func (*Message) Has

func (m *Message) Has(flag int64) bool

func (*Message) HasLabelID

func (m *Message) HasLabelID(labelID string) bool

HasLabelID returns whether the message has the `labelID`.

func (*Message) IsBodyEncrypted

func (m *Message) IsBodyEncrypted() bool

func (*Message) IsDraft

func (m *Message) IsDraft() bool

IsDraft returns whether the message should be considered to be a draft. A draft is complicated. It might have pmapi.DraftLabel but it might not. The real API definition of IsDraft is that it is neither sent nor received -- we should use that here.

func (*Message) IsEncrypted

func (m *Message) IsEncrypted() bool

func (*Message) IsLegacyMessage

func (m *Message) IsLegacyMessage() bool

func (*Message) MarshalJSON

func (m *Message) MarshalJSON() ([]byte, error)

func (*Message) UnmarshalJSON

func (m *Message) UnmarshalJSON(b []byte) error

type MessageAddress

type MessageAddress struct {
	Type                          PackageFlag
	EncryptedBodyKeyPacket        string `json:"BodyKeyPacket,omitempty"` // base64-encoded key packet.
	Signature                     SignatureFlag
	EncryptedAttachmentKeyPackets map[string]string `json:"AttachmentKeyPackets,omitempty"`
}

type MessagePackage

type MessagePackage struct {
	Addresses               map[string]*MessageAddress
	Type                    PackageFlag
	MIMEType                string
	EncryptedBody           string             `json:"Body"`                     // base64-encoded encrypted data packet.
	DecryptedBodyKey        *AlgoKey           `json:"BodyKey,omitempty"`        // base64-encoded session key (only if cleartext recipients).
	DecryptedAttachmentKeys map[string]AlgoKey `json:"AttachmentKeys,omitempty"` // Only include if cleartext & attachments.
}

type MessageRes

type MessageRes struct {
	Res

	Message *Message
}

type MessagesActionReq

type MessagesActionReq struct {
	IDs []string
}

type MessagesActionRes

type MessagesActionRes struct {
	Res

	Responses []struct {
		ID       string
		Response Res
	}
}

func (MessagesActionRes) Err

func (res MessagesActionRes) Err() error

type MessagesCount

type MessagesCount struct {
	LabelID string
	Total   int
	Unread  int
}

MessagesCount contains message counts for one label.

type MessagesCountsRes

type MessagesCountsRes struct {
	Res

	Counts []*MessagesCount
}

type MessagesFilter

type MessagesFilter struct {
	Page           int
	PageSize       int
	Limit          int
	LabelID        string
	Sort           string // Time by default (Time, To, From, Subject, Size).
	Desc           *bool
	Begin          int64 // Unix time.
	End            int64 // Unix time.
	BeginID        string
	EndID          string
	Keyword        string
	To             string
	From           string
	Subject        string
	ConversationID string
	AddressID      string
	ID             []string
	Attachments    *bool
	Unread         *bool
	ExternalID     string // MIME Message-Id (only valid for messages).
	AutoWildcard   *bool
}

MessagesFilter contains fields to filter messages.

type MessagesListRes

type MessagesListRes struct {
	Res

	Total    int
	Messages []*Message
}

type ModifyContactGroupsReq

type ModifyContactGroupsReq struct {
	LabelID         string
	Action          int
	ContactEmailIDs []string
}

type MultipartWriter

type MultipartWriter struct {
	*multipart.Writer
	// contains filtered or unexported fields
}

func (*MultipartWriter) Close

func (w *MultipartWriter) Close() error

type PMKey

type PMKey struct {
	ID          string
	Version     int
	Flags       int
	Fingerprint string
	PrivateKey  *crypto.Key
	Primary     int
	Token       *string `json:",omitempty"`
	Signature   *string `json:",omitempty"`
}

func (*PMKey) UnmarshalJSON

func (key *PMKey) UnmarshalJSON(b []byte) (err error)

type PMKeys

type PMKeys []PMKey

func (*PMKeys) UnlockAll

func (keys *PMKeys) UnlockAll(passphrase []byte, userKey *crypto.KeyRing) (kr *crypto.KeyRing, err error)

UnlockAll goes through each key and unlocks it, returning a keyring containing all unlocked keys, or an error if no keys could be unlocked. The passphrase is used to unlock the key unless the key's token and signature are both non-nil, in which case the given userkey is used to deduce the passphrase.

type PackageFlag

type PackageFlag int

PackageFlag for send message package types

func (*PackageFlag) Has

func (p *PackageFlag) Has(flag PackageFlag) bool

func (*PackageFlag) HasAtLeastOne

func (p *PackageFlag) HasAtLeastOne(flag PackageFlag) bool

func (*PackageFlag) HasNo

func (p *PackageFlag) HasNo(flag PackageFlag) bool

func (*PackageFlag) Is

func (p *PackageFlag) Is(flag PackageFlag) bool

type PinningTLSDialer

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

PinningTLSDialer wraps a TLSDialer to check fingerprints after connecting and to report errors if the fingerprint check fails.

func NewPinningTLSDialer

func NewPinningTLSDialer(dialer TLSDialer) *PinningTLSDialer

NewPinningTLSDialer constructs a new dialer which only returns tcp connections to servers which present known certificates. If enabled, it reports any invalid certificates it finds.

func (*PinningTLSDialer) DialTLS

func (p *PinningTLSDialer) DialTLS(network, address string) (net.Conn, error)

DialTLS dials the given network/address, returning an error if the certificates don't match the trusted pins.

func (*PinningTLSDialer) EnableRemoteTLSIssueReporting

func (p *PinningTLSDialer) EnableRemoteTLSIssueReporting(cm *ClientManager)

func (*PinningTLSDialer) SetTLSIssueNotifier

func (p *PinningTLSDialer) SetTLSIssueNotifier(notifier func())

type ProxyTLSDialer

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

ProxyTLSDialer wraps a TLSDialer to switch to a proxy if the initial dial fails.

func NewProxyTLSDialer

func NewProxyTLSDialer(dialer TLSDialer, cm *ClientManager) *ProxyTLSDialer

NewProxyTLSDialer constructs a dialer which provides a proxy-managing layer on top of an underlying dialer.

func (*ProxyTLSDialer) DialTLS

func (d *ProxyTLSDialer) DialTLS(network, address string) (conn net.Conn, err error)

DialTLS dials the given network/address. If it fails, it retries using a proxy.

type PublicKey

type PublicKey struct {
	Flags     int
	PublicKey string
}

type PublicKeyRes

type PublicKeyRes struct {
	Res

	RecipientType int
	MIMEType      string
	Keys          []PublicKey
}

type ReportReq

type ReportReq struct {
	OS                string      `json:",omitempty"`
	OSVersion         string      `json:",omitempty"`
	Browser           string      `json:",omitempty"`
	BrowserVersion    string      `json:",omitempty"`
	BrowserExtensions string      `json:",omitempty"`
	Resolution        string      `json:",omitempty"`
	DisplayMode       string      `json:",omitempty"`
	Client            string      `json:",omitempty"`
	ClientVersion     string      `json:",omitempty"`
	ClientType        int         `json:",omitempty"`
	Title             string      `json:",omitempty"`
	Description       string      `json:",omitempty"`
	Username          string      `json:",omitempty"`
	Email             string      `json:",omitempty"`
	Country           string      `json:",omitempty"`
	ISP               string      `json:",omitempty"`
	Debug             string      `json:",omitempty"`
	Attachments       []reportAtt `json:",omitempty"`
}

ReportReq stores data for report.

func (*ReportReq) AddAttachment

func (rep *ReportReq) AddAttachment(name, filename string, r io.Reader)

AddAttachment to report.

type Res

type Res struct {
	// The response code is the code from the body JSON. It's still used,
	// but preference is to use HTTP status code instead for new changes.
	Code       int
	StatusCode int

	// The error, if there is any.
	*ResError
}

Res is an API response.

func (Res) Err

func (res Res) Err() error

Err returns error if the response is an error. Otherwise, returns nil.

type ResError

type ResError struct {
	Error string
}

type SendMessageReq

type SendMessageReq struct {
	ExpirationTime int64 `json:",omitempty"`

	// Data for encrypted recipients.
	Packages []*MessagePackage `json:",omitempty"`
	// contains filtered or unexported fields
}

func NewSendMessageReq

func NewSendMessageReq(
	kr *crypto.KeyRing,
	mimeBody, plainBody, richBody string,
	attKeys map[string]*crypto.SessionKey,
) *SendMessageReq

func (*SendMessageReq) AddRecipient

func (req *SendMessageReq) AddRecipient(
	email string, sendScheme PackageFlag,
	pubkey *crypto.KeyRing, signature SignatureFlag,
	contentType string, doEncrypt bool,
) (err error)

func (*SendMessageReq) PreparePackages

func (req *SendMessageReq) PreparePackages()

type SendMessageRes

type SendMessageRes struct {
	Res

	Sent *Message

	// Parent is only present if the sent message has a parent (reply/reply all/forward).
	Parent *Message
}

type SignatureFlag

type SignatureFlag int

SignatureFlag for send signature types.

func (*SignatureFlag) Has

func (p *SignatureFlag) Has(flag SignatureFlag) bool

func (*SignatureFlag) HasNo

func (p *SignatureFlag) HasNo(flag SignatureFlag) bool

func (*SignatureFlag) Is

func (p *SignatureFlag) Is(flag SignatureFlag) bool

type SingleContactResponse

type SingleContactResponse struct {
	Res
	Contact Contact
}

type SingleIDResponse

type SingleIDResponse struct {
	Res
	ID string
}

type TLSDialer

type TLSDialer interface {
	DialTLS(network, address string) (conn net.Conn, err error)
}

type TwoFactorInfo

type TwoFactorInfo struct {
	Enabled int // 0 for disabled, 1 for OTP, 2 for U2F, 3 for both.
	TOTP    int
	U2F     U2FInfo
}

type U2FInfo

type U2FInfo struct {
	Challenge      string
	RegisteredKeys []struct {
		Version   string
		KeyHandle string
	}
}

type UpdateAttachmentSignatureReq

type UpdateAttachmentSignatureReq struct {
	Signature string
}

type UpdateContactGroupsResponse

type UpdateContactGroupsResponse struct {
	Res
	Response SingleIDResponse
}

type UpdateContactReq

type UpdateContactReq struct {
	Cards []Card
}

type UpdateContactResponse

type UpdateContactResponse struct {
	Res
	Contact Contact
}

type User

type User struct {
	ID         string
	Name       string
	UsedSpace  int64
	Currency   string
	Credit     int
	MaxSpace   int64
	MaxUpload  int64
	Role       int
	Private    int
	Subscribed int
	Services   int
	Deliquent  int

	Keys PMKeys

	VPN struct {
		Status         int
		ExpirationTime int
		PlanName       string
		MaxConnect     int
		MaxTier        int
	}
}

User holds the user details.

type UserRes

type UserRes struct {
	Res

	User *User
}

UserRes holds structure of JSON response.

type UserSettings

type UserSettings struct {
	PasswordMode int
	Email        struct {
		Value  string
		Status int
		Notify int
		Reset  int
	}
	Phone struct {
		Value  string
		Status int
		Notify int
		Reset  int
	}
	News        int
	Locale      string
	LogAuth     string
	InvoiceText string
	TOTP        int
	U2FKeys     []struct {
		Label       string
		KeyHandle   string
		Compromised int
	}
}

Directories

Path Synopsis
Package mocks is a generated GoMock package.
Package mocks is a generated GoMock package.

Jump to

Keyboard shortcuts

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