lib

package
v0.0.0-...-c490dda Latest Latest
Warning

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

Go to latest
Published: Oct 15, 2020 License: BSD-3-Clause Imports: 18 Imported by: 16

Documentation

Index

Constants

View Source
const (
	ConnectorName = "Google Cloud Print Connector"

	// A website with user-friendly information.
	ConnectorHomeURL = "https://github.com/google/cloud-print-connector"

	GCPAPIVersion = "2.0"
)

Variables

View Source
var (
	ConfigFilenameFlag = cli.StringFlag{
		Name:  "config-filename",
		Usage: "Connector config filename",
		Value: defaultConfigFilename,
	}

	// To be populated by something like:
	// go install -ldflags "-X github.com/google/cloud-print-connector/lib.BuildDate=`date +%Y.%m.%d`"
	BuildDate = "DEV"

	ShortName = platformName + " Connector " + BuildDate + "-" + runtime.GOOS

	FullName = ConnectorName + " for " + platformName + " version " + BuildDate + "-" + runtime.GOOS
)
View Source
var DefaultConfig = Config{
	LocalPrintingEnable:    true,
	CloudPrintingEnable:    false,
	FcmNotificationsEnable: false,

	XMPPServer:                "talk.google.com",
	XMPPPort:                  443,
	XMPPPingTimeout:           "5s",
	XMPPPingInterval:          "2m",
	FcmServerBindUrl:          "https://fcm-stream.googleapis.com/fcm/connect/bind",
	GCPBaseURL:                "https://www.google.com/cloudprint/",
	GCPOAuthClientID:          "539833558011-35iq8btpgas80nrs3o7mv99hm95d4dv6.apps.googleusercontent.com",
	GCPOAuthClientSecret:      "V9BfPOvdiYuw12hDx5Y5nR0a",
	GCPOAuthAuthURL:           "https://accounts.google.com/o/oauth2/auth",
	GCPOAuthTokenURL:          "https://accounts.google.com/o/oauth2/token",
	GCPMaxConcurrentDownloads: 5,

	NativeJobQueueSize:        3,
	NativePrinterPollInterval: "1m",
	PrefixJobIDToJobTitle:     PointerToBool(false),
	DisplayNamePrefix:         "",
	PrinterBlacklist:          []string{},
	PrinterWhitelist:          []string{},
	LogLevel:                  "INFO",

	LocalPortLow:  26000,
	LocalPortHigh: 26999,

	LogFileName:         "/tmp/cloud-print-connector",
	LogFileMaxMegabytes: 1,
	LogMaxFiles:         3,
	LogToJournal:        PointerToBool(false),

	MonitorSocketFilename: "/tmp/cloud-print-connector-monitor.sock",

	CUPSMaxConnections: 50,
	CUPSConnectTimeout: "5s",
	CUPSPrinterAttributes: []string{
		"cups-version",
		"device-uri",
		"document-format-supported",
		"print-color-mode-default",
		"print-color-mode-supported",
		"printer-name",
		"printer-info",
		"printer-location",
		"printer-make-and-model",
		"printer-state",
		"printer-state-reasons",
		"printer-uuid",
		"marker-names",
		"marker-types",
		"marker-levels",
		"copies-default",
		"copies-supported",
		"number-up-default",
		"number-up-supported",
		"orientation-requested-default",
		"orientation-requested-supported",
		"pdf-versions-supported",
	},
	CUPSJobFullUsername:              PointerToBool(false),
	CUPSIgnoreRawPrinters:            PointerToBool(true),
	CUPSIgnoreClassPrinters:          PointerToBool(true),
	CUPSCopyPrinterInfoToDisplayName: PointerToBool(true),
}

DefaultConfig represents reasonable default values for Config fields. Omitted Config fields are omitted on purpose; they are unique per connector instance.

Functions

func DeepHash

func DeepHash(data interface{}, h hash.Hash)

DeepHash writes an object's values to h. Struct member names are ignored, values are written to h. Map keys and values are written to h. Slice inde and values are written to h. Pointers are followed once. Recursive pointer references cause panic.

func FilterRawPrinters

func FilterRawPrinters(printers []Printer) ([]Printer, []Printer)

