Skip to content

Commit

Permalink
Added QR code.
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanfox1985 committed Jun 30, 2016
1 parent 5a6b322 commit 9f44e7b
Show file tree
Hide file tree
Showing 6 changed files with 122 additions and 12 deletions.
21 changes: 16 additions & 5 deletions cmd/client_add.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,14 @@ import (
)

func copyClipboard(strToCopy string) error {
fmt.Printf("Copied to clipboard: %s", strToCopy)
fmt.Printf("Copied to clipboard: %s\n", strToCopy)
return clipboard.WriteAll(strToCopy)
}

func selectOptionFrom(options []string) error {
func selectOptionFrom(options []string) (string, error) {
//TODO: check bad options
if len(options) == 1 {
return copyClipboard(options[0])
return options[0], nil
}

fmt.Println("Choose option to copy to clipboard:")
Expand All @@ -33,7 +33,8 @@ func selectOptionFrom(options []string) error {

var option int
fmt.Scanf("%d", &option)
return copyClipboard(options[option])

return options[option], nil
}

func runAddCmd(filePath string, settings lib.SettingsShare) error {
Expand All @@ -57,7 +58,17 @@ func runAddCmd(filePath string, settings lib.SettingsShare) error {
json.Unmarshal([]byte(body), &res)

if res.Status {
selectOptionFrom(res.Server.ListIps)
url, err := selectOptionFrom(res.Server.ListIps)
if err != nil {
return err
}

copyClipboard(url)

if qrOption {
filePath, _ := lib.GenerateQR(res.Server.UUID, url)
fmt.Printf("FILE: %v\n", filePath)
}
}

fmt.Printf("%s\n", res.ErrorMessage)
Expand Down
4 changes: 2 additions & 2 deletions cmd/client_ps.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,12 @@ func runPsCmd(settings lib.SettingsShare) {

if res.Status {
lines := []string{
"UUID | Folder | Flags | CreatedAt",
"UUID | Source | Flags | CreatedAt",
}

for i := 0; i < len(res.Servers); i++ {
server := res.Servers[i]
line := fmt.Sprintf("%v|%s|%v|%v", server.UUID, server.Path, server.Flags, server.CreatedAt)
line := fmt.Sprintf("%v|%s|%v|%v", server.UUID, server.Source, server.Flags, server.CreatedAt)
lines = append(lines, line)
}

Expand Down
2 changes: 2 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,11 +11,13 @@ import (
var (
appSettings lib.SettingsShare
zipOption bool
qrOption bool
)

func init() {
RootCmd.AddCommand(VersionCmd, ServerCmd, AddCmd, PsCmd, RmCmd)
AddCmd.PersistentFlags().BoolVar(&zipOption, "zip", false, "Package with tar")
AddCmd.PersistentFlags().BoolVar(&qrOption, "qr", false, "Save qr image")
}

var RootCmd = &cobra.Command{
Expand Down
3 changes: 2 additions & 1 deletion cmd/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ func newServerParams(c *gin.Context, path string) lib.Server {
flags = append(flags, "zip")
}

return lib.Server{UUID: uuid.NewV4().String(), Path: path, CreatedAt: time.Now(), Flags: flags}
return lib.Server{UUID: uuid.NewV4().String(), Source: path, Path: path, CreatedAt: time.Now(), Flags: flags}
}

func processAddServer(c *gin.Context) {
Expand Down Expand Up @@ -93,6 +93,7 @@ func processAddServer(c *gin.Context) {
c.JSON(http.StatusOK, msg)
}

// TODO: rm zip file
func processRmServer(uuid string, c *gin.Context) {
msg := api.RmResponse{Status: true}

Expand Down
11 changes: 7 additions & 4 deletions lib/database.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import (
type Server struct {
UUID string `json:"uuid"`
Path string `json:"path"`
Source string `json:"source"`
CreatedAt time.Time `json:"created_at"`
ListIps []string `json:"list_ips"`
Flags []string `json:"flags"`
Expand Down Expand Up @@ -45,6 +46,7 @@ func CreateTable() error {
CREATE TABLE IF NOT EXISTS Servers(
UUID string,
Path string,
Source string,
Flags string,
CreatedAt time
);
Expand Down Expand Up @@ -78,9 +80,10 @@ func StoreServer(server Server) error {
INSERT INTO Servers(
UUID,
Path,
Source,
Flags,
CreatedAt,
) values($1, $2, $3, $4)
) values($1, $2, $3, $4, $5)
`

destDb, err := OpenDatabase()
Expand All @@ -100,7 +103,7 @@ func StoreServer(server Server) error {
}
defer stmt.Close()

_, err = stmt.Exec(server.UUID, server.Path, strings.Join(server.Flags, "||"), server.CreatedAt)
_, err = stmt.Exec(server.UUID, server.Path, server.Source, strings.Join(server.Flags, "||"), server.CreatedAt)
if err != nil {
return err
}
Expand Down Expand Up @@ -158,7 +161,7 @@ func ListServers() ([]Server, error) {
var results []Server

sqlSelect := `
select UUID, Path, Flags, CreatedAt from Servers order by CreatedAt
select UUID, Path, Source, Flags, CreatedAt from Servers order by CreatedAt
`

destDb, err := OpenDatabase()
Expand All @@ -175,7 +178,7 @@ func ListServers() ([]Server, error) {
for rows.Next() {
item := Server{}
listFlags := ""
if err = rows.Scan(&item.UUID, &item.Path, &listFlags, &item.CreatedAt); err == nil {
if err = rows.Scan(&item.UUID, &item.Path, &item.Source, &listFlags, &item.CreatedAt); err == nil {
item.Flags = strings.Split(listFlags, "||")
results = append(results, item)
}
Expand Down
93 changes: 93 additions & 0 deletions lib/qr.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package lib

import (
"crypto/rand"
"encoding/hex"
"errors"
"image"
"image/color"
"image/png"
"io"
"os"
"path/filepath"

"github.com/boombuler/barcode"
"github.com/boombuler/barcode/qr"
)

func TempFilename(prefix string, extension string) string {
randBytes := make([]byte, 16)
rand.Read(randBytes)
return filepath.Join(os.TempDir(), prefix+hex.EncodeToString(randBytes)+extension)
}

func GenerateQR(uuid, input string) (string, error) {
//log.Println("Original data:", base64)
code, err := qr.Encode(input, qr.L, qr.Unicode)
if err != nil {
return "", err
}
//log.Println("Encoded data: ", code.Content())

if input != code.Content() {
return "", errors.New("data differs")
}

code, err = barcode.Scale(code, 60, 60)
if err != nil {
return "", err
}
printPng(os.Stdout, code)

code, err = barcode.Scale(code, 600, 600)
if err != nil {
return "", err
}
output := TempFilename(uuid, ".png")
writePng(output, code)

//log.Println(`Now open test.png and scan QR code, it will be: "IAV19ysYSl0HUuG5QiCDvdHkowqdGXb0HbqUAWUzHw==" instead of "IAV19ysYSl0HUuG5QiCDvdHkowqdGXb0HbaUAWUzHw==" ('a' is changed to 'q' in 'aUAWUzHw==' part)`)
return output, nil
}

const BLACK = "\033[40m \033[0m"
const WHITE = "\033[47m \033[0m"

func printPng(writer io.Writer, img image.Image) error {

// Create a new grayscale image
bounds := img.Bounds()
w, h := bounds.Max.X, bounds.Max.Y

for y := 11; y < h-14; y++ {
for x := 12; x < w-13; x++ {
if img.At(x, y) == color.White && img.At(x, y+1) == color.White {
writer.Write([]byte(WHITE))
} else if img.At(x, y) == color.White && img.At(x, y+1) == color.Black {
writer.Write([]byte(BLACK))
} else if img.At(x, y) == color.Black && img.At(x, y+1) == color.White {
writer.Write([]byte(WHITE))
} else {
writer.Write([]byte(BLACK))
}
}
writer.Write([]byte("\n"))
}

return nil
}

func writePng(filename string, img image.Image) error {
file, err := os.Create(filename)
if err != nil {
return err
}
defer file.Close()

err = png.Encode(file, img)
if err != nil {
return err
}

return nil
}

0 comments on commit 9f44e7b

Please sign in to comment.