Compare commits

..

2 Commits

Author SHA1 Message Date
f8bcc2c171 version 0.1.25 2020-08-13 13:45:27 +08:00
4b69d2b8bf 支持断点续传 2020-03-07 13:12:45 +08:00
17 changed files with 626 additions and 159 deletions

View File

@ -24,14 +24,14 @@ var attachcmd = &cobra.Command{
out, _ = this.Flags().GetString("out") out, _ = this.Flags().GetString("out")
} }
if src == "" || dst == "" { if src == "" || dst == "" {
starlog.Println("ERROR PATH", "red", "b") starlog.Criticalln("ERROR PATH")
this.Help() this.Help()
return return
} }
cryp := new(starainrt.StarCrypto) cryp := new(starainrt.StarCrypto)
err := cryp.Attach(src, dst, out) err := cryp.Attach(src, dst, out)
if err != nil { if err != nil {
starlog.Println(err.Error, "red", "b") starlog.Criticalln(err.Error)
} else { } else {
fmt.Println("完成") fmt.Println("完成")
} }

View File

@ -17,7 +17,7 @@ var b64cmd = &cobra.Command{
ok, _ := this.Flags().GetBool("file") ok, _ := this.Flags().GetBool("file")
de, _ := this.Flags().GetBool("decode") de, _ := this.Flags().GetBool("decode")
if len(args) != 1 { if len(args) != 1 {
starlog.Println("参数不足,请输入文件地址或字符串", "red", "b") starlog.Criticalln("参数不足,请输入文件地址或字符串")
this.Help() this.Help()
return return
} }
@ -47,7 +47,7 @@ var b64cmd = &cobra.Command{
} }
} }
if err != nil { if err != nil {
starlog.Println(err, "red", "b") starlog.Criticalln(err)
return return
} }
}, },

View File

