Compare commits
No commits in common. "master" and "v0.11.1" have entirely different histories.
1
.github/FUNDING.yml
vendored
1
.github/FUNDING.yml
vendored
@ -1 +0,0 @@
|
|||||||
github: tardisx
|
|
1
.gitignore
vendored
1
.gitignore
vendored
@ -5,4 +5,3 @@ discord-auto-upload.exe
|
|||||||
*.png
|
*.png
|
||||||
*.jpg
|
*.jpg
|
||||||
.DS_Store
|
.DS_Store
|
||||||
versioninfo.json
|
|
@ -1,45 +0,0 @@
|
|||||||
before:
|
|
||||||
hooks:
|
|
||||||
# clean up/install modules
|
|
||||||
- go mod tidy
|
|
||||||
- "go run tools/windows_metadata/release.go v{{- .Version }}"
|
|
||||||
builds:
|
|
||||||
- main:
|
|
||||||
hooks:
|
|
||||||
pre:
|
|
||||||
- "rm -f resource.syso"
|
|
||||||
- "go generate"
|
|
||||||
ignore:
|
|
||||||
- goos: windows
|
|
||||||
goarch: arm64
|
|
||||||
ldflags:
|
|
||||||
- '{{ if eq .Os "windows" }}-H=windowsgui{{ end }}'
|
|
||||||
env:
|
|
||||||
- CGO_ENABLED=0
|
|
||||||
goos:
|
|
||||||
- linux
|
|
||||||
- windows
|
|
||||||
- darwin
|
|
||||||
archives:
|
|
||||||
- replacements:
|
|
||||||
darwin: Darwin
|
|
||||||
linux: Linux
|
|
||||||
windows: Windows
|
|
||||||
386: i386
|
|
||||||
amd64: x86_64
|
|
||||||
format_overrides:
|
|
||||||
- goos: windows
|
|
||||||
format: zip
|
|
||||||
checksum:
|
|
||||||
name_template: 'checksums.txt'
|
|
||||||
snapshot:
|
|
||||||
name_template: "{{ incpatch .Version }}-next"
|
|
||||||
changelog:
|
|
||||||
sort: asc
|
|
||||||
filters:
|
|
||||||
exclude:
|
|
||||||
- '^Merge:'
|
|
||||||
- '^docs:'
|
|
||||||
- '^test:'
|
|
||||||
- '^[Bb]ump'
|
|
||||||
- '^[Cc]lean'
|
|
10
.vscode/settings.json
vendored
10
.vscode/settings.json
vendored
@ -1,10 +0,0 @@
|
|||||||
{
|
|
||||||
"cSpell.words": [
|
|
||||||
"daulog",
|
|
||||||
"Debugf",
|
|
||||||
"inconsolata",
|
|
||||||
"Infof",
|
|
||||||
"Markedup",
|
|
||||||
"skratchdot"
|
|
||||||
]
|
|
||||||
}
|
|
42
CHANGELOG.md
42
CHANGELOG.md
@ -3,46 +3,6 @@ All notable changes to this project will be documented in this file.
|
|||||||
|
|
||||||
## [Unreleased]
|
## [Unreleased]
|
||||||
|
|
||||||
## [v0.13.0] - 2022-11-01
|
|
||||||
|
|
||||||
- Resize images if needed to fit in discord 8Mb upload limits
|
|
||||||
|
|
||||||
|
|
||||||
## [v0.12.4] - 2022-09-15
|
|
||||||
|
|
||||||
- Document that watcher intervals are in seconds
|
|
||||||
|
|
||||||
## [v0.12.3] - 2022-05-09
|
|
||||||
|
|
||||||
- Fix a race condition occasionally causing multiple duplicate uploads
|
|
||||||
|
|
||||||
## [v0.12.2] - 2022-05-01
|
|
||||||
|
|
||||||
- Automatically open your web browser to the `dau` web interface
|
|
||||||
(can be disabled in configuration)
|
|
||||||
- Add system tray/menubar icon with menus to open web interface, quit and
|
|
||||||
other links
|
|
||||||
- Superfluous text console removed on windows
|
|
||||||
|
|
||||||
## [v0.12.1] - 2022-05-01
|
|
||||||
|
|
||||||
- Show if a new version is available in the web interface
|
|
||||||
- Rework logging and fix the log display in the web interface
|
|
||||||
|
|
||||||
## [v0.12.0] - 2022-04-03
|
|
||||||
|
|
||||||
- Break upload page into pending/current/complete sections
|
|
||||||
- Add preview thumbnails for each upload
|
|
||||||
- Add feature to hold an image for upload, so the user can
|
|
||||||
choose to upload it or not
|
|
||||||
- Add simple image editor to add text captions
|
|
||||||
- Discord server created: https://discord.gg/eErG9sntbZ
|
|
||||||
|
|
||||||
## [v0.11.2] - 2021-10-19
|
|
||||||
|
|
||||||
- Really fix the bug where too large attachments keep retrying
|
|
||||||
- Fix tests on Windows
|
|
||||||
|
|
||||||
## [v0.11.1] - 2021-10-11
|
## [v0.11.1] - 2021-10-11
|
||||||
|
|
||||||
- Improve logging and error handling
|
- Improve logging and error handling
|
||||||
@ -106,4 +66,4 @@ Add --exclude option to avoid uploading files in thumbnail directories
|
|||||||
|
|
||||||
## [0.1.0] - 2017-02-16
|
## [0.1.0] - 2017-02-16
|
||||||
|
|
||||||
Initial release
|
Initial release
|
63
README.md
63
README.md
@ -8,8 +8,6 @@ This program automatically uploads new screenshots that appear in a folder on yo
|
|||||||
|
|
||||||
Point it at your Steam screenshot folder, or similar, and shortly after you hit your screenshot hotkey the screenshot will appear in your discord chat.
|
Point it at your Steam screenshot folder, or similar, and shortly after you hit your screenshot hotkey the screenshot will appear in your discord chat.
|
||||||
|
|
||||||
Need help? Join our discord: https://discord.gg/eErG9sntbZ
|
|
||||||
|
|
||||||
## What you'll need
|
## What you'll need
|
||||||
|
|
||||||
* A folder where screenshots are stored
|
* A folder where screenshots are stored
|
||||||
@ -29,13 +27,8 @@ You'll need to [download Go](https://golang.org/dl/), check the code out somewhe
|
|||||||
## Using it
|
## Using it
|
||||||
|
|
||||||
`dau` configuration is managed via its internal web interface. When the executable is run, you can visit
|
`dau` configuration is managed via its internal web interface. When the executable is run, you can visit
|
||||||
`http://localhost:9090` in your web browser to configure it. On Windows, a tray icon is created to provide
|
`http://localhost:9090` in your web browser to configure the it. Configuration persists across runs, it is
|
||||||
access to the web interface.
|
saved in a file called '.dau.json' in your home directory.
|
||||||
|
|
||||||
The web browser will be loaded automatically when you start the program, if possible. This option can be
|
|
||||||
disabled in the settings.
|
|
||||||
|
|
||||||
Configuration persists across runs, it is saved in a file called '.dau.json' in your home directory.
|
|
||||||
|
|
||||||
The first time you run it, you will need to configure at least the discord web hook and the watch path for
|
The first time you run it, you will need to configure at least the discord web hook and the watch path for
|
||||||
`dau` to be useful.
|
`dau` to be useful.
|
||||||
@ -48,51 +41,39 @@ Thus, you do not have to worry about pointing `dau` at a directory full of image
|
|||||||
|
|
||||||
## Configuration options
|
## Configuration options
|
||||||
|
|
||||||
See the web interface at http://localhost:9090 to configure `dau`. The configuration is a single page of options,
|
See the web interface at http://localhost:9090 to configure `dau`.
|
||||||
no changes will take effect until the "Save All Configuration" button has been pressed.
|
|
||||||
|
|
||||||
### Global options
|
### 'Discord WebHook URL'
|
||||||
|
|
||||||
* Server port - the port number the web server listens on. Requires restart
|
The webhook URL from Discord. See https://support.discordapp.com/hc/en-us/articles/228383668-Intro-to-Webhooks
|
||||||
* Watch interval - how often each watcher will check the directory for new files, in seconds
|
for more information on setting one up.
|
||||||
|
|
||||||
### Watcher configuration
|
### 'Bot Username'
|
||||||
|
|
||||||
There can be one or more watchers configured. Each watcher looks in a particular directory,
|
This is completely optional and can be any arbitrary string. It makes the upload
|
||||||
and uploads new files to a different discord channel.
|
|
||||||
|
|
||||||
Each watcher has the following configuration options:
|
|
||||||
|
|
||||||
* Directory to watch - This is the path that `dau` will periodically inspect, looking for new images.
|
|
||||||
Note that subdirectories are also scanned. You need to enter the full filesystem path here.
|
|
||||||
* Discord WebHook URL - The webhook URL from Discord. See https://support.discordapp.com/hc/en-us/articles/228383668-Intro-to-Webhooks for more information on setting one up.
|
|
||||||
* Username - This is completely optional and can be any arbitrary string. It makes the upload
|
|
||||||
appear to come from a different user (though this is visual only, and does not
|
appear to come from a different user (though this is visual only, and does not
|
||||||
actually hide the bot identity in any way). You might like to set it to your own
|
actually hide the bot identity in any way). You might like to set it to your own
|
||||||
discord name.
|
discord name.
|
||||||
* Watermark - Disabling the watermark will prevent `dau` from putting a link to the projects
|
|
||||||
on the bottom left hand corner of your uploaded images. I really appreciate it when you leave this enabled :-)
|
|
||||||
* Hold Uploads - See "Holding uploads" below
|
|
||||||
* Exclusions - You can set one or more arbitrary strings to exclude files from being matched by this watcher.
|
|
||||||
This is most commonly used to prevent thumbnail images from being uploads.
|
|
||||||
|
|
||||||
## Holding uploads
|
### 'Directory to watch'
|
||||||
|
|
||||||
If the "Hold Uploads" option is selected, newly found files will not immediately be uploaded. They will be available
|
This is the path that `dau` will periodically inspect, looking for new images.
|
||||||
in the "uploads" tab of the web interface. This has two purposes:
|
Note that subdirectories are also scanned. You need to enter the full filesystem
|
||||||
|
path here.
|
||||||
|
|
||||||
* It gives you a chance to vet your screenshot selection before uploading
|
### 'Period between filesystem checks'
|
||||||
* It allows you to edit the images before uploading.
|
|
||||||
|
|
||||||
In the list of uploads there are three actions you can take on each file:
|
This is the number of seconds between which `dau` will look for new images.
|
||||||
|
|
||||||
* Press "upload" to upload the image
|
### 'Do not watermark images'
|
||||||
* Press "reject" to reject the image
|
|
||||||
* Click on the image thumbnail to edit the image
|
|
||||||
|
|
||||||
If you click on the image thumbnail, an image editor will open, and allow you to add text captions to your image.
|
This will disable the watermarking of images. I like it when you don't set this :-)
|
||||||
More functionality is coming soon. When you are finished editing, choose "Apply" and you will return to the uploads
|
|
||||||
list. Click "upload" to upload your edited image.
|
### 'Files to exclude'
|
||||||
|
|
||||||
|
This is a string to match against the filename to check for exclusions. The common
|
||||||
|
use case is to use 'thumbnail' or similar if your image directory contains additional
|
||||||
|
thumbnail files.
|
||||||
|
|
||||||
## Limitations/bugs
|
## Limitations/bugs
|
||||||
|
|
||||||
|
45
build-release.pl
Executable file
45
build-release.pl
Executable file
@ -0,0 +1,45 @@
|
|||||||
|
#!/usr/bin/env perl
|
||||||
|
|
||||||
|
use strict;
|
||||||
|
use warnings;
|
||||||
|
|
||||||
|
open my $fh, "<", "version/version.go" || die $!;
|
||||||
|
|
||||||
|
my $version;
|
||||||
|
while (<$fh>) {
|
||||||
|
$version = $1 if /^const\s+CurrentVersion.*?"(v[\d\.]+)"/;
|
||||||
|
}
|
||||||
|
close $fh;
|
||||||
|
|
||||||
|
die "no version?" unless defined $version;
|
||||||
|
|
||||||
|
# quit if tests fail
|
||||||
|
system("go test ./...") && die "not building release with failing tests";
|
||||||
|
|
||||||
|
# so lazy
|
||||||
|
system "rm", "-rf", "release", "dist";
|
||||||
|
system "mkdir", "release";
|
||||||
|
system "mkdir", "dist";
|
||||||
|
|
||||||
|
my %build = (
|
||||||
|
win => { env => { GOOS => 'windows', GOARCH => 'amd64' }, filename => 'dau.exe' },
|
||||||
|
linux => { env => { GOOS => 'linux', GOARCH => 'amd64' }, filename => 'dau' },
|
||||||
|
mac => { env => { GOOS => 'darwin', GOARCH => 'amd64' }, filename => 'dau' },
|
||||||
|
);
|
||||||
|
|
||||||
|
foreach my $type (keys %build) {
|
||||||
|
mkdir "release/$type";
|
||||||
|
}
|
||||||
|
|
||||||
|
add_extras();
|
||||||
|
|
||||||
|
foreach my $type (keys %build) {
|
||||||
|
local $ENV{GOOS} = $build{$type}->{env}->{GOOS};
|
||||||
|
local $ENV{GOARCH} = $build{$type}->{env}->{GOARCH};
|
||||||
|
system "go", "build", "-o", "release/$type/" . $build{$type}->{filename};
|
||||||
|
system "zip", "-j", "dist/dau-$type-$version.zip", ( glob "release/$type/*" );
|
||||||
|
}
|
||||||
|
|
||||||
|
sub add_extras {
|
||||||
|
# we used to have a .bat file here, but no longer needed
|
||||||
|
}
|
@ -27,7 +27,6 @@ type Watcher struct {
|
|||||||
Path string
|
Path string
|
||||||
Username string
|
Username string
|
||||||
NoWatermark bool
|
NoWatermark bool
|
||||||
HoldUploads bool
|
|
||||||
Exclude []string
|
Exclude []string
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -38,16 +37,8 @@ type ConfigV2 struct {
|
|||||||
Watchers []Watcher
|
Watchers []Watcher
|
||||||
}
|
}
|
||||||
|
|
||||||
type ConfigV3 struct {
|
|
||||||
WatchInterval int
|
|
||||||
Version int
|
|
||||||
Port int
|
|
||||||
OpenBrowserOnStart bool
|
|
||||||
Watchers []Watcher
|
|
||||||
}
|
|
||||||
|
|
||||||
type ConfigService struct {
|
type ConfigService struct {
|
||||||
Config *ConfigV3
|
Config *ConfigV2
|
||||||
Changed chan bool
|
Changed chan bool
|
||||||
ConfigFilename string
|
ConfigFilename string
|
||||||
}
|
}
|
||||||
@ -62,11 +53,11 @@ func DefaultConfigService() *ConfigService {
|
|||||||
// LoadOrInit loads the current configuration from the config file, or creates
|
// LoadOrInit loads the current configuration from the config file, or creates
|
||||||
// a new config file if none exists.
|
// a new config file if none exists.
|
||||||
func (c *ConfigService) LoadOrInit() error {
|
func (c *ConfigService) LoadOrInit() error {
|
||||||
daulog.Debugf("Trying to load config from %s\n", c.ConfigFilename)
|
daulog.SendLog(fmt.Sprintf("Trying to load config from %s\n", c.ConfigFilename), daulog.LogTypeDebug)
|
||||||
_, err := os.Stat(c.ConfigFilename)
|
_, err := os.Stat(c.ConfigFilename)
|
||||||
if os.IsNotExist(err) {
|
if os.IsNotExist(err) {
|
||||||
daulog.Info("NOTE: No config file, writing out sample configuration")
|
daulog.SendLog("NOTE: No config file, writing out sample configuration", daulog.LogTypeInfo)
|
||||||
daulog.Info("You need to set the configuration via the web interface")
|
daulog.SendLog("You need to set the configuration via the web interface", daulog.LogTypeInfo)
|
||||||
c.Config = DefaultConfig()
|
c.Config = DefaultConfig()
|
||||||
return c.Save()
|
return c.Save()
|
||||||
} else {
|
} else {
|
||||||
@ -74,12 +65,11 @@ func (c *ConfigService) LoadOrInit() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func DefaultConfig() *ConfigV3 {
|
func DefaultConfig() *ConfigV2 {
|
||||||
c := ConfigV3{}
|
c := ConfigV2{}
|
||||||
c.Version = 3
|
c.Version = 2
|
||||||
c.WatchInterval = 10
|
c.WatchInterval = 10
|
||||||
c.Port = 9090
|
c.Port = 9090
|
||||||
c.OpenBrowserOnStart = true
|
|
||||||
w := Watcher{
|
w := Watcher{
|
||||||
WebHookURL: "https://webhook.url.here",
|
WebHookURL: "https://webhook.url.here",
|
||||||
Path: "/your/screenshot/dir/here",
|
Path: "/your/screenshot/dir/here",
|
||||||
@ -93,7 +83,7 @@ func DefaultConfig() *ConfigV3 {
|
|||||||
|
|
||||||
// Load will load the configuration from a known-to-exist config file.
|
// Load will load the configuration from a known-to-exist config file.
|
||||||
func (c *ConfigService) Load() error {
|
func (c *ConfigService) Load() error {
|
||||||
daulog.Debugf("Loading from %s", c.ConfigFilename)
|
fmt.Printf("Loading from %s\n\n", c.ConfigFilename)
|
||||||
|
|
||||||
data, err := ioutil.ReadFile(c.ConfigFilename)
|
data, err := ioutil.ReadFile(c.ConfigFilename)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -104,10 +94,12 @@ func (c *ConfigService) Load() error {
|
|||||||
return fmt.Errorf("cannot decode config file %s: %s", c.ConfigFilename, err.Error())
|
return fmt.Errorf("cannot decode config file %s: %s", c.ConfigFilename, err.Error())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fmt.Printf("Got config: %#v", c.Config)
|
||||||
|
|
||||||
// Version 0 predates config migrations
|
// Version 0 predates config migrations
|
||||||
if c.Config.Version == 0 {
|
if c.Config.Version == 0 {
|
||||||
// need to migrate this
|
// need to migrate this
|
||||||
daulog.Info("Migrating config to V2")
|
daulog.SendLog("Migrating config to V2", daulog.LogTypeInfo)
|
||||||
|
|
||||||
configV1 := ConfigV1{}
|
configV1 := ConfigV1{}
|
||||||
err = json.Unmarshal([]byte(data), &configV1)
|
err = json.Unmarshal([]byte(data), &configV1)
|
||||||
@ -131,18 +123,11 @@ func (c *ConfigService) Load() error {
|
|||||||
c.Config.Watchers = []Watcher{onlyWatcher}
|
c.Config.Watchers = []Watcher{onlyWatcher}
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.Config.Version == 2 {
|
|
||||||
// need to migrate this
|
|
||||||
daulog.Info("Migrating config to V3")
|
|
||||||
c.Config.Version = 3
|
|
||||||
c.Config.OpenBrowserOnStart = true
|
|
||||||
}
|
|
||||||
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *ConfigService) Save() error {
|
func (c *ConfigService) Save() error {
|
||||||
daulog.Info("saving configuration")
|
daulog.SendLog("saving configuration", daulog.LogTypeInfo)
|
||||||
// sanity checks
|
// sanity checks
|
||||||
for _, watcher := range c.Config.Watchers {
|
for _, watcher := range c.Config.Watchers {
|
||||||
|
|
||||||
|
@ -10,20 +10,16 @@ func TestNoConfig(t *testing.T) {
|
|||||||
c := ConfigService{}
|
c := ConfigService{}
|
||||||
|
|
||||||
c.ConfigFilename = emptyTempFile()
|
c.ConfigFilename = emptyTempFile()
|
||||||
err := os.Remove(c.ConfigFilename)
|
os.Remove(c.ConfigFilename)
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("could not remove file: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
defer os.Remove(c.ConfigFilename) // because we are about to create it
|
defer os.Remove(c.ConfigFilename) // because we are about to create it
|
||||||
|
|
||||||
err = c.LoadOrInit()
|
err := c.LoadOrInit()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Errorf("unexpected failure from load: %s", err)
|
t.Errorf("unexpected failure from load: %s", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
if c.Config.Version != 3 {
|
if c.Config.Version != 2 {
|
||||||
t.Error("not version 3 starting config")
|
t.Error("not version 2 starting config")
|
||||||
}
|
}
|
||||||
|
|
||||||
if fileSize(c.ConfigFilename) < 40 {
|
if fileSize(c.ConfigFilename) < 40 {
|
||||||
@ -45,7 +41,7 @@ func TestEmptyFileConfig(t *testing.T) {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func TestMigrateFromV1toV3(t *testing.T) {
|
func TestMigrateFromV1toV2(t *testing.T) {
|
||||||
c := ConfigService{}
|
c := ConfigService{}
|
||||||
|
|
||||||
c.ConfigFilename = v1Config()
|
c.ConfigFilename = v1Config()
|
||||||
@ -53,12 +49,8 @@ func TestMigrateFromV1toV3(t *testing.T) {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
t.Error("unexpected error from LoadOrInit()")
|
t.Error("unexpected error from LoadOrInit()")
|
||||||
}
|
}
|
||||||
if c.Config.Version != 3 {
|
if c.Config.Version != 2 {
|
||||||
t.Errorf("Version %d not 3", c.Config.Version)
|
t.Errorf("Version %d not 2", c.Config.Version)
|
||||||
}
|
|
||||||
|
|
||||||
if c.Config.OpenBrowserOnStart != true {
|
|
||||||
t.Errorf("Open browser on start not true")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if len(c.Config.Watchers) != 1 {
|
if len(c.Config.Watchers) != 1 {
|
||||||
@ -92,7 +84,6 @@ func emptyTempFile() string {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
panic(err)
|
||||||
}
|
}
|
||||||
f.Close()
|
|
||||||
return f.Name()
|
return f.Name()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
103
dau.go
103
dau.go
@ -2,10 +2,13 @@ package main
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"flag"
|
"flag"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/fs"
|
"io/fs"
|
||||||
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
@ -15,12 +18,12 @@ import (
|
|||||||
_ "image/jpeg"
|
_ "image/jpeg"
|
||||||
_ "image/png"
|
_ "image/png"
|
||||||
|
|
||||||
|
// "github.com/skratchdot/open-golang/open"
|
||||||
|
|
||||||
"github.com/tardisx/discord-auto-upload/config"
|
"github.com/tardisx/discord-auto-upload/config"
|
||||||
daulog "github.com/tardisx/discord-auto-upload/log"
|
daulog "github.com/tardisx/discord-auto-upload/log"
|
||||||
"github.com/tardisx/discord-auto-upload/upload"
|
"github.com/tardisx/discord-auto-upload/upload"
|
||||||
|
|
||||||
"github.com/skratchdot/open-golang/open"
|
|
||||||
|
|
||||||
// "github.com/tardisx/discord-auto-upload/upload"
|
// "github.com/tardisx/discord-auto-upload/upload"
|
||||||
"github.com/tardisx/discord-auto-upload/version"
|
"github.com/tardisx/discord-auto-upload/version"
|
||||||
"github.com/tardisx/discord-auto-upload/web"
|
"github.com/tardisx/discord-auto-upload/web"
|
||||||
@ -37,58 +40,41 @@ func main() {
|
|||||||
|
|
||||||
parseOptions()
|
parseOptions()
|
||||||
|
|
||||||
// grab the conf, register to notice changes
|
// grab the config, register to notice changes
|
||||||
conf := config.DefaultConfigService()
|
config := config.DefaultConfigService()
|
||||||
configChanged := make(chan bool)
|
configChanged := make(chan bool)
|
||||||
conf.Changed = configChanged
|
config.Changed = configChanged
|
||||||
conf.LoadOrInit()
|
config.LoadOrInit()
|
||||||
|
|
||||||
// create the uploader
|
// create the uploader
|
||||||
up := upload.NewUploader()
|
up := upload.NewUploader()
|
||||||
|
|
||||||
// log.Print("Opening web browser")
|
// log.Print("Opening web browser")
|
||||||
// open.Start("http://localhost:9090")
|
// open.Start("http://localhost:9090")
|
||||||
web := web.WebService{Config: conf, Uploader: up}
|
web := web.WebService{Config: config, Uploader: up}
|
||||||
web.StartWebServer()
|
web.StartWebServer()
|
||||||
|
|
||||||
if conf.Config.OpenBrowserOnStart {
|
go func() { checkUpdates() }()
|
||||||
openWebBrowser(conf.Config.Port)
|
|
||||||
}
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
version.GetOnlineVersion()
|
|
||||||
if version.UpdateAvailable() {
|
|
||||||
daulog.Info("*** NEW VERSION AVAILABLE ***")
|
|
||||||
daulog.Infof("You are currently on version %s, but version %s is available\n", version.CurrentVersion, version.LatestVersionInfo.TagName)
|
|
||||||
daulog.Info("----------- Release Info -----------")
|
|
||||||
daulog.Info(version.LatestVersionInfo.Body)
|
|
||||||
daulog.Info("------------------------------------")
|
|
||||||
daulog.Info("Upgrade at https://github.com/tardisx/discord-auto-upload/releases/latest")
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// create the watchers, restart them if config changes
|
// create the watchers, restart them if config changes
|
||||||
// blocks forever
|
// blocks forever
|
||||||
go func() {
|
startWatchers(config, up, configChanged)
|
||||||
startWatchers(conf, up, configChanged)
|
|
||||||
}()
|
|
||||||
mainloop(conf)
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func startWatchers(config *config.ConfigService, up *upload.Uploader, configChange chan bool) {
|
func startWatchers(config *config.ConfigService, up *upload.Uploader, configChange chan bool) {
|
||||||
for {
|
for {
|
||||||
daulog.Debug("Creating watchers")
|
daulog.SendLog("Creating watchers", daulog.LogTypeInfo)
|
||||||
ctx, cancel := context.WithCancel(context.Background())
|
ctx, cancel := context.WithCancel(context.Background())
|
||||||
for _, c := range config.Config.Watchers {
|
for _, c := range config.Config.Watchers {
|
||||||
daulog.Infof("Creating watcher for %s with interval %d", c.Path, config.Config.WatchInterval)
|
log.Printf("Creating watcher for %s interval %d", c.Path, config.Config.WatchInterval)
|
||||||
watcher := watch{uploader: up, lastCheck: time.Now(), newLastCheck: time.Now(), config: c}
|
watcher := watch{uploader: up, lastCheck: time.Now(), newLastCheck: time.Now(), config: c}
|
||||||
go watcher.Watch(config.Config.WatchInterval, ctx)
|
go watcher.Watch(config.Config.WatchInterval, ctx)
|
||||||
}
|
}
|
||||||
// wait for single that the config changed
|
// wait for single that the config changed
|
||||||
<-configChange
|
<-configChange
|
||||||
cancel()
|
cancel()
|
||||||
daulog.Info("starting new watchers due to config change")
|
daulog.SendLog("starting new watchers due to config change", daulog.LogTypeInfo)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
@ -97,7 +83,7 @@ func (w *watch) Watch(interval int, ctx context.Context) {
|
|||||||
for {
|
for {
|
||||||
select {
|
select {
|
||||||
case <-ctx.Done():
|
case <-ctx.Done():
|
||||||
daulog.Info("Killing old watcher")
|
daulog.SendLog("Killing old watcher", daulog.LogTypeInfo)
|
||||||
return
|
return
|
||||||
default:
|
default:
|
||||||
newFiles := w.ProcessNewFiles()
|
newFiles := w.ProcessNewFiles()
|
||||||
@ -106,7 +92,7 @@ func (w *watch) Watch(interval int, ctx context.Context) {
|
|||||||
}
|
}
|
||||||
// upload them
|
// upload them
|
||||||
w.uploader.Upload()
|
w.uploader.Upload()
|
||||||
daulog.Debugf("sleeping for %ds before next check of %s", interval, w.config.Path)
|
daulog.SendLog(fmt.Sprintf("sleeping for %ds before next check of %s", interval, w.config.Path), daulog.LogTypeDebug)
|
||||||
time.Sleep(time.Duration(interval) * time.Second)
|
time.Sleep(time.Duration(interval) * time.Second)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -129,7 +115,6 @@ func (w *watch) ProcessNewFiles() []string {
|
|||||||
}
|
}
|
||||||
w.lastCheck = w.newLastCheck
|
w.lastCheck = w.newLastCheck
|
||||||
}
|
}
|
||||||
|
|
||||||
return newFiles
|
return newFiles
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -138,11 +123,11 @@ func (w *watch) ProcessNewFiles() []string {
|
|||||||
func (w *watch) checkPath() bool {
|
func (w *watch) checkPath() bool {
|
||||||
src, err := os.Stat(w.config.Path)
|
src, err := os.Stat(w.config.Path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
daulog.Errorf("Problem with path '%s': %s", w.config.Path, err)
|
daulog.SendLog(fmt.Sprintf("Problem with path '%s': %s", w.config.Path, err), daulog.LogTypeError)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
if !src.IsDir() {
|
if !src.IsDir() {
|
||||||
daulog.Errorf("Problem with path '%s': is not a directory", w.config.Path)
|
daulog.SendLog(fmt.Sprintf("Problem with path '%s': is not a directory", w.config.Path), daulog.LogTypeError)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
return true
|
return true
|
||||||
@ -184,6 +169,51 @@ func (w *watch) checkFile(path string, found *[]string, exclusions []string) err
|
|||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func checkUpdates() {
|
||||||
|
|
||||||
|
type GithubRelease struct {
|
||||||
|
HTMLURL string `json:"html_url"`
|
||||||
|
TagName string `json:"tag_name"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Body string `json:"body"`
|
||||||
|
}
|
||||||
|
|
||||||
|
daulog.SendLog("checking for new version", daulog.LogTypeInfo)
|
||||||
|
|
||||||
|
client := &http.Client{Timeout: time.Second * 5}
|
||||||
|
resp, err := client.Get("https://api.github.com/repos/tardisx/discord-auto-upload/releases/latest")
|
||||||
|
if err != nil {
|
||||||
|
daulog.SendLog(fmt.Sprintf("WARNING: Update check failed: %v", err), daulog.LogTypeError)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
body, err := ioutil.ReadAll(resp.Body)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("could not check read update response")
|
||||||
|
}
|
||||||
|
|
||||||
|
var latest GithubRelease
|
||||||
|
err = json.Unmarshal(body, &latest)
|
||||||
|
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal("could not parse JSON: ", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// pre v0.11.0 version (ie before semver) did a simple string comparison,
|
||||||
|
// but since "0.10.0" < "v0.11.0" they should still get prompted to upgrade
|
||||||
|
// ok
|
||||||
|
if version.NewVersionAvailable(latest.TagName) {
|
||||||
|
fmt.Printf("You are currently on version %s, but version %s is available\n", version.CurrentVersion, latest.TagName)
|
||||||
|
fmt.Println("----------- Release Info -----------")
|
||||||
|
fmt.Println(latest.Body)
|
||||||
|
fmt.Println("------------------------------------")
|
||||||
|
fmt.Println("Upgrade at https://github.com/tardisx/discord-auto-upload/releases/latest")
|
||||||
|
daulog.SendLog(fmt.Sprintf("New version available: %s - download at https://github.com/tardisx/discord-auto-upload/releases/latest", latest.TagName), daulog.LogTypeInfo)
|
||||||
|
}
|
||||||
|
|
||||||
|
daulog.SendLog("already running latest version", daulog.LogTypeInfo)
|
||||||
|
}
|
||||||
|
|
||||||
func parseOptions() {
|
func parseOptions() {
|
||||||
var versionFlag bool
|
var versionFlag bool
|
||||||
flag.BoolVar(&versionFlag, "version", false, "show version")
|
flag.BoolVar(&versionFlag, "version", false, "show version")
|
||||||
@ -196,8 +226,3 @@ func parseOptions() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func openWebBrowser(port int) {
|
|
||||||
address := fmt.Sprintf("http://localhost:%d", port)
|
|
||||||
open.Start(address)
|
|
||||||
}
|
|
||||||
|
@ -1,12 +0,0 @@
|
|||||||
//go:build darwin || linux
|
|
||||||
// +build darwin linux
|
|
||||||
|
|
||||||
package main
|
|
||||||
|
|
||||||
import "github.com/tardisx/discord-auto-upload/config"
|
|
||||||
|
|
||||||
func mainloop(c *config.ConfigService) {
|
|
||||||
|
|
||||||
ch := make(chan bool)
|
|
||||||
<-ch
|
|
||||||
}
|
|
16
dau_test.go
16
dau_test.go
@ -80,11 +80,7 @@ func TestCheckPath(t *testing.T) {
|
|||||||
if !w.checkPath() {
|
if !w.checkPath() {
|
||||||
t.Error("checkPath failed?")
|
t.Error("checkPath failed?")
|
||||||
}
|
}
|
||||||
|
os.RemoveAll(dir)
|
||||||
err := os.RemoveAll(dir)
|
|
||||||
if err != nil {
|
|
||||||
t.Fatalf("could not remove test dir: %v", err)
|
|
||||||
}
|
|
||||||
if w.checkPath() {
|
if w.checkPath() {
|
||||||
t.Error("checkPath succeeded when shouldn't?")
|
t.Error("checkPath succeeded when shouldn't?")
|
||||||
}
|
}
|
||||||
@ -95,11 +91,9 @@ func createFileTree() string {
|
|||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
f1, _ := os.Create(fmt.Sprintf("%s%c%s", dir, os.PathSeparator, "a.gif"))
|
os.Create(fmt.Sprintf("%s%c%s", dir, os.PathSeparator, "a.gif"))
|
||||||
f2, _ := os.Create(fmt.Sprintf("%s%c%s", dir, os.PathSeparator, "a.jpg"))
|
os.Create(fmt.Sprintf("%s%c%s", dir, os.PathSeparator, "a.jpg"))
|
||||||
f3, _ := os.Create(fmt.Sprintf("%s%c%s", dir, os.PathSeparator, "a.png"))
|
os.Create(fmt.Sprintf("%s%c%s", dir, os.PathSeparator, "a.png"))
|
||||||
f1.Close()
|
|
||||||
f2.Close()
|
|
||||||
f3.Close()
|
|
||||||
return dir
|
return dir
|
||||||
}
|
}
|
||||||
|
@ -1,60 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
_ "embed"
|
|
||||||
"fmt"
|
|
||||||
"github.com/getlantern/systray"
|
|
||||||
"github.com/skratchdot/open-golang/open"
|
|
||||||
"github.com/tardisx/discord-auto-upload/config"
|
|
||||||
daulog "github.com/tardisx/discord-auto-upload/log"
|
|
||||||
"github.com/tardisx/discord-auto-upload/version"
|
|
||||||
)
|
|
||||||
|
|
||||||
//go:generate goversioninfo
|
|
||||||
|
|
||||||
//go:embed dau.ico
|
|
||||||
var appIcon []byte
|
|
||||||
|
|
||||||
func mainloop(c *config.ConfigService) {
|
|
||||||
systray.Run(func() { onReady(c) }, onExit)
|
|
||||||
}
|
|
||||||
|
|
||||||
func onReady(c *config.ConfigService) {
|
|
||||||
|
|
||||||
systray.SetIcon(appIcon)
|
|
||||||
//systray.SetTitle("DAU")
|
|
||||||
systray.SetTooltip(fmt.Sprintf("discord-auto-upload %s", version.CurrentVersion))
|
|
||||||
openApp := systray.AddMenuItem("Open", "Open in web browser")
|
|
||||||
gh := systray.AddMenuItem("Github", "Open project page")
|
|
||||||
discord := systray.AddMenuItem("Discord", "Join us on discord")
|
|
||||||
ghr := systray.AddMenuItem("Release Notes", "Open project release notes")
|
|
||||||
quit := systray.AddMenuItem("Quit", "Quit")
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
<-quit.ClickedCh
|
|
||||||
systray.Quit()
|
|
||||||
}()
|
|
||||||
|
|
||||||
go func() {
|
|
||||||
for {
|
|
||||||
select {
|
|
||||||
case <-openApp.ClickedCh:
|
|
||||||
openWebBrowser(c.Config.Port)
|
|
||||||
case <-gh.ClickedCh:
|
|
||||||
open.Start("https://github.com/tardisx/discord-auto-upload")
|
|
||||||
case <-ghr.ClickedCh:
|
|
||||||
open.Start(fmt.Sprintf("https://github.com/tardisx/discord-auto-upload/releases/tag/%s", version.CurrentVersion))
|
|
||||||
case <-discord.ClickedCh:
|
|
||||||
open.Start("https://discord.gg/eErG9sntbZ")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}()
|
|
||||||
|
|
||||||
// Sets the icon of a menu item. Only available on Mac and Windows.
|
|
||||||
// mQuit.SetIcon(icon.Data)
|
|
||||||
}
|
|
||||||
|
|
||||||
func onExit() {
|
|
||||||
// clean up here
|
|
||||||
daulog.Info("quitting on user request")
|
|
||||||
}
|
|
6
go.mod
6
go.mod
@ -4,12 +4,8 @@ go 1.16
|
|||||||
|
|
||||||
require (
|
require (
|
||||||
github.com/fogleman/gg v1.3.0
|
github.com/fogleman/gg v1.3.0
|
||||||
github.com/getlantern/systray v1.2.1
|
|
||||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
|
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 // indirect
|
||||||
github.com/gorilla/mux v1.8.0
|
|
||||||
github.com/mitchellh/go-homedir v1.1.0
|
github.com/mitchellh/go-homedir v1.1.0
|
||||||
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966
|
|
||||||
github.com/stretchr/testify v1.6.1 // indirect
|
|
||||||
golang.org/x/image v0.0.0-20210504121937-7319ad40d33e
|
golang.org/x/image v0.0.0-20210504121937-7319ad40d33e
|
||||||
golang.org/x/mod v0.7.0
|
golang.org/x/mod v0.4.2
|
||||||
)
|
)
|
||||||
|
59
go.sum
59
go.sum
@ -1,68 +1,21 @@
|
|||||||
github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=
|
|
||||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
|
||||||
github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
|
github.com/fogleman/gg v1.3.0 h1:/7zJX8F6AaYQc57WQCyN9cAIz+4bCJGO9B+dyW29am8=
|
||||||
github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
|
github.com/fogleman/gg v1.3.0/go.mod h1:R/bRT+9gY/C5z7JzPU0zXsXHKM4/ayA+zqcVNZzPa1k=
|
||||||
github.com/getlantern/context v0.0.0-20190109183933-c447772a6520 h1:NRUJuo3v3WGC/g5YiyF790gut6oQr5f3FBI88Wv0dx4=
|
|
||||||
github.com/getlantern/context v0.0.0-20190109183933-c447772a6520/go.mod h1:L+mq6/vvYHKjCX2oez0CgEAJmbq1fbb/oNJIWQkBybY=
|
|
||||||
github.com/getlantern/errors v0.0.0-20190325191628-abdb3e3e36f7 h1:6uJ+sZ/e03gkbqZ0kUG6mfKoqDb4XMAzMIwlajq19So=
|
|
||||||
github.com/getlantern/errors v0.0.0-20190325191628-abdb3e3e36f7/go.mod h1:l+xpFBrCtDLpK9qNjxs+cHU6+BAdlBaxHqikB6Lku3A=
|
|
||||||
github.com/getlantern/golog v0.0.0-20190830074920-4ef2e798c2d7 h1:guBYzEaLz0Vfc/jv0czrr2z7qyzTOGC9hiQ0VC+hKjk=
|
|
||||||
github.com/getlantern/golog v0.0.0-20190830074920-4ef2e798c2d7/go.mod h1:zx/1xUUeYPy3Pcmet8OSXLbF47l+3y6hIPpyLWoR9oc=
|
|
||||||
github.com/getlantern/hex v0.0.0-20190417191902-c6586a6fe0b7 h1:micT5vkcr9tOVk1FiH8SWKID8ultN44Z+yzd2y/Vyb0=
|
|
||||||
github.com/getlantern/hex v0.0.0-20190417191902-c6586a6fe0b7/go.mod h1:dD3CgOrwlzca8ed61CsZouQS5h5jIzkK9ZWrTcf0s+o=
|
|
||||||
github.com/getlantern/hidden v0.0.0-20190325191715-f02dbb02be55 h1:XYzSdCbkzOC0FDNrgJqGRo8PCMFOBFL9py72DRs7bmc=
|
|
||||||
github.com/getlantern/hidden v0.0.0-20190325191715-f02dbb02be55/go.mod h1:6mmzY2kW1TOOrVy+r41Za2MxXM+hhqTtY3oBKd2AgFA=
|
|
||||||
github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f h1:wrYrQttPS8FHIRSlsrcuKazukx/xqO/PpLZzZXsF+EA=
|
|
||||||
github.com/getlantern/ops v0.0.0-20190325191751-d70cb0d6f85f/go.mod h1:D5ao98qkA6pxftxoqzibIBBrLSUli+kYnJqrgBf9cIA=
|
|
||||||
github.com/getlantern/systray v1.2.1 h1:udsC2k98v2hN359VTFShuQW6GGprRprw6kD6539JikI=
|
|
||||||
github.com/getlantern/systray v1.2.1/go.mod h1:AecygODWIsBquJCJFop8MEQcJbWFfw/1yWbVabNgpCM=
|
|
||||||
github.com/go-stack/stack v1.8.0 h1:5SgMzNM5HxrEjV0ww2lTmX6E2Izsfxas4+YHWRs3Lsk=
|
|
||||||
github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY=
|
|
||||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
|
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0 h1:DACJavvAHhabrF08vX0COfcOBJRhZ8lUbR+ZWIs0Y5g=
|
||||||
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
|
github.com/golang/freetype v0.0.0-20170609003504-e2365dfdc4a0/go.mod h1:E/TSTwGwJL78qG/PmXZO1EjYhfJinVAhrmmHX6Z8B9k=
|
||||||
github.com/gorilla/mux v1.8.0 h1:i40aqfkR1h2SlN9hojwV5ZA91wcXFOvkdNIeFDP5koI=
|
|
||||||
github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
|
|
||||||
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
|
github.com/mitchellh/go-homedir v1.1.0 h1:lukF9ziXFxDFPkA1vsr5zpc1XuPDn/wFntq5mG+4E0Y=
|
||||||
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
github.com/mitchellh/go-homedir v1.1.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0=
|
||||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c h1:rp5dCmg/yLR3mgFuSOe4oEnDDmGLROTvMragMUXpTQw=
|
|
||||||
github.com/oxtoacart/bpool v0.0.0-20190530202638-03653db5a59c/go.mod h1:X07ZCGwUbLaax7L0S3Tw4hpejzu63ZrrQiUe6W0hcy0=
|
|
||||||
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/skratchdot/open-golang v0.0.0-20200116055534-eef842397966 h1:JIAuq3EEf9cgbU6AtGPK4CTG3Zf6CKMNqf0MHTggAUA=
|
|
||||||
github.com/skratchdot/open-golang v0.0.0-20200116055534-eef842397966/go.mod h1:sUM3LWHvSMaG192sy56D9F7CNvL7jUJVXoqM1QKLnog=
|
|
||||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
|
||||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
|
||||||
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
|
|
||||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
|
||||||
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
|
|
||||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||||
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
|
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||||
golang.org/x/image v0.0.0-20210504121937-7319ad40d33e h1:PzJMNfFQx+QO9hrC1GwZ4BoPGeNGhfeQEgcQFArEjPk=
|
golang.org/x/image v0.0.0-20210504121937-7319ad40d33e h1:PzJMNfFQx+QO9hrC1GwZ4BoPGeNGhfeQEgcQFArEjPk=
|
||||||
golang.org/x/image v0.0.0-20210504121937-7319ad40d33e/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
golang.org/x/image v0.0.0-20210504121937-7319ad40d33e/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0=
|
||||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
golang.org/x/mod v0.4.2 h1:Gz96sIWK3OalVv/I/qNygP42zyoKp3xptRVCWRFEBvo=
|
||||||
golang.org/x/mod v0.7.0 h1:LapD9S96VoQRhi/GrNTqeBJFrUjs5UHCAtTlgwA5oZA=
|
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||||
golang.org/x/mod v0.7.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
|
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||||
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
|
||||||
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
|
|
||||||
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
|
|
||||||
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||||
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
|
||||||
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
|
||||||
golang.org/x/sys v0.0.0-20200515095857-1151b9dac4a9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
||||||
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
|
|
||||||
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f h1:v4INt8xihDGvnrfjMDVXGxw9wrfxYyCjk0KbXjhR55s=
|
|
||||||
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
|
||||||
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
|
|
||||||
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
|
|
||||||
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
|
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/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
|
||||||
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
|
|
||||||
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
|
||||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
|
||||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
|
|
||||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
|
||||||
|
188
image/image.go
188
image/image.go
@ -1,188 +0,0 @@
|
|||||||
// Package image is responsible for thumbnailing, resizing and watermarking
|
|
||||||
// images.
|
|
||||||
package image
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
i "image"
|
|
||||||
"image/jpeg"
|
|
||||||
"image/png"
|
|
||||||
"io"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
daulog "github.com/tardisx/discord-auto-upload/log"
|
|
||||||
|
|
||||||
"golang.org/x/image/draw"
|
|
||||||
)
|
|
||||||
|
|
||||||
// the filenames below are ordered in a specific way
|
|
||||||
// In the simplest case we only need the original filename.
|
|
||||||
// In more complex cases, we might have other files, created
|
|
||||||
// temporarily. These all need to be cleaned up.
|
|
||||||
// We upload the "final" file, depending on what actions have
|
|
||||||
// been taken.
|
|
||||||
|
|
||||||
type Store struct {
|
|
||||||
OriginalFilename string
|
|
||||||
OriginalFormat string // jpeg, png
|
|
||||||
ModifiedFilename string // if the user applied modifications
|
|
||||||
ResizedFilename string // if the file had to be resized to be uploaded
|
|
||||||
WatermarkedFilename string
|
|
||||||
MaxBytes int
|
|
||||||
Watermark bool
|
|
||||||
}
|
|
||||||
|
|
||||||
// ReadCloser returns an io.ReadCloser providing the imagedata
|
|
||||||
// with the manglings that have been requested
|
|
||||||
func (s *Store) ReadCloser() (io.ReadCloser, error) {
|
|
||||||
// determine format
|
|
||||||
s.determineFormat()
|
|
||||||
|
|
||||||
// check if we will fit the number of bytes, resize if necessary
|
|
||||||
err := s.resizeToUnder(int64(s.MaxBytes))
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
// the conundrum here is that the watermarking could modify the file size again, maybe going over
|
|
||||||
// the MaxBytes size. That would mostly be about jpeg compression levels I guess...
|
|
||||||
if s.Watermark {
|
|
||||||
s.applyWatermark()
|
|
||||||
}
|
|
||||||
|
|
||||||
// return the reader
|
|
||||||
f, err := os.Open(s.uploadSourceFilename())
|
|
||||||
if err != nil {
|
|
||||||
return nil, err
|
|
||||||
}
|
|
||||||
|
|
||||||
return f, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) determineFormat() error {
|
|
||||||
file, err := os.Open(s.OriginalFilename)
|
|
||||||
if err != nil {
|
|
||||||
panic(fmt.Errorf("could not open file: %s", err))
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
_, format, err := i.Decode(file)
|
|
||||||
if err != nil {
|
|
||||||
panic(fmt.Errorf("could not decode file: %s", err))
|
|
||||||
}
|
|
||||||
s.OriginalFormat = format
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
// resizeToUnder resizes the image, if necessary
|
|
||||||
func (s *Store) resizeToUnder(size int64) error {
|
|
||||||
fileToResize := s.uploadSourceFilename()
|
|
||||||
fi, err := os.Stat(s.uploadSourceFilename())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
currentSize := fi.Size()
|
|
||||||
if currentSize <= size {
|
|
||||||
return nil // nothing needs to be done
|
|
||||||
}
|
|
||||||
|
|
||||||
daulog.Infof("%s is %d bytes, need to resize to fit in %d", fileToResize, currentSize, size)
|
|
||||||
|
|
||||||
file, err := os.Open(fileToResize)
|
|
||||||
if err != nil {
|
|
||||||
panic(fmt.Errorf("could not open file: %s", err))
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
|
|
||||||
im, _, err := i.Decode(file)
|
|
||||||
if err != nil {
|
|
||||||
panic(fmt.Errorf("could not decode file: %s", err))
|
|
||||||
}
|
|
||||||
|
|
||||||
// if the size is 10% too big, we reduce X and Y by 10% - this is overkill but should
|
|
||||||
// get us across the line in most cases
|
|
||||||
fraction := float64(currentSize) / float64(size) // say 1.1 for 10%
|
|
||||||
newXY := i.Point{
|
|
||||||
X: int(float64(im.Bounds().Max.X) / fraction),
|
|
||||||
Y: int(float64(im.Bounds().Max.Y) / fraction),
|
|
||||||
}
|
|
||||||
|
|
||||||
daulog.Infof("fraction is %f, will resize to %dx%d", fraction, newXY.X, newXY.Y)
|
|
||||||
|
|
||||||
dst := i.NewRGBA(i.Rect(0, 0, newXY.X, newXY.Y))
|
|
||||||
draw.BiLinear.Scale(dst, dst.Rect, im, im.Bounds(), draw.Over, nil)
|
|
||||||
|
|
||||||
resizedFile, err := os.CreateTemp("", "dau_resize_file_*")
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
if s.OriginalFormat == "png" {
|
|
||||||
err = png.Encode(resizedFile, dst)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
} else if s.OriginalFormat == "jpeg" {
|
|
||||||
err = jpeg.Encode(resizedFile, dst, nil)
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
|
|
||||||
} else {
|
|
||||||
panic("unknown format " + s.OriginalFormat)
|
|
||||||
}
|
|
||||||
|
|
||||||
s.ResizedFilename = resizedFile.Name()
|
|
||||||
resizedFile.Close()
|
|
||||||
|
|
||||||
fi, err = os.Stat(s.uploadSourceFilename())
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
newSize := fi.Size()
|
|
||||||
if newSize <= size {
|
|
||||||
daulog.Infof("File resized, now %d", newSize)
|
|
||||||
return nil // nothing needs to be done
|
|
||||||
} else {
|
|
||||||
return fmt.Errorf("failed to resize: was %d, now %d, needed %d", currentSize, newSize, size)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
// uploadSourceFilename gives us the filename, which might be a watermarked, resized
|
|
||||||
// or markedup version, depending on what has happened to this file.
|
|
||||||
func (s Store) uploadSourceFilename() string {
|
|
||||||
if s.WatermarkedFilename != "" {
|
|
||||||
return s.WatermarkedFilename
|
|
||||||
}
|
|
||||||
if s.ResizedFilename != "" {
|
|
||||||
return s.ResizedFilename
|
|
||||||
}
|
|
||||||
if s.ModifiedFilename != "" {
|
|
||||||
return s.ModifiedFilename
|
|
||||||
}
|
|
||||||
return s.OriginalFilename
|
|
||||||
}
|
|
||||||
|
|
||||||
// UploadFilename provides a name to be assigned to the upload on Discord
|
|
||||||
func (s Store) UploadFilename() string {
|
|
||||||
return "image." + s.OriginalFormat
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cleanup removes all the temporary files that we might have created
|
|
||||||
func (s Store) Cleanup() {
|
|
||||||
daulog.Infof("cleaning temporary files %#v", s)
|
|
||||||
|
|
||||||
if s.ModifiedFilename != "" {
|
|
||||||
daulog.Infof("removing %s", s.ModifiedFilename)
|
|
||||||
os.Remove(s.ModifiedFilename)
|
|
||||||
}
|
|
||||||
if s.ResizedFilename != "" {
|
|
||||||
daulog.Infof("removing %s", s.ResizedFilename)
|
|
||||||
os.Remove(s.ResizedFilename)
|
|
||||||
}
|
|
||||||
if s.WatermarkedFilename != "" {
|
|
||||||
daulog.Infof("removing %s", s.WatermarkedFilename)
|
|
||||||
os.Remove(s.WatermarkedFilename)
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,62 +0,0 @@
|
|||||||
package image
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
i "image"
|
|
||||||
"image/png"
|
|
||||||
"io"
|
|
||||||
"log"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
"golang.org/x/image/draw"
|
|
||||||
)
|
|
||||||
|
|
||||||
const (
|
|
||||||
thumbnailMaxX = 128
|
|
||||||
thumbnailMaxY = 128
|
|
||||||
)
|
|
||||||
|
|
||||||
type ThumbType = string
|
|
||||||
|
|
||||||
const ThumbTypeOriginal = "orig"
|
|
||||||
const ThumbTypeMarkedUp = "markedup"
|
|
||||||
|
|
||||||
// ThumbPNG writes a thumbnail out to an io.Writer
|
|
||||||
func (ip *Store) ThumbPNG(t ThumbType, w io.Writer) error {
|
|
||||||
|
|
||||||
var filename string
|
|
||||||
if t == ThumbTypeOriginal {
|
|
||||||
filename = ip.OriginalFilename
|
|
||||||
} else if t == ThumbTypeMarkedUp {
|
|
||||||
filename = ip.ModifiedFilename
|
|
||||||
} else {
|
|
||||||
log.Fatal("was passed incorrect 'type' arg")
|
|
||||||
}
|
|
||||||
|
|
||||||
file, err := os.Open(filename)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not open file: %s", err)
|
|
||||||
}
|
|
||||||
defer file.Close()
|
|
||||||
im, _, err := i.Decode(file)
|
|
||||||
if err != nil {
|
|
||||||
return fmt.Errorf("could not decode file: %s", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
newXY := i.Point{}
|
|
||||||
if im.Bounds().Max.X/thumbnailMaxX > im.Bounds().Max.Y/thumbnailMaxY {
|
|
||||||
newXY.X = thumbnailMaxX
|
|
||||||
newXY.Y = im.Bounds().Max.Y / (im.Bounds().Max.X / thumbnailMaxX)
|
|
||||||
} else {
|
|
||||||
newXY.Y = thumbnailMaxY
|
|
||||||
newXY.X = im.Bounds().Max.X / (im.Bounds().Max.Y / thumbnailMaxY)
|
|
||||||
}
|
|
||||||
|
|
||||||
dst := i.NewRGBA(i.Rect(0, 0, newXY.X, newXY.Y))
|
|
||||||
draw.BiLinear.Scale(dst, dst.Rect, im, im.Bounds(), draw.Over, nil)
|
|
||||||
|
|
||||||
png.Encode(w, dst)
|
|
||||||
|
|
||||||
return nil
|
|
||||||
|
|
||||||
}
|
|
@ -1,64 +0,0 @@
|
|||||||
package image
|
|
||||||
|
|
||||||
import (
|
|
||||||
"fmt"
|
|
||||||
i "image"
|
|
||||||
"image/jpeg"
|
|
||||||
"image/png"
|
|
||||||
"os"
|
|
||||||
|
|
||||||
daulog "github.com/tardisx/discord-auto-upload/log"
|
|
||||||
|
|
||||||
"github.com/fogleman/gg"
|
|
||||||
"golang.org/x/image/font/inconsolata"
|
|
||||||
)
|
|
||||||
|
|
||||||
// applyWatermark applies the watermark to the image
|
|
||||||
func (s *Store) applyWatermark() error {
|
|
||||||
|
|
||||||
in, err := os.Open(s.uploadSourceFilename())
|
|
||||||
|
|
||||||
defer in.Close()
|
|
||||||
|
|
||||||
im, _, err := i.Decode(in)
|
|
||||||
if err != nil {
|
|
||||||
daulog.Errorf("Cannot decode image: %v - skipping watermarking", err)
|
|
||||||
return fmt.Errorf("cannot decode image: %w", err)
|
|
||||||
}
|
|
||||||
bounds := im.Bounds()
|
|
||||||
// var S float64 = float64(bounds.Max.X)
|
|
||||||
|
|
||||||
dc := gg.NewContext(bounds.Max.X, bounds.Max.Y)
|
|
||||||
dc.Clear()
|
|
||||||
dc.SetRGB(0, 0, 0)
|
|
||||||
|
|
||||||
dc.SetFontFace(inconsolata.Regular8x16)
|
|
||||||
|
|
||||||
dc.DrawImage(im, 0, 0)
|
|
||||||
|
|
||||||
dc.DrawRoundedRectangle(0, float64(bounds.Max.Y-18.0), 320, float64(bounds.Max.Y), 0)
|
|
||||||
dc.SetRGB(0, 0, 0)
|
|
||||||
dc.Fill()
|
|
||||||
|
|
||||||
dc.SetRGB(1, 1, 1)
|
|
||||||
|
|
||||||
dc.DrawString("github.com/tardisx/discord-auto-upload", 5.0, float64(bounds.Max.Y)-5.0)
|
|
||||||
|
|
||||||
waterMarkedFile, err := os.CreateTemp("", "dau_watermark_file_*")
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
return err
|
|
||||||
}
|
|
||||||
defer waterMarkedFile.Close()
|
|
||||||
|
|
||||||
if s.OriginalFormat == "png" {
|
|
||||||
png.Encode(waterMarkedFile, dc.Image())
|
|
||||||
} else if s.OriginalFormat == "jpeg" {
|
|
||||||
jpeg.Encode(waterMarkedFile, dc.Image(), nil)
|
|
||||||
} else {
|
|
||||||
panic("Cannot handle " + s.OriginalFormat)
|
|
||||||
}
|
|
||||||
|
|
||||||
s.WatermarkedFilename = waterMarkedFile.Name()
|
|
||||||
return nil
|
|
||||||
}
|
|
65
log/log.go
65
log/log.go
@ -1,14 +1,10 @@
|
|||||||
package log
|
package log
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"log"
|
||||||
"time"
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Logger interface {
|
|
||||||
WriteEntry(l LogEntry)
|
|
||||||
}
|
|
||||||
|
|
||||||
type LogEntryType string
|
type LogEntryType string
|
||||||
|
|
||||||
type LogEntry struct {
|
type LogEntry struct {
|
||||||
@ -23,73 +19,28 @@ const (
|
|||||||
LogTypeDebug = "debug"
|
LogTypeDebug = "debug"
|
||||||
)
|
)
|
||||||
|
|
||||||
var loggers []Logger
|
var LogEntries []LogEntry
|
||||||
var logInput chan LogEntry
|
var logInput chan LogEntry
|
||||||
var Memory *MemoryLogger
|
|
||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
|
|
||||||
// create some loggers
|
|
||||||
Memory = &MemoryLogger{maxsize: 100}
|
|
||||||
stdout := &StdoutLogger{}
|
|
||||||
|
|
||||||
loggers = []Logger{Memory, stdout}
|
|
||||||
|
|
||||||
// wait for log entries
|
// wait for log entries
|
||||||
logInput = make(chan LogEntry)
|
logInput = make(chan LogEntry)
|
||||||
go func() {
|
go func() {
|
||||||
for {
|
for {
|
||||||
aLog := <-logInput
|
aLog := <-logInput
|
||||||
for _, l := range loggers {
|
LogEntries = append(LogEntries, aLog)
|
||||||
l.WriteEntry(aLog)
|
for len(LogEntries) > 100 {
|
||||||
|
LogEntries = LogEntries[1:]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func Debug(entry string) {
|
func SendLog(entry string, entryType LogEntryType) {
|
||||||
logInput <- LogEntry{
|
logInput <- LogEntry{
|
||||||
Timestamp: time.Now(),
|
Timestamp: time.Now(),
|
||||||
Entry: entry,
|
Entry: entry,
|
||||||
Type: LogTypeDebug,
|
Type: entryType,
|
||||||
}
|
|
||||||
}
|
|
||||||
func Debugf(entry string, args ...interface{}) {
|
|
||||||
logInput <- LogEntry{
|
|
||||||
Timestamp: time.Now(),
|
|
||||||
Entry: fmt.Sprintf(entry, args...),
|
|
||||||
Type: LogTypeDebug,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func Info(entry string) {
|
|
||||||
logInput <- LogEntry{
|
|
||||||
Timestamp: time.Now(),
|
|
||||||
Entry: entry,
|
|
||||||
Type: LogTypeInfo,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func Infof(entry string, args ...interface{}) {
|
|
||||||
logInput <- LogEntry{
|
|
||||||
Timestamp: time.Now(),
|
|
||||||
Entry: fmt.Sprintf(entry, args...),
|
|
||||||
Type: LogTypeInfo,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func Error(entry string) {
|
|
||||||
logInput <- LogEntry{
|
|
||||||
Timestamp: time.Now(),
|
|
||||||
Entry: entry,
|
|
||||||
Type: LogTypeError,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func Errorf(entry string, args ...interface{}) {
|
|
||||||
logInput <- LogEntry{
|
|
||||||
Timestamp: time.Now(),
|
|
||||||
Entry: fmt.Sprintf(entry, args...),
|
|
||||||
Type: LogTypeError,
|
|
||||||
}
|
}
|
||||||
|
log.Printf("%6s: %s", entryType, entry)
|
||||||
}
|
}
|
||||||
|
@ -1,29 +0,0 @@
|
|||||||
package log
|
|
||||||
|
|
||||||
import (
|
|
||||||
"sync"
|
|
||||||
)
|
|
||||||
|
|
||||||
type MemoryLogger struct {
|
|
||||||
size int
|
|
||||||
entries []LogEntry
|
|
||||||
maxsize int
|
|
||||||
lock sync.Mutex
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *MemoryLogger) WriteEntry(l LogEntry) {
|
|
||||||
// xxx needs mutex
|
|
||||||
// if m.entries == nil {
|
|
||||||
// m.entries = make([]LogEntry, 0)
|
|
||||||
// }
|
|
||||||
m.lock.Lock()
|
|
||||||
m.entries = append(m.entries, l)
|
|
||||||
if len(m.entries) > m.maxsize {
|
|
||||||
m.entries = m.entries[1:]
|
|
||||||
}
|
|
||||||
m.lock.Unlock()
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m *MemoryLogger) Entries() []LogEntry {
|
|
||||||
return m.entries
|
|
||||||
}
|
|
@ -1,12 +0,0 @@
|
|||||||
package log
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
)
|
|
||||||
|
|
||||||
type StdoutLogger struct {
|
|
||||||
}
|
|
||||||
|
|
||||||
func (m StdoutLogger) WriteEntry(l LogEntry) {
|
|
||||||
log.Printf("%-6s %s", l.Type, l.Entry)
|
|
||||||
}
|
|
@ -1,84 +0,0 @@
|
|||||||
package main
|
|
||||||
|
|
||||||
import (
|
|
||||||
"log"
|
|
||||||
"os"
|
|
||||||
"regexp"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"golang.org/x/mod/semver"
|
|
||||||
)
|
|
||||||
|
|
||||||
const versionInfoTemplate = `
|
|
||||||
{
|
|
||||||
"FixedFileInfo": {
|
|
||||||
"FileVersion": {
|
|
||||||
"Major": MAJOR,
|
|
||||||
"Minor": MINOR,
|
|
||||||
"Patch": PATCH,
|
|
||||||
"Build": 0
|
|
||||||
},
|
|
||||||
"ProductVersion": {
|
|
||||||
"Major": MAJOR,
|
|
||||||
"Minor": MINOR,
|
|
||||||
"Patch": PATCH,
|
|
||||||
"Build": 0
|
|
||||||
},
|
|
||||||
"FileFlagsMask": "3f",
|
|
||||||
"FileFlags ": "00",
|
|
||||||
"FileOS": "040004",
|
|
||||||
"FileType": "01",
|
|
||||||
"FileSubType": "00"
|
|
||||||
},
|
|
||||||
"StringFileInfo": {
|
|
||||||
"Comments": "",
|
|
||||||
"CompanyName": "tardisx@github",
|
|
||||||
"FileDescription": "https://github.com/tardisx/discord-auto-upload",
|
|
||||||
"FileVersion": "",
|
|
||||||
"InternalName": "",
|
|
||||||
"LegalCopyright": "https://github.com/tardisx/discord-auto-upload/blob/master/LICENSE",
|
|
||||||
"LegalTrademarks": "",
|
|
||||||
"OriginalFilename": "",
|
|
||||||
"PrivateBuild": "",
|
|
||||||
"ProductName": "discord-auto-upload",
|
|
||||||
"ProductVersion": "VERSION",
|
|
||||||
"SpecialBuild": ""
|
|
||||||
},
|
|
||||||
"VarFileInfo": {
|
|
||||||
"Translation": {
|
|
||||||
"LangID": "0409",
|
|
||||||
"CharsetID": "04B0"
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"IconPath": "dau.ico",
|
|
||||||
"ManifestPath": ""
|
|
||||||
}
|
|
||||||
`
|
|
||||||
|
|
||||||
var nonAlphanumericRegex = regexp.MustCompile(`[^0-9]+`)
|
|
||||||
|
|
||||||
func main() {
|
|
||||||
version := os.Args[1]
|
|
||||||
if !semver.IsValid(version) {
|
|
||||||
panic("bad version" + version)
|
|
||||||
}
|
|
||||||
parts := strings.Split(version, ".")
|
|
||||||
if len(parts) < 3 {
|
|
||||||
log.Fatalf("bad version: %s", version)
|
|
||||||
}
|
|
||||||
|
|
||||||
parts[0] = nonAlphanumericRegex.ReplaceAllString(parts[0], "")
|
|
||||||
parts[1] = nonAlphanumericRegex.ReplaceAllString(parts[1], "")
|
|
||||||
parts[2] = nonAlphanumericRegex.ReplaceAllString(parts[2], "")
|
|
||||||
|
|
||||||
out := versionInfoTemplate
|
|
||||||
out = strings.Replace(out, "MAJOR", parts[0], -1)
|
|
||||||
out = strings.Replace(out, "MINOR", parts[1], -1)
|
|
||||||
out = strings.Replace(out, "PATCH", parts[2], -1)
|
|
||||||
out = strings.Replace(out, "VERSION", version, -1)
|
|
||||||
|
|
||||||
f, _ := os.Create("versioninfo.json")
|
|
||||||
f.Write([]byte(out))
|
|
||||||
f.Close()
|
|
||||||
|
|
||||||
}
|
|
200
upload/upload.go
200
upload/upload.go
@ -7,52 +7,43 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"image"
|
||||||
"io"
|
"io"
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
"mime/multipart"
|
"mime/multipart"
|
||||||
"net/http"
|
"net/http"
|
||||||
"sync"
|
"os"
|
||||||
"sync/atomic"
|
"path/filepath"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"github.com/fogleman/gg"
|
||||||
"github.com/tardisx/discord-auto-upload/config"
|
"github.com/tardisx/discord-auto-upload/config"
|
||||||
"github.com/tardisx/discord-auto-upload/image"
|
|
||||||
|
|
||||||
daulog "github.com/tardisx/discord-auto-upload/log"
|
daulog "github.com/tardisx/discord-auto-upload/log"
|
||||||
|
"golang.org/x/image/font/inconsolata"
|
||||||
)
|
)
|
||||||
|
|
||||||
type State string
|
|
||||||
|
|
||||||
const (
|
|
||||||
StatePending State = "Pending" // waiting for decision to upload (could be edited)
|
|
||||||
StateQueued State = "Queued" // ready for upload
|
|
||||||
StateWatermarking State = "Adding Watermark" // thumbnail generation
|
|
||||||
StateUploading State = "Uploading" // uploading
|
|
||||||
StateComplete State = "Complete" // finished successfully
|
|
||||||
StateFailed State = "Failed" // failed
|
|
||||||
StateSkipped State = "Skipped" // user did not want to upload
|
|
||||||
)
|
|
||||||
|
|
||||||
var currentId int32
|
|
||||||
|
|
||||||
type HTTPClient interface {
|
type HTTPClient interface {
|
||||||
Do(req *http.Request) (*http.Response, error)
|
Do(req *http.Request) (*http.Response, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type Uploader struct {
|
type Uploader struct {
|
||||||
Uploads []*Upload `json:"uploads"`
|
Uploads []*Upload `json:"uploads"`
|
||||||
Lock sync.Mutex
|
|
||||||
}
|
}
|
||||||
|
|
||||||
type Upload struct {
|
type Upload struct {
|
||||||
Id int32 `json:"id"`
|
Uploaded bool `json:"uploaded"` // has this file been uploaded to discord
|
||||||
UploadedAt time.Time `json:"uploaded_at"`
|
UploadedAt time.Time `json:"uploaded_at"`
|
||||||
|
|
||||||
Image *image.Store
|
Failed bool `json:"failed"`
|
||||||
|
|
||||||
|
originalFilename string // path on the local disk
|
||||||
|
filenameToUpload string // post-watermark, or just original if unwatermarked
|
||||||
|
|
||||||
webhookURL string
|
webhookURL string
|
||||||
|
|
||||||
|
watermark bool // should watermark
|
||||||
|
|
||||||
usernameOverride string
|
usernameOverride string
|
||||||
|
|
||||||
Url string `json:"url"` // url on the discord CDN
|
Url string `json:"url"` // url on the discord CDN
|
||||||
@ -60,9 +51,6 @@ type Upload struct {
|
|||||||
Width int `json:"width"`
|
Width int `json:"width"`
|
||||||
Height int `json:"height"`
|
Height int `json:"height"`
|
||||||
|
|
||||||
State State `json:"state"`
|
|
||||||
StateReason string `json:"state_reason"`
|
|
||||||
|
|
||||||
Client HTTPClient `json:"-"`
|
Client HTTPClient `json:"-"`
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -74,66 +62,45 @@ func NewUploader() *Uploader {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (u *Uploader) AddFile(file string, conf config.Watcher) {
|
func (u *Uploader) AddFile(file string, conf config.Watcher) {
|
||||||
u.Lock.Lock()
|
|
||||||
atomic.AddInt32(¤tId, 1)
|
|
||||||
thisUpload := Upload{
|
thisUpload := Upload{
|
||||||
Id: currentId,
|
Uploaded: false,
|
||||||
UploadedAt: time.Time{},
|
originalFilename: file,
|
||||||
Image: &image.Store{OriginalFilename: file, Watermark: !conf.NoWatermark, MaxBytes: 8_000_000},
|
watermark: !conf.NoWatermark,
|
||||||
webhookURL: conf.WebHookURL,
|
webhookURL: conf.WebHookURL,
|
||||||
usernameOverride: conf.Username,
|
usernameOverride: conf.Username,
|
||||||
Url: "",
|
|
||||||
State: StateQueued,
|
|
||||||
Client: nil,
|
|
||||||
}
|
|
||||||
// if the user wants uploads to be held for editing etc,
|
|
||||||
// set it to Pending instead
|
|
||||||
if conf.HoldUploads {
|
|
||||||
thisUpload.State = StatePending
|
|
||||||
thisUpload.StateReason = ""
|
|
||||||
}
|
}
|
||||||
u.Uploads = append(u.Uploads, &thisUpload)
|
u.Uploads = append(u.Uploads, &thisUpload)
|
||||||
u.Lock.Unlock()
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Upload uploads any files that have not yet been uploaded
|
// Upload uploads any files that have not yet been uploaded
|
||||||
func (u *Uploader) Upload() {
|
func (u *Uploader) Upload() {
|
||||||
u.Lock.Lock()
|
|
||||||
|
|
||||||
for _, upload := range u.Uploads {
|
for _, upload := range u.Uploads {
|
||||||
if upload.State == StateQueued {
|
if !upload.Uploaded && !upload.Failed {
|
||||||
upload.processUpload()
|
upload.processUpload()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
u.Lock.Unlock()
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func (u *Uploader) UploadById(id int32) *Upload {
|
|
||||||
u.Lock.Lock()
|
|
||||||
defer u.Lock.Unlock()
|
|
||||||
|
|
||||||
for _, anUpload := range u.Uploads {
|
|
||||||
if anUpload.Id == int32(id) {
|
|
||||||
return anUpload
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func (u *Upload) processUpload() error {
|
func (u *Upload) processUpload() error {
|
||||||
daulog.Infof("Uploading: %s", u.Image.OriginalFilename)
|
daulog.SendLog(fmt.Sprintf("Uploading: %s", u.originalFilename), daulog.LogTypeInfo)
|
||||||
|
|
||||||
if u.webhookURL == "" {
|
if u.webhookURL == "" {
|
||||||
daulog.Error("WebHookURL is not configured - cannot upload!")
|
daulog.SendLog("WebHookURL is not configured - cannot upload!", daulog.LogTypeError)
|
||||||
return errors.New("webhook url not configured")
|
return errors.New("webhook url not configured")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if u.watermark {
|
||||||
|
daulog.SendLog("Watermarking image", daulog.LogTypeInfo)
|
||||||
|
u.applyWatermark()
|
||||||
|
} else {
|
||||||
|
u.filenameToUpload = u.originalFilename
|
||||||
|
}
|
||||||
|
|
||||||
extraParams := map[string]string{}
|
extraParams := map[string]string{}
|
||||||
|
|
||||||
if u.usernameOverride != "" {
|
if u.usernameOverride != "" {
|
||||||
daulog.Infof("Overriding username with '%s'", u.usernameOverride)
|
daulog.SendLog("Overriding username with "+u.usernameOverride, daulog.LogTypeInfo)
|
||||||
extraParams["username"] = u.usernameOverride
|
extraParams["username"] = u.usernameOverride
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -154,17 +121,9 @@ func (u *Upload) processUpload() error {
|
|||||||
var retriesRemaining = 5
|
var retriesRemaining = 5
|
||||||
for retriesRemaining > 0 {
|
for retriesRemaining > 0 {
|
||||||
|
|
||||||
// open an io.ReadCloser for the file we intend to upload
|
request, err := newfileUploadRequest(u.webhookURL, extraParams, "file", u.filenameToUpload)
|
||||||
var err error
|
|
||||||
|
|
||||||
imageData, err := u.Image.ReadCloser()
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
panic(err)
|
log.Printf("error creating upload request: %s", err)
|
||||||
}
|
|
||||||
|
|
||||||
request, err := newfileUploadRequest(u.webhookURL, extraParams, "file", u.Image.UploadFilename(), imageData)
|
|
||||||
if err != nil {
|
|
||||||
daulog.Errorf("error creating upload request: %s", err)
|
|
||||||
return fmt.Errorf("could not create upload request: %s", err)
|
return fmt.Errorf("could not create upload request: %s", err)
|
||||||
}
|
}
|
||||||
start := time.Now()
|
start := time.Now()
|
||||||
@ -177,24 +136,23 @@ func (u *Upload) processUpload() error {
|
|||||||
|
|
||||||
resp, err := u.Client.Do(request)
|
resp, err := u.Client.Do(request)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
daulog.Errorf("Error performing request: %s", err)
|
log.Print("Error performing request:", err)
|
||||||
retriesRemaining--
|
retriesRemaining--
|
||||||
sleepForRetries(retriesRemaining)
|
sleepForRetries(retriesRemaining)
|
||||||
continue
|
continue
|
||||||
} else {
|
} else {
|
||||||
if resp.StatusCode == 413 {
|
if resp.StatusCode == 413 {
|
||||||
// just fail immediately, we know this means the file was too big
|
// just fail immediately, we know this means the file was too big
|
||||||
daulog.Error("413 received - file too large")
|
daulog.SendLog("413 received - file too large", daulog.LogTypeError)
|
||||||
u.State = StateFailed
|
|
||||||
u.StateReason = "discord API said file too large"
|
|
||||||
return errors.New("received 413 - file too large")
|
return errors.New("received 413 - file too large")
|
||||||
}
|
}
|
||||||
|
|
||||||
if resp.StatusCode != 200 {
|
if resp.StatusCode != 200 {
|
||||||
// {"message": "Request entity too large", "code": 40005}
|
// {"message": "Request entity too large", "code": 40005}
|
||||||
daulog.Errorf("Bad response code from server: %d", resp.StatusCode)
|
log.Print("Bad response from server:", resp.StatusCode)
|
||||||
if b, err := ioutil.ReadAll(resp.Body); err == nil {
|
if b, err := ioutil.ReadAll(resp.Body); err == nil {
|
||||||
daulog.Errorf("Body:\n%s", string(b))
|
log.Print("Body:", string(b))
|
||||||
|
daulog.SendLog(fmt.Sprintf("Bad response: %s", string(b)), daulog.LogTypeError)
|
||||||
}
|
}
|
||||||
retriesRemaining--
|
retriesRemaining--
|
||||||
sleepForRetries(retriesRemaining)
|
sleepForRetries(retriesRemaining)
|
||||||
@ -203,7 +161,7 @@ func (u *Upload) processUpload() error {
|
|||||||
|
|
||||||
resBody, err := ioutil.ReadAll(resp.Body)
|
resBody, err := ioutil.ReadAll(resp.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
daulog.Errorf("could not deal with body: %s", err)
|
log.Print("could not deal with body: ", err)
|
||||||
retriesRemaining--
|
retriesRemaining--
|
||||||
sleepForRetries(retriesRemaining)
|
sleepForRetries(retriesRemaining)
|
||||||
continue
|
continue
|
||||||
@ -215,17 +173,17 @@ func (u *Upload) processUpload() error {
|
|||||||
|
|
||||||
// {"id": "851092588608880670", "type": 0, "content": "", "channel_id": "849615269706203171", "author": {"bot": true, "id": "849615314274484224", "username": "abcdedf", "avatar": null, "discriminator": "0000"}, "attachments": [{"id": "851092588332449812", "filename": "dau480457962.png", "size": 859505, "url": "https://cdn.discordapp.com/attachments/849615269706203171/851092588332449812/dau480457962.png", "proxy_url": "https://media.discordapp.net/attachments/849615269706203171/851092588332449812/dau480457962.png", "width": 640, "height": 640, "content_type": "image/png"}], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-06-06T13:38:05.660000+00:00", "edited_timestamp": null, "flags": 0, "components": [], "webhook_id": "849615314274484224"}
|
// {"id": "851092588608880670", "type": 0, "content": "", "channel_id": "849615269706203171", "author": {"bot": true, "id": "849615314274484224", "username": "abcdedf", "avatar": null, "discriminator": "0000"}, "attachments": [{"id": "851092588332449812", "filename": "dau480457962.png", "size": 859505, "url": "https://cdn.discordapp.com/attachments/849615269706203171/851092588332449812/dau480457962.png", "proxy_url": "https://media.discordapp.net/attachments/849615269706203171/851092588332449812/dau480457962.png", "width": 640, "height": 640, "content_type": "image/png"}], "embeds": [], "mentions": [], "mention_roles": [], "pinned": false, "mention_everyone": false, "tts": false, "timestamp": "2021-06-06T13:38:05.660000+00:00", "edited_timestamp": null, "flags": 0, "components": [], "webhook_id": "849615314274484224"}
|
||||||
|
|
||||||
daulog.Debugf("Response: %s", string(resBody[:]))
|
daulog.SendLog(fmt.Sprintf("Response: %s", string(resBody[:])), daulog.LogTypeDebug)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
daulog.Errorf("could not parse JSON: %s", err)
|
log.Print("could not parse JSON: ", err)
|
||||||
daulog.Errorf("Response was: %s", string(resBody[:]))
|
fmt.Println("Response was:", string(resBody[:]))
|
||||||
retriesRemaining--
|
retriesRemaining--
|
||||||
sleepForRetries(retriesRemaining)
|
sleepForRetries(retriesRemaining)
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
if len(res.Attachments) < 1 {
|
if len(res.Attachments) < 1 {
|
||||||
daulog.Error("bad response - no attachments?")
|
log.Print("bad response - no attachments?")
|
||||||
retriesRemaining--
|
retriesRemaining--
|
||||||
sleepForRetries(retriesRemaining)
|
sleepForRetries(retriesRemaining)
|
||||||
continue
|
continue
|
||||||
@ -234,12 +192,11 @@ func (u *Upload) processUpload() error {
|
|||||||
elapsed := time.Since(start)
|
elapsed := time.Since(start)
|
||||||
rate := float64(a.Size) / elapsed.Seconds() / 1024.0
|
rate := float64(a.Size) / elapsed.Seconds() / 1024.0
|
||||||
|
|
||||||
daulog.Infof("Uploaded to %s %dx%d", a.URL, a.Width, a.Height)
|
daulog.SendLog(fmt.Sprintf("Uploaded to %s %dx%d", a.URL, a.Width, a.Height), daulog.LogTypeInfo)
|
||||||
daulog.Infof("id: %d, %d bytes transferred in %.2f seconds (%.2f KiB/s)", res.ID, a.Size, elapsed.Seconds(), rate)
|
daulog.SendLog(fmt.Sprintf("id: %d, %d bytes transferred in %.2f seconds (%.2f KiB/s)", res.ID, a.Size, elapsed.Seconds(), rate), daulog.LogTypeInfo)
|
||||||
|
|
||||||
u.Url = a.URL
|
u.Url = a.URL
|
||||||
u.State = StateComplete
|
u.Uploaded = true
|
||||||
u.StateReason = ""
|
|
||||||
u.Width = a.Width
|
u.Width = a.Width
|
||||||
u.Height = a.Height
|
u.Height = a.Height
|
||||||
u.UploadedAt = time.Now()
|
u.UploadedAt = time.Now()
|
||||||
@ -248,28 +205,33 @@ func (u *Upload) processUpload() error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// remove any temporary files
|
if u.watermark {
|
||||||
u.Image.Cleanup()
|
daulog.SendLog(fmt.Sprintf("Removing temporary file: %s", u.filenameToUpload), daulog.LogTypeDebug)
|
||||||
|
os.Remove(u.filenameToUpload)
|
||||||
if retriesRemaining == 0 {
|
|
||||||
daulog.Error("Failed to upload, even after all retries")
|
|
||||||
u.State = StateFailed
|
|
||||||
u.StateReason = "could not upload after all retries"
|
|
||||||
return errors.New("could not upload after all retries")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if retriesRemaining == 0 {
|
||||||
|
daulog.SendLog("Failed to upload, even after all retries", daulog.LogTypeError)
|
||||||
|
u.Failed = true
|
||||||
|
return errors.New("could not upload after all retries")
|
||||||
|
}
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func newfileUploadRequest(uri string, params map[string]string, paramName string, filename string, filedata io.Reader) (*http.Request, error) {
|
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
|
||||||
|
file, err := os.Open(path)
|
||||||
|
if err != nil {
|
||||||
|
return nil, fmt.Errorf("could not open file '%s': %s", path, err)
|
||||||
|
}
|
||||||
|
defer file.Close()
|
||||||
|
|
||||||
body := &bytes.Buffer{}
|
body := &bytes.Buffer{}
|
||||||
writer := multipart.NewWriter(body)
|
writer := multipart.NewWriter(body)
|
||||||
part, err := writer.CreateFormFile(paramName, filename)
|
part, err := writer.CreateFormFile(paramName, filepath.Base(path))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
_, err = io.Copy(part, filedata)
|
_, err = io.Copy(part, file)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.Fatal("Could not copy: ", err)
|
log.Fatal("Could not copy: ", err)
|
||||||
}
|
}
|
||||||
@ -287,11 +249,57 @@ func newfileUploadRequest(uri string, params map[string]string, paramName string
|
|||||||
return req, err
|
return req, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (u *Upload) applyWatermark() {
|
||||||
|
|
||||||
|
reader, err := os.Open(u.originalFilename)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
defer reader.Close()
|
||||||
|
|
||||||
|
im, _, err := image.Decode(reader)
|
||||||
|
if err != nil {
|
||||||
|
daulog.SendLog(fmt.Sprintf("Cannot decode image: %v - skipping watermarking", err), daulog.LogTypeError)
|
||||||
|
u.watermark = false
|
||||||
|
u.filenameToUpload = u.originalFilename
|
||||||
|
return
|
||||||
|
}
|
||||||
|
bounds := im.Bounds()
|
||||||
|
// var S float64 = float64(bounds.Max.X)
|
||||||
|
|
||||||
|
dc := gg.NewContext(bounds.Max.X, bounds.Max.Y)
|
||||||
|
dc.Clear()
|
||||||
|
dc.SetRGB(0, 0, 0)
|
||||||
|
|
||||||
|
dc.SetFontFace(inconsolata.Regular8x16)
|
||||||
|
|
||||||
|
dc.DrawImage(im, 0, 0)
|
||||||
|
|
||||||
|
dc.DrawRoundedRectangle(0, float64(bounds.Max.Y-18.0), 320, float64(bounds.Max.Y), 0)
|
||||||
|
dc.SetRGB(0, 0, 0)
|
||||||
|
dc.Fill()
|
||||||
|
|
||||||
|
dc.SetRGB(1, 1, 1)
|
||||||
|
|
||||||
|
dc.DrawString("github.com/tardisx/discord-auto-upload", 5.0, float64(bounds.Max.Y)-5.0)
|
||||||
|
|
||||||
|
tempfile, err := ioutil.TempFile("", "dau")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatal(err)
|
||||||
|
}
|
||||||
|
tempfile.Close()
|
||||||
|
os.Remove(tempfile.Name())
|
||||||
|
actualName := tempfile.Name() + ".png"
|
||||||
|
|
||||||
|
dc.SavePNG(actualName)
|
||||||
|
u.filenameToUpload = actualName
|
||||||
|
}
|
||||||
|
|
||||||
func sleepForRetries(retry int) {
|
func sleepForRetries(retry int) {
|
||||||
if retry == 0 {
|
if retry == 0 {
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
retryTime := (6-retry)*(6-retry) + 6
|
retryTime := (6-retry)*(6-retry) + 6
|
||||||
daulog.Errorf("Will retry in %d seconds (%d remaining attempts)", retryTime, retry)
|
daulog.SendLog(fmt.Sprintf("Will retry in %d seconds (%d remaining attempts)", retryTime, retry), daulog.LogTypeError)
|
||||||
time.Sleep(time.Duration(retryTime) * time.Second)
|
time.Sleep(time.Duration(retryTime) * time.Second)
|
||||||
}
|
}
|
||||||
|
@ -2,13 +2,11 @@ package upload
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
i "image"
|
|
||||||
"image/color"
|
|
||||||
"image/png"
|
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"math/rand"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"testing"
|
||||||
|
// "github.com/tardisx/discord-auto-upload/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
// https://www.thegreatcodeadventure.com/mocking-http-requests-in-golang/
|
// https://www.thegreatcodeadventure.com/mocking-http-requests-in-golang/
|
||||||
@ -36,62 +34,36 @@ func DoTooBigUpload(req *http.Request) (*http.Response, error) {
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// func TestSuccessfulUpload(t *testing.T) {
|
func TestSuccessfulUpload(t *testing.T) {
|
||||||
// // create temporary file, processUpload requires that it exists, even though
|
// create temporary file, processUpload requires that it exists, even though
|
||||||
// // we will not really be uploading it here
|
// we will not really be uploading it here
|
||||||
// f, _ := os.CreateTemp("", "dautest-upload-*")
|
f, _ := os.CreateTemp("", "dautest-upload-*")
|
||||||
// defer os.Remove(f.Name())
|
defer os.Remove(f.Name())
|
||||||
// u := Upload{webhookURL: "https://127.0.0.1/", Image: &image.Store{OriginalFilename: f.Name()}}
|
u := Upload{webhookURL: "https://127.0.0.1/", originalFilename: f.Name()}
|
||||||
// u.Client = &MockClient{DoFunc: DoGoodUpload}
|
u.Client = &MockClient{DoFunc: DoGoodUpload}
|
||||||
// err := u.processUpload()
|
err := u.processUpload()
|
||||||
// if err != nil {
|
if err != nil {
|
||||||
// t.Errorf("error occured: %s", err)
|
t.Errorf("error occured: %s", err)
|
||||||
// }
|
}
|
||||||
|
if u.Width != 640 || u.Height != 640 {
|
||||||
// if u.Url != "https://cdn.discordapp.com/attachments/849615269706203171/851092588332449812/dau480457962.png" {
|
t.Error("dimensions wrong")
|
||||||
// t.Error("URL wrong")
|
}
|
||||||
// }
|
if u.Url != "https://cdn.discordapp.com/attachments/849615269706203171/851092588332449812/dau480457962.png" {
|
||||||
// }
|
t.Error("URL wrong")
|
||||||
|
}
|
||||||
// func TestTooBigUpload(t *testing.T) {
|
}
|
||||||
// // create temporary file, processUpload requires that it exists, even though
|
|
||||||
// // we will not really be uploading it here
|
func TestTooBigUpload(t *testing.T) {
|
||||||
// f, _ := os.CreateTemp("", "dautest-upload-*")
|
// create temporary file, processUpload requires that it exists, even though
|
||||||
// defer os.Remove(f.Name())
|
// we will not really be uploading it here
|
||||||
// u := Upload{webhookURL: "https://127.0.0.1/", Image: &image.Store{OriginalFilename: f.Name()}}
|
f, _ := os.CreateTemp("", "dautest-upload-*")
|
||||||
// u.Client = &MockClient{DoFunc: DoTooBigUpload}
|
defer os.Remove(f.Name())
|
||||||
// err := u.processUpload()
|
u := Upload{webhookURL: "https://127.0.0.1/", originalFilename: f.Name()}
|
||||||
// if err == nil {
|
u.Client = &MockClient{DoFunc: DoTooBigUpload}
|
||||||
// t.Error("error did not occur?")
|
err := u.processUpload()
|
||||||
// } else if err.Error() != "received 413 - file too large" {
|
if err == nil {
|
||||||
// t.Errorf("wrong error occurred: %s", err.Error())
|
t.Error("error did not occur?")
|
||||||
// }
|
} else if err.Error() != "received 413 - file too large" {
|
||||||
// if u.State != StateFailed {
|
t.Errorf("wrong error occurred: %s", err.Error())
|
||||||
// t.Error("upload should have been marked failed")
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
|
|
||||||
func tempImageGt8Mb() {
|
|
||||||
// about 12Mb
|
|
||||||
width := 2000
|
|
||||||
height := 2000
|
|
||||||
|
|
||||||
upLeft := i.Point{0, 0}
|
|
||||||
lowRight := i.Point{width, height}
|
|
||||||
|
|
||||||
img := i.NewRGBA(i.Rectangle{upLeft, lowRight})
|
|
||||||
|
|
||||||
// Colors are defined by Red, Green, Blue, Alpha uint8 values.
|
|
||||||
|
|
||||||
// Set color for each pixel.
|
|
||||||
for x := 0; x < width; x++ {
|
|
||||||
for y := 0; y < height; y++ {
|
|
||||||
color := color.RGBA{uint8(rand.Int31n(256)), uint8(rand.Int31n(256)), uint8(rand.Int31n(256)), 0xff}
|
|
||||||
img.Set(x, y, color)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Encode as PNG.
|
|
||||||
f, _ := os.Create("image.png")
|
|
||||||
png.Encode(f, img)
|
|
||||||
}
|
}
|
||||||
|
@ -1,47 +1,24 @@
|
|||||||
package version
|
package version
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
|
||||||
"log"
|
"log"
|
||||||
"net/http"
|
|
||||||
"time"
|
|
||||||
|
|
||||||
daulog "github.com/tardisx/discord-auto-upload/log"
|
|
||||||
|
|
||||||
"golang.org/x/mod/semver"
|
"golang.org/x/mod/semver"
|
||||||
)
|
)
|
||||||
|
|
||||||
const CurrentVersion string = "v0.13.0"
|
const CurrentVersion string = "v0.11.1"
|
||||||
|
|
||||||
type GithubRelease struct {
|
func NewVersionAvailable(v string) bool {
|
||||||
HTMLURL string `json:"html_url"`
|
|
||||||
TagName string `json:"tag_name"`
|
|
||||||
Name string `json:"name"`
|
|
||||||
Body string `json:"body"`
|
|
||||||
}
|
|
||||||
|
|
||||||
var LatestVersion string
|
|
||||||
var LatestVersionInfo GithubRelease
|
|
||||||
|
|
||||||
// UpdateAvailable returns true or false, depending on whether not a new version is available.
|
|
||||||
// It always returns false if the OnlineVersion has not yet been fetched.
|
|
||||||
func UpdateAvailable() bool {
|
|
||||||
if !semver.IsValid(CurrentVersion) {
|
if !semver.IsValid(CurrentVersion) {
|
||||||
panic(fmt.Sprintf("my current version '%s' is not valid", CurrentVersion))
|
panic(fmt.Sprintf("my current version '%s' is not valid", CurrentVersion))
|
||||||
}
|
}
|
||||||
|
if !semver.IsValid(v) {
|
||||||
if LatestVersion == "" {
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
if !semver.IsValid(LatestVersion) {
|
|
||||||
// maybe this should just be a warning
|
// maybe this should just be a warning
|
||||||
daulog.Errorf("online version '%s' is not valid - assuming no new version", LatestVersion)
|
log.Printf("passed in version '%s' is not valid - assuming no new version", v)
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
comp := semver.Compare(LatestVersion, CurrentVersion)
|
comp := semver.Compare(v, CurrentVersion)
|
||||||
if comp == 0 {
|
if comp == 0 {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
@ -50,32 +27,3 @@ func UpdateAvailable() bool {
|
|||||||
}
|
}
|
||||||
return false // they are using a newer one than exists?
|
return false // they are using a newer one than exists?
|
||||||
}
|
}
|
||||||
|
|
||||||
func GetOnlineVersion() {
|
|
||||||
|
|
||||||
daulog.Info("checking for new version")
|
|
||||||
|
|
||||||
client := &http.Client{Timeout: time.Second * 5}
|
|
||||||
resp, err := client.Get("https://api.github.com/repos/tardisx/discord-auto-upload/releases/latest")
|
|
||||||
if err != nil {
|
|
||||||
daulog.Errorf("WARNING: Update check failed: %s", err)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer resp.Body.Close()
|
|
||||||
body, err := ioutil.ReadAll(resp.Body)
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("could not check read update response")
|
|
||||||
}
|
|
||||||
|
|
||||||
var latest GithubRelease
|
|
||||||
err = json.Unmarshal(body, &latest)
|
|
||||||
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal("could not parse JSON: ", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
LatestVersion = latest.TagName
|
|
||||||
LatestVersionInfo = latest
|
|
||||||
daulog.Debugf("Latest version: %s", LatestVersion)
|
|
||||||
|
|
||||||
}
|
|
||||||
|
@ -4,18 +4,8 @@ import (
|
|||||||
"testing"
|
"testing"
|
||||||
)
|
)
|
||||||
|
|
||||||
func TestVersioningUpdate(t *testing.T) {
|
func TestVersioning(t *testing.T) {
|
||||||
// pretend there is a new version
|
if !NewVersionAvailable("v1.0.0") {
|
||||||
LatestVersion = "v0.13.9"
|
t.Error("should be a version newer than v1.0.0")
|
||||||
if !UpdateAvailable() {
|
|
||||||
t.Error("should be a version newer than " + CurrentVersion)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func TestVersioningNoUpdate(t *testing.T) {
|
|
||||||
// pretend there is not a new version
|
|
||||||
LatestVersion = "v0.12.1"
|
|
||||||
if UpdateAvailable() {
|
|
||||||
t.Error("should NOT be a version newer than " + CurrentVersion)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
File diff suppressed because one or more lines are too long
@ -21,7 +21,7 @@
|
|||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p>The Watch Interval is how often new files will be discovered by your
|
<p>The Watch Interval is how often new files will be discovered by your
|
||||||
watchers in seconds (watchers are configured below).</p>
|
watchers (configured below).</p>
|
||||||
|
|
||||||
<div class="form-row align-items-center">
|
<div class="form-row align-items-center">
|
||||||
<div class="col-sm-6 my-1">
|
<div class="col-sm-6 my-1">
|
||||||
@ -33,17 +33,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="form-row align-items-center">
|
|
||||||
<div class="col-sm-6 my-1">
|
|
||||||
<span>Open browser on startup</span>
|
|
||||||
</div>
|
|
||||||
<div class="col-sm-6 my-1">
|
|
||||||
<label class="sr-only">Open browser</label>
|
|
||||||
<button type="button" @click="config.OpenBrowserOnStart = ! config.OpenBrowserOnStart" class="btn btn-success" x-text="config.OpenBrowserOnStart ? 'Enabled' : 'Disabled'"></button>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="form-row align-items-center">
|
<div class="form-row align-items-center">
|
||||||
<div class="col-sm-6 my-1">
|
<div class="col-sm-6 my-1">
|
||||||
<span>Watch interval</span>
|
<span>Watch interval</span>
|
||||||
@ -69,12 +58,6 @@
|
|||||||
change only, and does not hide the uploaders actual identity.
|
change only, and does not hide the uploaders actual identity.
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<p>A watcher can be configured to hold uploads. This causes the new images seen
|
|
||||||
by the watcher to be held for review on the <a href="/uploads.html">uploads page</a>.
|
|
||||||
This allows each image to be individually uploaded or skipped.
|
|
||||||
|
|
||||||
</p>
|
|
||||||
|
|
||||||
<p>Exclusions can be specified, zero or more arbitrary strings. If any
|
<p>Exclusions can be specified, zero or more arbitrary strings. If any
|
||||||
file matches one of those strings then it will not be uploaded. This is most
|
file matches one of those strings then it will not be uploaded. This is most
|
||||||
often used if you use software (like Steam) which automatically creates thumbnails
|
often used if you use software (like Steam) which automatically creates thumbnails
|
||||||
@ -122,15 +105,6 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div class="form-row align-items-center">
|
|
||||||
<div class="col-sm-6 my-1">
|
|
||||||
<span>Hold Uploads</span>
|
|
||||||
</div>
|
|
||||||
<div class="col-sm-6 my-1">
|
|
||||||
<button type="button" @click="config.Watchers[i].HoldUploads = ! config.Watchers[i].HoldUploads" class="btn btn-success" x-text="watcher.HoldUploads ? 'Enabled' : 'Disabled'"></button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
|
|
||||||
<div class="form-row align-items-center">
|
<div class="form-row align-items-center">
|
||||||
<div class="col-sm-6 my-1">
|
<div class="col-sm-6 my-1">
|
||||||
@ -167,7 +141,7 @@
|
|||||||
|
|
||||||
<div class="my-5">
|
<div class="my-5">
|
||||||
<button type="button" class="btn btn-secondary" href="#"
|
<button type="button" class="btn btn-secondary" href="#"
|
||||||
@click.prevent="config.Watchers.push({Username: '', WebHookURL: 'https://webhook.url.here/', Path: '/directory/path/here', NoWatermark: false, HoldUploads: false, Exclude: []});">
|
@click.prevent="config.Watchers.push({Username: '', WebHookURL: 'https://webhook.url.here/', Path: '/directory/path/here', NoWatermark: false, Exclude: []});">
|
||||||
Add a new watcher</button>
|
Add a new watcher</button>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
@ -186,6 +160,7 @@
|
|||||||
{{ end }}
|
{{ end }}
|
||||||
|
|
||||||
{{ define "js" }}
|
{{ define "js" }}
|
||||||
|
<script src="//unpkg.com/alpinejs" defer></script>
|
||||||
<script>
|
<script>
|
||||||
function configuration() {
|
function configuration() {
|
||||||
return {
|
return {
|
||||||
|
@ -28,8 +28,6 @@ html,
|
|||||||
body {
|
body {
|
||||||
height: 100%;
|
height: 100%;
|
||||||
background-color: #333;
|
background-color: #333;
|
||||||
padding: 2em;
|
|
||||||
max-width: 80em;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
@ -37,16 +35,13 @@ body {
|
|||||||
display: flex; */
|
display: flex; */
|
||||||
color: #fff;
|
color: #fff;
|
||||||
text-shadow: 0 .05rem .1rem rgba(0, 0, 0, .5);
|
text-shadow: 0 .05rem .1rem rgba(0, 0, 0, .5);
|
||||||
|
box-shadow: inset 0 0 5rem rgba(0, 0, 0, .5);
|
||||||
}
|
}
|
||||||
|
|
||||||
.DAU-container {
|
.DAU-container {
|
||||||
max-width: 52em;
|
max-width: 52em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.DAU-container-editor {
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
pre {
|
pre {
|
||||||
background-color: black;
|
background-color: black;
|
||||||
color: aliceblue;
|
color: aliceblue;
|
||||||
|
@ -1,233 +0,0 @@
|
|||||||
{{ define "content" }}
|
|
||||||
|
|
||||||
<main role="main" class="" x-data="editor()" x-init="setup_canvas();">
|
|
||||||
<div class="row">
|
|
||||||
<div class="col">
|
|
||||||
<canvas id="c" x-bind:style="canvas_style">
|
|
||||||
</canvas>
|
|
||||||
<img :src="img_data">
|
|
||||||
</div>
|
|
||||||
<div class="col">
|
|
||||||
<div id="tools-top" x-show="!toolbar">
|
|
||||||
<button type="button" @click="add_some_text()" class="btn btn-primary">Add text</button>
|
|
||||||
<!-- <button type="button" @click="crop()" class="btn btn-primary">Crop</button> -->
|
|
||||||
<button type="button" @click="apply()" class="btn btn-primary">Apply</button>
|
|
||||||
<button type="button" @click="cancel()" class="btn btn-primary">Cancel</button>
|
|
||||||
</div>
|
|
||||||
<div id="tools-delete" x-show="toolbar == 'text'">
|
|
||||||
<button type="button" @click="delete_selected();" class="btn btn-primary" style="">delete</button>
|
|
||||||
</div>
|
|
||||||
<div id="tools-crop" x-show="toolbar == 'crop'">
|
|
||||||
<button type="button" @click="apply_crop();" class="btn btn-primary" style="">crop</button>
|
|
||||||
<button type="button" @click="cancel_crop();" class="btn btn-primary" style="">cancel</button>
|
|
||||||
</div>
|
|
||||||
<div id="tools-colour" x-show="toolbar == 'text'">
|
|
||||||
<table>
|
|
||||||
<tr>
|
|
||||||
<th>foreground</th>
|
|
||||||
<template x-for="colour in colours">
|
|
||||||
<td>
|
|
||||||
<button type="button" @click="set_colour(colour, 'fg')" class="btn btn-primary" :style="'background-color: '+colour"> </button>
|
|
||||||
</td>
|
|
||||||
</template>
|
|
||||||
<td>
|
|
||||||
<button type="button" @click="set_colour('#fff0', 'fg')" class="btn btn-primary" style="">-</button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
<th>background</th>
|
|
||||||
<template x-for="colour in colours">
|
|
||||||
<td>
|
|
||||||
<button type="button" @click="set_colour(colour, 'bg')" class="btn btn-primary" :style="'background-color: '+colour"> </button>
|
|
||||||
</td>
|
|
||||||
</template>
|
|
||||||
<td>
|
|
||||||
<button type="button" @click="set_colour('#fff0', 'bg')" class="btn btn-primary" style="">-</button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
|
|
||||||
<tr>
|
|
||||||
<th>outline</th>
|
|
||||||
<template x-for="colour in colours">
|
|
||||||
<td>
|
|
||||||
<button type="button" @click="set_colour(colour, 'stroke')" class="btn btn-primary" :style="'background-color: '+colour"> </button>
|
|
||||||
</td>
|
|
||||||
</template>
|
|
||||||
<td>
|
|
||||||
<button type="button" @click="set_colour('#fff0', 'stroke')" class="btn btn-primary" style="">-</button>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</table>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
</main>
|
|
||||||
|
|
||||||
{{ end }}
|
|
||||||
|
|
||||||
{{ define "js" }}
|
|
||||||
|
|
||||||
<script>
|
|
||||||
// for some reason, canvas does not work correctly if the object
|
|
||||||
// is managed by alpine - see https://github.com/fabricjs/fabric.js/issues/7485
|
|
||||||
var canvas = null;
|
|
||||||
|
|
||||||
function editor() {
|
|
||||||
return {
|
|
||||||
img_data: "", scaleFactor: 0.5,
|
|
||||||
toolbar: null,
|
|
||||||
crop_state: {},
|
|
||||||
colours: [ 'red', 'blue', 'green', 'white', 'yellow', 'black', 'purple'],
|
|
||||||
|
|
||||||
canvas_style: "",
|
|
||||||
// "position: absolute; width: 100%; height: 100%; left: 0px; top: 0px; touch-action: none; -webkit-user-select: none;",
|
|
||||||
setup_canvas() {
|
|
||||||
// seriously javascript? just imagine, in 2021....
|
|
||||||
var url = new URL(window.location);
|
|
||||||
var id = url.searchParams.get("id");
|
|
||||||
var self = this;
|
|
||||||
canvas = new fabric.Canvas('c');
|
|
||||||
|
|
||||||
canvas.on('selection:cleared', function(options) {
|
|
||||||
self.toolbar = null;
|
|
||||||
});
|
|
||||||
|
|
||||||
fabric.Image.fromURL('/rest/image/'+id, function(oImg) {
|
|
||||||
self.scaleFactor = scalefactor(oImg.width, oImg.height);
|
|
||||||
canvas.setDimensions({width: oImg.width, height: oImg.height});
|
|
||||||
oImg.selectable = false;
|
|
||||||
canvas.add(oImg);
|
|
||||||
canvas.setHeight(canvas.getHeight() * (self.scaleFactor));
|
|
||||||
canvas.setWidth(canvas.getWidth() * (self.scaleFactor));
|
|
||||||
canvas.setZoom(self.scaleFactor);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
export_image() {
|
|
||||||
this.img_data = canvas.toDataURL({multiplier: 1/this.scaleFactor});
|
|
||||||
},
|
|
||||||
add_some_text() {
|
|
||||||
var text = new fabric.Textbox('double click to change', { left: 20, top: 20, width: 300, fontSize: 40 });
|
|
||||||
canvas.add(text);
|
|
||||||
canvas.setActiveObject(text);
|
|
||||||
this.toolbar = 'text';
|
|
||||||
var self = this;
|
|
||||||
text.on('selected', function(options) {
|
|
||||||
self.toolbar = 'text';
|
|
||||||
});
|
|
||||||
},
|
|
||||||
delete_selected() {
|
|
||||||
selected = canvas.getActiveObjects();
|
|
||||||
selected.forEach(el => {
|
|
||||||
canvas.discardActiveObject(el);
|
|
||||||
canvas.remove(el);
|
|
||||||
});
|
|
||||||
},
|
|
||||||
set_colour(colour, type) {
|
|
||||||
selected = canvas.getActiveObjects();
|
|
||||||
console.log();
|
|
||||||
selected.forEach(el => {
|
|
||||||
if (type === 'fg') {
|
|
||||||
el.set('fill', colour);
|
|
||||||
}
|
|
||||||
if (type === 'bg') {
|
|
||||||
el.set('textBackgroundColor', colour);
|
|
||||||
}
|
|
||||||
if (type === 'stroke') {
|
|
||||||
el.set('stroke', colour);
|
|
||||||
}
|
|
||||||
|
|
||||||
});
|
|
||||||
canvas.renderAll();
|
|
||||||
},
|
|
||||||
|
|
||||||
// crop mode - XXX not yet implemented
|
|
||||||
crop() {
|
|
||||||
this.toolbar = 'crop';
|
|
||||||
this.crop_state = {};
|
|
||||||
canvas.selection = false; // disable drag drop selection so we can see the crop rect
|
|
||||||
let self = this;
|
|
||||||
this.crop_state.rectangle = new fabric.Rect({
|
|
||||||
fill: 'transparent',
|
|
||||||
stroke: '#ccc',
|
|
||||||
strokeDashArray: [2, 2],
|
|
||||||
visible: false
|
|
||||||
});
|
|
||||||
console.log(this.crop_state.rectangle);
|
|
||||||
var container = document.getElementById('c').getBoundingClientRect();
|
|
||||||
canvas.add(this.crop_state.rectangle);
|
|
||||||
canvas.on("mouse:down", function(event) {
|
|
||||||
if(1) {
|
|
||||||
console.log('wow mouse is down', event.e);
|
|
||||||
self.crop_state.rectangle.width = 2;
|
|
||||||
self.crop_state.rectangle.height = 2;
|
|
||||||
self.crop_state.rectangle.left = event.e.offsetX / self.scaleFactor;
|
|
||||||
self.crop_state.rectangle.top = event.e.offsetY / self.scaleFactor;
|
|
||||||
self.crop_state.rectangle.visible = true;
|
|
||||||
self.crop_state.mouseDown = event.e;
|
|
||||||
canvas.bringToFront(self.crop_state.rectangle);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// draw the rectangle as the mouse is moved after a down click
|
|
||||||
canvas.on("mouse:move", function(event) {
|
|
||||||
if(self.crop_state.mouseDown && 1) {
|
|
||||||
|
|
||||||
self.crop_state.rectangle.width = event.e.offsetX / self.scaleFactor - self.crop_state.rectangle.left;
|
|
||||||
self.crop_state.rectangle.height = event.e.offsetY / self.scaleFactor - self.crop_state.rectangle.top;
|
|
||||||
canvas.renderAll();
|
|
||||||
|
|
||||||
}
|
|
||||||
});
|
|
||||||
// when mouse click is released, end cropping mode
|
|
||||||
canvas.on("mouse:up", function() {
|
|
||||||
console.log('MOUSE UP');
|
|
||||||
self.crop_state.mouseDown = null;
|
|
||||||
});
|
|
||||||
},
|
|
||||||
apply_crop() {
|
|
||||||
console.log(this.crop_state.rectangle.width);
|
|
||||||
},
|
|
||||||
apply() {
|
|
||||||
|
|
||||||
image_data = canvas.toDataURL({
|
|
||||||
format: 'png',
|
|
||||||
multiplier: 1.0/this.scaleFactor});
|
|
||||||
let formData = new FormData();
|
|
||||||
formData.append('image', image_data);
|
|
||||||
var url = new URL(window.location);
|
|
||||||
var id = url.searchParams.get("id");
|
|
||||||
fetch('/rest/upload/'+id+'/markup', {method: 'POST', body: formData})
|
|
||||||
.then(response => response.json()) // convert to json
|
|
||||||
.then(json => {
|
|
||||||
console.log(json);
|
|
||||||
window.location = '/uploads.html';
|
|
||||||
})
|
|
||||||
},
|
|
||||||
cancel() {
|
|
||||||
window.location = '/uploads.html';
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function scalefactor(width, height) {
|
|
||||||
max_width = window.innerWidth * 3/5;
|
|
||||||
max_height = window.innerHeight * 5/6;
|
|
||||||
|
|
||||||
if (width <= max_width && height <= max_height) {
|
|
||||||
return 1.0;
|
|
||||||
}
|
|
||||||
|
|
||||||
factor = max_width/width;
|
|
||||||
if (height*factor <= max_height) {
|
|
||||||
return factor;
|
|
||||||
}
|
|
||||||
|
|
||||||
return 1/ (height/max_height);
|
|
||||||
}
|
|
||||||
|
|
||||||
</script>
|
|
||||||
|
|
||||||
|
|
||||||
{{ end }}
|
|
1
web/data/fabric.min.js
vendored
1
web/data/fabric.min.js
vendored
File diff suppressed because one or more lines are too long
@ -1,21 +1,24 @@
|
|||||||
{{ define "content" }}
|
{{ define "content" }}
|
||||||
|
|
||||||
<main role="main" class="inner DAU" x-data="logs()" x-init="get_logs()">
|
<main role="main" class="inner DAU">
|
||||||
<h1 class="DAU-heading">Logs</h1>
|
<h1 class="DAU-heading">Logs</h1>
|
||||||
<p class="lead">Discord-auto-upload logs</p>
|
<p class="lead">Discord-auto-upload logs</p>
|
||||||
|
|
||||||
<div class="container">
|
<div class="container">
|
||||||
<div class="row">
|
<div class="row">
|
||||||
<div class="col-sm">
|
<div class="col-sm">
|
||||||
<button type="button" @click="debug = !debug" class="btn btn-primary" x-text="debug ? 'debug' : 'no debug'"></button>
|
<button type="button" onClick="debug=1; get_logs();" class="btn btn-primary">all logs</button>
|
||||||
</div>
|
</div>
|
||||||
<div class="col-sm">
|
<div class="col-sm">
|
||||||
<button type="button" @click="scroll = !scroll" class="btn btn-primary" x-text="scroll ? 'auto-scroll' : 'no scroll'"></button>
|
<button type="button" onClick="debug=0; get_logs();" class="btn btn-primary">no debug</button>
|
||||||
|
</div>
|
||||||
|
<div class="col-sm">
|
||||||
|
<button type="button" id="scroll-button" onClick="toggle_scroll();" class="btn btn-primary">disable auto-scroll</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<pre id="logs" x-text="text" class="text-left pre-scrollable">
|
<pre id="logs" class="text-left pre-scrollable">
|
||||||
</pre>
|
</pre>
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
@ -24,24 +27,35 @@
|
|||||||
{{ define "js" }}
|
{{ define "js" }}
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
function logs() {
|
var debug = 0;
|
||||||
return {
|
var scrl = true;
|
||||||
text: '', scroll: true, debug: false,
|
$(document).ready(function() {
|
||||||
get_logs() {
|
get_logs();
|
||||||
fetch('/rest/logs?' + new URLSearchParams({ debug: this.debug ? "1" : "0" }))
|
setInterval(function() { get_logs(); }, 1000);
|
||||||
.then(response => response.text())
|
});
|
||||||
.then(text => {
|
|
||||||
console.log(text);
|
function toggle_scroll() {
|
||||||
this.text = text;
|
scrl = !scrl;
|
||||||
if (this.scroll) {
|
if (scrl) {
|
||||||
document.getElementById('logs').scrollTop =10000;
|
$('#scroll-button').text('disable auto-scroll');
|
||||||
}
|
|
||||||
let self = this;
|
|
||||||
setTimeout(function() { self.get_logs(); }, 1000)
|
|
||||||
})
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
else {
|
||||||
|
$('#scroll-button').text('auto-scroll');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function get_logs() {
|
||||||
|
$.ajax({ method: 'get', url: '/rest/logs', data: { debug : debug }})
|
||||||
|
.done(function(data) {
|
||||||
|
$('#logs').text(data);
|
||||||
|
console.log('scrl is ', scrl);
|
||||||
|
if (scrl) {
|
||||||
|
$('#logs').scrollTop(10000);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
|
|
||||||
{{ end }}
|
{{ end }}
|
@ -1,146 +1,45 @@
|
|||||||
{{ define "content" }}
|
{{ define "content" }}
|
||||||
|
|
||||||
<main role="main" x-data="uploads()" x-init="get_uploads();" class="inner DAU">
|
<main role="main" class="inner DAU">
|
||||||
<h1 class="DAU-heading">Uploads</h1>
|
<h1 class="DAU-heading">Uploads</h1>
|
||||||
<p class="lead">Discord-auto-upload uploads</p>
|
<p class="lead">Discord-auto-upload uploads</p>
|
||||||
|
|
||||||
<h2>Pending uploads</h2>
|
|
||||||
|
|
||||||
<table class="table table-condensed table-dark">
|
<table class="table table-condensed table-dark">
|
||||||
<thead>
|
<thead>
|
||||||
<tr>
|
<tr><th>uploaded</th><th>dt</th><th>thumb</th></tr>
|
||||||
<th>filename</th>
|
|
||||||
<th>actions</th>
|
|
||||||
<th> </th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
</thead>
|
||||||
<tbody>
|
<tbody id="uploads">
|
||||||
<template x-for="ul in pending">
|
|
||||||
<tr>
|
|
||||||
<td x-text="ul.original_file"></td>
|
|
||||||
<td>
|
|
||||||
<button @click="start_upload(ul.id)" type="button" class="btn btn-primary">upload</button>
|
|
||||||
<button @click="skip_upload(ul.id)" type="button" class="btn btn-primary">reject</button>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<a x-bind:href="'/editor.html?id='+ul.id"><img x-bind:src="'/rest/image/'+ul.id+'/thumb'"></a>
|
|
||||||
<a x-show="ul.markedup_file" x-bind:href="'/editor.html?id='+ul.id"><img x-bind:src="'/rest/image/'+ul.id+'/markedup_thumb'"></a>
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
<h2>Current uploads</h2>
|
|
||||||
|
|
||||||
<table class="table table-condensed table-dark">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>filename</th>
|
|
||||||
<th>state</th>
|
|
||||||
<th> </th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
|
|
||||||
<template x-for="ul in uploads">
|
|
||||||
<tr>
|
|
||||||
<td x-text="ul.original_file"></td>
|
|
||||||
<td>
|
|
||||||
<span x-text="ul.state"></span>
|
|
||||||
<div x-if="ul.state_reason">(<span x-text="ul.state_reason"></span>)</div>
|
|
||||||
</td>
|
|
||||||
|
|
||||||
<td>
|
|
||||||
<img :src="'/rest/image/'+ul.id+'/thumb'">
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
|
|
||||||
<h2>Completed uploads</h2>
|
|
||||||
|
|
||||||
<table class="table table-condensed table-dark">
|
|
||||||
<thead>
|
|
||||||
<tr>
|
|
||||||
<th>filename</th>
|
|
||||||
<th>state</th>
|
|
||||||
<th> </th>
|
|
||||||
</tr>
|
|
||||||
</thead>
|
|
||||||
<tbody>
|
|
||||||
|
|
||||||
<template x-for="ul in finished">
|
|
||||||
<tr>
|
|
||||||
<td x-text="ul.original_file"></td>
|
|
||||||
<td>
|
|
||||||
<span x-text="ul.state"></span>
|
|
||||||
<div x-if="ul.state_reason">(<span x-text="ul.state_reason"></span>)</div>
|
|
||||||
</td>
|
|
||||||
<td>
|
|
||||||
<img :src="'/rest/image/'+ul.id+'/thumb'">
|
|
||||||
</td>
|
|
||||||
</tr>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
</tbody>
|
|
||||||
</table>
|
|
||||||
|
|
||||||
|
|
||||||
</main>
|
</main>
|
||||||
|
|
||||||
{{ end }}
|
{{ end }}
|
||||||
|
|
||||||
{{ define "js" }}
|
{{ define "js" }}
|
||||||
<script>
|
<script>
|
||||||
function uploads() {
|
|
||||||
return {
|
$(document).ready(function() {
|
||||||
pending: [], uploads: [], finished: [],
|
get_uploads();
|
||||||
start_upload(id) {
|
});
|
||||||
console.log(id);
|
|
||||||
fetch('/rest/upload/'+id+'/start', {method: 'POST'})
|
function get_uploads() {
|
||||||
.then(response => response.json()) // convert to json
|
$.ajax({ method: 'get', url: '/rest/uploads'})
|
||||||
.then(json => {
|
.done(function(data) {
|
||||||
console.log(json);
|
console.log(data);
|
||||||
})
|
$('#uploads').empty();
|
||||||
},
|
if (! data) { return }
|
||||||
skip_upload(id) {
|
data.forEach(i => {
|
||||||
console.log(id);
|
// {uploaded: true, uploaded_at: "2021-06-08T21:59:52.855936+09:30", url: "https://cdn.discordapp.com/attachments/849615269706203171/851800197046468628/dau736004285.png", width: 640, height: 640}
|
||||||
fetch('/rest/upload/'+id+'/skip', {method: 'POST'})
|
console.log(i);
|
||||||
.then(response => response.json()) // convert to json
|
row = $('<tr>');
|
||||||
.then(json => {
|
row.append($('<td>').text(i.uploaded ? 'yes' : 'no'));
|
||||||
console.log(json);
|
row.append($('<td>').text(i.uploaded_at));
|
||||||
})
|
row.append($('<td>').html($('<img>', { width : i.width/10, height : i.height/10, src : i.url })));
|
||||||
},
|
$('#uploads').prepend(row);
|
||||||
get_uploads() {
|
});
|
||||||
fetch('/rest/uploads')
|
});
|
||||||
.then(response => response.json()) // convert to json
|
}
|
||||||
.then(json => {
|
|
||||||
this.pending = [];
|
|
||||||
this.uploads = [];
|
|
||||||
this.finished = [];
|
|
||||||
json.forEach(ul => {
|
|
||||||
if (ul.state == 'Pending') {
|
|
||||||
this.pending.push(ul);
|
|
||||||
}
|
|
||||||
else if (ul.state == 'Complete' || ul.state == 'Failed' || ul.state == 'Skipped') {
|
|
||||||
this.finished.push(ul)
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
this.uploads.push(ul);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
this.config = json;
|
|
||||||
console.log(json);
|
|
||||||
let self = this;
|
|
||||||
setTimeout(function() { self.get_uploads(); } , 1000);
|
|
||||||
})
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
</script>
|
</script>
|
||||||
{{ end }}
|
{{ end }}
|
||||||
|
@ -6,9 +6,11 @@
|
|||||||
<meta charset="utf-8">
|
<meta charset="utf-8">
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
|
||||||
|
|
||||||
|
|
||||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
|
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">
|
||||||
<script src="/alpine.js" defer></script>
|
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
|
||||||
<script src="https://cdn.jsdelivr.net/npm/fabric@4.6.0/dist/fabric.min.js"></script>
|
<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
|
||||||
|
|
||||||
|
|
||||||
<style>
|
<style>
|
||||||
.bd-placeholder-img {
|
.bd-placeholder-img {
|
||||||
@ -33,7 +35,7 @@
|
|||||||
|
|
||||||
<body class="">
|
<body class="">
|
||||||
|
|
||||||
<div class="DAU-container-editor d-flex w-100 h-100 p-3 mx-auto flex-column">
|
<div class="DAU-container d-flex w-100 h-100 p-3 mx-auto flex-column">
|
||||||
<header class="masthead mb-auto">
|
<header class="masthead mb-auto">
|
||||||
<div class="inner">
|
<div class="inner">
|
||||||
<h3 class="masthead-brand">discord-auto-upload ({{.Version}})</h3>
|
<h3 class="masthead-brand">discord-auto-upload ({{.Version}})</h3>
|
||||||
@ -42,10 +44,6 @@
|
|||||||
<a class="nav-link {{ if eq .Path "config.html"}} active {{ end }}" href="/config.html">Config</a>
|
<a class="nav-link {{ if eq .Path "config.html"}} active {{ end }}" href="/config.html">Config</a>
|
||||||
<a class="nav-link {{ if eq .Path "uploads.html"}} active {{ end }}" href="/uploads.html">Uploads</a>
|
<a class="nav-link {{ if eq .Path "uploads.html"}} active {{ end }}" href="/uploads.html">Uploads</a>
|
||||||
<a class="nav-link {{ if eq .Path "logs.html"}} active {{ end }}" href="/logs.html">Logs</a>
|
<a class="nav-link {{ if eq .Path "logs.html"}} active {{ end }}" href="/logs.html">Logs</a>
|
||||||
{{ if eq .NewVersionAvailable true }}
|
|
||||||
<a class="nav-link" href="{{ .NewVersionInfo.HTMLURL }}">Ver {{ .NewVersionInfo.TagName }} available!</a>
|
|
||||||
{{ end }}
|
|
||||||
|
|
||||||
</nav>
|
</nav>
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
@ -62,7 +60,6 @@
|
|||||||
|
|
||||||
|
|
||||||
</body>
|
</body>
|
||||||
|
|
||||||
{{ template "js" . }}
|
{{ template "js" . }}
|
||||||
</html>
|
</html>
|
||||||
|
|
||||||
|
251
web/server.go
251
web/server.go
@ -2,24 +2,17 @@ package web
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"embed"
|
"embed"
|
||||||
"encoding/base64"
|
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"html/template"
|
"html/template"
|
||||||
"io"
|
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
"log"
|
"log"
|
||||||
"mime"
|
"mime"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
"strconv"
|
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
|
||||||
"github.com/tardisx/discord-auto-upload/config"
|
"github.com/tardisx/discord-auto-upload/config"
|
||||||
"github.com/tardisx/discord-auto-upload/image"
|
|
||||||
daulog "github.com/tardisx/discord-auto-upload/log"
|
daulog "github.com/tardisx/discord-auto-upload/log"
|
||||||
"github.com/tardisx/discord-auto-upload/upload"
|
"github.com/tardisx/discord-auto-upload/upload"
|
||||||
"github.com/tardisx/discord-auto-upload/version"
|
"github.com/tardisx/discord-auto-upload/version"
|
||||||
@ -30,19 +23,6 @@ type WebService struct {
|
|||||||
Uploader *upload.Uploader
|
Uploader *upload.Uploader
|
||||||
}
|
}
|
||||||
|
|
||||||
type ErrorResponse struct {
|
|
||||||
Error string `json:"error"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type StartUploadRequest struct {
|
|
||||||
Id int32 `json:"id"`
|
|
||||||
}
|
|
||||||
|
|
||||||
type StartUploadResponse struct {
|
|
||||||
Success bool `json:"success"`
|
|
||||||
Message string `json:"message"`
|
|
||||||
}
|
|
||||||
|
|
||||||
//go:embed data
|
//go:embed data
|
||||||
var webFS embed.FS
|
var webFS embed.FS
|
||||||
|
|
||||||
@ -63,10 +43,9 @@ func (ws *WebService) getStatic(w http.ResponseWriter, r *http.Request) {
|
|||||||
extension := filepath.Ext(string(path))
|
extension := filepath.Ext(string(path))
|
||||||
|
|
||||||
if extension == ".html" { // html file
|
if extension == ".html" { // html file
|
||||||
|
|
||||||
t, err := template.ParseFS(webFS, "data/wrapper.tmpl", "data/"+path)
|
t, err := template.ParseFS(webFS, "data/wrapper.tmpl", "data/"+path)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
daulog.Errorf("when fetching: %s got: %s", path, err)
|
daulog.SendLog(fmt.Sprintf("when fetching: %s got: %s", path, err), daulog.LogTypeError)
|
||||||
w.Header().Add("Content-Type", "text/plain")
|
w.Header().Add("Content-Type", "text/plain")
|
||||||
w.WriteHeader(http.StatusNotFound)
|
w.WriteHeader(http.StatusNotFound)
|
||||||
w.Write([]byte("not found"))
|
w.Write([]byte("not found"))
|
||||||
@ -74,16 +53,12 @@ func (ws *WebService) getStatic(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
var b struct {
|
var b struct {
|
||||||
Body string
|
Body string
|
||||||
Path string
|
Path string
|
||||||
Version string
|
Version string
|
||||||
NewVersionAvailable bool
|
|
||||||
NewVersionInfo version.GithubRelease
|
|
||||||
}
|
}
|
||||||
b.Path = path
|
b.Path = path
|
||||||
b.Version = version.CurrentVersion
|
b.Version = version.CurrentVersion
|
||||||
b.NewVersionAvailable = version.UpdateAvailable()
|
|
||||||
b.NewVersionInfo = version.LatestVersionInfo
|
|
||||||
|
|
||||||
err = t.ExecuteTemplate(w, "layout", b)
|
err = t.ExecuteTemplate(w, "layout", b)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@ -94,7 +69,7 @@ func (ws *WebService) getStatic(w http.ResponseWriter, r *http.Request) {
|
|||||||
otherStatic, err := webFS.ReadFile("data/" + path)
|
otherStatic, err := webFS.ReadFile("data/" + path)
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
daulog.Errorf("when fetching: %s got: %s", path, err)
|
daulog.SendLog(fmt.Sprintf("when fetching: %s got: %s", path, err), daulog.LogTypeError)
|
||||||
w.Header().Add("Content-Type", "text/plain")
|
w.Header().Add("Content-Type", "text/plain")
|
||||||
w.WriteHeader(http.StatusNotFound)
|
w.WriteHeader(http.StatusNotFound)
|
||||||
w.Write([]byte("not found"))
|
w.Write([]byte("not found"))
|
||||||
@ -118,7 +93,7 @@ func (ws *WebService) getLogs(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
text := ""
|
text := ""
|
||||||
for _, log := range daulog.Memory.Entries() {
|
for _, log := range daulog.LogEntries {
|
||||||
if !showDebug && log.Type == daulog.LogTypeDebug {
|
if !showDebug && log.Type == daulog.LogTypeDebug {
|
||||||
continue
|
continue
|
||||||
}
|
}
|
||||||
@ -127,29 +102,40 @@ func (ws *WebService) getLogs(w http.ResponseWriter, r *http.Request) {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// js, _ := json.Marshal(daulog.LogEntries)
|
||||||
w.Write([]byte(text))
|
w.Write([]byte(text))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ws *WebService) handleConfig(w http.ResponseWriter, r *http.Request) {
|
func (ws *WebService) handleConfig(w http.ResponseWriter, r *http.Request) {
|
||||||
if r.Method == "POST" {
|
if r.Method == "POST" {
|
||||||
|
|
||||||
newConfig := config.ConfigV3{}
|
type ErrorResponse struct {
|
||||||
|
Error string `json:"error"`
|
||||||
|
}
|
||||||
|
|
||||||
|
newConfig := config.ConfigV2{}
|
||||||
|
|
||||||
defer r.Body.Close()
|
defer r.Body.Close()
|
||||||
b, err := ioutil.ReadAll(r.Body)
|
b, err := ioutil.ReadAll(r.Body)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnJSONError(w, "could not read body?")
|
w.WriteHeader(400)
|
||||||
|
w.Write([]byte("bad body"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
err = json.Unmarshal(b, &newConfig)
|
err = json.Unmarshal(b, &newConfig)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnJSONError(w, "badly formed JSON")
|
w.WriteHeader(400)
|
||||||
|
j, _ := json.Marshal(ErrorResponse{Error: "badly formed JSON"})
|
||||||
|
w.Write(j)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
ws.Config.Config = &newConfig
|
ws.Config.Config = &newConfig
|
||||||
err = ws.Config.Save()
|
err = ws.Config.Save()
|
||||||
if err != nil {
|
if err != nil {
|
||||||
returnJSONError(w, err.Error())
|
w.WriteHeader(400)
|
||||||
|
j, _ := json.Marshal(ErrorResponse{Error: err.Error()})
|
||||||
|
w.Write(j)
|
||||||
|
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// config has changed, so tell the world
|
// config has changed, so tell the world
|
||||||
@ -169,200 +155,27 @@ func (ws *WebService) getUploads(w http.ResponseWriter, r *http.Request) {
|
|||||||
|
|
||||||
text, err := json.Marshal(ups)
|
text, err := json.Marshal(ups)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
// not sure how this would happen, so we probably want to find out the hard way
|
daulog.SendLog(fmt.Sprintf("err: %v", err), daulog.LogTypeError)
|
||||||
panic(err)
|
w.Write([]byte("could not marshall uploads?"))
|
||||||
|
return
|
||||||
}
|
}
|
||||||
w.Write([]byte(text))
|
w.Write([]byte(text))
|
||||||
}
|
}
|
||||||
|
|
||||||
func (ws *WebService) imageThumb(w http.ResponseWriter, r *http.Request) {
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "image/png")
|
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
|
||||||
id, err := strconv.ParseInt(vars["id"], 10, 32)
|
|
||||||
if err != nil {
|
|
||||||
returnJSONError(w, "bad id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ul := ws.Uploader.UploadById(int32(id))
|
|
||||||
if ul == nil {
|
|
||||||
returnJSONError(w, "bad id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
err = ul.Image.ThumbPNG(image.ThumbTypeOriginal, w)
|
|
||||||
if err != nil {
|
|
||||||
returnJSONError(w, "could not create thumb")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WebService) imageMarkedupThumb(w http.ResponseWriter, r *http.Request) {
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "image/png")
|
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
|
||||||
id, err := strconv.ParseInt(vars["id"], 10, 32)
|
|
||||||
if err != nil {
|
|
||||||
returnJSONError(w, "bad id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ul := ws.Uploader.UploadById(int32(id))
|
|
||||||
if ul == nil {
|
|
||||||
returnJSONError(w, "bad id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
err = ul.Image.ThumbPNG(image.ThumbTypeMarkedUp, w)
|
|
||||||
if err != nil {
|
|
||||||
returnJSONError(w, "could not create thumb")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WebService) image(w http.ResponseWriter, r *http.Request) {
|
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
|
||||||
id, err := strconv.ParseInt(vars["id"], 10, 32)
|
|
||||||
if err != nil {
|
|
||||||
returnJSONError(w, "bad id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
ul := ws.Uploader.UploadById(int32(id))
|
|
||||||
if ul == nil {
|
|
||||||
returnJSONError(w, "bad id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
img, err := os.Open(ul.Image.OriginalFilename)
|
|
||||||
if err != nil {
|
|
||||||
returnJSONError(w, "could not open image file")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
defer img.Close()
|
|
||||||
io.Copy(w, img)
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WebService) modifyUpload(w http.ResponseWriter, r *http.Request) {
|
|
||||||
|
|
||||||
w.Header().Set("Content-Type", "application/json")
|
|
||||||
|
|
||||||
if r.Method == "POST" {
|
|
||||||
|
|
||||||
vars := mux.Vars(r)
|
|
||||||
change := vars["change"]
|
|
||||||
id, err := strconv.ParseInt(vars["id"], 10, 32)
|
|
||||||
if err != nil {
|
|
||||||
returnJSONError(w, "bad id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
anUpload := ws.Uploader.UploadById(int32(id))
|
|
||||||
if anUpload == nil {
|
|
||||||
returnJSONError(w, "bad id")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
if anUpload.State == upload.StatePending {
|
|
||||||
if change == "start" {
|
|
||||||
anUpload.State = upload.StateQueued
|
|
||||||
res := StartUploadResponse{Success: true, Message: "upload queued"}
|
|
||||||
resString, _ := json.Marshal(res)
|
|
||||||
w.Write(resString)
|
|
||||||
return
|
|
||||||
} else if change == "skip" {
|
|
||||||
anUpload.State = upload.StateSkipped
|
|
||||||
anUpload.Image.Cleanup()
|
|
||||||
res := StartUploadResponse{Success: true, Message: "upload skipped"}
|
|
||||||
resString, _ := json.Marshal(res)
|
|
||||||
w.Write(resString)
|
|
||||||
return
|
|
||||||
} else if change == "markup" {
|
|
||||||
newImageData := r.FormValue("image")
|
|
||||||
//data:image/png;base64,xxxx
|
|
||||||
// I know this is dumb, we should just send binary image data, but I can't
|
|
||||||
// see that Fabric makes that possible.
|
|
||||||
if strings.Index(newImageData, "data:image/png;base64,") != 0 {
|
|
||||||
returnJSONError(w, "bad image data")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
imageDataBase64 := newImageData[22:]
|
|
||||||
b, err := base64.StdEncoding.DecodeString(imageDataBase64)
|
|
||||||
if err != nil {
|
|
||||||
returnJSONError(w, err.Error())
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
// write to a temporary file
|
|
||||||
tempfile, err := ioutil.TempFile("", "dau_markup-*")
|
|
||||||
if err != nil {
|
|
||||||
log.Fatal(err)
|
|
||||||
}
|
|
||||||
n, err := tempfile.Write(b)
|
|
||||||
if n != len(b) {
|
|
||||||
log.Fatalf("only wrote %d bytes??", n)
|
|
||||||
}
|
|
||||||
if err != nil {
|
|
||||||
log.Fatalf("Could not write temp file: %v", err)
|
|
||||||
}
|
|
||||||
|
|
||||||
tempfile.Close()
|
|
||||||
anUpload.Image.ModifiedFilename = tempfile.Name()
|
|
||||||
|
|
||||||
} else {
|
|
||||||
returnJSONError(w, "bad change type")
|
|
||||||
return
|
|
||||||
}
|
|
||||||
}
|
|
||||||
res := StartUploadResponse{Success: false, Message: "upload does not exist, or already queued"}
|
|
||||||
resString, _ := json.Marshal(res)
|
|
||||||
w.WriteHeader(400)
|
|
||||||
w.Write(resString)
|
|
||||||
return
|
|
||||||
}
|
|
||||||
returnJSONError(w, "bad request")
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
func (ws *WebService) StartWebServer() {
|
func (ws *WebService) StartWebServer() {
|
||||||
|
|
||||||
r := mux.NewRouter()
|
http.HandleFunc("/", ws.getStatic)
|
||||||
|
|
||||||
r.HandleFunc("/rest/logs", ws.getLogs)
|
http.HandleFunc("/rest/logs", ws.getLogs)
|
||||||
r.HandleFunc("/rest/uploads", ws.getUploads)
|
http.HandleFunc("/rest/uploads", ws.getUploads)
|
||||||
r.HandleFunc("/rest/upload/{id:[0-9]+}/{change}", ws.modifyUpload)
|
http.HandleFunc("/rest/config", ws.handleConfig)
|
||||||
|
|
||||||
r.HandleFunc("/rest/image/{id:[0-9]+}/thumb", ws.imageThumb)
|
|
||||||
r.HandleFunc("/rest/image/{id:[0-9]+}/markedup_thumb", ws.imageMarkedupThumb)
|
|
||||||
|
|
||||||
r.HandleFunc("/rest/image/{id:[0-9]+}", ws.image)
|
|
||||||
|
|
||||||
r.HandleFunc("/rest/config", ws.handleConfig)
|
|
||||||
r.PathPrefix("/").HandlerFunc(ws.getStatic)
|
|
||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
listen := fmt.Sprintf(":%d", ws.Config.Config.Port)
|
listen := fmt.Sprintf(":%d", ws.Config.Config.Port)
|
||||||
daulog.Infof("Starting web server on http://localhost%s", listen)
|
log.Printf("Starting web server on http://localhost%s", listen)
|
||||||
|
err := http.ListenAndServe(listen, nil) // set listen port
|
||||||
srv := &http.Server{
|
if err != nil {
|
||||||
Handler: r,
|
log.Fatal("ListenAndServe: ", err)
|
||||||
Addr: listen,
|
|
||||||
WriteTimeout: 15 * time.Second,
|
|
||||||
ReadTimeout: 15 * time.Second,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
log.Fatal(srv.ListenAndServe())
|
|
||||||
|
|
||||||
}()
|
}()
|
||||||
}
|
}
|
||||||
|
|
||||||
func returnJSONError(w http.ResponseWriter, errMessage string) {
|
|
||||||
w.WriteHeader(400)
|
|
||||||
errJSON := ErrorResponse{
|
|
||||||
Error: errMessage,
|
|
||||||
}
|
|
||||||
errString, _ := json.Marshal(errJSON)
|
|
||||||
w.Write(errString)
|
|
||||||
}
|
|
||||||
|
@ -78,8 +78,7 @@ func TestGetConfig(t *testing.T) {
|
|||||||
t.Errorf("expected error to be nil got %v", err)
|
t.Errorf("expected error to be nil got %v", err)
|
||||||
}
|
}
|
||||||
|
|
||||||
exp := `{"WatchInterval":10,"Version":3,"Port":9090,"OpenBrowserOnStart":true,"Watchers":[{"WebHookURL":"https://webhook.url.here","Path":"/your/screenshot/dir/here","Username":"","NoWatermark":false,"HoldUploads":false,"Exclude":[]}]}`
|
if string(b) != `{"WatchInterval":10,"Version":2,"Port":9090,"Watchers":[{"WebHookURL":"https://webhook.url.here","Path":"/your/screenshot/dir/here","Username":"","NoWatermark":false,"Exclude":[]}]}` {
|
||||||
if string(b) != exp {
|
t.Errorf("Got unexpected response %v", string(b))
|
||||||
t.Errorf("Got unexpected response\n%v\n%v", string(b), exp)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user