mirror of
https://github.com/elyby/chrly.git
synced 2025-05-31 14:11:51 +05:30
Compare commits
43 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a661f9aac3 | ||
|
|
9ffdf99b77 | ||
|
|
ad35872fc1 | ||
|
|
a8d8fffaa5 | ||
|
|
0d41f0c347 | ||
|
|
b22f0551fa | ||
|
|
1a906cfc09 | ||
|
|
f610667aa5 | ||
|
|
8b51c1bd0c | ||
|
|
cbe940f8ec | ||
|
|
8693673a71 | ||
|
|
73205648d2 | ||
|
|
3d73cc9402 | ||
|
|
39f5ec5bee | ||
|
|
e652691b29 | ||
|
|
d3b4bee3b0 | ||
|
|
ae50e90ea7 | ||
|
|
c74151c558 | ||
|
|
445bd18fbc | ||
|
|
6a881a62e3 | ||
|
|
201a257d69 | ||
|
|
5d46094643 | ||
|
|
1694403c79 | ||
|
|
66c61dc3cd | ||
|
|
a0d940f8cd | ||
|
|
58a1c6ec33 | ||
|
|
34179ae1fe | ||
|
|
6a54af62aa | ||
|
|
e05c5f200c | ||
|
|
9c4930a0be | ||
|
|
aab7ba9517 | ||
|
|
dea674f52e | ||
|
|
e8a7008e11 | ||
|
|
9467911025 | ||
|
|
a9acfb954f | ||
|
|
98b787fa99 | ||
|
|
4bcd0495ed | ||
|
|
e03832b4e8 | ||
|
|
0d6ca356d1 | ||
|
|
2477433dc9 | ||
|
|
3e3ba296d5 | ||
|
|
e8bd90d8d9 | ||
|
|
408d411846 |
2
.dockerignore
Normal file
2
.dockerignore
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
# Игнорим данные, т.к. они не нужны для внутреннего содержимого этого контейнера
|
||||||
|
data
|
||||||
33
.gitlab-ci.yml
Normal file
33
.gitlab-ci.yml
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
image: docker:latest
|
||||||
|
|
||||||
|
stages:
|
||||||
|
- build
|
||||||
|
- push
|
||||||
|
|
||||||
|
before_script:
|
||||||
|
- docker login -u gitlab-ci -p $CI_BUILD_TOKEN registry.ely.by
|
||||||
|
|
||||||
|
variables:
|
||||||
|
CONTAINER_IMAGE: registry.ely.by/elyby/skinsystem
|
||||||
|
|
||||||
|
build:
|
||||||
|
stage: build
|
||||||
|
script:
|
||||||
|
- export IMAGE_NAME="$CONTAINER_IMAGE:dev"
|
||||||
|
- docker build --pull -t $IMAGE_NAME .
|
||||||
|
- docker push $IMAGE_NAME
|
||||||
|
only:
|
||||||
|
- develop
|
||||||
|
|
||||||
|
push_tags:
|
||||||
|
stage: push
|
||||||
|
variables:
|
||||||
|
GIT_STRATEGY: none
|
||||||
|
script:
|
||||||
|
- export IMAGE_NAME="$CONTAINER_IMAGE:$CI_BUILD_TAG"
|
||||||
|
- docker tag $CONTAINER_IMAGE:dev $CONTAINER_IMAGE:latest
|
||||||
|
- docker tag $CONTAINER_IMAGE:latest $IMAGE_NAME
|
||||||
|
- docker push $IMAGE_NAME
|
||||||
|
- docker push $CONTAINER_IMAGE:latest
|
||||||
|
only:
|
||||||
|
- tags
|
||||||
@@ -1,6 +1,9 @@
|
|||||||
FROM golang:1.7
|
FROM golang:1.7-alpine
|
||||||
|
|
||||||
|
RUN apk add --no-cache git
|
||||||
|
|
||||||
RUN mkdir -p /go/src/elyby/minecraft-skinsystem \
|
RUN mkdir -p /go/src/elyby/minecraft-skinsystem \
|
||||||
|
/go/src/elyby/minecraft-skinsystem/data/capes \
|
||||||
&& ln -s /go/src/elyby/minecraft-skinsystem /go/src/app
|
&& ln -s /go/src/elyby/minecraft-skinsystem /go/src/app
|
||||||
|
|
||||||
WORKDIR /go/src/app
|
WORKDIR /go/src/app
|
||||||
|
|||||||
2
data/capes/.gitignore
vendored
Normal file
2
data/capes/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
*
|
||||||
|
!.gitignore
|
||||||
2
data/statsd/.gitignore
vendored
Normal file
2
data/statsd/.gitignore
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
*
|
||||||
|
!.gitignore
|
||||||
@@ -1,10 +1,20 @@
|
|||||||
version: '2'
|
version: '2'
|
||||||
services:
|
services:
|
||||||
app:
|
|
||||||
ports:
|
|
||||||
- "80:80"
|
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
image: redis:3.0
|
image: redis:3.2-32bit
|
||||||
volumes:
|
volumes:
|
||||||
- ./data/redis:/data
|
- ./data/redis:/data
|
||||||
|
|
||||||
|
rabbitmq:
|
||||||
|
image: rabbitmq:3.6
|
||||||
|
environment:
|
||||||
|
RABBITMQ_DEFAULT_USER: "ely-skinsystem-app"
|
||||||
|
RABBITMQ_DEFAULT_PASS: "ely-skinsystem-app-password"
|
||||||
|
RABBITMQ_DEFAULT_VHOST: "/ely"
|
||||||
|
|
||||||
|
statsd:
|
||||||
|
image: hopsoft/graphite-statsd
|
||||||
|
volumes:
|
||||||
|
- ./data/statsd:/opt/graphite/storage
|
||||||
|
- ./data/graphite-config:/opt/graphite/conf
|
||||||
|
- ./data/statsd-config/config.json:/opt/statsd/config.js
|
||||||
|
|||||||
@@ -1,17 +1,35 @@
|
|||||||
version: '2'
|
version: '2'
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
extends:
|
|
||||||
file: docker-compose.base.yml
|
|
||||||
service: app
|
|
||||||
build: .
|
build: .
|
||||||
|
image: registry.ely.by/elyby/skinsystem:latest
|
||||||
|
ports:
|
||||||
|
- "80:80"
|
||||||
volumes:
|
volumes:
|
||||||
- ./:/go/src/app
|
- ./:/go/src/app
|
||||||
command: ["go", "run", "minecraft-skinsystem.go"]
|
command: ["go", "run", "minecraft-skinsystem.go"]
|
||||||
links:
|
links:
|
||||||
- redis
|
- redis
|
||||||
|
- rabbitmq
|
||||||
|
- statsd
|
||||||
|
environment:
|
||||||
|
ACCOUNTS_API_ID: ""
|
||||||
|
ACCOUNTS_API_SECRET: ""
|
||||||
|
STATSD_ADDR: ""
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
extends:
|
extends:
|
||||||
file: docker-compose.base.yml
|
file: docker-compose.base.yml
|
||||||
service: redis
|
service: redis
|
||||||
|
|
||||||
|
rabbitmq:
|
||||||
|
extends:
|
||||||
|
file: docker-compose.base.yml
|
||||||
|
service: rabbitmq
|
||||||
|
|
||||||
|
statsd:
|
||||||
|
extends:
|
||||||
|
file: docker-compose.base.yml
|
||||||
|
service: statsd
|
||||||
|
ports:
|
||||||
|
- "8123:80"
|
||||||
|
|||||||
@@ -1,16 +1,26 @@
|
|||||||
version: '2'
|
version: '2'
|
||||||
services:
|
services:
|
||||||
app:
|
app:
|
||||||
extends:
|
image: registry.ely.by/elyby/skinsystem:latest
|
||||||
file: docker-compose.base.yml
|
ports:
|
||||||
service: app
|
- "80:80"
|
||||||
image: erickskrauch/ely-by-skinsystem:master
|
|
||||||
links:
|
links:
|
||||||
- redis
|
- redis
|
||||||
|
- rabbitmq
|
||||||
restart: always
|
restart: always
|
||||||
|
environment:
|
||||||
|
ACCOUNTS_API_ID: ""
|
||||||
|
ACCOUNTS_API_SECRET: ""
|
||||||
|
STATSD_ADDR: ""
|
||||||
|
|
||||||
redis:
|
redis:
|
||||||
extends:
|
extends:
|
||||||
file: docker-compose.base.yml
|
file: docker-compose.base.yml
|
||||||
service: redis
|
service: redis
|
||||||
restart: always
|
restart: always
|
||||||
|
|
||||||
|
rabbitmq:
|
||||||
|
extends:
|
||||||
|
file: docker-compose.base.yml
|
||||||
|
service: rabbitmq
|
||||||
|
restart: always
|
||||||
|
|||||||
43
lib/data/CapeItem.go
Normal file
43
lib/data/CapeItem.go
Normal file
@@ -0,0 +1,43 @@
|
|||||||
|
package data
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"os"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
"crypto/md5"
|
||||||
|
"encoding/hex"
|
||||||
|
|
||||||
|
"elyby/minecraft-skinsystem/lib/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
type CapeItem struct {
|
||||||
|
File *os.File
|
||||||
|
}
|
||||||
|
|
||||||
|
func FindCapeByUsername(username string) (CapeItem, error) {
|
||||||
|
var record CapeItem
|
||||||
|
file, err := os.Open(services.RootFolder + "/data/capes/" + strings.ToLower(username) + ".png")
|
||||||
|
if (err != nil) {
|
||||||
|
return record, CapeNotFound{username}
|
||||||
|
}
|
||||||
|
|
||||||
|
record.File = file
|
||||||
|
|
||||||
|
return record, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (cape *CapeItem) CalculateHash() string {
|
||||||
|
hasher := md5.New()
|
||||||
|
io.Copy(hasher, cape.File)
|
||||||
|
|
||||||
|
return hex.EncodeToString(hasher.Sum(nil))
|
||||||
|
}
|
||||||
|
|
||||||
|
type CapeNotFound struct {
|
||||||
|
Who string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e CapeNotFound) Error() string {
|
||||||
|
return fmt.Sprintf("Cape file not found. Required username \"%v\"", e.Who)
|
||||||
|
}
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
package data
|
|
||||||
|
|
||||||
import "fmt"
|
|
||||||
|
|
||||||
type DataNotFound struct {
|
|
||||||
Who string
|
|
||||||
}
|
|
||||||
|
|
||||||
func (e DataNotFound) Error() string {
|
|
||||||
return fmt.Sprintf("Skin data not found. Required username \"%v\"", e.Who)
|
|
||||||
}
|
|
||||||
14
lib/data/SignedTexturesResponse.go
Normal file
14
lib/data/SignedTexturesResponse.go
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
package data
|
||||||
|
|
||||||
|
type SignedTexturesResponse struct {
|
||||||
|
Id string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
IsEly bool `json:"ely,omitempty"`
|
||||||
|
Props []Property `json:"properties"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type Property struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
Signature string `json:"signature,omitempty"`
|
||||||
|
Value string `json:"value"`
|
||||||
|
}
|
||||||
@@ -2,6 +2,7 @@ package data
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"log"
|
||||||
|
"fmt"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
|
||||||
"elyby/minecraft-skinsystem/lib/services"
|
"elyby/minecraft-skinsystem/lib/services"
|
||||||
@@ -12,33 +13,94 @@ import (
|
|||||||
|
|
||||||
type SkinItem struct {
|
type SkinItem struct {
|
||||||
UserId int `json:"userId"`
|
UserId int `json:"userId"`
|
||||||
|
Uuid string `json:"uuid"`
|
||||||
Username string `json:"username"`
|
Username string `json:"username"`
|
||||||
SkinId int `json:"skinId"`
|
SkinId int `json:"skinId"`
|
||||||
Url string `json:"url"`
|
Url string `json:"url"`
|
||||||
Is1_8 bool `json:"is1_8"`
|
Is1_8 bool `json:"is1_8"`
|
||||||
IsSlim bool `json:"isSlim"`
|
IsSlim bool `json:"isSlim"`
|
||||||
Hash string `json:"hash"`
|
Hash string `json:"hash"`
|
||||||
|
MojangTextures string `json:"mojangTextures"`
|
||||||
|
MojangSignature string `json:"mojangSignature"`
|
||||||
|
oldUsername string
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const accountIdToUsernameKey string = "hash:username-to-account-id"
|
||||||
|
|
||||||
func (s *SkinItem) Save() {
|
func (s *SkinItem) Save() {
|
||||||
str, _ := json.Marshal(s)
|
str, _ := json.Marshal(s)
|
||||||
services.RedisPool.Cmd("SET", tools.BuildKey(s.Username), str)
|
pool, _ := services.RedisPool.Get()
|
||||||
|
pool.Cmd("MULTI")
|
||||||
|
|
||||||
|
// Если пользователь сменил ник, то мы должны удать его ключ
|
||||||
|
if (s.oldUsername != "" && s.oldUsername != s.Username) {
|
||||||
|
pool.Cmd("DEL", tools.BuildKey(s.oldUsername))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Если это новая запись или если пользователь сменил ник, то обновляем значение в хэш-таблице
|
||||||
|
if (s.oldUsername != "" || s.oldUsername != s.Username) {
|
||||||
|
pool.Cmd("HSET", accountIdToUsernameKey, s.UserId, s.Username)
|
||||||
|
}
|
||||||
|
|
||||||
|
pool.Cmd("SET", tools.BuildKey(s.Username), str)
|
||||||
|
|
||||||
|
pool.Cmd("EXEC")
|
||||||
|
|
||||||
|
s.oldUsername = s.Username
|
||||||
}
|
}
|
||||||
|
|
||||||
func FindRecord(username string) (SkinItem, error) {
|
func (s *SkinItem) Delete() {
|
||||||
|
if (s.oldUsername == "") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
pool, _ := services.RedisPool.Get()
|
||||||
|
pool.Cmd("MULTI")
|
||||||
|
|
||||||
|
pool.Cmd("DEL", tools.BuildKey(s.oldUsername))
|
||||||
|
pool.Cmd("HDEL", accountIdToUsernameKey, s.UserId)
|
||||||
|
|
||||||
|
pool.Cmd("EXEC")
|
||||||
|
}
|
||||||
|
|
||||||
|
func FindSkinByUsername(username string) (SkinItem, error) {
|
||||||
var record SkinItem;
|
var record SkinItem;
|
||||||
|
services.Logger.IncCounter("storage.query", 1)
|
||||||
response := services.RedisPool.Cmd("GET", tools.BuildKey(username));
|
response := services.RedisPool.Cmd("GET", tools.BuildKey(username));
|
||||||
if (response.IsType(redis.Nil)) {
|
if (response.IsType(redis.Nil)) {
|
||||||
return record, DataNotFound{username}
|
services.Logger.IncCounter("storage.not_found", 1)
|
||||||
|
return record, SkinNotFound{username}
|
||||||
}
|
}
|
||||||
|
|
||||||
result, err := response.Str()
|
result, err := response.Str()
|
||||||
if (err == nil) {
|
if (err == nil) {
|
||||||
|
services.Logger.IncCounter("storage.found", 1)
|
||||||
decodeErr := json.Unmarshal([]byte(result), &record)
|
decodeErr := json.Unmarshal([]byte(result), &record)
|
||||||
if (decodeErr != nil) {
|
if (decodeErr != nil) {
|
||||||
log.Println("Cannot decode record data")
|
log.Println("Cannot decode record data")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
record.oldUsername = record.Username
|
||||||
}
|
}
|
||||||
|
|
||||||
return record, err
|
return record, err
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func FindSkinById(id int) (SkinItem, error) {
|
||||||
|
response := services.RedisPool.Cmd("HGET", accountIdToUsernameKey, id);
|
||||||
|
if (response.IsType(redis.Nil)) {
|
||||||
|
return SkinItem{}, SkinNotFound{"unknown"}
|
||||||
|
}
|
||||||
|
|
||||||
|
username, _ := response.Str()
|
||||||
|
|
||||||
|
return FindSkinByUsername(username)
|
||||||
|
}
|
||||||
|
|
||||||
|
type SkinNotFound struct {
|
||||||
|
Who string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e SkinNotFound) Error() string {
|
||||||
|
return fmt.Sprintf("Skin data not found. Required username \"%v\"", e.Who)
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ package data
|
|||||||
|
|
||||||
type TexturesResponse struct {
|
type TexturesResponse struct {
|
||||||
Skin *Skin `json:"SKIN"`
|
Skin *Skin `json:"SKIN"`
|
||||||
|
Cape *Cape `json:"CAPE,omitempty"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type Skin struct {
|
type Skin struct {
|
||||||
@@ -13,3 +14,8 @@ type Skin struct {
|
|||||||
type SkinMetadata struct {
|
type SkinMetadata struct {
|
||||||
Model string `json:"model"`
|
Model string `json:"model"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Cape struct {
|
||||||
|
Url string `json:"url"`
|
||||||
|
Hash string `json:"hash"`
|
||||||
|
}
|
||||||
|
|||||||
44
lib/external/accounts/AccountInfo.go
vendored
Normal file
44
lib/external/accounts/AccountInfo.go
vendored
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
package accounts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"io/ioutil"
|
||||||
|
"encoding/json"
|
||||||
|
)
|
||||||
|
|
||||||
|
type AccountInfoResponse struct {
|
||||||
|
Id int `json:"id"`
|
||||||
|
Uuid string `json:"uuid"`
|
||||||
|
Username string `json:"username"`
|
||||||
|
Email string `json:"email"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const internalAccountInfoUrl = domain + "/api/internal/accounts/info"
|
||||||
|
|
||||||
|
func (token *Token) AccountInfo(attribute string, value string) (AccountInfoResponse, error) {
|
||||||
|
request, err := http.NewRequest("GET", internalAccountInfoUrl, nil)
|
||||||
|
request.Header.Add("Authorization", "Bearer " + token.AccessToken)
|
||||||
|
query := request.URL.Query()
|
||||||
|
query.Add(attribute, value)
|
||||||
|
request.URL.RawQuery = query.Encode()
|
||||||
|
|
||||||
|
response, err := Client.Do(request)
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer response.Body.Close()
|
||||||
|
|
||||||
|
var info AccountInfoResponse
|
||||||
|
|
||||||
|
responseError := handleResponse(response)
|
||||||
|
if responseError != nil {
|
||||||
|
return info, responseError
|
||||||
|
}
|
||||||
|
|
||||||
|
body, _ := ioutil.ReadAll(response.Body)
|
||||||
|
println("Raw account info response is " + string(body))
|
||||||
|
json.Unmarshal(body, &info)
|
||||||
|
|
||||||
|
return info, nil
|
||||||
|
}
|
||||||
49
lib/external/accounts/GetToken.go
vendored
Normal file
49
lib/external/accounts/GetToken.go
vendored
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
package accounts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"net/url"
|
||||||
|
"io/ioutil"
|
||||||
|
"encoding/json"
|
||||||
|
)
|
||||||
|
|
||||||
|
type TokenRequest struct {
|
||||||
|
Id string
|
||||||
|
Secret string
|
||||||
|
Scopes []string
|
||||||
|
}
|
||||||
|
|
||||||
|
type Token struct {
|
||||||
|
AccessToken string `json:"access_token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
ExpiresIn int `json:"expires_in"`
|
||||||
|
}
|
||||||
|
|
||||||
|
const tokenUrl = domain + "/api/oauth2/v1/token"
|
||||||
|
|
||||||
|
func GetToken(request TokenRequest) (Token, error) {
|
||||||
|
form := url.Values{}
|
||||||
|
form.Add("client_id", request.Id)
|
||||||
|
form.Add("client_secret", request.Secret)
|
||||||
|
form.Add("grant_type", "client_credentials")
|
||||||
|
form.Add("scope", strings.Join(request.Scopes, ","))
|
||||||
|
|
||||||
|
response, err := Client.Post(tokenUrl, "application/x-www-form-urlencoded", strings.NewReader(form.Encode()))
|
||||||
|
if err != nil {
|
||||||
|
panic(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
defer response.Body.Close()
|
||||||
|
|
||||||
|
var result Token
|
||||||
|
responseError := handleResponse(response)
|
||||||
|
if responseError != nil {
|
||||||
|
return result, responseError
|
||||||
|
}
|
||||||
|
|
||||||
|
body, _ := ioutil.ReadAll(response.Body)
|
||||||
|
|
||||||
|
json.Unmarshal(body, &result)
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
51
lib/external/accounts/base.go
vendored
Normal file
51
lib/external/accounts/base.go
vendored
Normal file
@@ -0,0 +1,51 @@
|
|||||||
|
package accounts
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
)
|
||||||
|
|
||||||
|
const domain = "https://account.ely.by"
|
||||||
|
|
||||||
|
var Client = &http.Client{}
|
||||||
|
|
||||||
|
type UnauthorizedResponse struct {}
|
||||||
|
|
||||||
|
func (err UnauthorizedResponse) Error() string {
|
||||||
|
return "Unauthorized response"
|
||||||
|
}
|
||||||
|
|
||||||
|
type ForbiddenResponse struct {}
|
||||||
|
|
||||||
|
func (err ForbiddenResponse) Error() string {
|
||||||
|
return "Forbidden response"
|
||||||
|
}
|
||||||
|
|
||||||
|
type NotFoundResponse struct {}
|
||||||
|
|
||||||
|
func (err NotFoundResponse) Error() string {
|
||||||
|
return "Not found"
|
||||||
|
}
|
||||||
|
|
||||||
|
type NotSuccessResponse struct {
|
||||||
|
StatusCode int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (err NotSuccessResponse) Error() string {
|
||||||
|
return fmt.Sprintf("Response code is \"%d\"", err.StatusCode)
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleResponse(response *http.Response) error {
|
||||||
|
switch status := response.StatusCode; status {
|
||||||
|
case 200:
|
||||||
|
return nil
|
||||||
|
case 401:
|
||||||
|
return &UnauthorizedResponse{}
|
||||||
|
case 403:
|
||||||
|
return &ForbiddenResponse{}
|
||||||
|
case 404:
|
||||||
|
return &NotFoundResponse{}
|
||||||
|
default:
|
||||||
|
return &NotSuccessResponse{status}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,21 +1,33 @@
|
|||||||
package routes
|
package routes
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
"io"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
"elyby/minecraft-skinsystem/lib/tools"
|
"elyby/minecraft-skinsystem/lib/tools"
|
||||||
|
"elyby/minecraft-skinsystem/lib/data"
|
||||||
|
"elyby/minecraft-skinsystem/lib/services"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Cape(w http.ResponseWriter, r *http.Request) {
|
func Cape(response http.ResponseWriter, request *http.Request) {
|
||||||
username := tools.ParseUsername(mux.Vars(r)["username"])
|
if (mux.Vars(request)["converted"] == "") {
|
||||||
log.Println("request cape for username " + username)
|
services.Logger.IncCounter("capes.request", 1)
|
||||||
http.Redirect(w, r, "http://skins.minecraft.net/MinecraftCloaks/" + username + ".png", 301)
|
}
|
||||||
|
|
||||||
|
username := tools.ParseUsername(mux.Vars(request)["username"])
|
||||||
|
rec, err := data.FindCapeByUsername(username)
|
||||||
|
if (err != nil) {
|
||||||
|
http.Redirect(response, request, "http://skins.minecraft.net/MinecraftCloaks/" + username + ".png", 301)
|
||||||
|
}
|
||||||
|
|
||||||
|
request.Header.Set("Content-Type", "image/png")
|
||||||
|
io.Copy(response, rec.File)
|
||||||
}
|
}
|
||||||
|
|
||||||
func CapeGET(w http.ResponseWriter, r *http.Request) {
|
func CapeGET(w http.ResponseWriter, r *http.Request) {
|
||||||
|
services.Logger.IncCounter("capes.get_request", 1)
|
||||||
username := r.URL.Query().Get("name")
|
username := r.URL.Query().Get("name")
|
||||||
if username == "" {
|
if username == "" {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
@@ -23,5 +35,6 @@ func CapeGET(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mux.Vars(r)["username"] = username
|
mux.Vars(r)["username"] = username
|
||||||
|
mux.Vars(r)["converted"] = "1"
|
||||||
Cape(w, r)
|
Cape(w, r)
|
||||||
}
|
}
|
||||||
|
|||||||
29
lib/routes/Face.go
Normal file
29
lib/routes/Face.go
Normal file
@@ -0,0 +1,29 @@
|
|||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
|
||||||
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
|
"elyby/minecraft-skinsystem/lib/tools"
|
||||||
|
"elyby/minecraft-skinsystem/lib/data"
|
||||||
|
)
|
||||||
|
|
||||||
|
const defaultHash = "default"
|
||||||
|
|
||||||
|
func Face(w http.ResponseWriter, r *http.Request) {
|
||||||
|
username := tools.ParseUsername(mux.Vars(r)["username"])
|
||||||
|
rec, err := data.FindSkinByUsername(username)
|
||||||
|
var hash string
|
||||||
|
if (err != nil || rec.SkinId == 0) {
|
||||||
|
hash = defaultHash;
|
||||||
|
} else {
|
||||||
|
hash = rec.Hash
|
||||||
|
}
|
||||||
|
|
||||||
|
http.Redirect(w, r, tools.BuildElyUrl(buildFaceUrl(hash)), 301);
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildFaceUrl(hash string) string {
|
||||||
|
return "/minecraft/skin_buffer/faces/" + hash + ".png"
|
||||||
|
}
|
||||||
@@ -4,6 +4,8 @@ import (
|
|||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
|
"elyby/minecraft-skinsystem/lib/services"
|
||||||
)
|
)
|
||||||
|
|
||||||
// Метод-наследие от первой версии системы скинов.
|
// Метод-наследие от первой версии системы скинов.
|
||||||
@@ -18,11 +20,15 @@ func MinecraftPHP(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mux.Vars(r)["username"] = username
|
mux.Vars(r)["username"] = username
|
||||||
|
mux.Vars(r)["converted"] = "1"
|
||||||
switch required {
|
switch required {
|
||||||
case "skin": Skin(w, r)
|
case "skin":
|
||||||
case "cloack": Cape(w, r)
|
services.Logger.IncCounter("skins.minecraft-php-request", 1)
|
||||||
default: {
|
Skin(w, r)
|
||||||
|
case "cloack":
|
||||||
|
services.Logger.IncCounter("capes.minecraft-php-request", 1)
|
||||||
|
Cape(w, r)
|
||||||
|
default:
|
||||||
w.WriteHeader(http.StatusNotFound)
|
w.WriteHeader(http.StatusNotFound)
|
||||||
}
|
}
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,29 +0,0 @@
|
|||||||
package routes
|
|
||||||
|
|
||||||
import (
|
|
||||||
"net/http"
|
|
||||||
"strconv"
|
|
||||||
|
|
||||||
"elyby/minecraft-skinsystem/lib/data"
|
|
||||||
)
|
|
||||||
|
|
||||||
func SetSkin(w http.ResponseWriter, r *http.Request) {
|
|
||||||
key := r.Header.Get("X-Ely-key")
|
|
||||||
if key != "43fd2ce61b3f5704dfd729c1f2d6ffdb" {
|
|
||||||
w.WriteHeader(http.StatusForbidden)
|
|
||||||
w.Write([]byte("Nice try"))
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
skin := new(data.SkinItem)
|
|
||||||
skin.Username = r.PostFormValue("username")
|
|
||||||
skin.UserId, _ = strconv.Atoi(r.PostFormValue("userId"))
|
|
||||||
skin.SkinId, _ = strconv.Atoi(r.PostFormValue("skinId"))
|
|
||||||
skin.Hash = r.PostFormValue("hash")
|
|
||||||
skin.Is1_8, _ = strconv.ParseBool(r.PostFormValue("is1_8"))
|
|
||||||
skin.IsSlim, _ = strconv.ParseBool(r.PostFormValue("isSlim"))
|
|
||||||
skin.Url = r.PostFormValue("url")
|
|
||||||
skin.Save()
|
|
||||||
|
|
||||||
w.Write([]byte("OK"))
|
|
||||||
}
|
|
||||||
44
lib/routes/SignedTextures.go
Normal file
44
lib/routes/SignedTextures.go
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
package routes
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"net/http"
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
|
"elyby/minecraft-skinsystem/lib/data"
|
||||||
|
"elyby/minecraft-skinsystem/lib/tools"
|
||||||
|
"elyby/minecraft-skinsystem/lib/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
func SignedTextures(w http.ResponseWriter, r *http.Request) {
|
||||||
|
services.Logger.IncCounter("signed_textures.request", 1)
|
||||||
|
username := tools.ParseUsername(mux.Vars(r)["username"])
|
||||||
|
|
||||||
|
rec, err := data.FindSkinByUsername(username)
|
||||||
|
if (err != nil || rec.SkinId == 0 || rec.MojangTextures == "") {
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
responseData:= data.SignedTexturesResponse{
|
||||||
|
Id: strings.Replace(rec.Uuid, "-", "", -1),
|
||||||
|
Name: rec.Username,
|
||||||
|
Props: []data.Property{
|
||||||
|
{
|
||||||
|
Name: "textures",
|
||||||
|
Signature: rec.MojangSignature,
|
||||||
|
Value: rec.MojangTextures,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
Name: "ely",
|
||||||
|
Value: "but why are you asking?",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
response,_ := json.Marshal(responseData)
|
||||||
|
w.Header().Set("Content-Type", "application/json")
|
||||||
|
w.Write(response)
|
||||||
|
}
|
||||||
@@ -1,19 +1,22 @@
|
|||||||
package routes
|
package routes
|
||||||
|
|
||||||
import (
|
import (
|
||||||
"log"
|
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
|
||||||
"elyby/minecraft-skinsystem/lib/tools"
|
"elyby/minecraft-skinsystem/lib/tools"
|
||||||
"elyby/minecraft-skinsystem/lib/data"
|
"elyby/minecraft-skinsystem/lib/data"
|
||||||
|
"elyby/minecraft-skinsystem/lib/services"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Skin(w http.ResponseWriter, r *http.Request) {
|
func Skin(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if (mux.Vars(r)["converted"] == "") {
|
||||||
|
services.Logger.IncCounter("skins.request", 1)
|
||||||
|
}
|
||||||
|
|
||||||
username := tools.ParseUsername(mux.Vars(r)["username"])
|
username := tools.ParseUsername(mux.Vars(r)["username"])
|
||||||
log.Println("request skin for username " + username);
|
rec, err := data.FindSkinByUsername(username)
|
||||||
rec, err := data.FindRecord(username)
|
|
||||||
if (err != nil) {
|
if (err != nil) {
|
||||||
http.Redirect(w, r, "http://skins.minecraft.net/MinecraftSkins/" + username + ".png", 301)
|
http.Redirect(w, r, "http://skins.minecraft.net/MinecraftSkins/" + username + ".png", 301)
|
||||||
return
|
return
|
||||||
@@ -23,6 +26,7 @@ func Skin(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func SkinGET(w http.ResponseWriter, r *http.Request) {
|
func SkinGET(w http.ResponseWriter, r *http.Request) {
|
||||||
|
services.Logger.IncCounter("skins.get_request", 1)
|
||||||
username := r.URL.Query().Get("name")
|
username := r.URL.Query().Get("name")
|
||||||
if username == "" {
|
if username == "" {
|
||||||
w.WriteHeader(http.StatusBadRequest)
|
w.WriteHeader(http.StatusBadRequest)
|
||||||
@@ -30,5 +34,6 @@ func SkinGET(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
mux.Vars(r)["username"] = username
|
mux.Vars(r)["username"] = username
|
||||||
|
mux.Vars(r)["converted"] = "1"
|
||||||
Skin(w, r)
|
Skin(w, r)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -9,13 +9,14 @@ import (
|
|||||||
|
|
||||||
"elyby/minecraft-skinsystem/lib/data"
|
"elyby/minecraft-skinsystem/lib/data"
|
||||||
"elyby/minecraft-skinsystem/lib/tools"
|
"elyby/minecraft-skinsystem/lib/tools"
|
||||||
|
"elyby/minecraft-skinsystem/lib/services"
|
||||||
)
|
)
|
||||||
|
|
||||||
func Textures(w http.ResponseWriter, r *http.Request) {
|
func Textures(w http.ResponseWriter, r *http.Request) {
|
||||||
|
services.Logger.IncCounter("textures.request", 1)
|
||||||
username := tools.ParseUsername(mux.Vars(r)["username"])
|
username := tools.ParseUsername(mux.Vars(r)["username"])
|
||||||
log.Println("request textures for username " + username)
|
|
||||||
|
|
||||||
rec, err := data.FindRecord(username)
|
rec, err := data.FindSkinByUsername(username)
|
||||||
if (err != nil || rec.SkinId == 0) {
|
if (err != nil || rec.SkinId == 0) {
|
||||||
rec.Url = "http://skins.minecraft.net/MinecraftSkins/" + username + ".png"
|
rec.Url = "http://skins.minecraft.net/MinecraftSkins/" + username + ".png"
|
||||||
rec.Hash = string(tools.BuildNonElyTexturesHash(username))
|
rec.Hash = string(tools.BuildNonElyTexturesHash(username))
|
||||||
@@ -36,6 +37,24 @@ func Textures(w http.ResponseWriter, r *http.Request) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
capeRec, err := data.FindCapeByUsername(username)
|
||||||
|
if (err == nil) {
|
||||||
|
capeUrl, err := services.Router.Get("cloaks").URL("username", username)
|
||||||
|
if (err != nil) {
|
||||||
|
log.Println(err.Error())
|
||||||
|
}
|
||||||
|
|
||||||
|
var scheme string = "http://";
|
||||||
|
if (r.TLS != nil) {
|
||||||
|
scheme = "https://"
|
||||||
|
}
|
||||||
|
|
||||||
|
textures.Cape = &data.Cape{
|
||||||
|
Url: scheme + r.Host + capeUrl.String(),
|
||||||
|
Hash: capeRec.CalculateHash(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
response,_ := json.Marshal(textures)
|
response,_ := json.Marshal(textures)
|
||||||
w.Header().Set("Content-Type", "application/json")
|
w.Header().Set("Content-Type", "application/json")
|
||||||
w.Write(response)
|
w.Write(response)
|
||||||
|
|||||||
@@ -2,9 +2,17 @@ package services
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"github.com/mediocregopher/radix.v2/pool"
|
"github.com/mediocregopher/radix.v2/pool"
|
||||||
|
"github.com/streadway/amqp"
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
"github.com/mono83/slf/wd"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
var Router *mux.Router
|
||||||
|
|
||||||
var RedisPool *pool.Pool
|
var RedisPool *pool.Pool
|
||||||
|
|
||||||
var Router *mux.Router
|
var RabbitMQChannel *amqp.Channel
|
||||||
|
|
||||||
|
var RootFolder string
|
||||||
|
|
||||||
|
var Logger wd.Watchdog
|
||||||
|
|||||||
@@ -30,7 +30,12 @@ func BuildKey(username string) string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func BuildElyUrl(route string) string {
|
func BuildElyUrl(route string) string {
|
||||||
return "http://ely.by" + route
|
prefix := "http://ely.by"
|
||||||
|
if !strings.HasPrefix(route, prefix) {
|
||||||
|
route = prefix + route
|
||||||
|
}
|
||||||
|
|
||||||
|
return route
|
||||||
}
|
}
|
||||||
|
|
||||||
func getCurrentHour() int64 {
|
func getCurrentHour() int64 {
|
||||||
|
|||||||
@@ -20,3 +20,13 @@ func TestBuildKey(t *testing.T) {
|
|||||||
t.Error("Function shound convert string to lower case and concatenate it with usernmae:")
|
t.Error("Function shound convert string to lower case and concatenate it with usernmae:")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestBuildElyUrl(t *testing.T) {
|
||||||
|
if BuildElyUrl("/route") != "http://ely.by/route" {
|
||||||
|
t.Error("Function should add prefix to the provided relative url.")
|
||||||
|
}
|
||||||
|
|
||||||
|
if BuildElyUrl("http://ely.by/test/route") != "http://ely.by/test/route" {
|
||||||
|
t.Error("Function should do not add prefix to the provided prefixed url.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
82
lib/worker/handlers.go
Normal file
82
lib/worker/handlers.go
Normal file
@@ -0,0 +1,82 @@
|
|||||||
|
package worker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"elyby/minecraft-skinsystem/lib/data"
|
||||||
|
"elyby/minecraft-skinsystem/lib/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
func handleChangeUsername(model usernameChanged) (bool) {
|
||||||
|
if (model.OldUsername == "") {
|
||||||
|
services.Logger.IncCounter("worker.change_username.empty_old_username", 1)
|
||||||
|
record := data.SkinItem{
|
||||||
|
UserId: model.AccountId,
|
||||||
|
Username: model.NewUsername,
|
||||||
|
}
|
||||||
|
|
||||||
|
record.Save()
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
record, err := data.FindSkinById(model.AccountId)
|
||||||
|
if (err != nil) {
|
||||||
|
services.Logger.IncCounter("worker.change_username.id_not_found", 1)
|
||||||
|
fmt.Println("Cannot find user id. Trying to search.")
|
||||||
|
response, err := getById(model.AccountId)
|
||||||
|
if err != nil {
|
||||||
|
services.Logger.IncCounter("worker.change_username.id_not_restored", 1)
|
||||||
|
fmt.Printf("Cannot restore user info. %T\n", err)
|
||||||
|
// TODO: логгировать в какой-нибудь Sentry, если там не 404
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
services.Logger.IncCounter("worker.change_username.id_restored", 1)
|
||||||
|
fmt.Println("User info successfully restored.")
|
||||||
|
record = data.SkinItem{
|
||||||
|
UserId: response.Id,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
record.Username = model.NewUsername
|
||||||
|
record.Save()
|
||||||
|
|
||||||
|
services.Logger.IncCounter("worker.change_username.processed", 1)
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func handleSkinChanged(model skinChanged) bool {
|
||||||
|
record, err := data.FindSkinById(model.AccountId)
|
||||||
|
if err != nil {
|
||||||
|
services.Logger.IncCounter("worker.skin_changed.id_not_found", 1)
|
||||||
|
fmt.Println("Cannot find user id. Trying to search.")
|
||||||
|
response, err := getById(model.AccountId)
|
||||||
|
if err != nil {
|
||||||
|
services.Logger.IncCounter("worker.skin_changed.id_not_restored", 1)
|
||||||
|
fmt.Printf("Cannot restore user info. %T\n", err)
|
||||||
|
// TODO: логгировать в какой-нибудь Sentry, если там не 404
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
services.Logger.IncCounter("worker.skin_changed.id_restored", 1)
|
||||||
|
fmt.Println("User info successfully restored.")
|
||||||
|
record.UserId = response.Id
|
||||||
|
record.Username = response.Username
|
||||||
|
}
|
||||||
|
|
||||||
|
record.Uuid = model.Uuid
|
||||||
|
record.SkinId = model.SkinId
|
||||||
|
record.Hash = model.Hash
|
||||||
|
record.Is1_8 = model.Is1_8
|
||||||
|
record.IsSlim = model.IsSlim
|
||||||
|
record.Url = model.Url
|
||||||
|
record.MojangTextures = model.MojangTextures
|
||||||
|
record.MojangSignature = model.MojangSignature
|
||||||
|
|
||||||
|
record.Save()
|
||||||
|
|
||||||
|
services.Logger.IncCounter("worker.skin_changed.processed", 1)
|
||||||
|
|
||||||
|
return true
|
||||||
|
}
|
||||||
20
lib/worker/models.go
Normal file
20
lib/worker/models.go
Normal file
@@ -0,0 +1,20 @@
|
|||||||
|
package worker
|
||||||
|
|
||||||
|
type usernameChanged struct {
|
||||||
|
AccountId int `json:"accountId"`
|
||||||
|
OldUsername string `json:"oldUsername"`
|
||||||
|
NewUsername string `json:"newUsername"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type skinChanged struct {
|
||||||
|
AccountId int `json:"userId"`
|
||||||
|
Uuid string `json:"uuid"`
|
||||||
|
SkinId int `json:"skinId"`
|
||||||
|
OldSkinId int `json:"oldSkinId"`
|
||||||
|
Hash string `json:"hash"`
|
||||||
|
Is1_8 bool `json:"is1_8"`
|
||||||
|
IsSlim bool `json:"isSlim"`
|
||||||
|
Url string `json:"url"`
|
||||||
|
MojangTextures string `json:"mojangTextures"`
|
||||||
|
MojangSignature string `json:"mojangSignature"`
|
||||||
|
}
|
||||||
60
lib/worker/supports.go
Normal file
60
lib/worker/supports.go
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
package worker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strconv"
|
||||||
|
"elyby/minecraft-skinsystem/lib/external/accounts"
|
||||||
|
)
|
||||||
|
|
||||||
|
var AccountsTokenConfig *accounts.TokenRequest
|
||||||
|
|
||||||
|
var token *accounts.Token
|
||||||
|
|
||||||
|
const repeatsLimit = 3
|
||||||
|
var repeatsCount = 0
|
||||||
|
|
||||||
|
func getById(id int) (accounts.AccountInfoResponse, error) {
|
||||||
|
return _getByField("id", strconv.Itoa(id))
|
||||||
|
}
|
||||||
|
|
||||||
|
func _getByField(field string, value string) (accounts.AccountInfoResponse, error) {
|
||||||
|
defer resetRepeatsCount()
|
||||||
|
|
||||||
|
apiToken, err := getToken()
|
||||||
|
if err != nil {
|
||||||
|
return accounts.AccountInfoResponse{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := apiToken.AccountInfo(field, value)
|
||||||
|
if err != nil {
|
||||||
|
_, ok := err.(*accounts.UnauthorizedResponse)
|
||||||
|
if !ok || repeatsCount >= repeatsLimit {
|
||||||
|
return accounts.AccountInfoResponse{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
repeatsCount++
|
||||||
|
token = nil
|
||||||
|
|
||||||
|
return _getByField(field, value)
|
||||||
|
}
|
||||||
|
|
||||||
|
return result, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func getToken() (*accounts.Token, error) {
|
||||||
|
if token == nil {
|
||||||
|
println("token is nil, trying to obtain new one")
|
||||||
|
tempToken, err := accounts.GetToken(*AccountsTokenConfig)
|
||||||
|
if err != nil {
|
||||||
|
println("cannot obtain new one token", err)
|
||||||
|
return &accounts.Token{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
token = &tempToken
|
||||||
|
}
|
||||||
|
|
||||||
|
return token, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func resetRepeatsCount() {
|
||||||
|
repeatsCount = 0
|
||||||
|
}
|
||||||
88
lib/worker/worker.go
Normal file
88
lib/worker/worker.go
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
package worker
|
||||||
|
|
||||||
|
import (
|
||||||
|
"log"
|
||||||
|
|
||||||
|
"encoding/json"
|
||||||
|
|
||||||
|
"elyby/minecraft-skinsystem/lib/services"
|
||||||
|
)
|
||||||
|
|
||||||
|
const exchangeName string = "events"
|
||||||
|
const queueName string = "skinsystem-accounts-events"
|
||||||
|
|
||||||
|
func Listen() {
|
||||||
|
var err error
|
||||||
|
ch := services.RabbitMQChannel
|
||||||
|
|
||||||
|
err = ch.ExchangeDeclare(
|
||||||
|
exchangeName, // name
|
||||||
|
"topic", // type
|
||||||
|
true, // durable
|
||||||
|
false, // auto-deleted
|
||||||
|
false, // internal
|
||||||
|
false, // no-wait
|
||||||
|
nil, // arguments
|
||||||
|
)
|
||||||
|
failOnError(err, "Failed to declare an exchange")
|
||||||
|
|
||||||
|
_, err = ch.QueueDeclare(
|
||||||
|
queueName, // name
|
||||||
|
true, // durable
|
||||||
|
false, // delete when usused
|
||||||
|
false, // exclusive
|
||||||
|
false, // no-wait
|
||||||
|
nil, // arguments
|
||||||
|
)
|
||||||
|
failOnError(err, "Failed to declare a queue")
|
||||||
|
|
||||||
|
err = ch.QueueBind(queueName, "accounts.username-changed", exchangeName, false, nil)
|
||||||
|
failOnError(err, "Failed to bind a queue")
|
||||||
|
|
||||||
|
err = ch.QueueBind(queueName, "accounts.skin-changed", exchangeName, false, nil)
|
||||||
|
failOnError(err, "Failed to bind a queue")
|
||||||
|
|
||||||
|
msgs, err := ch.Consume(
|
||||||
|
queueName, // queue
|
||||||
|
"", // consumer
|
||||||
|
false, // auto-ack
|
||||||
|
false, // exclusive
|
||||||
|
false, // no-local
|
||||||
|
false, // no-wait
|
||||||
|
nil, // args
|
||||||
|
)
|
||||||
|
failOnError(err, "Failed to register a consumer")
|
||||||
|
|
||||||
|
forever := make(chan bool)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
for d := range msgs {
|
||||||
|
log.Println("Incoming message with routing key " + d.RoutingKey)
|
||||||
|
var result bool = true;
|
||||||
|
switch d.RoutingKey {
|
||||||
|
case "accounts.username-changed":
|
||||||
|
var model usernameChanged
|
||||||
|
json.Unmarshal(d.Body, &model)
|
||||||
|
result = handleChangeUsername(model)
|
||||||
|
case "accounts.skin-changed":
|
||||||
|
var model skinChanged
|
||||||
|
json.Unmarshal(d.Body, &model)
|
||||||
|
result = handleSkinChanged(model)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
d.Ack(false)
|
||||||
|
} else {
|
||||||
|
d.Reject(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
<-forever
|
||||||
|
}
|
||||||
|
|
||||||
|
func failOnError(err error, msg string) {
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("%s: %s", msg, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,37 +1,108 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"os"
|
||||||
"log"
|
"log"
|
||||||
"runtime"
|
"runtime"
|
||||||
//"time"
|
"time"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"path/filepath"
|
||||||
|
|
||||||
"github.com/gorilla/mux"
|
"github.com/gorilla/mux"
|
||||||
|
"github.com/streadway/amqp"
|
||||||
"github.com/mediocregopher/radix.v2/pool"
|
"github.com/mediocregopher/radix.v2/pool"
|
||||||
|
"github.com/mono83/slf/wd"
|
||||||
|
"github.com/mono83/slf/rays"
|
||||||
|
"github.com/mono83/slf/recievers/ansi"
|
||||||
|
"github.com/mono83/slf/recievers/statsd"
|
||||||
|
|
||||||
"elyby/minecraft-skinsystem/lib/routes"
|
"elyby/minecraft-skinsystem/lib/routes"
|
||||||
"elyby/minecraft-skinsystem/lib/services"
|
"elyby/minecraft-skinsystem/lib/services"
|
||||||
//"github.com/mediocregopher/radix.v2/redis"
|
"elyby/minecraft-skinsystem/lib/worker"
|
||||||
|
"elyby/minecraft-skinsystem/lib/external/accounts"
|
||||||
)
|
)
|
||||||
|
|
||||||
const redisString string = "redis:6379"
|
const redisPoolSize int = 10
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
log.Println("Starting...")
|
log.Println("Starting...")
|
||||||
|
|
||||||
runtime.GOMAXPROCS(runtime.NumCPU())
|
runtime.GOMAXPROCS(runtime.NumCPU())
|
||||||
|
|
||||||
|
accountsApiId := os.Getenv("ACCOUNTS_API_ID")
|
||||||
|
accountsApiSecret := os.Getenv("ACCOUNTS_API_SECRET")
|
||||||
|
if accountsApiId == "" || accountsApiSecret == "" {
|
||||||
|
log.Fatal("ACCOUNTS_API params must be provided")
|
||||||
|
}
|
||||||
|
|
||||||
|
worker.AccountsTokenConfig = &accounts.TokenRequest{
|
||||||
|
Id: accountsApiId,
|
||||||
|
Secret: accountsApiSecret,
|
||||||
|
Scopes: []string{
|
||||||
|
"internal_account_info",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
log.Println("Connecting to redis")
|
log.Println("Connecting to redis")
|
||||||
redisPool, redisErr := pool.New("tcp", redisString, 10)
|
|
||||||
if redisErr != nil {
|
var redisString = os.Getenv("REDIS_ADDR")
|
||||||
|
if (redisString == "") {
|
||||||
|
redisString = "redis:6379"
|
||||||
|
}
|
||||||
|
|
||||||
|
redisPool, redisErr := pool.New("tcp", redisString, redisPoolSize)
|
||||||
|
if (redisErr != nil) {
|
||||||
log.Fatal("Redis unavailable")
|
log.Fatal("Redis unavailable")
|
||||||
}
|
}
|
||||||
log.Println("Connected to redis")
|
log.Println("Connected to redis")
|
||||||
|
|
||||||
|
log.Println("Connecting to rabbitmq")
|
||||||
|
// TODO: rabbitmq становится доступен не сразу. Нужно дождаться, пока он станет доступен, периодически повторяя запросы
|
||||||
|
|
||||||
|
var rabbitmqString = os.Getenv("RABBITMQ_ADDR")
|
||||||
|
if (rabbitmqString == "") {
|
||||||
|
rabbitmqString = "amqp://ely-skinsystem-app:ely-skinsystem-app-password@rabbitmq:5672/%2fely"
|
||||||
|
}
|
||||||
|
|
||||||
|
rabbitConnection, rabbitmqErr := amqp.Dial(rabbitmqString)
|
||||||
|
if (rabbitmqErr != nil) {
|
||||||
|
log.Fatalf("%s", rabbitmqErr)
|
||||||
|
}
|
||||||
|
log.Println("Connected to rabbitmq. Trying to open a channel")
|
||||||
|
rabbitChannel, rabbitmqErr := rabbitConnection.Channel()
|
||||||
|
if (rabbitmqErr != nil) {
|
||||||
|
log.Fatalf("%s", rabbitmqErr)
|
||||||
|
}
|
||||||
|
log.Println("Connected to rabbitmq channel")
|
||||||
|
|
||||||
|
// statsd
|
||||||
|
var statsdString = os.Getenv("STATSD_ADDR")
|
||||||
|
if (statsdString != "") {
|
||||||
|
log.Println("Connecting to statsd")
|
||||||
|
hostname, _ := os.Hostname()
|
||||||
|
statsdReceiver, err := statsd.NewReceiver(statsd.Config{
|
||||||
|
Address: statsdString,
|
||||||
|
Prefix: "ely.skinsystem." + hostname + ".app.",
|
||||||
|
FlushEvery: 1,
|
||||||
|
})
|
||||||
|
if (err != nil) {
|
||||||
|
log.Fatal("statsd connection error")
|
||||||
|
}
|
||||||
|
|
||||||
|
wd.AddReceiver(statsdReceiver)
|
||||||
|
} else {
|
||||||
|
wd.AddReceiver(ansi.New(true, true, false))
|
||||||
|
}
|
||||||
|
|
||||||
|
logger := wd.New("", "").WithParams(rays.Host)
|
||||||
|
|
||||||
router := mux.NewRouter().StrictSlash(true)
|
router := mux.NewRouter().StrictSlash(true)
|
||||||
router.HandleFunc("/skins/{username}", routes.Skin).Methods("GET").Name("skins")
|
router.HandleFunc("/skins/{username}", routes.Skin).Methods("GET").Name("skins")
|
||||||
router.HandleFunc("/cloaks/{username}", routes.Cape).Methods("GET").Name("cloaks")
|
router.HandleFunc("/cloaks/{username}", routes.Cape).Methods("GET").Name("cloaks")
|
||||||
router.HandleFunc("/textures/{username}", routes.Textures).Methods("GET").Name("textures")
|
router.HandleFunc("/textures/{username}", routes.Textures).Methods("GET").Name("textures")
|
||||||
|
router.HandleFunc("/textures/signed/{username}", routes.SignedTextures).Methods("GET").Name("signedTextures")
|
||||||
|
router.HandleFunc("/skins/{username}/face", routes.Face).Methods("GET").Name("faces")
|
||||||
|
router.HandleFunc("/skins/{username}/face.png", routes.Face).Methods("GET").Name("faces")
|
||||||
// Legacy
|
// Legacy
|
||||||
router.HandleFunc("/minecraft.php", routes.MinecraftPHP).Methods("GET")
|
router.HandleFunc("/minecraft.php", routes.MinecraftPHP).Methods("GET")
|
||||||
router.HandleFunc("/skins/", routes.SkinGET).Methods("GET")
|
router.HandleFunc("/skins/", routes.SkinGET).Methods("GET")
|
||||||
@@ -39,29 +110,37 @@ func main() {
|
|||||||
// 404
|
// 404
|
||||||
router.NotFoundHandler = http.HandlerFunc(routes.NotFound)
|
router.NotFoundHandler = http.HandlerFunc(routes.NotFound)
|
||||||
|
|
||||||
apiRouter := router.PathPrefix("/api").Subrouter()
|
|
||||||
apiRouter.HandleFunc("/user/{username}/skin", routes.SetSkin).Methods("POST")
|
|
||||||
|
|
||||||
services.RedisPool = redisPool
|
|
||||||
services.Router = router
|
services.Router = router
|
||||||
|
services.RedisPool = redisPool
|
||||||
|
services.RabbitMQChannel = rabbitChannel
|
||||||
|
services.Logger = logger
|
||||||
|
|
||||||
/*go func() {
|
_, file, _, _ := runtime.Caller(0)
|
||||||
|
services.RootFolder = filepath.Dir(file)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
period := 5
|
||||||
for {
|
for {
|
||||||
time.Sleep(5 * time.Second)
|
time.Sleep(time.Duration(period) * time.Second)
|
||||||
|
|
||||||
|
resp := services.RedisPool.Cmd("PING")
|
||||||
|
if (resp.Err == nil) {
|
||||||
|
// Если редис успешно пинганулся, значит всё хорошо
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
resp := services.Redis.Cmd("PING")
|
|
||||||
if (resp.Err != nil) {
|
|
||||||
log.Println("Redis not pinged. Try to reconnect")
|
log.Println("Redis not pinged. Try to reconnect")
|
||||||
newClient, redisErr := redis.Dial("tcp", redisString)
|
newPool, redisErr := pool.New("tcp", redisString, redisPoolSize)
|
||||||
if (redisErr != nil) {
|
if (redisErr != nil) {
|
||||||
log.Println("Cannot reconnect to redis")
|
log.Printf("Cannot reconnect to redis, waiting %d seconds\n", period)
|
||||||
} else {
|
} else {
|
||||||
services.Redis = newClient
|
services.RedisPool = newPool
|
||||||
log.Println("Reconnected")
|
log.Println("Reconnected")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}()
|
||||||
}()*/
|
|
||||||
|
go worker.Listen()
|
||||||
|
|
||||||
log.Println("Started");
|
log.Println("Started");
|
||||||
log.Fatal(http.ListenAndServe(":80", router))
|
log.Fatal(http.ListenAndServe(":80", router))
|
||||||
|
|||||||
Reference in New Issue
Block a user