pmapi

package
v2.2.1 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2022 License: GPL-3.0 Imports: 39 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DisabledAddress = iota
	EnabledAddress
)

Address statuses.

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 (
	DispositionInline     = "inline"
	DispositionAttachment = "attachment"
)
View Source
const (
	CardEncrypted = 1
	CardSigned    = 2
)
View Source
const (
	Quad9Provider     = "https://dns11.quad9.net/dns-query"
	Quad9PortProvider = "https://dns11.quad9.net:5053/dns-query"
	GoogleProvider    = "https://dns.google/dns-query"
)
View Source
const (
	EventRefreshMail    = 1
	EventRefreshContact = 2
	EventRefreshAll     = 255
)

Flags for event refresh.

View Source
const (
	MaxImportMessageRequestLength = 10
	MaxImportMessageRequestSize   = 25 * 1024 * 1024 // 25 MB total limit
)
View Source
const (
	UseToVerifyFlag = 1 << iota
	UseToEncryptFlag
)

Key flags.

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 (
	LabelTypeV4Label        = 1
	LabelTypeV4ContactGroup = 2
	LabelTypeV4Folder       = 3
)
View Source
const (
	EmailClientType = iota + 1
	VPNClientType
)

ClientType is required by API.

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   = int64(1)
	FlagSent       = int64(2)
	FlagInternal   = int64(4)
	FlagE2E        = int64(8)
	FlagAuto       = int64(16)
	FlagReplied    = int64(32)
	FlagRepliedAll = int64(64)
	FlagForwarded  = int64(128)

	FlagAutoreplied = int64(256)
	FlagImported    = int64(512)
	FlagOpened      = int64(1024)
	FlagReceiptSent = int64(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 (
	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 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 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.

Variables

View Source
var (
	ErrNoConnection       = errors.New("no internet connection")
	ErrUnauthorized       = errors.New("API client is unauthorized")
	ErrUpgradeApplication = errors.New("application upgrade required")

	ErrBad2FACode         = errors.New("incorrect 2FA code")
	ErrBad2FACodeTryAgain = errors.New("incorrect 2FA code: please try again")

	ErrPaidPlanRequired = errors.New("paid subscription plan is required")
	ErrPasswordWrong    = errors.New("wrong password")
)
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 ComputeMessageFlagsByLabels

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

ComputeMessageFlagsByLabels returns flags based on labels.

func ConstructAddress

func ConstructAddress(headerEmail string, addressEmail string) string

func ContextWithoutAuthRefresh

func ContextWithoutAuthRefresh(parent context.Context) context.Context

func ContextWithoutRetry

func ContextWithoutRetry(parent context.Context) context.Context

func CreateTransportWithDialer

func CreateTransportWithDialer(dialer TLSDialer) *http.Transport

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

func HashMailboxPassword

func HashMailboxPassword(password []byte, salt string) ([]byte, error)

HashMailboxPassword expectects 128bit long salt encoded by standard base64.

func IsBadRequest

func IsBadRequest(err error) bool

func IsFailedAuth

func IsFailedAuth(err error) bool

func IsFailedUnlock

func IsFailedUnlock(err error) bool

func IsSystemLabel

func IsSystemLabel(label string) bool

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

func IsUnprocessableEntity

func IsUnprocessableEntity(err error) bool

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 Address

type Address struct {
	ID          string
	DomainID    string
	Email       string
	Send        int
	Receive     Boolean
	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 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"`
	Disposition string
	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 {
	AuthRefresh

	UserID       string
	ServerProof  string
	PasswordMode PasswordMode
	TwoFA        *TwoFAInfo `json:"2FA,omitempty"`
}

func (Auth) HasMailboxPassword

func (a Auth) HasMailboxPassword() bool

func (Auth) HasTwoFactor

func (a Auth) HasTwoFactor() bool

type AuthInfo

type AuthInfo struct {
	Version         int
	Modulus         string
	ServerEphemeral string
	Salt            string
	SRPSession      string
}

type AuthModulus

type AuthModulus struct {
	Modulus   string
	ModulusID string
}

type AuthRefresh

type AuthRefresh struct {
	UID          string
	AccessToken  string
	RefreshToken string
	ExpiresIn    int64
	Scopes       []string
}

type AuthRefreshHandler

type AuthRefreshHandler func(*AuthRefresh)

type AuthReq

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

type BasicTLSDialer

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

BasicTLSDialer implements TLSDialer.

func NewBasicTLSDialer

func NewBasicTLSDialer(cfg Config) *BasicTLSDialer

NewBasicTLSDialer returns a new BasicTLSDialer.

func (*BasicTLSDialer) DialTLS

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

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

type Boolean

type Boolean bool

func (Boolean) MarshalJSON

func (boolean Boolean) MarshalJSON() ([]byte, error)

func (*Boolean) UnmarshalJSON

func (boolean *Boolean) UnmarshalJSON(b []byte) error

type Card

type Card struct {
	Type      int
	Data      string
	Signature string
}

type Client

type Client interface {
	Auth2FA(context.Context, string) error
	AuthSalt(ctx context.Context) (string, error)
	AuthDelete(context.Context) error
	AddAuthRefreshHandler(AuthRefreshHandler)

	GetUser(ctx context.Context) (*User, error)
	CurrentUser(ctx context.Context) (*User, error)
	UpdateUser(ctx context.Context) (*User, error)
	Unlock(ctx context.Context, passphrase []byte) (err error)
	ReloadKeys(ctx context.Context, passphrase []byte) (err error)
	IsUnlocked() bool

	Addresses() AddressList
	GetAddresses(context.Context) (addresses AddressList, err error)
	ReorderAddresses(ctx context.Context, addressIDs []string) error

	GetEvent(ctx context.Context, eventID string) (*Event, error)

	SendMessage(context.Context, string, *SendMessageReq) (sent, parent *Message, err error)
	CreateDraft(ctx context.Context, m *Message, parent string, action int) (created *Message, err error)
	Import(context.Context, ImportMsgReqs) ([]*ImportMsgRes, error)

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

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

	// /core/V4/labels routes
	ListLabelsOnly(ctx context.Context) ([]*Label, error)
	ListFoldersOnly(ctx context.Context) ([]*Label, error)
	CreateLabelV4(ctx context.Context, label *Label) (*Label, error)
	UpdateLabelV4(ctx context.Context, label *Label) (*Label, error)
	DeleteLabelV4(ctx context.Context, labelID string) error

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

	GetAttachment(ctx context.Context, id string) (att io.ReadCloser, err error)
	CreateAttachment(ctx context.Context, att *Attachment, r io.Reader, sig io.Reader) (created *Attachment, err error)

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

Client defines the interface of a PMAPI client.

type Config

type Config struct {
	// HostURL is the base URL of API.
	HostURL string

	// AppVersion sets version to headers of each request.
	AppVersion string

	// UserAgent sets user agent to headers of each request.
	// Used only if GetUserAgent is not set.
	UserAgent string

	// GetUserAgent is dynamic version of UserAgent.
	// Overrides UserAgent.
	GetUserAgent func() string

	// UpgradeApplicationHandler is used to notify when there is a force upgrade.
	UpgradeApplicationHandler func()

	// TLSIssueHandler is used to notify when there is a TLS issue.
	TLSIssueHandler func()
}

func NewConfig

func NewConfig(appVersionName, appVersion string) Config

type ConnectionObserver

type ConnectionObserver interface {
	OnDown()
	OnUp()
}

func NewConnectionObserver

func NewConnectionObserver(onDown, onUp func()) ConnectionObserver

NewConnectionObserver is a helper function to create a new connection observer from two callbacks. It doesn't need to be used; anything which implements the ConnectionObserver interface can be an observer.

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 DraftReq

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

DraftReq defines paylod for creating drafts.

type ErrAuthFailed

type ErrAuthFailed struct {
	OriginalError error
}

ErrAuthFailed ...

func (ErrAuthFailed) Error

func (err ErrAuthFailed) Error() string

type ErrBadRequest

type ErrBadRequest struct {
	OriginalError error
}

ErrBadRequest ...

func (ErrBadRequest) Error

func (err ErrBadRequest) Error() string

type ErrUnlockFailed

type ErrUnlockFailed struct {
	OriginalError error
}

ErrUnlockFailed ...

func (ErrUnlockFailed) Error

func (err ErrUnlockFailed) Error() string

type ErrUnprocessableEntity

type ErrUnprocessableEntity struct {
	OriginalError error
}

ErrUnprocessableEntity ...

func (ErrUnprocessableEntity) Error

func (err ErrUnprocessableEntity) Error() string

type Error

type Error struct {
	Code    int
	Message string `json:"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 Boolean
	// 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

	// Update of used user space
	UsedSpace *int64
}

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  *Boolean
	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 GetAuthInfoReq

type GetAuthInfoReq struct {
	Username string
}

type ImportMetadata

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

type ImportMsgReq

type ImportMsgReq struct {
	Metadata *ImportMetadata // Metadata about the message to import.
	Message  []byte          // The raw RFC822 message.
}

type ImportMsgReqs

type ImportMsgReqs []*ImportMsgReq

type ImportMsgRes

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

type KeySalt

type KeySalt struct {
	ID, KeySalt string
}

KeySalt contains id and salt for key.

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 Boolean
	Type      int
	Notify    Boolean
}

Label for message.

type LabelMessagesReq

type LabelMessagesReq struct {
	LabelID string
	IDs     []string
}

type LabelReq

type LabelReq struct {
	*Label
}

type LabelTypeV4

type LabelTypeV4 int

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 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 Manager

type Manager interface {
	NewClient(string, string, string, time.Time) Client
	NewClientWithRefresh(context.Context, string, string) (Client, *AuthRefresh, error)
	NewClientWithLogin(context.Context, string, []byte) (Client, *Auth, error)

	DownloadAndVerify(kr *crypto.KeyRing, url, sig string) ([]byte, error)
	ReportBug(context.Context, ReportBugReq) error
	SendSimpleMetric(context.Context, string, string, string) error

	SetLogging(logger *logrus.Entry, verbose bool)
	SetTransport(http.RoundTripper)
	SetCookieJar(http.CookieJar)
	SetRetryCount(int)
	AddConnectionObserver(ConnectionObserver)

	AllowProxy()
	DisallowProxy()
}

func New

func New(cfg Config) Manager

type Message

type Message struct {
	ID             string `json:",omitempty"`
	Order          int64  `json:",omitempty"`
	ConversationID string `json:",omitempty"` // only filter
	Subject        string
	Unread         Boolean
	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
	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) ([]byte, error)

func (*Message) Encrypt

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

func (*Message) ExtractSignatures

func (m *Message) ExtractSignatures(kr *crypto.KeyRing) ([]Signature, 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) Recipients

func (m *Message) Recipients() []*mail.Address

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 MessagesActionReq

type MessagesActionReq struct {
	IDs []string
}

type MessagesCount

type MessagesCount struct {
	LabelID string
	Total   int
	Unread  int
}

MessagesCount contains message counts for one label.

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 PMKey

type PMKey struct {
	ID          string
	Version     int
	Flags       int
	Fingerprint string
	PrivateKey  *crypto.Key
	Primary     int
	Token       string
	Active      Boolean
	Signature   string
}

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 PasswordMode

type PasswordMode int
const (
	OnePasswordMode PasswordMode = iota + 1
	TwoPasswordMode
)

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(cfg Config, 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.

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(cfg Config, dialer TLSDialer) *ProxyTLSDialer

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

func (*ProxyTLSDialer) AllowProxy

func (d *ProxyTLSDialer) AllowProxy()

AllowProxy allows the dialer to switch to a proxy if need be.

func (*ProxyTLSDialer) DialTLS

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

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

func (*ProxyTLSDialer) DisallowProxy

func (d *ProxyTLSDialer) DisallowProxy()

DisallowProxy prevents the dialer from switching to a proxy if need be.

type PublicKey

type PublicKey struct {
	Flags     int
	PublicKey string
}

type RecipientType

type RecipientType int
const (
	RecipientTypeInternal RecipientType = iota + 1
	RecipientTypeExternal
)

type ReportBugReq

type ReportBugReq 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"`
}

ReportBugReq stores data for report.

func (*ReportBugReq) AddAttachment

func (rep *ReportBugReq) AddAttachment(name, mime string, r io.Reader)

AddAttachment to report.

func (*ReportBugReq) GetMultipartFormData

func (rep *ReportBugReq) GetMultipartFormData() map[string]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 Signature

type Signature struct {
	Hash string
	Data []byte
}

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 TLSDialer

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

type TwoFAInfo

type TwoFAInfo struct {
	Enabled TwoFAStatus
}

type TwoFAStatus

type TwoFAStatus int
const (
	TwoFADisabled TwoFAStatus = iota
	TOTPEnabled
	U2FEnabled
	TOTPAndU2FEnabled
)

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.

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