subcmd

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Aug 15, 2023 License: MIT Imports: 11 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var BillCmd = &cobra.Command{
	Use:   "usage",
	Short: "find out the usage from arg1 to arg2. if 1 arg, from arg1 to Today. if 0 arg, get last month",
	Run: func(cmd *cobra.Command, args []string) {
		if client.Client == nil {
			log.Errorln("No available client")
			os.Exit(-1)
		}
		var resp platform.UsageResponse
		var err error
		var from, to string
		if len(args) == 2 {
			from = args[0]
			to = args[1]
		} else if len(args) == 1 {
			now := time.Now()
			from = args[0]
			to = fmt.Sprintf("%v-%02d-%v", now.Year(), now.Month(), now.Day())
		} else {
			from, to = platform.GetLastMonth()
		}
		resp, err = client.Client.UsageWithSessionToken(from, to)
		if err != nil {
			log.Errorln("Get Usage hits error", err)
			log.Debug(client.Client.LastResponse())
			return
		}
		log.Infof("From %v To %v", from, to)
		log.Infof("Total count: $%v", resp.TotalUsage/100)
		if ui {
			var days []struct {
				Cost float64
				Time float64
			}
			bigestCost := 0.0
			for _, dc := range resp.DailyCosts {
				fullCost := 0.0
				for _, li := range dc.LineItems {
					fullCost += li.Cost
				}
				bigestCost = math.Max(bigestCost, fullCost)
				days = append(days, struct {
					Cost float64
					Time float64
				}{
					Cost: fullCost,
					Time: dc.Timestamp,
				})
			}
			eachP := bigestCost / 32

			fmt.Println("------------------------------------------------------")
			fmt.Println("|    DATE    | COST |           Status               |")
			fmt.Println("------------------------------------------------------")
			for _, day := range days {
				if day.Time == 0 {
					continue
				}
				star := ""
				for i := 0; i < 32; i++ {
					if i < int(day.Cost/eachP) {
						star += "*"
					} else {
						star += " "
					}
				}
				fmt.Printf("| %v | %.2f |%v|\n",
					time.Unix(int64(day.Time), 0).Format("2006-01-02"),
					day.Cost/100,
					star,
				)
			}
			fmt.Println("------------------------------------------------------")
			fmt.Printf("       TOTAL: %.2f\n", resp.TotalUsage/100)
			fmt.Println("------------------------------------------------------")
		}
	},
}
View Source
var KeyAddCmd = &cobra.Command{
	Use:     "create",
	Aliases: []string{"a", "add"},
	Short:   "create a key, not delete",
	Run: func(cmd *cobra.Command, args []string) {
		if client.Client == nil {
			log.Errorln("No available client")
			os.Exit(-1)
		}
		name := "temp"
		if key := config.C.Config.SecretKeyPrefix; key != "" {
			name = key
		}
		if len(args) > 1 {
			name = args[0]
		}
		resp, err := client.Client.CreateSecretKey(name)
		if err != nil {
			log.Errorln("Get Secret Keys hits error", err)
			log.Debug(client.Client.LastResponse())
			os.Exit(-2)
		}
		log.Infoln("Create Key ", resp.Result)
		log.Infoln("")
		log.Infof("  %v '%v': %v\n", resp.Key.Object, resp.Key.Name, resp.Key.SensitiveID)
		log.Infoln("")
	},
}
View Source
var KeyCmd = &cobra.Command{
	Use:     "key",
	Aliases: []string{"k"},
	Short:   "Key sub command for key management",
	Run: func(cmd *cobra.Command, args []string) {
		cmd.Help()
	},
}
View Source
var KeyDelCmd = &cobra.Command{
	Use:     "del",
	Aliases: []string{"rm"},
	Short:   "delete the key",
	Run: func(cmd *cobra.Command, args []string) {
		if client.Client == nil {
			log.Errorln("No available client")
			os.Exit(-1)
		}
		resp, err := client.Client.GetSecretKeys()
		if err != nil {
			log.Errorln("Get Secret Keys hits error", err)
			log.Debug(client.Client.LastResponse())
			os.Exit(-2)
		}

		var option []string
		for _, key := range resp.Data {
			log.Infof("Detect %v, Creatd at %v, Lasted Used at %v, name: \"%v\" value: %v",
				key.Object,
				time.Unix(int64(key.Created), 0).Format("2006-01-02"),
				time.Unix(int64(key.LastUse), 0).Format("2006-01-02"),
				key.Name,
				key.SensitiveID)
			option = append(option, fmt.Sprintf("%v - %v", key.Name, key.SensitiveID))
		}

		var selectedKey string
		err = survey.AskOne(&survey.Select{
			Message: "Choose the key you need delete",
			Options: option,
		}, &selectedKey)
		if err != nil {
			log.Errorln("Exit without asking", err)
			os.Exit(-3)
		}

		for _, key := range resp.Data {
			if selectedKey == fmt.Sprintf("%v - %v", key.Name, key.SensitiveID) {
				respDelete, err := client.Client.DeleteSecretKey(key)
				if err != nil {
					log.Errorln("Delete Key Errored", err)
					log.Debug(client.Client.LastResponse())
					os.Exit(-3)
				}
				log.Infoln("Delete Key ", respDelete.Result)
				os.Exit(0)
			}
		}
		log.Warnln("The key is not found.")
	},
}
View Source
var KeyListCmd = &cobra.Command{
	Use:     "list",
	Aliases: []string{"ls", "get"},
	Short:   "list the keys currently",
	Run: func(cmd *cobra.Command, args []string) {
		if client.Client == nil {
			log.Errorln("No available client")
			os.Exit(-1)
		}
		resp, err := client.Client.GetSecretKeys()
		if err != nil {
			log.Errorln("Get Secret Keys hits error", err)
			log.Debug(client.Client.LastResponse())
			os.Exit(-2)
		}
		for _, key := range resp.Data {
			log.Infof("Detect %v, Creatd at %v, Lasted Used at %v, name: \"%v\" value: %v",
				key.Object,
				time.Unix(int64(key.Created), 0).Format("2006-01-02"),
				time.Unix(int64(key.LastUse), 0).Format("2006-01-02"),
				key.Name,
				key.SensitiveID)
		}
	},
}
View Source
var KeyTempCmd = &cobra.Command{
	Use:     "temp",
	Aliases: []string{"t"},
	Short:   "create a temp key, delete with graceful shutdown",
	Run: func(cmd *cobra.Command, args []string) {
		if client.Client == nil {
			log.Errorln("No available client")
			os.Exit(-1)
		}
		name := "temp"
		if key := config.C.Config.SecretKeyPrefix; key != "" {
			name = key
		}
		if len(args) > 1 {
			name = args[0]
		}
		resp, err := client.Client.CreateSecretKey(name)
		if err != nil {
			log.Errorln("Get Secret Keys hits error", err)
			log.Debug(client.Client.LastResponse())
			os.Exit(-2)
		}
		log.Infoln("Create Key ", resp.Result)
		log.Infof("%v: %v", resp.Key.Object, resp.Key.SensitiveID)

		quit := make(chan os.Signal, 1)
		signal.Notify(quit, os.Interrupt, os.Kill)
		<-quit

		respDelete, err := client.Client.DeleteSecretKey(resp.Key)
		if err != nil {
			log.Errorln("Delete Key Errored", err)
			log.Debug(client.Client.LastResponse())
			os.Exit(-3)
		}
		log.Infoln("Delete Key ", respDelete.Result)
	},
}
View Source
var MeCmd = &cobra.Command{
	Use:     "me",
	Aliases: []string{"user", "u"},
	Short:   "Operating personal data",
	Run: func(cmd *cobra.Command, args []string) {
		cmd.Help()
	},
}
View Source
var MeInfoCmd = &cobra.Command{
	Use:   "info",
	Short: `display your information`,
	Run: func(cmd *cobra.Command, args []string) {
		if client.Client == nil {
			log.Errorln("No available client")
			os.Exit(-1)
		}

		f("===== User Basic Information =====")
		resp, err := client.Client.DashboardOnBoarding()
		if err != nil {
			log.Errorln("Dashboard On boarding hits error", err)
			log.Debug(client.Client.LastResponse())
			os.Exit(-2)
		}
		f("Username:", resp.User.Name)
		f("UserID:", resp.User.ID)
		f("Email:", resp.User.Email)
		f("SessionToken:", resp.User.Session.SensitiveID)
	},
}
View Source
var MeSubCmd = &cobra.Command{
	Use:     "sub",
	Aliases: []string{"subscription", "pay", "payment"},
	Short:   "Show user subscription data",
	Run: func(cmd *cobra.Command, args []string) {
		if client.Client == nil {
			log.Errorln("No available client")
			os.Exit(-1)
		}

		f("===== User Subscription Data =====")
		resp3, err := client.Client.DashboardSubscription()
		if err != nil {
			log.Errorln("payment subscription hits error", err)
			log.Debug(client.Client.LastResponse())
			os.Exit(-3)
		}
		f("Account Name:", resp3.AccountName)
		f("Soft Limit: $", resp3.SoftLimitUsd)
		f("Hard Limit: $", resp3.HardLimitUsd)
		f("Bill Address Country:", resp3.BillingAddress.Country)
		f("Bill Address State:", resp3.BillingAddress.State)
		f("Bill Address City:", resp3.BillingAddress.City)
		f("Bill Address Ln.1:", resp3.BillingAddress.Line1)
		f("Bill Address Ln.2:", resp3.BillingAddress.Line2)
		f("Post Code:", resp3.BillingAddress.PostalCode)

		f("===== User Payment Information =====")
		if resp3.HasPaymentMethod {
			resp2, err := client.Client.PaymentMethod()
			if err != nil {
				log.Errorln("payment data hits error", err)
				log.Debug(client.Client.LastResponse())
				os.Exit(-3)
			}
			for i, data := range resp2.Data {
				f("Payment #", i)
				if data.IsDefault == true {
					f("* This is Default Payment")
				}
				f("Payment Type:", data.Type)
				f("Card Type:", data.Card.Brand)
				f("Card Number: ******", data.Card.Last4)
				f("Card Exp:", data.Card.ExpYear, "-", data.Card.ExpMonth)
				f("Card Country:", data.Card.Country)
			}
		} else {
			f("User has no payment method.")
		}
	},
}
View Source
var RootCmd = &cobra.Command{
	Use:   "openai-cli",
	Short: "Openai platform API cli tools",
	PersistentPreRun: func(cmd *cobra.Command, args []string) {
		log.SetLevel(log.DebugLevel)
		config.Init()
		if config.C.Config.AccessToken != "" {
			client.Client = platform.NewUserPlatformClient(config.C.Config.AccessToken)
			_, err := client.Client.DashboardOnBoarding()
			if err == nil {
				log.Infoln("Connect to platform successful")
				return
			}
			log.Warnln("AccessToken Expired or bad one")
		}
		client.Client = platform.NewUserPlatformClient("")
		log.Infoln("Try login as username and password....")
		username := config.C.Config.Openai.Username
		password := config.C.Config.Openai.Password
		if username == "" || password == "" {
			log.Errorln("Empty username or password")
			client.Client = nil
			return
		}
		err := client.Client.LoginWithAuth0(username, password)
		if err == nil {
			config.C.Set("access_token", client.Client.AccessToken())
			config.C.WriteConfig()
			return
		}
		log.Errorln("Login fail")
		client.Client = nil
		return
	},
	Run: func(cmd *cobra.Command, args []string) {
		cmd.Help()
	},
}

Functions

This section is empty.

Types

This section is empty.

Jump to

Keyboard shortcuts

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