FilterRawPrinters splits a slice of printers into non-raw and raw.

func PointerToBool

func PointerToBool(b bool) *bool

PointerToBool converts a boolean value (constant) to a pointer-to-bool.

func PrinterIsClass

func PrinterIsClass(printer Printer) bool

func PrinterIsRaw

func PrinterIsRaw(printer Printer) bool

Types

type Backoff

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

Backoff provides a mechanism for determining a good amount of time before retrying an operation.

func (*Backoff) Pause

func (b *Backoff) Pause() (time.Duration, bool)

Pause returns the amount of time to wait before retrying an operation and true if it is ok to try again or false if the operation should be abandoned.

type ConcurrentPrinterMap

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

ConcurrentPrinterMap is a map-like data structure that is also thread-safe. Printers are keyed by Printer.Name and Printer.GCPID.

func NewConcurrentPrinterMap

func NewConcurrentPrinterMap(printers []Printer) *ConcurrentPrinterMap

NewConcurrentPrinterMap initializes an empty ConcurrentPrinterMap.

func (*ConcurrentPrinterMap) GetAll

func (cpm *ConcurrentPrinterMap) GetAll() []Printer

GetAll returns a slice of all printers.

func (*ConcurrentPrinterMap) GetByGCPID

func (cpm *ConcurrentPrinterMap) GetByGCPID(gcpID string) (Printer, bool)

Get gets a printer, using the GCP ID as key.

The second return value is true if the entry exists.

func (*ConcurrentPrinterMap) GetByNativeName

func (cpm *ConcurrentPrinterMap) GetByNativeName(name string) (Printer, bool)

Get gets a printer, using the native name as key.

The second return value is true if the entry exists.

func (*ConcurrentPrinterMap) Refresh

func (cpm *ConcurrentPrinterMap) Refresh(newPrinters []Printer)

Refresh replaces the internal (non-concurrent) map with newPrinters.

type Config

