Skip to content

Commit

Permalink
feat: better cli interactions
Browse files Browse the repository at this point in the history
  • Loading branch information
j1g5awi committed Apr 8, 2022
1 parent ca2dcaa commit acdb4f0
Show file tree
Hide file tree
Showing 4 changed files with 173 additions and 76 deletions.
22 changes: 20 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,26 @@ module simpread-sync
go 1.18

require (
github.com/valyala/fastjson v1.6.3
github.com/spf13/cobra v1.4.0
github.com/spf13/viper v1.10.1
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df
)

require gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
require (
github.com/fsnotify/fsnotify v1.5.1 // indirect
github.com/hashicorp/hcl v1.0.0 // indirect
github.com/inconshreveable/mousetrap v1.0.0 // indirect
github.com/magiconair/properties v1.8.5 // indirect
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/spf13/afero v1.6.0 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
github.com/subosito/gotenv v1.2.0 // indirect
golang.org/x/sys v0.0.0-20211210111614-af8b64212486 // indirect
golang.org/x/text v0.3.7 // indirect
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc // indirect
gopkg.in/ini.v1 v1.66.2 // indirect
gopkg.in/yaml.v2 v2.4.0 // indirect
)
63 changes: 61 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
@@ -1,6 +1,65 @@
github.com/valyala/fastjson v1.6.3 h1:tAKFnnwmeMGPbwJ7IwxcTPCNr3uIzoIj3/Fh90ra4xc=
github.com/valyala/fastjson v1.6.3/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
github.com/cpuguy83/go-md2man/v2 v2.0.1/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/fsnotify/fsnotify v1.5.1 h1:mZcQUHVQUQWoPXXtuf9yuEXKudkV2sx1E06UadKWpgI=
github.com/fsnotify/fsnotify v1.5.1/go.mod h1:T3375wBYaZdLLcVNkcVbzGHY7f1l/uK5T5Ai1i3InKU=
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
github.com/kr/fs v0.1.0/go.mod h1:FFnZGqtBN9Gxj7eW1uZ42v5BccTP0vu6NEaFoC2HwRg=
github.com/magiconair/properties v1.8.5 h1:b6kJs+EmPFMYGkow9GiUyCyOvIwYetYJ3fSaWak/Gls=
github.com/magiconair/properties v1.8.5/go.mod h1:y3VJvCyxH9uVvJTWEGAELF3aiYNyPKd5NZ3oSwXrF60=
github.com/mitchellh/mapstructure v1.4.3 h1:OVowDSCllw/YjdLkam3/sm7wEtOy59d8ndGgCcyj8cs=
github.com/mitchellh/mapstructure v1.4.3/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
github.com/pelletier/go-toml v1.9.4 h1:tjENF6MfZAg8e4ZmZTeWaWiT2vXtsoO6+iuOjFhECwM=
github.com/pelletier/go-toml v1.9.4/go.mod h1:u1nR/EPcESfeI/szUZKdtJ0xRNbUoANCkoOuaOx1Y+c=
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pkg/sftp v1.10.1/go.mod h1:lYOWFsE0bwd1+KfKJaKeuokY15vzFx25BLbzYYoAxZI=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY=
github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
github.com/spf13/cast v1.4.1 h1:s0hze+J0196ZfEMTs80N7UlFt0BDuQ7Q+JDnHiMWKdA=
github.com/spf13/cast v1.4.1/go.mod h1:Qx5cxh0v+4UWYiBimWS+eyWzqEqokIECu5etghLkUJE=
github.com/spf13/cobra v1.4.0 h1:y+wJpx64xcgO1V+RcnwW0LEHxTKRi2ZDPSBjWnrg88Q=
github.com/spf13/cobra v1.4.0/go.mod h1:Wo4iy3BUC+X2Fybo0PDqwJIv3dNRiZLHQymsfxlB84g=
github.com/spf13/jwalterweatherman v1.1.0 h1:ue6voC5bR5F8YxI5S67j9i582FU4Qvo2bmqnqMYADFk=
github.com/spf13/jwalterweatherman v1.1.0/go.mod h1:aNWZUN0dPAAO/Ljvb5BEdw96iTZ0EXowPYD95IqWIGo=
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.10.1 h1:nuJZuYpG7gTj/XqiUwg8bA0cp1+M2mC3J4g5luUYBKk=
github.com/spf13/viper v1.10.1/go.mod h1:IGlFPqhNAPKRxohIzWpI5QEy4kuI7tcl5WvR+8qy1rU=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
github.com/subosito/gotenv v1.2.0 h1:Slr1R9HxAlEKefgq5jn9U+DnETlIUa6HfgEzj0g5d7s=
github.com/subosito/gotenv v1.2.0/go.mod h1:N0PQaV/YGNqwC0u51sEeR/aUtSLEXKX9iv69rRypqCw=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190820162420-60c769a6c586/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20211210111614-af8b64212486 h1:5hpz5aRr+W1erYCL5JRhSUBJRph7l9XkNveoExlrKYk=
golang.org/x/sys v0.0.0-20211210111614-af8b64212486/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc h1:2gGKlE2+asNV9m7xrywl36YYNnBG5ZQ0r/BOOxqPpmk=
gopkg.in/alexcesaro/quotedprintable.v3 v3.0.0-20150716171945-2caba252f4dc/go.mod h1:m7x9LTH6d71AHyAX77c9yqWCCa3UKHcVEj9y7hAtKDk=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df h1:n7WqCuqOuCbNr617RXOY0AWRXxgwEyPp2z+p0+hgMuE=
gopkg.in/gomail.v2 v2.0.0-20160411212932-81ebce5c23df/go.mod h1:LRQQ+SO6ZHR7tOkpBDuZnXENFzX8qRjMDMyPD6BRkCw=
gopkg.in/ini.v1 v1.66.2 h1:XfR1dOYubytKy4Shzc2LHrrGhU0lDCfDGG1yLPmpgsI=
gopkg.in/ini.v1 v1.66.2/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b h1:h8qDotaEPuJATrMmW04NCwg7v22aHH28wwpauUhK9Oo=
162 changes: 91 additions & 71 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,66 +4,105 @@ import (
"encoding/json"
"fmt"
"io"
"os/exec"
"runtime"
"strings"

"io/ioutil"
"log"
"net/http"
"os"
"os/exec"
"path/filepath"
"runtime"
"strings"

"github.com/valyala/fastjson"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gopkg.in/gomail.v2"
)

