Skip to content

Commit

Permalink
大量优化
Browse files Browse the repository at this point in the history
  • Loading branch information
vouv committed Nov 3, 2020
1 parent 69ba288 commit 6b81662
Show file tree
Hide file tree
Showing 8 changed files with 54 additions and 124 deletions.
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@

## Update Log

2020.11.2
2020.11.3

- 优化新版登陆逻辑
- 优化新版登录逻辑
- 优化命令行框架
- 删除无用代码
- 删除无用代码,优化代码结构

2020.9.6

Expand Down
19 changes: 8 additions & 11 deletions cmd/srun/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,12 @@ func LoginE(cmd *cobra.Command, args []string) error {
}
log.Info("尝试登录...")

if err = core.Login(&account); err != nil {
if err = core.Login(account); err != nil {
return err
}
log.Info("登录成功!")

err = store.SetInfo(account.AccessToken, account.Acid)
if err != nil {
return err
}
return nil
return store.WriteAccount(account)
}

func LogoutE(cmd *cobra.Command, args []string) error {
Expand All @@ -39,11 +35,12 @@ func LogoutE(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
if err = core.Logout(account.Username); err != nil {
return err
}

_ = core.Logout(account)

log.Info("注销成功!")
return nil

return store.WriteAccount(account)
}

func InfoE(cmd *cobra.Command, args []string) error {
Expand All @@ -67,7 +64,7 @@ func ConfigE(cmd *cobra.Command, args []string) error {
if err != nil {
return err
}
fmt.Print("设置校园网密码:\n>")
fmt.Print("设置校园网密码(隐私输入):\n>")

// read in stdin
_ = term.DisableEcho(fd, oldState)
Expand Down
2 changes: 1 addition & 1 deletion cmd/srun/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import (
"os"
)

const Version = "v1.0.0"
const Version = "v1.0.1"

var loginCmd = &cobra.Command{
Use: "login",
Expand Down
9 changes: 7 additions & 2 deletions core/core.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,13 @@ func Info() (info *model.InfoResp, err error) {
}

// api logout
func Logout(username string) (err error) {
q := model.Logout(username)
func Logout(account *model.Account) (err error) {
defer func() {
account.AccessToken = ""
account.Acid = 0
}()

q := model.Logout(account.Username)
ra := resp.ActionResp{}
if err = utils.GetJson(baseAddr+portalUrl, q, &ra); err != nil {
log.Debug(err)
Expand Down
1 change: 0 additions & 1 deletion model/response.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ func (r *InfoResp) String() string {
return sb.String()
}

// query info
type InfoResult struct {
Acid int `json:"ac_id"`
Username string `json:"username"`
Expand Down
103 changes: 21 additions & 82 deletions store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,120 +3,59 @@ package store
import (
"encoding/base64"
"encoding/json"
"errors"
log "github.com/sirupsen/logrus"
"github.com/vouv/srun/model"
"io/ioutil"
"os"
"os/user"
"path/filepath"
)

const accountFileName = "account.json"

// 读取账号文件错误
var ErrReadFile = errors.New("读取账号文件错误")
var ErrWriteFile = errors.New("写入账号文件错误")
var ErrParse = errors.New("序列化账号错误")

var RootPath string

// 写入账号信息到文件
// 统一错误
func SetAccount(username, password string) (err error) {
//write to local dir
account, err := ReadAccount()
if err != nil {
err = ErrReadFile
}
account.Username = username
account.Password = password

return WriteAccount(account)
return WriteAccount(&model.Account{
Username: username,
Password: password,
})
}

// 保存token
func SetInfo(token string, acId int) (err error) {
//write to local dir
account, err := ReadAccount()
func ReadAccount() (account *model.Account, err error) {
file, err := OpenAccountFile(os.O_RDONLY)
if err != nil {
log.Debugf("打开账号文件错误, %s,", err)
return
}
defer file.Close()

account.AccessToken = token
account.Acid = acId

return WriteAccount(account)
err = json.NewDecoder(base64.NewDecoder(base64.RawStdEncoding, file)).Decode(&account)
return
}

// 从文件系统读取账号信息
func ReadAccount() (account model.Account, err error) {
func OpenAccountFile(flag int) (file *os.File, err error) {
accountFilename, err := getAccountFilename()
if err != nil {
log.Debug(err)
err = ErrReadFile
return
}
file, openErr := os.Open(accountFilename)
if openErr != nil {
log.Debugf("打开账号文件错误, %s,", openErr)
err = ErrReadFile
return
}
defer file.Close()

readed, readErr := ioutil.ReadAll(file)
if readErr != nil {
log.Debugf("读取账号文件错误, %s", readErr)
err = ErrReadFile
return
}
// decode base64
decoded, err := base64.StdEncoding.DecodeString(string(readed))
if err != nil {
log.Debugf("解析账号文件错误, %s", err)
err = ErrReadFile
}

if umError := json.Unmarshal(decoded, &account); umError != nil {
log.Debugf("解析账号文件错误, %s", umError)
err = ErrReadFile
return
}
log.Debug("读取账号信息: ", accountFilename)
return
return os.OpenFile(accountFilename, flag, 0600)
}

// 写入文件信息到文件系统
func WriteAccount(account model.Account) (err error) {
accountFilename, err := getAccountFilename()
func WriteAccount(account *model.Account) (err error) {
file, err := OpenAccountFile(os.O_CREATE | os.O_TRUNC | os.O_WRONLY)
if err != nil {
log.Debugf("打开账号文件错误, %s", err)
err = ErrReadFile
return
}
file, openErr := os.OpenFile(accountFilename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0600)
if openErr != nil {
log.Debugf("打开账号文件错误, %s", openErr)
err = ErrReadFile
return
}

defer file.Close()
jBytes, mErr := account.JSONBytes()
if mErr != nil {
log.Debugf("序列化账号错误, %s", mErr)
err = ErrParse
return
}
// encode base64
str := base64.StdEncoding.EncodeToString(jBytes)
_, wErr := file.WriteString(str)
if wErr != nil {
log.Debugf("写入账号文件错误, %s", wErr)
err = ErrWriteFile
return

enc := base64.NewEncoder(base64.RawStdEncoding, file)
err = json.NewEncoder(enc).Encode(account)
if err != nil {
return err
}
return
return enc.Close()
}

func getAccountFilename() (fileSrc string, err error) {
Expand Down
17 changes: 9 additions & 8 deletions utils/format.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package utils

import (
"fmt"
"strings"
)

func FormatFlux(byte int64) string {
Expand Down Expand Up @@ -30,21 +31,21 @@ func FormatTime(sec int64) string {
m := sec / 60
sec %= 60
s := sec
out := ""
out := strings.Builder{}
if h < 10 {
out += fmt.Sprint("0", h, "时")
out.WriteString(fmt.Sprint("0", h, "时"))
} else {
out += fmt.Sprint(h, "时")
out.WriteString(fmt.Sprint(h, "时"))
}
if m < 10 {
out += fmt.Sprint("0", m, "分")
out.WriteString(fmt.Sprint("0", m, "分"))
} else {
out += fmt.Sprint(m, "分")
out.WriteString(fmt.Sprint(m, "分"))
}
if s < 10 {
out += fmt.Sprint("0", s, "秒")
out.WriteString(fmt.Sprint("0", s, "秒"))
} else {
out += fmt.Sprint(s, "秒")
out.WriteString(fmt.Sprint(s, "秒"))
}
return out
return out.String()
}
21 changes: 5 additions & 16 deletions utils/request.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,14 @@ func genCallback() string {
return fmt.Sprintf("jsonp%d", int(time.Now().Unix()))
}

// make request with data
// make jsonp with callback
func DoRequest(url string, params url.Values) (*http.Response, error) {

// add callback
params.Add("callback", genCallback())
params.Add("_", fmt.Sprint(time.Now().UnixNano()))
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
log.Debug(err)
return nil, err
}

Expand All @@ -36,41 +35,31 @@ func DoRequest(url string, params url.Values) (*http.Response, error) {

resp, err := client.Do(req)
if err != nil {
log.Error("network error")
log.Debug(err)
return nil, err
}
return resp, nil
}

// request for login and get json response
func GetJson(url string, data url.Values, res interface{}) (err error) {
resp, err := DoRequest(url, data)
if err != nil {
log.Error("network error")
log.Debug(err)
return
return err
}
defer resp.Body.Close()
raw, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Error("network error")
log.Debug(err)
return
return err
}
rawStr := string(raw)

// cut jsonp
start := strings.Index(rawStr, "(")
end := strings.LastIndex(rawStr, ")")
if start == -1 && end == -1 {
log.Error(rawStr)
log.Debug("raw response:", rawStr)
return errParse
}
dt := string(raw)[start+1 : end]

if err = json.Unmarshal([]byte(dt), &res); err != nil {
return
}
return nil
return json.Unmarshal([]byte(dt), &res)
}

0 comments on commit 6b81662

Please sign in to comment.