Improved avatar background job

This commit is contained in:
Eduard Urbach 2017-06-12 21:11:20 +02:00
parent 586befcb1a
commit d3f49ad53d
2 changed files with 37 additions and 10 deletions

View File

@ -1,7 +1,6 @@
package main
import (
"fmt"
"io/ioutil"
"os"
"runtime"
@ -24,9 +23,14 @@ func main() {
go func(workerID int) {
for user := range usersQueue {
<-rateLimiter.C
os.Stdout.WriteString("[" + fmt.Sprint(workerID) + "] ")
downloadAvatar(user)
makeWebPAvatar(user)
if downloadAvatar(user) {
makeWebPAvatar(user)
user.Avatar = "/+" + user.Nick + "/avatar"
} else {
user.Avatar = ""
}
user.Save()
}
}(w)
}
@ -37,7 +41,7 @@ func main() {
}
func findAvatar(user *arn.User, dir string) string {
testExtensions := []string{"", ".jpg", ".png", ".gif", ".webp"}
testExtensions := []string{".jpg", ".png", ".gif", ".webp", ""}
for _, testExt := range testExtensions {
if _, err := os.Stat(dir + user.ID + testExt); !os.IsNotExist(err) {
@ -67,9 +71,9 @@ func makeWebPAvatar(user *arn.User) {
}
}
func downloadAvatar(user *arn.User) {
func downloadAvatar(user *arn.User) bool {
if user.Email == "" {
return
return false
}
directory := "../../images/avatars/original/"
@ -81,7 +85,7 @@ func downloadAvatar(user *arn.User) {
// Skip existing avatars
if findAvatar(user, directory) != "" {
color.Yellow(url)
return
return true
}
// Download
@ -89,14 +93,14 @@ func downloadAvatar(user *arn.User) {
if err != nil {
color.Red(url)
return
return false
}
contentType := response.Header.Get("content-type")
if response.StatusCode != 200 {
color.Red(url)
return
return false
}
color.Green(url)
@ -119,4 +123,6 @@ func downloadAvatar(user *arn.User) {
// Write to disk
ioutil.WriteFile(fileName, data, 0644)
return true
}

21
main.go
View File

@ -1,6 +1,9 @@
package main
import (
"errors"
"net/http"
"github.com/aerogo/aero"
"github.com/animenotifier/arn"
"github.com/animenotifier/notify.moe/components"
@ -76,6 +79,24 @@ func main() {
return ctx.File("images/cover/" + ctx.Get("file") + format)
})
// Avatars
app.Get("/user/:nick/avatar", func(ctx *aero.Context) string {
nick := ctx.Get("nick")
user, err := arn.GetUserByNick(nick)
if err != nil {
return ctx.Error(http.StatusNotFound, "User not found", err)
}
if ctx.CanUseWebP() {
return ctx.File("images/avatars/webp/" + user.ID + ".webp")
}
err = errors.New("Your browser doesn't support the WebP image format")
return ctx.Error(http.StatusBadRequest, err.Error(), err)
})
// Elements
app.Get("/images/elements/:file", func(ctx *aero.Context) string {
return ctx.File("images/elements/" + ctx.Get("file"))
})