Refactor according to lint
This commit is contained in:
parent
73b33f5872
commit
65b9241492
382
dau.go
382
dau.go
@ -1,249 +1,255 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"bytes"
|
||||||
"strings"
|
"encoding/json"
|
||||||
"github.com/pborman/getopt"
|
"fmt"
|
||||||
"path/filepath"
|
"io"
|
||||||
"os"
|
"io/ioutil"
|
||||||
"time"
|
"log"
|
||||||
"net/http"
|
"mime/multipart"
|
||||||
"log"
|
"net/http"
|
||||||
"io"
|
"os"
|
||||||
"bytes"
|
"path/filepath"
|
||||||
"mime/multipart"
|
"strings"
|
||||||
"encoding/json"
|
"time"
|
||||||
"io/ioutil"
|
|
||||||
|
"github.com/pborman/getopt"
|
||||||
)
|
)
|
||||||
|
|
||||||
const current_version = "0.4"
|
const currentVersion = "0.4"
|
||||||
|
|
||||||
var last_check = time.Now()
|
var lastCheck = time.Now()
|
||||||
var new_last_check = time.Now()
|
var newLastCheck = time.Now()
|
||||||
|
|
||||||
var webhook_url string
|
var webhookURL string
|
||||||
var username string
|
var username string
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
webhook_opt, path, watch, username_opt := parse_options()
|
webhookOpt, path, watch, usernameOpt := parseOptions()
|
||||||
webhook_url = webhook_opt
|
webhookURL = webhookOpt
|
||||||
username = username_opt
|
username = usernameOpt
|
||||||
|
|
||||||
check_path(path)
|
checkPath(path)
|
||||||
check_updates()
|
checkUpdates()
|
||||||
|
|
||||||
log.Print("Waiting for images to appear in ", path)
|
log.Print("Waiting for images to appear in ", path)
|
||||||
|
|
||||||
// wander the path, forever
|
// wander the path, forever
|
||||||
for {
|
for {
|
||||||
err := filepath.Walk(path, check_file)
|
err := filepath.Walk(path, checkFile)
|
||||||
if err != nil { log.Fatal("could not watch path", err) }
|
if err != nil {
|
||||||
last_check = new_last_check
|
log.Fatal("could not watch path", err)
|
||||||
time.Sleep(time.Duration(watch)*time.Second)
|
}
|
||||||
}
|
lastCheck = newLastCheck
|
||||||
|
time.Sleep(time.Duration(watch) * time.Second)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func check_path(path string) {
|
func checkPath(path string) {
|
||||||
src, err := os.Stat(path)
|
src, err := os.Stat(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
if !src.IsDir() {
|
if !src.IsDir() {
|
||||||
log.Fatal(path, " is not a directory")
|
log.Fatal(path, " is not a directory")
|
||||||
os.Exit(1)
|
os.Exit(1)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func check_updates() {
|
func checkUpdates() {
|
||||||
|
|
||||||
type GithubRelease struct {
|
type GithubRelease struct {
|
||||||
Html_url string
|
HTMLURL string
|
||||||
Tag_name string
|
TagName string
|
||||||
Name string
|
Name string
|
||||||
Body string
|
Body string
|
||||||
}
|
}
|
||||||
|
|
||||||
client := &http.Client{ Timeout: time.Second * 5 }
|
client := &http.Client{Timeout: time.Second * 5}
|
||||||
resp, err := client.Get("https://api.github.com/repos/tardisx/discord-auto-upload/releases/latest")
|
resp, err := client.Get("https://api.github.com/repos/tardisx/discord-auto-upload/releases/latest")
|
||||||
if (err != nil) {
|
if err != nil {
|
||||||
log.Fatal("could not check for updates:", err)
|
log.Fatal("could not check for updates:", err)
|
||||||
}
|
}
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
body, err := ioutil.ReadAll(resp.Body)
|
||||||
if (err != nil) {
|
if err != nil {
|
||||||
log.Fatal("could not check read update response")
|
log.Fatal("could not check read update response")
|
||||||
}
|
}
|
||||||
|
|
||||||
var latest GithubRelease
|
var latest GithubRelease
|
||||||
err = json.Unmarshal(body, &latest)
|
err = json.Unmarshal(body, &latest)
|
||||||
|
|
||||||
if (err != nil) {
|
if err != nil {
|
||||||
log.Fatal("could not parse JSON: ", err)
|
log.Fatal("could not parse JSON: ", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (current_version < latest.Tag_name) {
|
if currentVersion < latest.TagName {
|
||||||
fmt.Printf("You are currently on version %s, but version %s is available\n", current_version, latest.Tag_name)
|
fmt.Printf("You are currently on version %s, but version %s is available\n", currentVersion, latest.TagName)
|
||||||
fmt.Println("----------- Release Info -----------")
|
fmt.Println("----------- Release Info -----------")
|
||||||
fmt.Println(latest.Body)
|
fmt.Println(latest.Body)
|
||||||
fmt.Println("------------------------------------")
|
fmt.Println("------------------------------------")
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func parse_options() (webhook_url string, path string, watch int, username string) {
|
func parseOptions() (webhookURL string, path string, watch int, username string) {
|
||||||
|
|
||||||
// Declare the flags to be used
|
// Declare the flags to be used
|
||||||
webhookFlag := getopt.StringLong("webhook", 'w', "", "discord webhook URL")
|
webhookFlag := getopt.StringLong("webhook", 'w', "", "discord webhook URL")
|
||||||
pathFlag := getopt.StringLong("directory", 'd', "", "directory to scan, optional, defaults to current directory")
|
pathFlag := getopt.StringLong("directory", 'd', "", "directory to scan, optional, defaults to current directory")
|
||||||
watchFlag := getopt.Int16Long ("watch", 's', 10, "time between scans")
|
watchFlag := getopt.Int16Long("watch", 's', 10, "time between scans")
|
||||||
usernameFlag := getopt.StringLong("username", 'u', "", "username for the bot upload")
|
usernameFlag := getopt.StringLong("username", 'u', "", "username for the bot upload")
|
||||||
helpFlag := getopt.BoolLong ("help", 'h', "help")
|
helpFlag := getopt.BoolLong("help", 'h', "help")
|
||||||
versionFlag := getopt.BoolLong ("version", 'v', "show version")
|
versionFlag := getopt.BoolLong("version", 'v', "show version")
|
||||||
getopt.SetParameters("")
|
getopt.SetParameters("")
|
||||||
|
|
||||||
getopt.Parse()
|
getopt.Parse()
|
||||||
|
|
||||||
if (*helpFlag) {
|
if *helpFlag {
|
||||||
getopt.PrintUsage(os.Stderr)
|
getopt.PrintUsage(os.Stderr)
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (*versionFlag) {
|
if *versionFlag {
|
||||||
fmt.Println("dau - https://github.com/tardisx/discord-auto-upload")
|
fmt.Println("dau - https://github.com/tardisx/discord-auto-upload")
|
||||||
fmt.Printf("Version: %s\n", current_version)
|
fmt.Printf("Version: %s\n", currentVersion)
|
||||||
os.Exit(0)
|
os.Exit(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
if ! getopt.IsSet("directory") {
|
if !getopt.IsSet("directory") {
|
||||||
*pathFlag = "./"
|
*pathFlag = "./"
|
||||||
log.Println("Defaulting to current directory")
|
log.Println("Defaulting to current directory")
|
||||||
}
|
}
|
||||||
|
|
||||||
if ! getopt.IsSet("webhook") {
|
if !getopt.IsSet("webhook") {
|
||||||
log.Fatal("ERROR: You must specify a --webhook URL")
|
log.Fatal("ERROR: You must specify a --webhook URL")
|
||||||
}
|
}
|
||||||
|
|
||||||
return *webhookFlag, *pathFlag, int(*watchFlag), *usernameFlag
|
return *webhookFlag, *pathFlag, int(*watchFlag), *usernameFlag
|
||||||
}
|
}
|
||||||
|
|
||||||
func check_file(path string, f os.FileInfo, err error) error {
|
func checkFile(path string, f os.FileInfo, err error) error {
|
||||||
|
|
||||||
if f.ModTime().After(last_check) && f.Mode().IsRegular() {
|
if f.ModTime().After(lastCheck) && f.Mode().IsRegular() {
|
||||||
|
|
||||||
if file_eligible(path) {
|
if fileEligible(path) {
|
||||||
// process file
|
// process file
|
||||||
process_file(path)
|
processFile(path)
|
||||||
}
|
}
|
||||||
|
|
||||||
if new_last_check.Before(f.ModTime()) {
|
if newLastCheck.Before(f.ModTime()) {
|
||||||
new_last_check = f.ModTime()
|
newLastCheck = f.ModTime()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func file_eligible(file string) (bool) {
|
func fileEligible(file string) bool {
|
||||||
extension := strings.ToLower(filepath.Ext(file))
|
extension := strings.ToLower(filepath.Ext(file))
|
||||||
if extension == ".png" || extension == ".jpg" || extension == ".gif" {
|
if extension == ".png" || extension == ".jpg" || extension == ".gif" {
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
func process_file(file string) {
|
func processFile(file string) {
|
||||||
log.Print("Uploading ", file)
|
log.Print("Uploading ", file)
|
||||||
|
|
||||||
extraParams := map[string]string{ }
|
extraParams := map[string]string{}
|
||||||
|
|
||||||
if (username != "") {
|
if username != "" {
|
||||||
extraParams["username"] = username
|
extraParams["username"] = username
|
||||||
}
|
}
|
||||||
|
|
||||||
type DiscordAPIResponseAttachment struct {
|
type DiscordAPIResponseAttachment struct {
|
||||||
Url string
|
URL string
|
||||||
Proxy_url string
|
ProxyURL string
|
||||||
Size int
|
Size int
|
||||||
Width int
|
Width int
|
||||||
Height int
|
Height int
|
||||||
Filename string
|
Filename string
|
||||||
}
|
}
|
||||||
|
|
||||||
type DiscordAPIResponse struct {
|
type DiscordAPIResponse struct {
|
||||||
Attachments []DiscordAPIResponseAttachment
|
Attachments []DiscordAPIResponseAttachment
|
||||||
Id int64 `json:",string"`
|
ID int64 `json:",string"`
|
||||||
}
|
}
|
||||||
|
|
||||||
request, err := newfileUploadRequest(webhook_url, extraParams, "file", file)
|
request, err := newfileUploadRequest(webhookURL, extraParams, "file", file)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
client := &http.Client{ Timeout: time.Second * 30 }
|
client := &http.Client{Timeout: time.Second * 30}
|
||||||
resp, err := client.Do(request)
|
resp, err := client.Do(request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
|
|
||||||
log.Fatal("Error performing request:", err)
|
log.Fatal("Error performing request:", err)
|
||||||
|
|
||||||
} else {
|
} else {
|
||||||
|
|
||||||
if (resp.StatusCode != 200) {
|
if resp.StatusCode != 200 {
|
||||||
log.Print("Bad response from server:", resp.StatusCode)
|
log.Print("Bad response from server:", resp.StatusCode)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
res_body, err := ioutil.ReadAll(resp.Body)
|
resBody, err := ioutil.ReadAll(resp.Body)
|
||||||
if (err != nil) {
|
if err != nil {
|
||||||
log.Fatal("could not deal with body", err)
|
log.Fatal("could not deal with body", err)
|
||||||
}
|
}
|
||||||
resp.Body.Close()
|
resp.Body.Close()
|
||||||
|
|
||||||
var res DiscordAPIResponse
|
var res DiscordAPIResponse
|
||||||
err = json.Unmarshal(res_body, &res)
|
err = json.Unmarshal(resBody, &res)
|
||||||
|
|
||||||
if (err != nil) {
|
if err != nil {
|
||||||
log.Print("could not parse JSON: ", err)
|
log.Print("could not parse JSON: ", err)
|
||||||
fmt.Println("Response was:", string(res_body[:]))
|
fmt.Println("Response was:", string(resBody[:]))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (len(res.Attachments) < 1) {
|
if len(res.Attachments) < 1 {
|
||||||
log.Print("bad response - no attachments?")
|
log.Print("bad response - no attachments?")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
var a = res.Attachments[0]
|
var a = res.Attachments[0]
|
||||||
elapsed := time.Since(start)
|
elapsed := time.Since(start)
|
||||||
rate := float64(a.Size) / elapsed.Seconds() / 1024.0
|
rate := float64(a.Size) / elapsed.Seconds() / 1024.0
|
||||||
|
|
||||||
log.Printf("Uploaded to %s %dx%d", a.Url, a.Width, a.Height)
|
log.Printf("Uploaded to %s %dx%d", a.URL, a.Width, a.Height)
|
||||||
log.Printf("id: %d, %d bytes transferred in %.2f seconds (%.2f KiB/s)", res.Id, a.Size, elapsed.Seconds(), rate)
|
log.Printf("id: %d, %d bytes transferred in %.2f seconds (%.2f KiB/s)", res.ID, a.Size, elapsed.Seconds(), rate)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
|
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
|
||||||
file, err := os.Open(path)
|
file, err := os.Open(path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
defer file.Close()
|
defer file.Close()
|
||||||
|
|
||||||
body := &bytes.Buffer{}
|
body := &bytes.Buffer{}
|
||||||
writer := multipart.NewWriter(body)
|
writer := multipart.NewWriter(body)
|
||||||
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
|
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
_, err = io.Copy(part, file)
|
_, err = io.Copy(part, file)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("Could not copy: ", err)
|
||||||
|
}
|
||||||
|
|
||||||
for key, val := range params {
|
for key, val := range params {
|
||||||
_ = writer.WriteField(key, val)
|
_ = writer.WriteField(key, val)
|
||||||
}
|
}
|
||||||
err = writer.Close()
|
err = writer.Close()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|
||||||
req, err := http.NewRequest("POST", uri, body)
|
req, err := http.NewRequest("POST", uri, body)
|
||||||
req.Header.Set("Content-Type", writer.FormDataContentType())
|
req.Header.Set("Content-Type", writer.FormDataContentType())
|
||||||
return req, err
|
return req, err
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user