graph

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 28, 2026 License: MIT Imports: 22 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package graph is Frostmail's client for the part of Microsoft Graph that Microsoft accounts' contacts and calendars need (ADR-0039, ADR-0040; docs/design/pim.md, Microsoft Graph): listing calendars and contact folders, delta rounds, reading events, series and contacts, and turning them into the iCalendar and vCard sources the rest of maild reads.

Index

Constants

View Source
const BaseURL = "https://graph.microsoft.com/v1.0/"

BaseURL is Microsoft Graph v1.0.

View Source
const DefaultFolder = "contacts"

DefaultFolder is the default contact folder's href.

Variables

View Source
var (
	// ErrUnauthorized is a 401: the access token was refused.
	ErrUnauthorized = errors.New("graph: unauthorized")
	// ErrNotFound is a 404.
	ErrNotFound = errors.New("graph: not found")
	// ErrPrecondition is a 412: the If-Match change key is stale.
	ErrPrecondition = errors.New("graph: the item changed on the server")
	// ErrDeltaExpired means Graph no longer knows a delta link (410, or
	// syncStateNotFound): the collection is listed again.
	ErrDeltaExpired = errors.New("graph: the delta link expired")
)

Errors a request ends with, besides StatusError.

View Source
var ErrUnsupported = errors.New("graph: Outlook cannot store this")

ErrUnsupported means a source holds what Outlook cannot store, such as a recurrence rule outside Graph's patterns.

Functions

func CalendarDelta

func CalendarDelta(calendarID string, from, to time.Time) string

CalendarDelta is the first request of a calendar's delta round over a window.

func ContactSource

func ContactSource(c Contact, photo []byte, photoType string) []byte

ContactSource derives a contact's vCard 4.0; photo is its JPEG (or other image), nil for none.

func ContactsDelta

func ContactsDelta(folder string) string

ContactsDelta is the first request of a contact folder's delta round; DefaultFolder is the default folder's href.

func Diff

func Diff(base, next map[string]any) map[string]any

Diff is the fields of next whose JSON differs from base's.

func EventSource

func EventSource(master Event, exceptions []Event, userEmail string) ([]byte, error)

EventSource derives the iCalendar object of an event that does not recur, or of a series: its master and exceptions. userEmail is the account's address, whose answer is the event's responseStatus.

func GraphZone

func GraphZone(name string) string

GraphZone names an IANA zone as Graph takes it: by its Windows name when it has one, else by its IANA name; "UTC" for a zone without a name.

func KeyTime

func KeyTime(key string) (time.Time, error)

KeyTime reads a calendar.RecurrenceKey: a date's midnight UTC, or an instant.

func OutlookUID

func OutlookUID(uid string) string

OutlookUID is the iCalUId Outlook gives an invitation that came with uid: the class, an instance date, a time and reserved bytes left zero, and the data's size and the data.

func RRule

func RRule(r Recurrence, start time.Time, loc *time.Location, allDay bool) (string, error)

RRule is a series' pattern and range as an RRULE value. An end date is the last day an occurrence may fall on, in the series' zone.

func RecurrenceFromRule

func RecurrenceFromRule(rule string, start time.Time, zone *time.Location, zoneName string, allDay bool) (map[string]any, error)

RecurrenceFromRule is an RRULE value as Graph's recurrence, for a series starting at start in zone (named zoneName for Graph): the reverse of RRule. A rule outside Graph's patterns is ErrUnsupported.

func SourceUID

func SourceUID(iCalUID string) string

SourceUID is the iCalendar UID of an event with Outlook's iCalUId: the UID an invitation came with, else the iCalUId itself.

Types

type Attendee

type Attendee struct {
	Type   string `json:"type"` // required, optional, resource
	Status struct {
		Response string `json:"response"`
	} `json:"status"`
	EmailAddress EmailAddress `json:"emailAddress"`
}

Attendee is an invitee and their answer.

type Calendar

type Calendar struct {
	ID                string `json:"id"`
	Name              string `json:"name"`
	Color             string `json:"color"`
	HexColor          string `json:"hexColor"`
	CanEdit           bool   `json:"canEdit"`
	IsDefaultCalendar bool   `json:"isDefaultCalendar"`
	ChangeKey         string `json:"changeKey"`
}

Calendar is a calendar the account can see.

type Client

