// Package googleimport supplies the optional Google Drive file chooser. Tokens // stay in the browser; selected exports use the caller's normal upload form. package googleimport import ( "crypto/sha256" "embed" "errors" "fmt" "io/fs" "regexp" ) const MaxExportBytes = 10 << 20 type Kind string const ( Docs Kind = "docs" Sheets Kind = "sheets" ) // Config is public browser configuration, all from the same Google project. // No client secret or access/refresh token belongs here. type Config struct{ ClientID, APIKey, AppID string } func (c Config) Enabled() bool { return c.ClientID != "" && c.APIKey != "" && c.AppID != "" } var clientID = regexp.MustCompile(`^[0-9]+-[a-zA-Z0-9_-]+\.apps\.googleusercontent\.com$`) var apiKey = regexp.MustCompile(`^[a-zA-Z0-9_-]{20,100}$`) var appID = regexp.MustCompile(`^[0-9]{1,30}$`) func (c Config) Validate() error { if c == (Config{}) { return nil } if !c.Enabled() { return errors.New("googleimport: client ID, API key and project number must be configured together") } if len(c.ClientID) > 256 || !clientID.MatchString(c.ClientID) || !apiKey.MatchString(c.APIKey) || !appID.MatchString(c.AppID) { return errors.New("googleimport: invalid public Google configuration") } return nil } // View attaches to an existing same-origin multipart form and its file input. // The app owns the surrounding fidelity note, upload handler and import report. type View struct { Config Config Kind Kind FormID, InputID string Labels Labels } func (v View) Enabled() bool { return v.Config.Enabled() && v.Config.Validate() == nil && (v.Kind == Docs || v.Kind == Sheets) } //go:embed templates/*.html var templates embed.FS //go:embed google-import.mjs var javascript []byte //go:embed google-import.css var stylesheet []byte func Templates() fs.FS { return templates } func Template() string { b, _ := templates.ReadFile("templates/google-import.html"); return string(b) } func JS() []byte { return append([]byte(nil), javascript...) } // CSS is the chooser's stylesheet: its blocks on the spacing scale. An // app links it on the page that renders the chooser, beside JSName's // script, and drops any [estilo-google-import] rules of its own, which // would add their gap to these margins. Without it the chooser's // paragraphs keep the browser's margins. It has no hashed name: serve // it under whatever path and cache policy the app gives its other // estilo stylesheets. func CSS() []byte { return append([]byte(nil), stylesheet...) } func JSName() string { h := sha256.Sum256(javascript) return fmt.Sprintf("google-import.%x.mjs", h[:8]) }