gmailalert

package module
v0.0.0-...-0ad1cf8 Latest Latest
Warning

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

Go to latest
Published: Mar 4, 2023 License: MIT Imports: 17 Imported by: 0

README

gmailalert

gmailalert is a Go package and command-line app that scans a Gmail user's account for emails matching specified patterns and emits Pushover alerts when matches are found.

Installation

  1. Install the gmailalert command-line app by running go install https://github.com/elskohder/gmailalert/cmd/gmailalert@latest
  2. You will need to create a Google Cloud Project with the API enabled.
  3. You will need to create access credentials for a Google desktop application and download them to your local machine. These are typically saved in a file called credentials.json.
  4. You will need to have a Pushover account with at least one application configured in it. See the Pushover support page for more help setting up a Pushover application.

Usage

$ ./gmailalert -h
Usage of gmailalert:
  -alerts-cfg-file string
        json file containing the alerting criteria (default "alerts.json")
  -credentials-file string
        json file containing your Google Developers Console credentials (default "credentials.json")
  -debug
        enable debug-level-logging
  -port int
        the port for the local http server to listen on for redirects from the Gmail OAuth2 resource provider (default 9999)
  -token-file string
        json file to read your Gmail OAuth2 token from (if present), or to save your Gmail OAuth2 token into (if not present) (default "token.json")

The gmailalert app reads a JSON configuration file containing email matching criteria (in Gmail query format) and the corresponding Pushover message to send when matches occur. This JSON configuration file is specified with the -alerts-cfg flag in the gmailalert command-line app.

Here is an example configuration:

{
    "pushoverapp": "NOT SHOWN HERE",
    "alerts": [
        {   
            "gmailquery": "is:unread subject:Your Bill is Available Online",     
            "pushovertarget": "NOT SHOWN HERE",
            "pushovertitle": "Bill Due!",
            "pushoversound": "cashregister"
        },
        {   
            "gmailquery": "is:unread subject:Your zoom meeting has started",     
            "pushovertarget": "NOT SHOWN HERE",
            "pushovertitle": "Zoom Meeting Started!",
            "pushoversound": "siren"
        }
    ]
}

Some points to note here:

  • The value of the "pushoverapp" field is the API token for the pushover application that you want to emit notifications with.
  • The value of the "pushovertarget" field is your Pushover account user key.

For example, assuming the JSON configuration shown above is saved in a file called alerts.json:

$ ./gmailalert -alerts-cfg-file alerts.json 
INFO: 2022/08/17 22:31:21 Found 0 emails matching query "is:unread subject:Your zoom meeting has started"
INFO: 2022/08/17 22:31:21 Found 1 emails matching query "is:unread subject:Your Bill is Available Online"
INFO: 2022/08/17 22:31:21 notification titled "Bill Due!" successfully sent via gmailalert.PushoverClient

References

Documentation

Overview

Package gmailalert provides types and functions for searching for Gmail messages matching specified criteria and emitting Pushover notifications when matches are found.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CLI

func CLI(args []string) error

CLI accepts a slice of command-line flags for a user's Google Developers Console file ("-credentials-file"), a user's local Google OAuth2 token JSON file ("-token-file"), an alert configuration JSON file ("-alerts-cfg-file") which provides the email criteria to alert on, a TCP port for the local HTTP server to listen on for redirect requests from the Google OAuth2 resource provider ("-port"), and a debug flag ("-debug") which indicates if debug-level output will be written.

The command line flags are parsed, validated, and then used to create an Alerter struct to process alerts with. An error is returned if any of the command-line flags are invalid or if there is a problem during the processing of alerts.

Types

type Alert

type Alert struct {
	// The Gmail query expression to match emails against.
	// See https://support.google.com/mail/answer/7190?hl=en
	GmailQuery string `json:"gmailquery"`
	// The pushover notification recipient.
	PushoverTarget string `json:"pushovertarget"`
	// The title of the pushover notification.
	PushoverTitle string `json:"pushovertitle"`
	// The pushover sound to use for the notification.
	PushoverSound string `json:"pushoversound"`
	// The message to put in the pushover notification.
	PushoverMsg string
}

Alert represents a Gmail filtering query to find matches against and the corresponding configuration to use in the Pushover notification.

func (Alert) OK

func (a Alert) OK() error

OK validates a given Alert and returns an error if any of its fields are empty.

type AlertConfig

type AlertConfig struct {
	PushoverApp string  `json:"pushoverapp"`
	Alerts      []Alert `json:"alerts"`
}

AlertConfig represents a configuration containing a Pushover application to send alerts to and the alerts to notify on.

func DecodeAlerts

func DecodeAlerts(rdr io.Reader) (AlertConfig, error)

DecodeAlerts accepts an io.Reader containing JSON-formatted alert configuration, decodes the JSON object into an AlertConfig value and returns the AlertConfig. An error is returned if the io.Reader argument is nil or if there is a problem JSON-decoding the io.Reader.

type Alerter

type Alerter struct {
	Matcher  Matcher
	Notifier Notifier
	Logger   Logger
}

Alerter is a type that provides behavior for matching emails and sending a notification for any positive match results.

func NewAlerter