type Config struct {
	// Enable local discovery and printing.
	LocalPrintingEnable bool `json:"local_printing_enable"`

	// Enable cloud discovery and printing.
	CloudPrintingEnable bool `json:"cloud_printing_enable"`

	// Enable fcm notifications instead of xmpp notifications.
	FcmNotificationsEnable bool `json:"fcm_notifications_enable"`

	// Associated with root account. XMPP credential.
	XMPPJID string `json:"xmpp_jid,omitempty"`

	// Associated with robot account. Used for acquiring OAuth access tokens.
	RobotRefreshToken string `json:"robot_refresh_token,omitempty"`

	// Associated with user account. Used for sharing GCP printers; may be omitted.
	UserRefreshToken string `json:"user_refresh_token,omitempty"`

	// Scope (user, group, domain) to share printers with.
	ShareScope string `json:"share_scope,omitempty"`

	// User-chosen name of this proxy. Should be unique per Google user account.
	ProxyName string `json:"proxy_name,omitempty"`

	// FCM url client should listen on.
	FcmServerBindUrl string `json:"fcm_server_bind_url,omitempty"`

	// XMPP server FQDN.
	XMPPServer string `json:"xmpp_server,omitempty"`

	// XMPP server port number.
	XMPPPort uint16 `json:"xmpp_port,omitempty"`

	// XMPP ping timeout (give up waiting after this time).
	// TODO: Rename with "gcp_" removed.
	XMPPPingTimeout string `json:"gcp_xmpp_ping_timeout,omitempty"`

	// XMPP ping interval (time between ping attempts).
	// TODO: Rename with "gcp_" removed.
	// TODO: Rename with "_default" removed.
	XMPPPingInterval string `json:"gcp_xmpp_ping_interval_default,omitempty"`

	// GCP API URL prefix.
	GCPBaseURL string `json:"gcp_base_url,omitempty"`

	// OAuth2 client ID (not unique per client).
	GCPOAuthClientID string `json:"gcp_oauth_client_id,omitempty"`

	// OAuth2 client secret (not unique per client).
	GCPOAuthClientSecret string `json:"gcp_oauth_client_secret,omitempty"`

	// OAuth2 auth URL.
	GCPOAuthAuthURL string `json:"gcp_oauth_auth_url,omitempty"`

	// OAuth2 token URL.
	GCPOAuthTokenURL string `json:"gcp_oauth_token_url,omitempty"`

	// Maximum quantity of jobs (data) to download concurrently.
	GCPMaxConcurrentDownloads uint `json:"gcp_max_concurrent_downloads,omitempty"`

	// CUPS job queue size, must be greater than zero.
	// TODO: rename without cups_ prefix
	NativeJobQueueSize uint `json:"cups_job_queue_size,omitempty"`

	// Interval (eg 10s, 1m) between CUPS printer state polls.
	// TODO: rename without cups_ prefix
	NativePrinterPollInterval string `json:"cups_printer_poll_interval,omitempty"`

	// Use the full username (joe@example.com) in job.
	// TODO: rename without cups_ prefix
	CUPSJobFullUsername *bool `json:"cups_job_full_username,omitempty"`

	// Add the job ID to the beginning of the job title. Useful for debugging.
	PrefixJobIDToJobTitle *bool `json:"prefix_job_id_to_job_title,omitempty"`

	// Prefix for all GCP printers hosted by this connector.
	DisplayNamePrefix string `json:"display_name_prefix,omitempty"`

	// Ignore printers with native names.
	PrinterBlacklist []string `json:"printer_blacklist,omitempty"`

	// Allow printers with native names.
	PrinterWhitelist []string `json:"printer_whitelist,omitempty"`

	// Least severity to log.
	LogLevel string `json:"log_level"`

	// Local only: HTTP API port range, low.
	LocalPortLow uint16 `json:"local_port_low,omitempty"`

	// Local only: HTTP API port range, high.
	LocalPortHigh uint16 `json:"local_port_high,omitempty"`

	// CUPS only: Where to place log file.
	LogFileName string `json:"log_file_name"`

	// CUPS only: Maximum log file size.
	LogFileMaxMegabytes uint `json:"log_file_max_megabytes,omitempty"`

	// CUPS only: Maximum log file quantity.
	LogMaxFiles uint `json:"log_max_files,omitempty"`

	// CUPS only: Log to the systemd journal instead of to files?
	LogToJournal *bool `json:"log_to_journal,omitempty"`

	// CUPS only: Filename of unix socket for connector-check to talk to connector.
	MonitorSocketFilename string `json:"monitor_socket_filename,omitempty"`

	// CUPS only: Maximum quantity of open CUPS connections.
	CUPSMaxConnections uint `json:"cups_max_connections,omitempty"`

	// CUPS only: timeout for opening a new connection.
	CUPSConnectTimeout string `json:"cups_connect_timeout,omitempty"`

	// CUPS only: printer attributes to copy to GCP.
	CUPSPrinterAttributes []string `json:"cups_printer_attributes,omitempty"`

	// CUPS only: non-standard PPD options to add as GCP vendor capabilities.
	CUPSVendorPPDOptions []string `json:"cups_vendor_ppd_options,omitempty"`

	// CUPS only: ignore printers with make/model 'Local Raw Printer'.
	CUPSIgnoreRawPrinters *bool `json:"cups_ignore_raw_printers,omitempty"`

	// CUPS only: ignore printers with make/model 'Local Printer Class'.
	CUPSIgnoreClassPrinters *bool `json:"cups_ignore_class_printers,omitempty"`

	// CUPS only: copy the CUPS printer's printer-info attribute to the GCP printer's defaultDisplayName.
	// TODO: rename with cups_ prefix
	CUPSCopyPrinterInfoToDisplayName *bool `json:"copy_printer_info_to_display_name,omitempty"`
}

func GetConfig

func GetConfig(context *cli.Context) (*Config, string, error)

GetConfig reads a Config object from the config file indicated by the config filename flag. If no such file exists, then DefaultConfig is returned.

func (*Config) Backfill

func (c *Config) Backfill(configMap map[string]interface{}) *Config

Backfill returns a copy of this config with all missing keys set to default values.

func (*Config) Sparse

func (c *Config) Sparse(context *cli.Context) *Config

Sparse returns a copy of this config with obvious values removed.

func (*Config) ToFile

func (c *Config) ToFile(context *cli.Context) (string, error)