@ -4,10 +4,13 @@ package tools
import ( import (
"bufio" "bufio"
"fmt"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"b612.me/starainrt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -18,7 +21,8 @@ var cdcmd = &cobra.Command{
Run: func(this *cobra.Command, args []string) { Run: func(this *cobra.Command, args []string) {
fileInfo, _ := os.Stdin.Stat() fileInfo, _ := os.Stdin.Stat()
if (fileInfo.Mode() & os.ModeNamedPipe) != os.ModeNamedPipe { if (fileInfo.Mode() & os.ModeNamedPipe) != os.ModeNamedPipe {
if len(args) != 1 { fmt.Println(args)
if len(args) != 0 {
os.Exit(1) os.Exit(1)
} else { } else {
exec.Command("cmd.exe", "/c", "explorer "+filepath.Dir(args[0])).Run() exec.Command("cmd.exe", "/c", "explorer "+filepath.Dir(args[0])).Run()
@ -27,7 +31,12 @@ var cdcmd = &cobra.Command{
} }
s := bufio.NewScanner(os.Stdin) s := bufio.NewScanner(os.Stdin)
for s.Scan() { for s.Scan() {
exec.Command("cmd.exe", "/c", "explorer "+filepath.Dir(s.Text())).Run() dir := s.Text()
if starainrt.IsFile(dir) {
exec.Command("cmd.exe", "/c", "explorer /n,/select,"+dir).Run()
} else {
exec.Command("cmd.exe", "/c", "explorer "+dir).Run()
}
return return
} }
}, },

View File

@ -4,7 +4,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
var Version string = "0.1.20" var Version string = "0.1.25"
var Maincmd = &cobra.Command{ var Maincmd = &cobra.Command{
Use: "", Use: "",
@ -14,5 +14,6 @@ var Maincmd = &cobra.Command{
func init() { func init() {
cobra.MousetrapHelpText = "" cobra.MousetrapHelpText = ""
Maincmd.Flags().BoolP("version", "v", false, "查看版本号")
Maincmd.Version = Version Maincmd.Version = Version
} }

View File

@ -73,7 +73,7 @@ var curlcmd = &cobra.Command{
if h != "" { if h != "" {
head := strings.Split(h, ",") head := strings.Split(h, ",")
for _, v := range head { for _, v := range head {
hp := strings.Split(v, "=") hp := strings.Split(v, ":")
if len(hp) != 2 { if len(hp) != 2 {
continue continue
} }

View File

@ -25,14 +25,14 @@ var detachcmd = &cobra.Command{
} }
num, _ := this.Flags().GetInt("num") num, _ := this.Flags().GetInt("num")
if src == "" || dst == "" { if src == "" || dst == "" {
starlog.Println("ERROR PATH", "red", "b") starlog.Criticalln("ERROR PATH")
this.Help() this.Help()
return return
} }
cryp := new(starainrt.StarCrypto) cryp := new(starainrt.StarCrypto)
err := cryp.Detach(src, num, dst, out) err := cryp.Detach(src, num, dst, out)
if err != nil { if err != nil {
starlog.Println(err.Error, "red", "b") starlog.Criticalln(err.Error)
} else { } else {
fmt.Println("完成") fmt.Println("完成")
} }

View File

@ -2,6 +2,8 @@ package tools
import ( import (
"fmt" "fmt"
"os"
"time"
"b612.me/starainrt" "b612.me/starainrt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -14,26 +16,38 @@ var gencmd = &cobra.Command{
Run: func(this *cobra.Command, args []string) { Run: func(this *cobra.Command, args []string) {
sum, _ := this.Flags().GetInt("sum") sum, _ := this.Flags().GetInt("sum")
num, _ := this.Flags().GetInt("num") num, _ := this.Flags().GetInt("num")
cap, _ := this.Flags().GetInt("cap")
if len(args) != 1 { if len(args) != 1 {
this.Help() this.Help()
return return
} }
err := starainrt.FillWithRandom(args[0], num, 1024*1024, sum, func(pect float64) { if num <= 0 {
if pect == 100 { fmt.Println("num不合法不应该小于1")
fmt.Println("文件已处理100.000000%") os.Exit(2)
} else {
fmt.Printf("文件已处理:%f%%\r", pect)
} }
if sum <= 0 {
fmt.Println("sum不合法不应该小于1")
os.Exit(2)
}
if cap <= 0 {
fmt.Println("cap不合法不应该小于1")
os.Exit(2)
}
err := starainrt.FillWithRandom(args[0], num, cap, sum, func(pect float64) {
fmt.Printf("文件已处理:%f%%\r", pect)
}) })
if err != nil { if err != nil {
fmt.Println("err:" + err.Error()) fmt.Println("err:" + err.Error())
} }
fmt.Println("文件已处理100.0000000%")
time.Sleep(time.Millisecond * 10)
}, },
} }
func init() { func init() {
gencmd.Flags().IntP("sum", "s", 3, "随机的种子组数") gencmd.Flags().IntP("sum", "s", 3, "随机的种子组数")
gencmd.Flags().IntP("num", "n", 1024, "生成的文件大小") gencmd.Flags().IntP("num", "n", 1024, "生成的文件大小")
gencmd.Flags().IntP("cap", "c", 1048576, "bufcap大小")
gencmd.MarkFlagRequired("num") gencmd.MarkFlagRequired("num")
Maincmd.AddCommand(gencmd) Maincmd.AddCommand(gencmd)
} }

View File

@ -49,7 +49,7 @@ var hashcmd = &cobra.Command{
result, err = crypto.SumAll([]byte(args[0]), method) result, err = crypto.SumAll([]byte(args[0]), method)
} }
if err != nil { if err != nil {
starlog.Println("错误:"+err.Error(), "red", "") starlog.Criticalln("错误:" + err.Error())
} }
for _, v := range method { for _, v := range method {
fmt.Printf("%s%s\n", v, result[v]) fmt.Printf("%s%s\n", v, result[v])

View File

@ -1,6 +1,7 @@
package tools package tools
import ( import (
"encoding/base64"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -19,27 +20,48 @@ import (
var port, ip, path string var port, ip, path string
var up bool var up bool
var basicAuth, certKey string
type TraceHandler struct { type TraceHandler struct {
h http.Handler h http.Handler
} }
func init() {
httpcmd.Flags().StringVarP(&port, "port", "p", "80", "监听端口")
httpcmd.Flags().StringVarP(&ip, "ip", "i", "0.0.0.0", "监听ip")
httpcmd.Flags().StringVarP(&path, "folder", "f", "./", "本地文件地址")
httpcmd.Flags().BoolVarP(&up, "upload", "u", false, "是否开启文件上传")
httpcmd.Flags().StringVarP(&basicAuth, "auth", "a", "", "HTTP BASIC AUTH认证(用户名:密码)")
httpcmd.Flags().StringVarP(&certKey, "cert", "c", "", "TLS证书路径用:分割证书与密钥")
Maincmd.AddCommand(httpcmd)
}
// httpCmd represents the http command // httpCmd represents the http command
var httpcmd = &cobra.Command{ var httpcmd = &cobra.Command{
Use: "http", Use: "http",
Short: "HTTP文件服务器", Short: "HTTP文件服务器",
Long: `HTTP文件服务器`, Long: `HTTP文件服务器`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
var err error
http.HandleFunc("/", httplisten) http.HandleFunc("/", httplisten)
path, _ = filepath.Abs(path) path, _ = filepath.Abs(path)
fmt.Println("Listening On Port:" + port) starlog.Infoln("Listening On Port:" + port)
if up { if up {
fmt.Println("upload is openned,path is /vtqeupload1127") starlog.Infoln("upload is openned,path is /vtqeupload1127")
http.HandleFunc("/vtqeupload1127", uploadfile) http.HandleFunc("/vtqeupload1127", uploadfile)
} }
err := http.ListenAndServe(ip+":"+port, nil) if certKey == "" {
err = http.ListenAndServe(ip+":"+port, nil)
} else {
certs := strings.Split(certKey, ":")
if len(certs) != 2 {
starlog.Criticalln("证书不正确!")
return
}
err = http.ListenAndServeTLS(ip+":"+port, certs[0], certs[1], nil)
}
if err != nil { if err != nil {
starlog.Println("Error:"+err.Error(), "red", "") starlog.Criticalln("Error:" + err.Error())
} }
}, },
} }
@ -52,18 +74,18 @@ func uploadfile(w http.ResponseWriter, r *http.Request) {
r.ParseMultipartForm(10485760) r.ParseMultipartForm(10485760)
file, handler, err := r.FormFile("victorique") file, handler, err := r.FormFile("victorique")
if err != nil { if err != nil {
fmt.Println(err) starlog.Errorln(err)
w.WriteHeader(502) w.WriteHeader(502)
w.Write([]byte(err.Error())) w.Write([]byte(err.Error()))
return return
} }
defer file.Close() defer file.Close()
fmt.Printf("Upload %s From %s\n", handler.Filename, r.RemoteAddr) starlog.Noticef("Upload %s From %s\n", handler.Filename, r.RemoteAddr)
fmt.Fprintf(w, `<html><body><p>%v</p><h2><a href="./vtqeupload1127/web">Return To Web Page</a></h2></body></html>`, handler.Header) fmt.Fprintf(w, `<html><body><p>%v</p><h2><a href="./vtqeupload1127/web">Return To Web Page</a></h2></body></html>`, handler.Header)
os.Mkdir("./vtqeupload1127", 0755) os.Mkdir("./vtqeupload1127", 0755)
f, err := os.OpenFile("./vtqeupload1127/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0755) f, err := os.OpenFile("./vtqeupload1127/"+handler.Filename, os.O_WRONLY|os.O_CREATE, 0755)
if err != nil { if err != nil {
fmt.Println(err) starlog.Errorln(err)
return return
} }
defer f.Close() defer f.Close()
@ -71,10 +93,40 @@ func uploadfile(w http.ResponseWriter, r *http.Request) {
} }
func httplisten(w http.ResponseWriter, r *http.Request) { func httplisten(w http.ResponseWriter, r *http.Request) {
log := starlog.Std.NewFlag()
w.Header().Set("Server", "Vicorique") w.Header().Set("Server", "Vicorique")
w.Header().Set("Powered", "B612.ME")
write401 := func() {
w.Header().Set("WWW-Authenticate", ` Basic realm="Please Enter Passwd"`)
w.WriteHeader(401)
w.Write([]byte(`
<html>
<head><title>401 Authorization Required</title></head>
<body>
<center><h1>401 Authorization Required</h1></center>
<hr><center>B612 HTTP SERVER</center>
</body>
</html>`))
}
if basicAuth != "" {
authHeader := strings.TrimSpace(r.Header.Get("Authorization"))
if len(authHeader) == 0 {
log.Noticeln("No Authed! Get Path is", r.URL.Path, r.RemoteAddr)
write401()
return
} else {
userAuth := base64.StdEncoding.EncodeToString([]byte(basicAuth))
authStr := strings.Split(authHeader, " ")
if strings.TrimSpace(authStr[1]) != userAuth {
log.Noticeln("Auth Failed! Get Path is", r.URL.Path, r.RemoteAddr, "pwd enter is", authHeader)
write401()
return
}
}
}
p := r.URL.Path p := r.URL.Path
cmd := r.URL.Query()["cmd"] cmd := r.URL.Query()["cmd"]
fmt.Println("Get " + p + " " + r.RemoteAddr) log.Noticeln("Get " + p + " " + r.RemoteAddr)
fullpath, _ := filepath.Abs(path + p) fullpath, _ := filepath.Abs(path + p)
if p == "/" { if p == "/" {
@ -84,7 +136,7 @@ func httplisten(w http.ResponseWriter, r *http.Request) {
if up { if up {
if p == "/vtqeupload1127/web" { if p == "/vtqeupload1127/web" {
w.Write([]byte(`<html><body><form id= "uploadForm" action= "../vtqeupload1127" method= "post" enctype ="multipart/form-data"> w.Write([]byte(`<html><body><form id= "uploadForm" action= "../vtqeupload1127" method= "post" enctype ="multipart/form-data">
<h1 >Victorique's File Upload Page </h1> <h1 >B612 File Upload Page </h1>
<p >上传文件 <input type ="file" name="victorique" /></p> <p >上传文件 <input type ="file" name="victorique" /></p>
<input type ="submit" value="上传"/> <input type ="submit" value="上传"/>
</form> </form>
@ -112,7 +164,7 @@ func httplisten(w http.ResponseWriter, r *http.Request) {
} }
fpdst, err := os.Open(fullpath) fpdst, err := os.Open(fullpath)
if err != nil { if err != nil {
fmt.Println(err) log.Errorln(err)
w.WriteHeader(403) w.WriteHeader(403)
w.Write([]byte("<h1>403 NO ACCESS</h1>")) w.Write([]byte("<h1>403 NO ACCESS</h1>"))
return return
@ -137,11 +189,67 @@ func httplisten(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/download") w.Header().Set("Content-Type", "application/download")
w.Header().Set("Content-Disposition", "attachment;filename="+name) w.Header().Set("Content-Disposition", "attachment;filename="+name)
} }
etag := new(starainrt.StarCrypto).MD5([]byte(fpinfo.ModTime().String()))
w.Header().Set("Content-Transfer-Encoding", "binary") w.Header().Set("Content-Transfer-Encoding", "binary")
w.Header().Set("Accept-Ranges", "bytes") w.Header().Set("Accept-Ranges", "bytes")
w.Header().Set("Content-Length", strconv.Itoa(int(fpinfo.Size()))) w.Header().Set("ETag", etag)
w.WriteHeader(200) w.Header().Set("Last-Modified", strings.ReplaceAll(fpinfo.ModTime().UTC().Format("Mon, 2 Jan 2006 15:04:05 MST"), "UTC", "GMT"))
isRange := false
var rangeStart, rangeEnd int64
rangeEnd = -1
for k, v := range r.Header {
if strings.ToLower(k) == "range" {
if strings.Index(v[0], "bytes=") < 0 {
break
}
v[0] = strings.Replace(v[0], "bytes=", "", -1)
data := strings.Split(v[0], "-")
if len(data) == 0 {
break
}
rangeStart, _ = strconv.ParseInt(data[0], 10, 64)
if len(data) == 2 {
rangeEnd, _ = strconv.ParseInt(data[1], 10, 64)
}
//w.WriteHeader(206) //206 支持断点续传
isRange = true
break
}
}
defer fpdst.Close() defer fpdst.Close()
var transferData int
if !isRange {
w.Header().Set("Content-Length", strconv.FormatInt(fpinfo.Size(), 10))
w.WriteHeader(200)
for {
buf := make([]byte, 1048576)
n, err := fpdst.Read(buf)
if n != 0 {
ns, err := w.Write(buf[0:n])
transferData += ns
if err != nil {
starlog.Errorln("Transfer Error:", err)
}
}
if err != nil {
if err == io.EOF {
break
}
break
}
}
} else {
w.Header().Set("Content-Length", strconv.FormatInt(fpinfo.Size(), 10))
if rangeEnd == -1 {
w.Header().Set("Content-Range", `bytes `+strconv.FormatInt(rangeStart, 10)+"-"+strconv.FormatInt(fpinfo.Size(), 10)+"/"+strconv.FormatInt(fpinfo.Size(), 10))
//w.Header().Set("Content-Length", strconv.FormatInt(fpinfo.Size()-rangeStart, 10))
} else {
w.Header().Set("Content-Range", `bytes `+strconv.FormatInt(rangeStart, 10)+"-"+strconv.FormatInt(rangeEnd, 10)+"/"+strconv.FormatInt(fpinfo.Size(), 10))
//w.Header().Set("Content-Length", strconv.FormatInt(1+rangeEnd-rangeStart, 10))
}
w.WriteHeader(206)
fpdst.Seek(int64(rangeStart), 0)
count := rangeStart
for { for {
buf := make([]byte, 1048576) buf := make([]byte, 1048576)
n, err := fpdst.Read(buf) n, err := fpdst.Read(buf)
@ -151,18 +259,52 @@ func httplisten(w http.ResponseWriter, r *http.Request) {
} }
return return
} }
w.Write(buf[0:n]) if rangeEnd == -1 {
ns, err := w.Write(buf[0:n])
transferData += ns
if err != nil {
starlog.Errorln("Transfer Error:", err)
} }
} else {
if count > rangeEnd {
break
}
if count+int64(n) > rangeEnd {
w.Write(buf[0 : rangeEnd-count+1])
break
} else {
ns, err := w.Write(buf[0:n])
transferData += ns
if err != nil {
starlog.Errorln("Transfer Error:", err)
}
count += int64(n)
}
}
}
}
var tani string
tani = fmt.Sprintf("%v Byte", transferData)
if f64 := float64(transferData) / 1024; f64 > 1 {
tani = fmt.Sprintf("%v KB", f64)
if f64 = float64(f64) / 1024; f64 > 1 {
tani = fmt.Sprintf("%v MB", f64)
if f64 = float64(f64) / 1024; f64 > 1 {
tani = fmt.Sprintf("%v GB", f64)
}
}
}
log.Infoln(fpinfo.Name(), "客户端下载已结束,共传输大小:"+tani)
} }
func ReadFolder(w http.ResponseWriter, r *http.Request, fullpath string, isroot bool) { func ReadFolder(w http.ResponseWriter, r *http.Request, fullpath string, isroot bool) {
dir, err := ioutil.ReadDir(fullpath) dir, err := ioutil.ReadDir(fullpath)
if err != nil { if err != nil {
fmt.Println(err) starlog.Errorln(err)
w.WriteHeader(403) w.WriteHeader(403)
w.Write([]byte("<h1>May Cannot Access!</h1>")) w.Write([]byte("<h1>May Cannot Access!</h1>"))
} }
w.Write([]byte("<html>\n<style>\np{margin: 2px auto}\n</style>\n<h1>Victorique Http Server - " + Version + "</h1>")) w.Write([]byte("<html>\n<style>\np{margin: 2px auto}\n</style>\n<h1>B612 Http Server - " + Version + "</h1>"))
if up { if up {
w.Write([]byte("<a href=/vtqeupload1127/web>Upload Web Page Is Openned!</a><br /><br />")) w.Write([]byte("<a href=/vtqeupload1127/web>Upload Web Page Is Openned!</a><br /><br />"))
} }
@ -187,10 +329,3 @@ func ReadFolder(w http.ResponseWriter, r *http.Request, fullpath string, isroot
w.Write([]byte("</pre>\n</html>")) w.Write([]byte("</pre>\n</html>"))
return return
} }
func init() {
httpcmd.Flags().StringVarP(&port, "port", "p", "80", "监听端口")
httpcmd.Flags().StringVarP(&ip, "ip", "i", "0.0.0.0", "监听ip")
httpcmd.Flags().StringVarP(&path, "folder", "f", "./", "本地文件地址")
httpcmd.Flags().BoolVarP(&up, "upload", "u", false, "是否开启文件上传")
Maincmd.AddCommand(httpcmd)
}

194
vtqe/tools/image-basic.go Normal file
View File

@ -0,0 +1,194 @@
package tools
import (
"errors"
"image"
"io/ioutil"
"os"
"github.com/golang/freetype"
"github.com/nfnt/resize"
"image/color"
"image/draw"
_ "image/gif"
_ "image/jpeg"
"image/png"
_ "image/png"
"b612.me/starainrt"
)
func OpenImage(name string) (image.Image, error) {
if !starainrt.Exists(name) {
return nil, errors.New("File Not Exists")
}
fso, err := os.Open(name)
if err != nil {
return nil, err
}
img, _, err := image.Decode(fso)
if err != nil {
return nil, err
}
return img, nil
}
func MergePhoto(big, small image.Image, bigsize, smallsize uint, x, y int) image.Image {
big = resize.Resize(bigsize, bigsize, big, resize.Lanczos3)
small = resize.Resize(smallsize, smallsize, small, resize.Lanczos3)
offset := image.Pt(x, y)
b := big.Bounds()
nimg := image.NewRGBA(b)
draw.Draw(nimg, b, big, image.ZP, draw.Src)
draw.Draw(nimg, small.Bounds(), small, offset, draw.Over)
return nimg
}
func SavePhoto(path string, img image.Image) error {
imgf, err := os.Create(path)
if err != nil {
return err
}
defer imgf.Close()
return png.Encode(imgf, img)
}
func SetAlpha(img image.Image, alpha uint8) image.Image {
size := img.Bounds()
nimg := image.NewRGBA(size)
for x := 0; x < size.Dx(); x++ {
for y := 0; y < size.Dy(); y++ {
r, g, b, a := img.At(x, y).RGBA()
r = r >> 8
g = g >> 8
b = b >> 8
a = a >> 8
nimg.Set(x, y, color.NRGBA{uint8(r), uint8(g), uint8(b), alpha})
//nimg.Set(x, y, color.Alpha{alpha})
//nimg.Set(x, y, img.At(x, y))
}
}
return nimg
}
func AddText(text string, img image.Image, x, y int, dpi, size float64, colors color.RGBA, ttf string) (image.Image, error) {
if !starainrt.Exists(ttf) {
return nil, errors.New("File Not Exists")
}
fontbyte, err := ioutil.ReadFile(ttf)
if err != nil {
return nil, err
}
font, err := freetype.ParseFont(fontbyte)
if err != nil {
return nil, err
}
nimg, ok := img.(draw.Image)
if !ok {
size := img.Bounds()
nimg = image.NewRGBA(img.Bounds())
for x := 0; x < size.Dx(); x++ {
for y := 0; y < size.Dy(); y++ {
r, g, b, a := img.At(x, y).RGBA()
nimg.Set(x, y, color.NRGBA{uint8(r), uint8(g), uint8(b), uint8(a)})
}
}
}
f := freetype.NewContext()
f.SetDPI(dpi)
f.SetFontSize(size)
f.SetFont(font)
f.SetClip(nimg.Bounds())
f.SetDst(nimg)
f.SetSrc(image.NewUniform(colors))
_, err = f.DrawString(text, freetype.Pt(x, y))
if err != nil {
return nil, err
}
return nimg, nil
}
type TextImg struct {
Text string
X int
Y int
Dpi float64
Size float64
Color color.NRGBA
}
type TextList struct {
List []TextImg
TTF []byte
}
func AddListTests(list TextList, img image.Image) (image.Image, error) {
font, err := freetype.ParseFont(list.TTF)
if err != nil {
return nil, err
}
nimg, ok := img.(draw.Image)
if !ok {
size := img.Bounds()
nimg = image.NewRGBA(img.Bounds())
for x := 0; x < size.Dx(); x++ {
for y := 0; y < size.Dy(); y++ {
r, g, b, a := img.At(x, y).RGBA()
nimg.Set(x, y, color.NRGBA{uint8(r), uint8(g), uint8(b), uint8(a)})
}
}
}
for _, v := range list.List {
f := freetype.NewContext()
f.SetDPI(v.Dpi)
f.SetFontSize(v.Size)
f.SetFont(font)
f.SetClip(nimg.Bounds())
f.SetDst(nimg)
f.SetSrc(image.NewUniform(v.Color))
_, err = f.DrawString(v.Text, freetype.Pt(v.X, v.Y))
if err != nil {
return nil, err
}
}
return nimg, nil
}
func AddTexts(text string, img image.Image, x, y int, dpi, size float64, colors color.NRGBA, ttf string) (image.Image, error) {
if !starainrt.Exists(ttf) {
return nil, errors.New("File Not Exists")
}
fontbyte, err := ioutil.ReadFile(ttf)
if err != nil {
return nil, err
}
font, err := freetype.ParseFont(fontbyte)
if err != nil {
return nil, err
}
nimg, ok := img.(draw.Image)
if !ok {
size := img.Bounds()
nimg = image.NewRGBA(img.Bounds())
for x := 0; x < size.Dx(); x++ {
for y := 0; y < size.Dy(); y++ {
r, g, b, a := img.At(x, y).RGBA()
nimg.Set(x, y, color.NRGBA{uint8(r), uint8(g), uint8(b), uint8(a)})
}
}
}
f := freetype.NewContext()
f.SetDPI(dpi)
f.SetFontSize(size)
f.SetFont(font)
f.SetClip(nimg.Bounds())
f.SetDst(nimg)
f.SetSrc(image.NewUniform(colors))
_, err = f.DrawString(text, freetype.Pt(x, y))
if err != nil {
return nil, err
}
return nimg, nil
}

83
vtqe/tools/image.go Normal file
View File

@ -0,0 +1,83 @@
package tools
import (
"fmt"
"image"
"b612.me/starlog"
"github.com/spf13/cobra"
)
func init() {
imageCmd.AddCommand(imgMirrorCmd)
Maincmd.AddCommand(imageCmd)
}
var imageCmd = &cobra.Command{
Use: "image",
Short: "图像处理",
Long: "简单的图像处理工具",
Run: func(this *cobra.Command, args []string) {
this.Help()
},
}
var imgMirrorCmd = &cobra.Command{
Use: "mirror",
Short: "图像镜像翻转",
Long: "图像镜像翻转<水平>",
Run: func(this *cobra.Command, args []string) {
if len(args) == 0 {
starlog.Errorln("请指定需要转换的图像!")
return
}
for _, v := range args {
img, err := OpenImage(v)
if err != nil {
starlog.Errorln(err, v)
continue
}
size := img.Bounds()
nimg := image.NewRGBA(size)
for x := 0; x < size.Dx(); x++ {
for y := 0; y < size.Dy(); y++ {
nimg.Set(size.Dx()-x, y, img.At(x, y))
}
}
if err := SavePhoto(v, nimg); err != nil {
starlog.Errorln(err, v)
continue
} else {
fmt.Println(v, "转换已完成!")
}
}
fmt.Println("任务完成!")
},
}
var imgAlpha = &cobra.Command{
Use: "alpha",
Short: "设置透明度",
Long: "设置alpha通道透明度",
Run: func(this *cobra.Command, args []string) {
if len(args) == 0 {
starlog.Errorln("请指定需要转换的图像!")
return
}
for _, v := range args {
img, err := OpenImage(v)
if err != nil {
starlog.Errorln(err, v)
continue
}
img = SetAlpha(img, 4)
if err := SavePhoto(v, img); err != nil {
starlog.Errorln(err, v)
continue
} else {
fmt.Println(v, "转换已完成!")
}
}
fmt.Println("任务完成!")
},
}

View File

@ -35,7 +35,7 @@ var mergecmd = &cobra.Command{
} }
}) })
if err != nil { if err != nil {
starlog.Println(err.Error, "red", "") starlog.Errorln(err.Error)
} }
}, },

View File

@ -5,6 +5,7 @@ import (
"io" "io"
"net" "net"
"strconv" "strconv"
"strings"
"time" "time"
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -668,21 +669,24 @@ func TcpNatServer(tcplocal *net.TCPAddr, pwd string) {
}() }()
} }
return return
} } else {
}() isRun := false
go func() {
if isconn {
buf := make([]byte, 7) buf := make([]byte, 7)
if strings.Split(conn.RemoteAddr().String(), ":")[0] == strings.Split(trueconn.RemoteAddr().String(), ":")[0] {
isRun = true
n, err := conn.Read(buf) n, err := conn.Read(buf)
if n != 7 || err != nil { if n != 7 || err != nil {
conn.Close() conn.Close()
return return
} }
}
if string(buf) == "v%2^f&K" { if string(buf) == "v%2^f&K" {
fmt.Println("穿透客户端已建立新连接") fmt.Println("穿透客户端已建立新连接")
if len(waitconn) != 0 { if len(waitconn) != 0 {
if waitconn[0].Msg != nil {
conn.Write(waitconn[0].Msg) conn.Write(waitconn[0].Msg)
}
waitconn[0].Msg = []byte{}
go TcpCopy(waitconn[0].Conn, conn) go TcpCopy(waitconn[0].Conn, conn)
go TcpCopy(conn, waitconn[0].Conn) go TcpCopy(conn, waitconn[0].Conn)
if len(waitconn) > 1 { if len(waitconn) > 1 {
@ -695,7 +699,12 @@ func TcpNatServer(tcplocal *net.TCPAddr, pwd string) {
} }
} else { } else {
fmt.Println("链接已加入等待列表") fmt.Println("链接已加入等待列表")
tcpnats := tcpnat{Msg: buf, Conn: conn, Date: time.Now().Unix()} var tcpnats tcpnat
if isRun {
tcpnats = tcpnat{Msg: buf, Conn: conn, Date: time.Now().Unix()}
} else {
tcpnats = tcpnat{Msg: nil, Conn: conn, Date: time.Now().Unix()}
}
waitconn = append(waitconn, tcpnats) waitconn = append(waitconn, tcpnats)
if trueconn == nil { if trueconn == nil {
isconn = false isconn = false

View File

@ -27,12 +27,12 @@ var splitcmd = &cobra.Command{
num, _ = this.Flags().GetInt("num") num, _ = this.Flags().GetInt("num")
} }
if !starainrt.Exists(src) { if !starainrt.Exists(src) {
starlog.Println("源文件不存在", "red", "b") starlog.Errorln("源文件不存在")
this.Help() this.Help()
return return
} }
if num == 0 { if num == 0 {
starlog.Println("参数num不合法", "red", "b") starlog.Errorln("参数num不合法", "red")
this.Help() this.Help()
return return
} }
@ -46,7 +46,7 @@ var splitcmd = &cobra.Command{
} }
}) })
if err != nil { if err != nil {
starlog.Println(err.Error, "red", "") starlog.Errorln(err.Error)
} }
}, },

View File

@ -14,6 +14,7 @@ import (
"time" "time"
"b612.me/starainrt" "b612.me/starainrt"
"b612.me/starlog"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -23,7 +24,8 @@ var tcpcmd = &cobra.Command{
Short: "发送并监听tcp数据包", Short: "发送并监听tcp数据包",
Long: "发送并监听tcp数据包", Long: "发送并监听tcp数据包",
Run: func(this *cobra.Command, args []string) { Run: func(this *cobra.Command, args []string) {
if len(args) != 1 { r, _ := this.Flags().GetBool("recvonly")
if len(args) != 1 && !r {
fmt.Println("请指定远程tcp地址") fmt.Println("请指定远程tcp地址")
return return
} }
@ -51,19 +53,19 @@ var tcpcmd = &cobra.Command{
fmt.Printf("Error Connect From %s : %s\n", conn.RemoteAddr(), err.Error()) fmt.Printf("Error Connect From %s : %s\n", conn.RemoteAddr(), err.Error())
continue continue
} }
fmt.Printf("Accept Connect From %s\n", conn.RemoteAddr()) starlog.Infof("Accept Connect From %s\n", conn.RemoteAddr())
go func(conns *net.TCPConn) { go func(conns *net.TCPConn) {
for { for {
buf := make([]byte, 204800) buf := make([]byte, 204800)
n, err := conns.Read(buf) n, err := conns.Read(buf)
if err != nil { if err != nil {
fmt.Printf("Error from %s Where Message=%s\n", conns.RemoteAddr(), err.Error()) starlog.Infof("Error from %s Where Message=%s\n", conns.RemoteAddr(), err.Error())
conn.Close() conn.Close()
return return
} }
fmt.Printf("Receive Msg From %s : %s\n", conns.RemoteAddr(), string(buf[0:n])) starlog.Infof("Receive Msg From %s : %s\n", conns.RemoteAddr(), string(buf[0:n]))
if b { if b {
fmt.Println(buf[0:n]) starlog.Infof("%#v", buf[0:n])
} }
} }
@ -71,6 +73,7 @@ var tcpcmd = &cobra.Command{
} }
}() }()
} }
if !r {
mytcp, err := net.DialTimeout("tcp", args[0], time.Second*15) mytcp, err := net.DialTimeout("tcp", args[0], time.Second*15)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
@ -105,7 +108,7 @@ var tcpcmd = &cobra.Command{
_, err = mytcp.Write(sendbyte) _, err = mytcp.Write(sendbyte)
} }
if err != nil { if err != nil {
fmt.Printf("Error from %s Where Message=%s\n", mytcp.RemoteAddr().String(), err.Error()) starlog.Errorf("Error from %s Where Message=%s\n", mytcp.RemoteAddr().String(), err.Error())
return return
} }
} }
@ -114,13 +117,18 @@ var tcpcmd = &cobra.Command{
buf := make([]byte, 204800) buf := make([]byte, 204800)
n, err := mytcp.Read(buf) n, err := mytcp.Read(buf)
if err != nil { if err != nil {
fmt.Printf("Error from %s Where Message=%s\n", mytcp.RemoteAddr().String(), err.Error()) starlog.Errorf("Error from %s Where Message=%s\n", mytcp.RemoteAddr().String(), err.Error())
return return
} }
fmt.Printf("Receive Msg From %s : %s\n", mytcp.RemoteAddr().String(), string(buf[0:n])) starlog.Infof("Receive Msg From %s : %s\n", mytcp.RemoteAddr().String(), string(buf[0:n]))
if b { if b {
fmt.Println(buf[0:n]) starlog.Infof("%#v", buf[0:n])
}
}
} else {
for {
time.Sleep(time.Second)
} }
} }
}, },
@ -141,6 +149,7 @@ func init() {
tcpsendcmd.Flags().StringP("regexp", "r", "", "正则匹配字符串") tcpsendcmd.Flags().StringP("regexp", "r", "", "正则匹配字符串")
tcprecvcmd.Flags().StringP("port", "p", "1127", "本地监听端口") tcprecvcmd.Flags().StringP("port", "p", "1127", "本地监听端口")
tcprecvcmd.Flags().StringP("addr", "a", "0.0.0.0", "本地监听ip") tcprecvcmd.Flags().StringP("addr", "a", "0.0.0.0", "本地监听ip")
tcpcmd.Flags().BoolP("recvonly", "r", false, "仅接收udp包")
tcpcmd.AddCommand(tcpsendcmd, tcprecvcmd) tcpcmd.AddCommand(tcpsendcmd, tcprecvcmd)
} }

View File

@ -5,8 +5,10 @@ import (
"net" "net"
"strconv" "strconv"
"strings" "strings"
"time"
"b612.me/starainrt" "b612.me/starainrt"
"b612.me/starlog"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@ -16,7 +18,9 @@ var udpcmd = &cobra.Command{
Short: "发送并监听udp数据包", Short: "发送并监听udp数据包",
Long: "发送并监听udp数据包", Long: "发送并监听udp数据包",
Run: func(this *cobra.Command, args []string) { Run: func(this *cobra.Command, args []string) {
if len(args) != 1 { var raddr *net.UDPAddr
r, _ := this.Flags().GetBool("recvonly")
if len(args) != 1 && !r {
fmt.Println("请指定远程udp地址") fmt.Println("请指定远程udp地址")
return return
} }
@ -25,7 +29,9 @@ var udpcmd = &cobra.Command{
s, _ := this.Flags().GetBool("local") s, _ := this.Flags().GetBool("local")
b, _ := this.Flags().GetBool("byte") b, _ := this.Flags().GetBool("byte")
laddr, err := net.ResolveUDPAddr("udp", a+":"+l) laddr, err := net.ResolveUDPAddr("udp", a+":"+l)
raddr, err := net.ResolveUDPAddr("udp", args[0]) if !r {
raddr, err = net.ResolveUDPAddr("udp", args[0])
}
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
return return
@ -42,16 +48,17 @@ var udpcmd = &cobra.Command{
buf := make([]byte, 204800) buf := make([]byte, 204800)
n, addr, err := udplisten.ReadFromUDP(buf) n, addr, err := udplisten.ReadFromUDP(buf)
if err != nil { if err != nil {
fmt.Printf("Error from %s Where Message=%s\n", addr.String(), err.Error()) starlog.Errorln("Error from %s Where Message=%s\n", addr.String(), err.Error())
continue continue
} }
fmt.Printf("Receive Msg From %s : %s\n", addr.String(), string(buf[0:n])) starlog.Infof("Receive Msg From %s : %s\n", addr.String(), string(buf[0:n]))
if b { if b {
fmt.Println(buf[0:n]) starlog.Infof("%#v\n", buf[0:n])
} }
} }
}() }()
} }
if !r {
myudp, err := net.DialUDP("udp", nil, raddr) myudp, err := net.DialUDP("udp", nil, raddr)
if err != nil { if err != nil {
fmt.Println(err) fmt.Println(err)
@ -89,13 +96,18 @@ var udpcmd = &cobra.Command{
buf := make([]byte, 204800) buf := make([]byte, 204800)
n, err := myudp.Read(buf) n, err := myudp.Read(buf)
if err != nil { if err != nil {
fmt.Printf("Error from %s Where Message=%s\n", myudp.RemoteAddr().String(), err.Error()) starlog.Infof("Error from %s Where Message=%s\n", myudp.RemoteAddr().String(), err.Error())
return return
} }
fmt.Printf("Receive Msg From %s : %s\n", myudp.RemoteAddr().String(), string(buf[0:n])) starlog.Infof("Receive Msg From %s : %s\n", myudp.RemoteAddr().String(), string(buf[0:n]))
if b { if b {
fmt.Println(buf[0:n]) starlog.Infof("%#v", buf[0:n])
}
}
} else {
for {
time.Sleep(time.Second)
} }
} }
}, },
@ -111,4 +123,5 @@ func init() {
udpcmd.Flags().StringP("port", "p", "1127", "本地监听端口") udpcmd.Flags().StringP("port", "p", "1127", "本地监听端口")
udpcmd.Flags().StringP("addr", "a", "0.0.0.0", "本地监听ip") udpcmd.Flags().StringP("addr", "a", "0.0.0.0", "本地监听ip")
udpcmd.Flags().BoolP("local", "s", false, "启动本地监听") udpcmd.Flags().BoolP("local", "s", false, "启动本地监听")
udpcmd.Flags().BoolP("recvonly", "r", false, "仅接收udp包")
} }

View File

@ -22,7 +22,7 @@ var viccmd = &cobra.Command{
rep, _ := this.Flags().GetBool("replace") rep, _ := this.Flags().GetBool("replace")
ext, _ := this.Flags().GetBool("extension") ext, _ := this.Flags().GetBool("extension")
if len(args) != 2 || args[1] != "sakura" { if len(args) != 2 || args[1] != "sakura" {
starlog.Println("ヴィクトリカだけが使えるよ", "red", "b") starlog.Errorln("ヴィクトリカだけが使えるよ")
return return
} }
shell := func(pect float64) { shell := func(pect float64) {
@ -77,7 +77,7 @@ var viccmd = &cobra.Command{
} }
} }
if err != nil { if err != nil {
starlog.Println(err, "red", "b") starlog.Errorln(err)
return return
} }
}, },