type Client struct {
	// Base is Graph's URL, BaseURL unless a test server stands in.
	Base string
	HTTP *http.Client
	// Token gives the account's access token for Graph's audience.
	Token     func(ctx context.Context) (string, error)
	UserAgent string
	// Wait sleeps before a retry; nil waits for real.
	Wait func(ctx context.Context, d time.Duration) error
}

Client talks to Graph for one account.

func (*Client) Answer

func (c *Client) Answer(ctx context.Context, id, answer string) error

Answer answers an invitation, or one occurrence of it, for the user, telling the organizer. answer is a PARTSTAT: accepted, tentative or declined.

func (*Client) CalendarView

func (c *Client) CalendarView(ctx context.Context, calendarID string, from, to time.Time) ([]Event, error)

CalendarView lists the events of a calendar that have occurrences in a window, as occurrences: single events, and a series' occurrences and exceptions with seriesMasterId, each with its ID, type and ETag.

func (*Client) Calendars

func (c *Client) Calendars(ctx context.Context) ([]Calendar, error)

Calendars lists the account's calendars.

func (*Client) ChangeKey

func (c *Client) ChangeKey(ctx context.Context, id string) (string, error)

ChangeKey reads an event's ETag, to check it before writes that cannot carry it.

func (*Client) Contact

func (c *Client) Contact(ctx context.Context, id string) (jsontext.Value, error)

Contact reads one contact.

func (*Client) ContactFolders

func (c *Client) ContactFolders(ctx context.Context) ([]ContactFolder, error)

ContactFolders lists the account's contact folders besides the default.

func (*Client) Contacts

func (c *Client) Contacts(ctx context.Context, folder string) ([]Contact, error)

Contacts lists a contact folder's contacts, each with its ID and ETag.

func (*Client) CreateContact

func (c *Client) CreateContact(ctx context.Context, folder string, fields map[string]any) (Contact, error)

CreateContact creates a contact in a folder (DefaultFolder for the default) and returns it.

func (*Client) CreateEvent

func (c *Client) CreateEvent(ctx context.Context, calendarID string, fields map[string]any) (Event, error)

CreateEvent creates an event or a series in a calendar and returns it.

func (*Client) DeleteContact

func (c *Client) DeleteContact(ctx context.Context, id, ifMatch string) error

DeleteContact deletes a contact, on its change key when ifMatch is set.

func (*Client) DeleteEvent

func (c *Client) DeleteEvent(ctx context.Context, id, ifMatch string) error

DeleteEvent deletes an event, a series or one occurrence, on its change key when ifMatch is set.

func (*Client) Delta

func (c *Client) Delta(ctx context.Context, link string) ([]jsontext.Value, string, error)

Delta runs a delta round from link, a delta link or a first request, to its end and returns the items and the delta link of the next round.

func (*Client) Do

func (c *Client) Do(ctx context.Context, method, path string, body []byte, headers map[string]string) ([]byte, http.Header, error)

