From 795b7250ed3a6af3e654db370cdb3aecdb376e3c Mon Sep 17 00:00:00 2001 From: Alessio Date: Tue, 26 Dec 2023 12:20:58 -0600 Subject: [PATCH] Add flag to auto-open page in web browser --- cmd/twitter/main.go | 17 +++++++---------- internal/webserver/server.go | 18 +++++++++++++++++- 2 files changed, 24 insertions(+), 11 deletions(-) diff --git a/cmd/twitter/main.go b/cmd/twitter/main.go index b70b0cd..6497a0e 100644 --- a/cmd/twitter/main.go +++ b/cmd/twitter/main.go @@ -15,16 +15,11 @@ import ( "gitlab.com/offline-twitter/twitter_offline_engine/pkg/scraper" ) -/** - * Global variable referencing the open data profile - */ +// Global variable referencing the open data profile var profile persistence.Profile var version_string string -/** - * Main method - */ func main() { profile_dir := flag.String("profile", ".", "") flag.StringVar(profile_dir, "p", ".", "") @@ -159,7 +154,10 @@ func main() { case "unlike_tweet": unlike_tweet(target) case "webserver": - start_webserver(*addr) + fs := flag.NewFlagSet("", flag.ExitOnError) + should_auto_open := fs.Bool("auto-open", false, "") + fs.Parse(args[1:]) + start_webserver(*addr, *should_auto_open) case "fetch_inbox": fetch_inbox(*how_many) case "fetch_dm": @@ -184,7 +182,6 @@ func main() { // args: // - username: twitter username or email address // - password: twitter account password - func login(username string, password string) { // Skip the scraper.the_api variable, just use a local one since no scraping is happening api := scraper.NewGuestSession() @@ -406,9 +403,9 @@ func list_followed() { } } -func start_webserver(addr string) { +func start_webserver(addr string, should_auto_open bool) { app := webserver.NewApp(profile) - app.Run(addr) + app.Run(addr, should_auto_open) } func fetch_inbox(how_many int) { diff --git a/internal/webserver/server.go b/internal/webserver/server.go index 0816b5f..ebe8699 100644 --- a/internal/webserver/server.go +++ b/internal/webserver/server.go @@ -8,6 +8,8 @@ import ( "log" "net/http" "os" + "os/exec" + "runtime" "path" "strconv" "strings" @@ -130,7 +132,7 @@ func (app *Application) ServeHTTP(w http.ResponseWriter, r *http.Request) { } } -func (app *Application) Run(address string) { +func (app *Application) Run(address string, should_auto_open bool) { srv := &http.Server{ Addr: address, ErrorLog: app.ErrorLog, @@ -147,10 +149,24 @@ func (app *Application) Run(address string) { app.start_background() + if should_auto_open { + go openWebPage("http://" + address) + } err := srv.ListenAndServe() app.ErrorLog.Fatal(err) } +func openWebPage(url string) error { + switch runtime.GOOS { + case "darwin": // macOS + return exec.Command("open", url).Run() + case "windows": + return exec.Command("cmd", "/c", "start", url).Run() + default: // Linux and others + return exec.Command("xdg-open", url).Run() + } +} + func parse_cursor_value(c *persistence.Cursor, r *http.Request) error { cursor_param := r.URL.Query().Get("cursor") if cursor_param != "" {