type Config struct {
var (
configFile string
port int
syncPath string
outputPath string
smtpHost string
smtpPort int
username string
password string
smtpUsername string
smtpPassword string
mailTitle string
receiverMail string
title string
kindleMail string
)

var rootCmd = &cobra.Command{
Use: "simpread-sync",
Run: func(cmd *cobra.Command, args []string) {
http.HandleFunc("/verify", verifyHandle)
http.HandleFunc("/config", configHandle)
http.HandleFunc("/plain", plainHandle)
http.HandleFunc("/mail", mailHandle)
http.HandleFunc("/convert", convertHandle)
http.HandleFunc("/reading/", readingHandle)
http.HandleFunc("/proxy", proxyHandle)

err := http.ListenAndServe(fmt.Sprint(":", port), nil)
if err != nil {
log.Fatal(err)
}
},
}

func initConfig(path string) *Config {
func init() {
cobra.OnInitialize(initConfig)

rootCmd.Flags().StringVarP(&configFile, "config", "c", "", "config file")
rootCmd.Flags().IntVarP(&port, "port", "p", 7026, "port")
rootCmd.Flags().StringVar(&syncPath, "sync-path", "", "sync path")
rootCmd.Flags().StringVar(&outputPath, "output-path", "", "output path")
rootCmd.Flags().StringVar(&smtpHost, "smtp-host", "", "smtp host")
rootCmd.Flags().IntVar(&smtpPort, "smtp-port", 465, "smtp port")
rootCmd.Flags().StringVar(&smtpUsername, "smtp-username", "", "smtp username")
rootCmd.Flags().StringVar(&smtpPassword, "smtp-password", "", "smtp password")
rootCmd.Flags().StringVar(&mailTitle, "mail-title", "[简悦] - {{ title }}", "mail title")
rootCmd.Flags().StringVar(&receiverMail, "receiver-mail", "", "receiver mail")
rootCmd.Flags().StringVar(&kindleMail, "kindle-mail", "", "kindle mail")

viper.BindPFlag("port", rootCmd.Flags().Lookup("port"))
viper.BindPFlag("syncPath", rootCmd.Flags().Lookup("sync-path"))
viper.BindPFlag("outputPath", rootCmd.Flags().Lookup("output-path"))
viper.BindPFlag("smtpHost", rootCmd.Flags().Lookup("smtp-host"))
viper.BindPFlag("smtpPort", rootCmd.Flags().Lookup("smtp-port"))
viper.BindPFlag("smtpUsername", rootCmd.Flags().Lookup("smtp-username"))
viper.BindPFlag("smtpPassword", rootCmd.Flags().Lookup("smtp-password"))
viper.BindPFlag("mailTitle", rootCmd.Flags().Lookup("mail-title"))
viper.BindPFlag("receiverMail", rootCmd.Flags().Lookup("receiver-mail"))
viper.BindPFlag("kindleMail", rootCmd.Flags().Lookup("kindle-mail"))
}

data, err := ioutil.ReadFile(path)
if err != nil {
log.Fatal(err)
func initConfig() {
if configFile != "" {
viper.SetConfigFile(configFile)
}

config := &Config{
port: fastjson.GetInt(data, "port"),
syncPath: fastjson.GetString(data, "syncPath"),
outputPath: fastjson.GetString(data, "outputPath"),
title: fastjson.GetString(data, "title"),
smtpHost: fastjson.GetString(data, "smtpHost"),
smtpPort: fastjson.GetInt(data, "smtpPort"),
username: fastjson.GetString(data, "username"),
password: fastjson.GetString(data, "password"),
receiverMail: fastjson.GetString(data, "receiverMail"),
kindleMail: fastjson.GetString(data, "kindleMail"),
if err := viper.ReadInConfig(); err == nil {
log.Println("加载配置文件:", viper.ConfigFileUsed())
}

if config.port == 0 {
config.port = 7026
}
if config.title == "" {
config.title = "[简悦] - {{ title }}"
port = viper.GetInt("port")
syncPath = viper.GetString("syncPath")
outputPath = viper.GetString("outputPath")
smtpHost = viper.GetString("smtpHost")
smtpPort = viper.GetInt("smtpPort")
smtpUsername = viper.GetString("smtpUsername")
smtpPassword = viper.GetString("smtpPassword")
mailTitle = viper.GetString("mailTitle")
receiverMail = viper.GetString("receiverMail")
kindleMail = viper.GetString("kindleMail")

if syncPath == "" {
log.Fatal("未读取到 syncPath!")
}
if config.syncPath != "" && config.outputPath == "" {
config.outputPath = filepath.Join(config.syncPath, "output")
if outputPath == "" {
outputPath = filepath.Join(syncPath, "output")
}

log.Println("init config")

return config
}

// 未验证 json 返回 201
Expand Down Expand Up @@ -96,13 +135,13 @@ func verifyHandle(w http.ResponseWriter, r *http.Request) {
// 剩余情况下,返回一个 key 为 result 的 json
func configHandle(w http.ResponseWriter, r *http.Request) {
w.Header().Set("content-type", "application/json")
if config.syncPath != "" {
if syncPath != "" {
err := r.ParseForm()
if err != nil {
log.Fatal(err)
}
if data := r.Form.Get("config"); data != "" {
err := ioutil.WriteFile(filepath.Join(config.syncPath, "simpread_config.json"), []byte(data), 644)
err := ioutil.WriteFile(filepath.Join(syncPath, "simpread_config.json"), []byte(data), 0644)
if err != nil {
log.Fatal(err)
}
Expand All @@ -120,7 +159,7 @@ func configHandle(w http.ResponseWriter, r *http.Request) {
}
log.Println("sync config from browser")
} else {
config, err := ioutil.ReadFile(filepath.Join(config.syncPath, "simpread_config.json"))
config, err := ioutil.ReadFile(filepath.Join(syncPath, "simpread_config.json"))
if err != nil {
log.Fatal(err)
}
Expand Down Expand Up @@ -155,7 +194,6 @@ func configHandle(w http.ResponseWriter, r *http.Request) {
if err != nil {
log.Fatal(err)
}
log.Fatal("Please set syncPath first !")
}
}

Expand All @@ -169,7 +207,7 @@ func plainHandle(w http.ResponseWriter, r *http.Request) {
title := r.Form.Get("title")
content := r.Form.Get("content")

err = ioutil.WriteFile(filepath.Join(config.outputPath, title), []byte(content), 0644)
err = ioutil.WriteFile(filepath.Join(outputPath, title), []byte(content), 0644)
if err != nil {
log.Fatal(err)
}
Expand All @@ -195,20 +233,20 @@ func mailHandle(w http.ResponseWriter, r *http.Request) {
log.Fatal(err)
}
// 这里偷懒直接替换文本
title := strings.ReplaceAll(config.title, "{{ title }}", r.Form.Get("title"))
log.Print(title)
title := strings.ReplaceAll(mailTitle, "{{ title }}", r.Form.Get("title"))

content := r.Form.Get("content")
attach := r.Form.Get("attach")

d := gomail.NewDialer(config.smtpHost, config.smtpPort, config.username, config.password)
d := gomail.NewDialer(smtpHost, smtpPort, smtpUsername, smtpPassword)
s, err := d.Dial()
if err != nil {
panic(err)
}

m := gomail.NewMessage()
m.SetHeader("From", config.username)
m.SetHeader("To", config.receiverMail)
m.SetHeader("From", smtpUsername)
m.SetHeader("To", receiverMail)
m.SetHeader("Subject", title)
m.SetBody("text/html", content)

Expand Down Expand Up @@ -252,7 +290,7 @@ func convertHandle(w http.ResponseWriter, r *http.Request) {
in := r.Form.Get("in") //md
out := r.Form.Get("out") //epub

err = ioutil.WriteFile(title+"."+in, []byte(content), 0644)
err = ioutil.WriteFile("tmp-"+title+"."+in, []byte(content), 0644)
if err != nil {
log.Fatal(err)
}
Expand All @@ -261,7 +299,7 @@ func convertHandle(w http.ResponseWriter, r *http.Request) {
if runtime.GOOS == "darwin" {
pandoc = "/usr/local/bin/pandoc"
}
cmd := exec.Command(pandoc, title+"."+in, "-o", filepath.Join(config.outputPath, title+"."+out))
cmd := exec.Command(pandoc, "tmp-"+title+"."+in, "-o", filepath.Join(outputPath, title+"."+out))

err = cmd.Start()
if err != nil {
Expand All @@ -273,7 +311,7 @@ func convertHandle(w http.ResponseWriter, r *http.Request) {
log.Fatal(err)
}

os.Remove(title + "." + in)
os.Remove("tmp-" + title + "." + in)

result, err := json.Marshal(struct {
Status int `json:"status"`
Expand All @@ -296,7 +334,7 @@ func readingHandle(w http.ResponseWriter, r *http.Request) {
}

var files []string
fileInfo, err := ioutil.ReadDir(config.outputPath)
fileInfo, err := ioutil.ReadDir(outputPath)
if err != nil {
log.Fatal(err)
}
Expand Down Expand Up @@ -340,7 +378,7 @@ func readingHandle(w http.ResponseWriter, r *http.Request) {
}

if title != "" {
result, err = ioutil.ReadFile(filepath.Join(config.outputPath, title))
result, err = ioutil.ReadFile(filepath.Join(outputPath, title))
if err != nil {
log.Fatal(err)
}
Expand Down Expand Up @@ -384,27 +422,9 @@ func proxyHandle(w http.ResponseWriter, r *http.Request) {
}
}

var config *Config

func main() {
var path string
if len(os.Args) < 2 {
path = "config.json"
} else {
path = os.Args[1]
}
config = initConfig(path)

http.HandleFunc("/verify", verifyHandle)
http.HandleFunc("/config", configHandle)
http.HandleFunc("/plain", plainHandle)
http.HandleFunc("/mail", mailHandle)
http.HandleFunc("/convert", convertHandle)
http.HandleFunc("/reading/", readingHandle)
http.HandleFunc("/proxy", proxyHandle)

err := http.ListenAndServe(fmt.Sprint(":", config.port), nil)
if err != nil {
log.Fatal(err)
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
2 changes: 1 addition & 1 deletion systemd/simpread-sync@.service
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ ProtectKernelTunables=true
#ProtectKernelLogs=true
ProtectControlGroups=true
RestrictRealtime=true
ExecStart=/usr/bin/simpread-sync /home/%i/Documents/OneDrive/simpread_config.json
ExecStart=/usr/bin/simpread-sync --sync-path /home/%i/SimpRead
User=%i
Group=users
Restart=on-failure
Expand Down

0 comments on commit acdb4f0

Please sign in to comment.