ToFile writes this Config object to the config file indicated by ConfigFile.

type DuplexVendorMap

type DuplexVendorMap map[cdd.DuplexType]string

DuplexVendorMap maps a DuplexType to a CUPS key:value option string for a given printer.

type Job

type Job struct {
	NativePrinterName string
	Filename          string
	Title             string
	User              string
	JobID             string
	Ticket            *cdd.CloudJobTicket
	UpdateJob         func(string, *cdd.PrintJobStateDiff) error
}

type Printer

type Printer struct {
	GCPID               string                         //                                    GCP: printerid (GCP key)
	Name                string                         // CUPS: cups_dest_t.name (CUPS key); GCP: name field
	DefaultDisplayName  string                         // CUPS: printer-info;                GCP: default_display_name field
	UUID                string                         // CUPS: printer-uuid;                GCP: uuid field
	Manufacturer        string                         // CUPS: PPD;                         GCP: manufacturer field
	Model               string                         // CUPS: PPD;                         GCP: model field
	GCPVersion          string                         //                                    GCP: gcpVersion field
	SetupURL            string                         //                                    GCP: setup_url field
	SupportURL          string                         //                                    GCP: support_url field
	UpdateURL           string                         //                                    GCP: update_url field
	ConnectorVersion    string                         //                                    GCP: firmware field
	State               *cdd.PrinterStateSection       // CUPS: various;                     GCP: semantic_state field
	Description         *cdd.PrinterDescriptionSection // CUPS: translated PPD;              GCP: capabilities field
	CapsHash            string                         // CUPS: hash of PPD;                 GCP: capsHash field
	Tags                map[string]string              // CUPS: all printer attributes;      GCP: repeated tag field
	DuplexMap           DuplexVendorMap                // CUPS: PPD;
	NativeJobSemaphore  *Semaphore
	QuotaEnabled        bool
	DailyQuota          int
	NotificationChannel string
}

CUPS: cups_dest_t; GCP: /register and /update interfaces

func (*Printer) GetHostname

func (p *Printer) GetHostname() (string, bool)

GetHostname gets the network hostname, parsed from Printer.Tags["device-uri"].

type PrinterDiff

type PrinterDiff struct {
	Operation PrinterDiffOperation
	Printer   Printer

	DefaultDisplayNameChanged  bool
	ManufacturerChanged        bool
	ModelChanged               bool
	GCPVersionChanged          bool
	SetupURLChanged            bool
	SupportURLChanged          bool
	UpdateURLChanged           bool
	ConnectorVersionChanged    bool
	StateChanged               bool
	DescriptionChanged         bool
	CapsHashChanged            bool
	TagsChanged                bool
	DuplexMapChanged           bool
	QuotaEnabledChanged        bool
	DailyQuotaChanged          bool
	NotificationChannelChanged bool
}

Describes changes to be pushed to a GCP printer.

func DiffPrinters

func DiffPrinters(nativePrinters, gcpPrinters []Printer) []PrinterDiff

DiffPrinters returns the diff between old (GCP) and new (native) printers. Returns nil if zero printers or if all diffs are NoChangeToPrinter operation.

type PrinterDiffOperation

type PrinterDiffOperation int8
const (
	RegisterPrinter PrinterDiffOperation = iota
	UpdatePrinter
	DeletePrinter
	NoChangeToPrinter
)

type PrinterState

type PrinterState uint8

type Semaphore

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

func NewSemaphore

func NewSemaphore(size uint) *Semaphore

func (*Semaphore) Acquire

func (s *Semaphore) Acquire()

Acquire increments the semaphore, blocking if necessary.

func (*Semaphore) Count

func (s *Semaphore) Count() uint

Count returns the current value of the semaphore.

func (*Semaphore) Release

func (s *Semaphore) Release()

Release decrements the semaphore. If this operation causes the semaphore value to be negative, then panics.

func (*Semaphore) Size

func (s *Semaphore) Size() uint

Size returns the maximum semaphore value.

func (*Semaphore) TryAcquire

func (s *Semaphore) TryAcquire() bool

TryAcquire increments the semaphore without blocking. Returns false if the semaphore was not acquired.

Jump to

Keyboard shortcuts

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