func NewAlerter(m Matcher, n Notifier, opts ...AlerterOption) (Alerter, error)

NewAlerter accepts a Matcher, a Notifier, and a slice of AlerterOptions creates a new Alerter struct from them, and returns the Alerter. An error is returned if the Matcher or Notifier arguments are nil.

func (Alerter) Process

func (a Alerter) Process(alerts []Alert) error

Process accepts a slice of Alert structs, processes them concurrently to determine if any emails satisfying the alert criteria are found, and sends a notification if any matches are found. An error is returned if the the Alerter receiver has any nil fields.

type AlerterOption

type AlerterOption func(a *Alerter)

AlerterOption represents a functional option that can be passed to an Alerter.

func WithAlerterLogger

func WithAlerterLogger(l Logger) AlerterOption

WithAlerterLogger accepts a Logger and returns a functional option for wiring the Logger to an Alerter.

type GmailClient

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

GmailClient represents a client for communicating with the Gmail API.

func NewGmailClient

func NewGmailClient(cfg GmailClientConfig) (*GmailClient, error)

NewGmailClient accepts a GmailClientConfig and returns a new GmailClient. An error is returned if the GmailClientConfig is invalid, if the gmail oauth2 configuration cannot be generated, or if there is a problem creating the gmail service.

func (GmailClient) Match

func (g GmailClient) Match(query string) ([]string, error)

Match queries Gmail for any emails matching the given query, which can be any valid Gmail query expression, like "is:unread", "from:gopher@gmail.com", etc. It returns a slice of raw email messages matching the query where raw means the email message is RFC 2822 formatted and base64 encoded. An error is returned if the query to the Gmail API fails.

type GmailClientConfig

type GmailClientConfig struct {
	// The file containing the user's Google Developers Console credentials.
	CredentialsFile string
	// The file containing the user's Gmail OAuth2 token.
	TokenFile string
	// The input source for entering the Gmail OAuth2 authentication code.
	UserInput io.Reader
	// The port that the local HTTP server should listen on for handling
	// redirect requests from the Gmail OAuth2 resource provider.
	RedirectSvrPort int
	// The Logger to use for debugging.
	Logger Logger
}

GmailClientConfig represents the configuration needed to create a GmailClient.

func (GmailClientConfig) OK

func (g GmailClientConfig) OK() error

OK returns an error if the given GmailClientConfig contains invalid values for the Gmail OAuth2 credentials file, the user input source, or the port that the local HTTP server should listen on for redirect requests coming from the Gmail OAuth2 resource provider.

type Logger

type Logger interface {
	Printf(string, ...interface{})
}

Logger represents logger behavior that can be used by the Alerter.

type Matcher

type Matcher interface {
	Match(query string) ([]string, error)
}

Matcher is the interface that wraps the Match method used by any types implementing email searching behavior.

type Notifier

type Notifier interface {
	Notify(a Alert) error
}

Notifier is the interface that wraps the Notify method used by any types implementing notification behavior.

type PushoverClient

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

PushoverClient represents a type providing behavior for sending Pushover notifications.

func NewPushoverClient

func NewPushoverClient(token string, opts ...PushoverClientOpt) (PushoverClient, error)

NewPushoverClient accepts a Pushover app token and returns a new PushoverClient. An error is returned if the Pushover app token is invalid.

func (PushoverClient) Notify

func (p PushoverClient) Notify(alt Alert) error

Notify accepts an Alert struct, constructs a Pushover notification from the data in the Alert and emits the Pushover notification. An error is returned if the message send fails.

type PushoverClientOpt

type PushoverClientOpt func(p *PushoverClient)

PushoverClientOpt represents a functional option that can be wired to a PushoverClient.

func WithPushoverClientLogger

func WithPushoverClientLogger(l Logger) PushoverClientOpt

WithPushoverClientLogger accepts a Logger and returns a function that wires the Logger to a PushoverClient.

type RedirectServer

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

RedirectServer represents an HTTP server that handles oauth2 redirect requests and displays the state token returned by the oauth2 resource provider.

func NewRedirectServer

func NewRedirectServer(opts ...RedirectServerOpt) *RedirectServer

NewRedirectServer accepts an optional slice of RedirectServerOpt functional options and returns a RedirectServer that is configured to handle redirects from an oauth2 resource provider to the local host. If the server address is not overridden with a RedirectServerOpt argument, then the server will listen on TCP port 9999.

func (*RedirectServer) ListenAndServe

func (r *RedirectServer) ListenAndServe() error

ListenAndServe listens on the TCP address configured in the HTTP server wrapped by r and sends all requests to the handler configured in the HTTP server wrapped by r.

func (*RedirectServer) Shutdown

func (r *RedirectServer) Shutdown() error

Shutdown gracefully shuts down the HTTP server wrapped by r. If the server is not shutdown within 5 seconds, then it is force-stopped.

type RedirectServerOpt

type RedirectServerOpt func(*RedirectServer)

RedirectServerOpt represents a functional option that can be used when creating a new RedirectServer.

func WithRedirectSvrAddr

func WithRedirectSvrAddr(addr string) RedirectServerOpt

WithAddr accepts a TCP address in the form "host:port" and returns a RedirectServerOpt that applies this address to a RedirectServer.

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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