Do sends one request and returns the response's body, retrying throttled and failing requests after Graph's Retry-After. headers may carry If-Match and Content-Type (JSON's when body is set).

func (*Client) Event

func (c *Client) Event(ctx context.Context, id string) (jsontext.Value, error)

Event reads one event.

func (*Client) EventsByUID

func (c *Client) EventsByUID(ctx context.Context, calendarID, uid string) ([]Event, error)

EventsByUID finds a calendar's events and series with an iCalendar UID.

func (*Client) Instances

func (c *Client) Instances(ctx context.Context, masterID string, from, to time.Time) ([]Event, error)

Instances lists a series' occurrences and exceptions that start in a window.

func (*Client) Photo

func (c *Client) Photo(ctx context.Context, contactID string) ([]byte, error)

Photo reads a contact's photo; nil when it has none.

func (*Client) Series

func (c *Client) Series(ctx context.Context, id string) (jsontext.Value, error)

Series reads a series' master with its exceptions.

func (*Client) SetPhoto

func (c *Client) SetPhoto(ctx context.Context, contactID string, data []byte, contentType string) error

SetPhoto replaces a contact's photo; contentType is the image's media type.

func (*Client) UpdateContact

func (c *Client) UpdateContact(ctx context.Context, id string, fields map[string]any, ifMatch string) error

UpdateContact changes a contact's fields, on its change key when ifMatch is set.

func (*Client) UpdateEvent

func (c *Client) UpdateEvent(ctx context.Context, id string, fields map[string]any, ifMatch string) error

UpdateEvent changes an event's fields, on its change key when ifMatch is set.

type Contact

type Contact struct {
	ID               string           `json:"id"`
	ETag             string           `json:"@odata.etag"`
	ChangeKey        string           `json:"changeKey"`
	ParentFolderID   string           `json:"parentFolderId"`
	DisplayName      string           `json:"displayName"`
	GivenName        string           `json:"givenName"`
	MiddleName       string           `json:"middleName"`
	Surname          string           `json:"surname"`
	Title            string           `json:"title"`
	Generation       string           `json:"generation"`
	NickName         string           `json:"nickName"`
	CompanyName      string           `json:"companyName"`
	Department       string           `json:"department"`
	JobTitle         string           `json:"jobTitle"`
	EmailAddresses   []EmailAddress   `json:"emailAddresses"`
	BusinessPhones   []string         `json:"businessPhones"`
	HomePhones       []string         `json:"homePhones"`
	MobilePhone      string           `json:"mobilePhone"`
	HomeAddress      *PhysicalAddress `json:"homeAddress"`
	BusinessAddress  *PhysicalAddress `json:"businessAddress"`
	OtherAddress     *PhysicalAddress `json:"otherAddress"`
	IMAddresses      []string         `json:"imAddresses"`
	BusinessHomePage string           `json:"businessHomePage"`
	Birthday         string           `json:"birthday"`
	PersonalNotes    string           `json:"personalNotes"`
	Categories       []string         `json:"categories"`
	LastModified     string           `json:"lastModifiedDateTime"`
	Removed          *struct {
		Reason string `json:"reason"`
	} `json:"@removed"`
}

Contact is an Outlook contact.

type ContactFolder

type ContactFolder struct {
	ID          string `json:"id"`
	DisplayName string `json:"displayName"`
}

ContactFolder is a contact folder besides the default one.

type ContactProjection

type ContactProjection struct {
	Fields    map[string]any
	Photo     []byte
	PhotoType string
}

ContactProjection is a contact as Graph's fields, and its photo.

func ProjectContact

func ProjectContact(src []byte) (ContactProjection, error)

ProjectContact reads a vCard into Graph's fields. Phones go to Graph's slots by label: the first mobile number to mobilePhone, home numbers to homePhones, the rest to businessPhones.

type DateTimeTimeZone

type DateTimeTimeZone struct {
	DateTime string `json:"dateTime"`
	TimeZone string `json:"timeZone"`
}

DateTimeTimeZone is Graph's local time with a zone name; Frostmail asks for UTC.

type EmailAddress

type EmailAddress struct {
	Name    string `json:"name"`
	Address string `json:"address"`
}

EmailAddress names a person.

type Event

type Event struct {
	ID             string `json:"id"`
	ETag           string `json:"@odata.etag"`
	ChangeKey      string `json:"changeKey"`
	ICalUID        string `json:"iCalUId"`
	Type           string `json:"type"` // singleInstance, seriesMaster, exception, occurrence
	SeriesMasterID string `json:"seriesMasterId"`
	OccurrenceID   string `json:"occurrenceId"`
	// OriginalStart is an exception's start before it moved (UTC).
	OriginalStart string `json:"originalStart"`
	Subject       string `json:"subject"`
	Body          struct {
		ContentType string `json:"contentType"`
		Content     string `json:"content"`
	} `json:"body"`
	Start                      DateTimeTimeZone `json:"start"`
	End                        DateTimeTimeZone `json:"end"`
	OriginalStartTimeZone      string           `json:"originalStartTimeZone"`
	OriginalEndTimeZone        string           `json:"originalEndTimeZone"`
	IsAllDay                   bool             `json:"isAllDay"`
	IsCancelled                bool             `json:"isCancelled"`
	IsOrganizer                bool             `json:"isOrganizer"`
	IsReminderOn               bool             `json:"isReminderOn"`
	ReminderMinutesBeforeStart int              `json:"reminderMinutesBeforeStart"`
	ShowAs                     string           `json:"showAs"`
	Sensitivity                string           `json:"sensitivity"`
	Categories                 []string         `json:"categories"`
	Location                   struct {
		DisplayName string `json:"displayName"`
	} `json:"location"`
	Organizer      *Recipient `json:"organizer"`
	Attendees      []Attendee `json:"attendees"`
	ResponseStatus struct {
		Response string `json:"response"`
	} `json:"responseStatus"`
	Recurrence    *Recurrence `json:"recurrence"`
	OnlineMeeting *struct {
		JoinURL string `json:"joinUrl"`
	} `json:"onlineMeeting"`
	CreatedDateTime      string `json:"createdDateTime"`
	LastModifiedDateTime string `json:"lastModifiedDateTime"`
	// A master's cancelled occurrences, as occurrence IDs, and its
	// exceptions ($expand=exceptionOccurrences).
	CancelledOccurrences []string `json:"cancelledOccurrences"`
	ExceptionOccurrences []Event  `json:"exceptionOccurrences"`
	// Removed is set on a delta round's deletions, which carry only an ID.
	Removed *struct {
		Reason string `json:"reason"`
	} `json:"@removed"`
}

Event is an event, a series' master, an exception or an occurrence.

type EventPart

type EventPart struct {
	Fields     map[string]any
	Answer     string
	Start, End time.Time
}

EventPart is one VEVENT: its fields but the recurrence's, and the user's answer (calendar.Event's PartStat) when invited.

type EventProjection

type EventProjection struct {
	UID    string
	Master EventPart
	// Overrides are the series' changed occurrences, by
	// calendar.RecurrenceKey of their original start.
	Overrides map[string]EventPart
	// Cancelled are the series' deleted occurrences, by RecurrenceKey.
	Cancelled []string
	// Organizer is whether the user organizes the event: an event without
	// people is the user's own.
	Organizer bool
	AllDay    bool
	// contains filtered or unexported fields
}

EventProjection is an event or a series as Graph's fields.

func ProjectEvent

func ProjectEvent(src []byte, userEmails []string, local *time.Location) (EventProjection, error)

ProjectEvent reads an iCalendar source into Graph's fields. userEmails are the account's addresses, lowercased; local is the zone floating times are read in and all-day events are written in.

func (EventProjection) Generates

func (p EventProjection) Generates(key string) bool

Generates reports whether the series makes an occurrence with the key, its overrides aside: one its rule makes and no EXDATE takes away.

func (EventProjection) Occurrence

func (p EventProjection) Occurrence(key string) (map[string]any, error)

Occurrence is an occurrence of the series as the master makes it: the master's fields at the occurrence's start, the base an override's fields are compared with.

type PhysicalAddress

type PhysicalAddress struct {
	Street          string `json:"street"`
	City            string `json:"city"`
	State           string `json:"state"`
	CountryOrRegion string `json:"countryOrRegion"`
	PostalCode      string `json:"postalCode"`
}

PhysicalAddress is a contact's postal address.

type Recipient

type Recipient struct {
	EmailAddress EmailAddress `json:"emailAddress"`
}

Recipient is an organizer.

type Recurrence

type Recurrence struct {
	Pattern struct {
		Type           string   `json:"type"`
		Interval       int      `json:"interval"`
		Month          int      `json:"month"`
		DayOfMonth     int      `json:"dayOfMonth"`
		DaysOfWeek     []string `json:"daysOfWeek"`
		FirstDayOfWeek string   `json:"firstDayOfWeek"`
		Index          string   `json:"index"`
	} `json:"pattern"`
	Range struct {
		Type                string `json:"type"` // endDate, noEnd, numbered
		StartDate           string `json:"startDate"`
		EndDate             string `json:"endDate"`
		RecurrenceTimeZone  string `json:"recurrenceTimeZone"`
		NumberOfOccurrences int    `json:"numberOfOccurrences"`
	} `json:"range"`
}

Recurrence is a series' pattern and range.

type Series

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

Series names a series' occurrences as the derived source does, by calendar.RecurrenceKey of their original starts, for writes to one occurrence.

func SeriesOf

func SeriesOf(master Event) (Series, error)

SeriesOf reads a master (or a single event) and its exceptions.

func (Series) Exception

func (s Series) Exception(key string) (string, bool)

Exception is the ID of the exception an occurrence key names.

func (Series) Key

func (s Series) Key(occurrence Event) (string, error)

Key is an unchanged occurrence's key, from its start (Instances).

type StatusError

type StatusError struct {
	Status  int
	Code    string // Graph's error code
	Message string
}

StatusError is a request Graph refused for another reason.

func (*StatusError) Error

func (e *StatusError) Error() string

Jump to

Keyboard shortcuts

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