cmd

package
v0.0.0-...-671fe2d Latest Latest
Warning

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

Go to latest
Published: Oct 22, 2023 License: MIT Imports: 16 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var DeleteCommand = cli.Command{
	Name:      "delete",
	Aliases:   []string{"del", "rm"},
	Usage:     "Delete a paste.",
	ArgsUsage: `PASTE_ID`,
	Action: func(cCtx *cli.Context) error {
		pasteId := cCtx.Args().First()

		if pasteId == "" {
			cli.Exit("Please provide a paste ID.", 1)
		}

		user, err := supabase.Auth.User(ctx, settings.AccessToken)

		if err != nil {
			cli.Exit("You don't seem to be signed in. Try running `openbin login` to sign in.", 1)
			return err
		}

		supabase.DB.AddHeader("Authorization", fmt.Sprintf("Bearer %s", settings.AccessToken))

		var paste []Paste

		err = supabase.DB.From("pastes").Select("file").Eq("id", pasteId).Eq("author", user.ID).Execute(&paste)

		if err != nil {
			cli.Exit("Could not get the paste.", 1)
			return err
		}

		if len(paste) == 0 {
			cli.Exit("Could not find the paste.", 1)
			return err
		}

		err = supabase.DB.From("pastes").Delete().Eq("id", pasteId).Execute(nil)

		if err != nil {
			cli.Exit("Could not delete the paste.", 1)
			return err
		}

		sbAuth := db.NewAuth()

		sbAuth.Storage.From("pastes").Remove([]string{paste[0].File})

		fmt.Println("Deleted the paste! 🗑️")

		return nil
	},
}
View Source
var LoginCommand = cli.Command{
	Name:    "login",
	Aliases: []string{"auth", "signin"},
	Usage:   "Login to your Openbin account.",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:     "email",
			Aliases:  []string{"e"},
			Usage:    "Your Openbin account email.",
			Required: false,
		},
		&cli.StringFlag{
			Name:        "provider",
			Aliases:     []string{"p"},
			Usage:       "Your Openbin account provider.",
			Required:    false,
			DefaultText: "github",
		},
	},
	Action: func(cCtx *cli.Context) error {
		codeVerifier := ""
		if cCtx.String("email") != "" {
			d, err := supabase.Auth.SignInWithOtp(ctx, sb.OtpSignInOptions{
				Email:      cCtx.String("email"),
				RedirectTo: "http://localhost:8089/auth-callback",
				FlowType:   sb.PKCE,
			})

			if err != nil {
				return err
			}

			codeVerifier = d.CodeVerifier

			fmt.Println("Check your email! 📧")
		} else {
			provider := cCtx.String("provider")

			if provider == "" {
				provider = "github"
			}

			d, err := supabase.Auth.SignInWithProvider(sb.ProviderSignInOptions{
				Provider:   provider,
				RedirectTo: "http://localhost:8089/auth-callback",
				FlowType:   sb.PKCE,
			})

			if err != nil {
				return err
			}

			codeVerifier = d.CodeVerifier

			fmt.Printf("Please go to the following URL to login: %s\n", d.URL)
		}

		stopServer := make(chan bool)

		http.HandleFunc("/auth-callback", func(w http.ResponseWriter, r *http.Request) {

			code := r.URL.Query().Get("code")

			token, err := supabase.Auth.ExchangeCode(ctx, sb.ExchangeCodeOpts{
				AuthCode:     code,
				CodeVerifier: codeVerifier,
			})

			if err != nil {
				fmt.Println(err)
			}

			expiryDate := time.Now().Add(time.Second * time.Duration(token.ExpiresIn))

			settings.SetAccessToken(token.AccessToken)
			settings.SetRefreshToken(token.RefreshToken)
			settings.SetTokenExpiry(expiryDate)

			fmt.Println("Successfully logged in! 🎉")

			w.Write([]byte("Successfully logged in! 🎉"))

			stopServer <- true
		})

		server := &http.Server{Addr: ":8089"}

		go func() {
			if err := server.ListenAndServe(); err != nil {
				fmt.Println(err)
			}
		}()

		<-stopServer

		if err := server.Shutdown(ctx); err != nil {
			fmt.Println(err)
		}

		return nil
	},
}
View Source
var LogoutCommand = cli.Command{
	Name:    "logout",
	Aliases: []string{"signout"},
	Usage:   "Logout from your Openbin account.",
	Action: func(cCtx *cli.Context) error {
		settings.SetAccessToken("")
		settings.SetRefreshToken("")

		fmt.Println("Successfully logged out! 👋")

		return nil
	},
}
View Source
var PastesCommand = cli.Command{
	Name:    "pastes",
	Aliases: []string{"ls", "list"},
	Usage:   "Manage your pastes.",
	Action: func(cCtx *cli.Context) error {
		user, err := supabase.Auth.User(ctx, settings.AccessToken)

		if err != nil {
			cli.Exit("You don't seem to be signed in. Try running `openbin login` to sign in.", 1)
		}

		if user == nil {
			cli.Exit("You don't seem to be signed in. Try running `openbin login` to sign in.", 1)
		}

		supabase.DB.AddHeader("Authorization", fmt.Sprintf("Bearer %s", settings.AccessToken))

		var pastes []Paste
		err = supabase.DB.From("pastes").Select("*").Eq("author", user.ID).Execute(&pastes)

		if err != nil {
			cli.Exit("Could not get the pastes.", 1)
			return err
		}

		for _, paste := range pastes {
			visibility := "Public"

			if paste.Draft {
				visibility = "Draft"
			}

			title := paste.Title

			if title == "" {
				title = "Untitled Paste"
			}

			fmt.Printf("\n- %s: %s [%s]\n", title, fmt.Sprintf("https://openbin.dev/paste/%s", paste.ID), visibility)
		}

		return nil
	},
}
View Source
var UploadCommand = cli.Command{
	Name:      "upload",
	Aliases:   []string{"u", "up"},
	Usage:     "Upload a file to Openbin.",
	ArgsUsage: "[FILE]",
	Flags: []cli.Flag{
		&cli.StringFlag{
			Name:     "editor",
			Aliases:  []string{"E"},
			Usage:    "Set the editor to use to edit the paste. Must be the command executable (i.e. code, vim, nano, etc.)",
			Required: false,
		},
		&cli.BoolFlag{
			Name:     "draft",
			Aliases:  []string{"d"},
			Usage:    "Set the paste to draft (private).",
			Required: false,
		},
		&cli.StringFlag{
			Name:     "expire",
			Aliases:  []string{"e"},
			Usage:    "Set the paste to expire after a certain time.",
			Required: false,
		},
		&cli.StringFlag{
			Name:     "title",
			Aliases:  []string{"t"},
			Usage:    "Set the paste title. Use quotes if it has spaces.",
			Required: false,
		},
		&cli.StringFlag{
			Name:     "description",
			Usage:    "Set the paste description. Use quotes if it has spaces.",
			Required: false,
		},
		&cli.StringFlag{
			Name:     "language",
			Aliases:  []string{"l"},
			Usage:    "Set the paste language.",
			Required: false,
		},
		&cli.BoolFlag{
			Name:     "copy",
			Aliases:  []string{"c"},
			Usage:    "Copy the paste URL to the clipboard.",
			Required: false,
		},
		&cli.BoolFlag{
			Name:     "open",
			Aliases:  []string{"o"},
			Usage:    "Open the paste URL in the browser.",
			Required: false,
		},
		&cli.BoolFlag{
			Name:     "quiet",
			Aliases:  []string{"q"},
			Usage:    "Don't print anything to the console. Errors will still be printed.",
			Required: false,
		},
	},
	Action: func(cCtx *cli.Context) error {
		user, err := supabase.Auth.User(ctx, settings.AccessToken)

		if err != nil {
			cli.Exit("You don't seem to be signed in. Try running `openbin login` to sign in.", 1)
		}

		if user == nil {
			cli.Exit("You don't seem to be signed in. Try running `openbin login` to sign in.", 1)
		}

		args := UploadOptions{
			File:        cCtx.Args().First(),
			Editor:      cCtx.String("editor"),
			Draft:       cCtx.Bool("draft"),
			Expire:      cCtx.String("expire"),
			Title:       cCtx.String("title"),
			Description: cCtx.String("description"),
			Language:    cCtx.String("language"),
			Copy:        cCtx.Bool("copy"),
			Open:        cCtx.Bool("open"),
			Quiet:       cCtx.Bool("quiet"),
		}

		if args.File != "" {

			if _, err := os.Stat(args.File); os.IsNotExist(err) {
				return cli.Exit("The file you specified does not exist.", 1)
			}
		}

		if args.Language == "" {

			if args.File != "" {
				fileExt := config.GetFileExtension(args.File)
				if config.IsFileTypeAllowed(fileExt) {
					filetype := config.GetFileTypeByFilePath(args.File)
					args.Language = filetype.Value
				} else {
					return cli.Exit(fmt.Sprintf("The file type you specified is not allowed.\nYou specified: %s\nAllowed types: %s", config.GetFileExtension(args.File), strings.Join(config.GetAllowedTypes(), ", ")), 1)
				}
			}
		} else {

			if !config.IsFileTypeAllowedByValue(args.Language) {
				return cli.Exit(fmt.Sprintf("The file type you specified is not allowed.\nYou specified: %s\nAllowed types: %s", config.GetFileExtension(args.Language), strings.Join(config.GetAllowedTypes(), ", ")), 1)
			}
		}

		if args.Editor != "" {
			editorPath := which.Which(args.Editor)
			if editorPath == "" {
				return cli.Exit("The editor you specified could not be found.", 1)
			}

			path := ""

			if args.File == "" {

				f, err := ioutil.TempFile("", "openbin-*.txt")

				if err != nil {
					return cli.Exit("Could not create a temporary file.", 1)
				}

				path = f.Name()
			} else {
				path = args.File
			}

			if !args.Quiet {
				fmt.Println("Waiting for you to finish editing...")
			}

			if args.Editor == "code" {
				err := exec.Command(editorPath, "-r", "--wait", path).Run()

				if err != nil {
					return cli.Exit("Could not open the editor.", 1)
				}
			} else {
				err := exec.Command(editorPath, path).Run()

				if err != nil {
					return cli.Exit("Could not open the editor.", 1)
				}
			}

			UploadFile(path, args)

			if args.File == "" {
				os.Remove(path)
			}

			if !args.Quiet {
				fmt.Println("Uploaded the file! 🎉")
			}
			return nil
		}

		if args.File == "" && args.Editor == "" {
			return cli.Exit("You must specify a file or an editor.", 1)
		}

		if args.File != "" {
			UploadFile(args.File, args)
			if !args.Quiet {
				fmt.Println("Uploaded the file! 🎉")
			}
		}

		return nil
	},
}

Functions

func UploadFile

func UploadFile(path string, opts UploadOptions)

Types

type CustomTime

type CustomTime struct {
	time.Time
}

func (*CustomTime) UnmarshalJSON

func (ct *CustomTime) UnmarshalJSON(data []byte) error

Implement the UnmarshalJSON method for CustomTime

type Paste

type Paste struct {
	ID          string     `json:"id"`
	CreatedAt   CustomTime `json:"created_at,omitempty"`
	Author      string     `json:"author"`
	File        string     `json:"file"`
	Draft       bool       `json:"draft"`
	ExpiresAt   CustomTime `json:"expires_at,omitempty"`
	Title       string     `json:"title"`
	Description string     `json:"description"`
	Language    string     `json:"language"`
}

type UploadOptions

type UploadOptions struct {
	File        string
	Editor      string
	Draft       bool
	Expire      string
	Title       string
	Description string
	Language    string
	Copy        bool
	Open        bool
	Quiet       bool
}

Jump to

Keyboard shortcuts

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