Add initial code

This commit is contained in:
Jacob Gunther
2022-03-08 21:28:46 -06:00
commit b0518288da
33 changed files with 2175 additions and 0 deletions

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
bin/
config.yml

2
README.md Normal file
View File

@@ -0,0 +1,2 @@
# API Server
The REST server that powers the API for mineatar.io.

5
config.example.yml Normal file
View File

@@ -0,0 +1,5 @@
host: 0.0.0.0
port: 3001
redis:
uri: 127.0.0.1:6379
database: 0

19
go.mod Normal file
View File

@@ -0,0 +1,19 @@
module main
go 1.17
require (
github.com/buaazp/fasthttprouter v0.1.1
github.com/go-redis/redis/v8 v8.11.4
github.com/valyala/fasthttp v1.34.0
golang.org/x/image v0.0.0-20220302094943-723b81ca9867
gopkg.in/yaml.v2 v2.4.0
)
require (
github.com/andybalholm/brotli v1.0.4 // indirect
github.com/cespare/xxhash/v2 v2.1.2 // indirect
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect
github.com/klauspost/compress v1.15.0 // indirect
github.com/valyala/bytebufferpool v1.0.0 // indirect
)

119
go.sum Normal file
View File

@@ -0,0 +1,119 @@
github.com/andybalholm/brotli v1.0.4 h1:V7DdXeJtZscaqfNuAdSRuRFzuiKlHSC/Zh3zl9qY3JY=
github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig=
github.com/buaazp/fasthttprouter v0.1.1 h1:4oAnN0C3xZjylvZJdP35cxfclyn4TYkW6Y+DSvS+h8Q=
github.com/buaazp/fasthttprouter v0.1.1/go.mod h1:h/Ap5oRVLeItGKTVBb+heQPks+HdIUtGmI4H5WCYijM=
github.com/cespare/xxhash/v2 v2.1.2 h1:YRXhKfTDauu4ajMg1TPgFO5jnlC2HCbmLXMcTG5cbYE=
github.com/cespare/xxhash/v2 v2.1.2/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78=
github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc=
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
github.com/fsnotify/fsnotify v1.4.9 h1:hsms1Qyu0jgnwNXIxa+/V/PDsU6CfLf6CNO8H7IWoS4=
github.com/fsnotify/fsnotify v1.4.9/go.mod h1:znqG4EE+3YCdAaPaxE2ZRY/06pZUdp0tY4IgpuI1SZQ=
github.com/go-redis/redis/v8 v8.11.4 h1:kHoYkfZP6+pe04aFTnhDH6GDROa5yJdHJVNxV3F46Tg=
github.com/go-redis/redis/v8 v8.11.4/go.mod h1:2Z2wHZXdQpCDXEGzqMockDpNyYvi2l4Pxt6RJr792+w=
github.com/go-task/slim-sprig v0.0.0-20210107165309-348f09dbbbc0/go.mod h1:fyg7847qk6SyHyPtNmDHnmrv/HOrqktSC+C9fM+CJOE=
github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U=
github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8=
github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA=
github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs=
github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w=
github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0=
github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI=
github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk=
github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY=
github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU=
github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU=
github.com/klauspost/compress v1.15.0 h1:xqfchp4whNFxn5A4XFyyYtitiWI8Hy5EW59jEwcyL6U=
github.com/klauspost/compress v1.15.0/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
github.com/nxadm/tail v1.4.4/go.mod h1:kenIhsEOeOJmVchQTgglprH7qJGnHDVpk1VPCcaMI8A=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE=
github.com/onsi/ginkgo v1.12.1/go.mod h1:zj2OWP4+oCPe1qIXoGWkgMRwljMUYCdkwsT2108oapk=
github.com/onsi/ginkgo v1.16.4 h1:29JGrr5oVBm5ulCWet69zQkzWipVXIol6ygQUe/EzNc=
github.com/onsi/ginkgo v1.16.4/go.mod h1:dX+/inL/fNMqNlz0e9LfyB9TswhZpCVdJM/Z6Vvnwo0=
github.com/onsi/gomega v1.7.1/go.mod h1:XdKZgCCFLUoM/7CFJVPcG8C1xQ1AJ0vpAezJrB7JYyY=
github.com/onsi/gomega v1.10.1/go.mod h1:iN09h71vgCQne3DLsj+A5owkum+a2tYe+TOCB1ybHNo=
github.com/onsi/gomega v1.16.0 h1:6gjqkI8iiRHMvdccRJM8rVKjCWk6ZIm6FTm3ddIe4/c=
github.com/onsi/gomega v1.16.0/go.mod h1:HnhC7FXeEQY45zxNK3PPoIUhzk/80Xly9PcubAlGdZY=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA=
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
github.com/valyala/fasthttp v1.34.0 h1:d3AAQJ2DRcxJYHm7OXNXtXt2as1vMDfxeIcFvhmGGm4=
github.com/valyala/fasthttp v1.34.0/go.mod h1:epZA5N+7pY6ZaEKRmstzOuYJx9HI8DI1oaCGZpdH4h0=
github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/image v0.0.0-20220302094943-723b81ca9867 h1:TcHcE0vrmgzNH1v3ppjcMGbhG5+9fMuvOmUYwNEF4q4=
golang.org/x/image v0.0.0-20220302094943-723b81ca9867/go.mod h1:023OzeP/+EPmXeapQh35lcL3II3LrY8Ic+EFFKVhULM=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
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-20200520004742-59133d7f0dd7/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.0.0-20210428140749-89ef3d95e781/go.mod h1:OJAsFXCWl8Ukc7SiCT/9KSuxbyM7479/AVlXFRxuMCk=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f h1:oA4XRj0qtSt8Yo1Zms0CUlsT3KG69V2UGQWPBxujDmc=
golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/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-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/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-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190904154756-749cb33beabd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191005200804-aed5e4c7ecf9/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20191120155948-bd437916bb0e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210112080510-489259a85091/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/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-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 h1:nhht2DYV/Sn3qOayu8lM+cU1ii9sTLUeBQwQQfUHtrs=
golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/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.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7 h1:olpwvP2KacW1ZWvsR7uQhoyTYvKAupfQrRGBFM352Gk=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20201224043029-2b0845dc783e/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE=
google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo=
google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw=
google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.2.4/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=

2
scripts/build Executable file
View File

@@ -0,0 +1,2 @@
#!/bin/bash
go build -o bin/main src/*.go

26
src/config.go Normal file
View File

@@ -0,0 +1,26 @@
package main
import (
"io/ioutil"
"gopkg.in/yaml.v2"
)
type Configuration struct {
Host string `yaml:"host"`
Port uint16 `yaml:"port"`
Redis struct {
URI string `yaml:"uri"`
Database int `yaml:"database"`
} `yaml:"redis"`
}
func (c *Configuration) ReadFile(file string) error {
data, err := ioutil.ReadFile(file)
if err != nil {
return err
}
return yaml.Unmarshal(data, c)
}

56
src/main.go Normal file
View File

@@ -0,0 +1,56 @@
package main
import (
"fmt"
"log"
"main/src/redis"
"main/src/routes"
"time"
"github.com/buaazp/fasthttprouter"
"github.com/valyala/fasthttp"
)
var (
config *Configuration = &Configuration{}
r *redis.Redis = &redis.Redis{}
)
func init() {
var err error
if err = config.ReadFile("config.yml"); err != nil {
log.Fatal(err)
}
start := time.Now()
if err = r.Connect(config.Redis.URI, config.Redis.Database); err != nil {
log.Fatal(err)
}
log.Printf("Successfully connected to Redis (%s)\n", time.Since(start))
routes.InitRoutes(r)
}
func main() {
defer r.Close()
router := fasthttprouter.New()
router.GET("/ping", routes.PingHandler)
router.GET("/uuid/:user", routes.UUIDHandler)
router.GET("/skin/:user", routes.SkinHandler)
router.GET("/face/:user", routes.FaceHandler)
router.GET("/head/:user", routes.HeadHandler)
router.GET("/body/full/:user", routes.FullBodyHandler)
router.GET("/body/front/:user", routes.FrontBodyHandler)
router.GET("/body/back/:user", routes.BackBodyHandler)
router.GET("/body/left/:user", routes.LeftBodyHandler)
router.GET("/body/right/:user", routes.RightBodyHandler)
log.Printf("Listening on %s:%d\n", config.Host, config.Port)
log.Fatal(fasthttp.ListenAndServe(fmt.Sprintf("%s:%d", config.Host, config.Port), router.Handler))
}

103
src/redis/redis.go Normal file
View File

@@ -0,0 +1,103 @@
package redis
import (
"context"
"time"
"github.com/go-redis/redis/v8"
)
type Redis struct {
conn *redis.Client
}
func (r *Redis) Connect(uri string, database int) error {
c := redis.NewClient(&redis.Options{
Addr: uri,
DB: database,
})
r.conn = c
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
return c.Ping(ctx).Err()
}
func (r *Redis) GetString(key string) (string, bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
existsResult := r.conn.Exists(ctx, key)
if err := existsResult.Err(); err != nil {
return "", false, err
}
if existsResult.Val() == 0 {
return "", false, nil
}
result := r.conn.Get(ctx, key)
return result.Val(), true, result.Err()
}
func (r *Redis) GetBytes(key string) ([]byte, bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
existsResult := r.conn.Exists(ctx, key)
if err := existsResult.Err(); err != nil {
return nil, false, err
}
if existsResult.Val() == 0 {
return nil, false, nil
}
result := r.conn.Get(ctx, key)
if err := result.Err(); err != nil {
return nil, true, err
}
data, err := result.Bytes()
return data, true, err
}
func (r *Redis) Exists(key string) (bool, error) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
result := r.conn.Exists(ctx, key)
return result.Val() == 1, result.Err()
}
func (r *Redis) Delete(key string) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
return r.conn.Del(ctx, key).Err()
}
func (r *Redis) Set(key string, value interface{}, ttl time.Duration) error {
ctx, cancel := context.WithTimeout(context.Background(), time.Second*5)
defer cancel()
return r.conn.Set(ctx, key, value, ttl).Err()
}
func (r *Redis) Close() error {
return r.conn.Close()
}

538
src/routes/body.go Normal file
View File

@@ -0,0 +1,538 @@
package routes
import (
"fmt"
"log"
"main/src/util"
"main/src/util/renders"
"math"
"net/http"
"time"
"github.com/valyala/fasthttp"
)
func FullBodyHandler(ctx *fasthttp.RequestCtx) {
user := ctx.UserValue("user").(string)
download := ctx.QueryArgs().GetBool("download")
scale, err := ctx.QueryArgs().GetUint("scale")
if err != nil {
scale = 4
}
scale = int(math.Max(math.Min(float64(scale), MaxScaleFullBody), MinScale))
overlay := true
if ctx.QueryArgs().Has("overlay") {
overlay = ctx.QueryArgs().GetBool("overlay")
}
uuid, err := util.GetUUID(r, user)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
cacheKey := fmt.Sprintf("result:fullbody-%d-%t-%s", scale, overlay, uuid)
cache, ok, err := r.GetBytes(cacheKey)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if ok {
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "TRUE")
ctx.SetContentType("image/png")
ctx.SetBody(cache)
return
}
skin, slim, err := util.GetPlayerSkin(r, uuid)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if skin == nil {
skin = util.GetDefaultSkin(slim)
}
render := renders.RenderBody(skin, renders.RenderOptions{
Overlay: overlay,
Slim: slim,
Scale: scale,
})
data, err := util.EncodePNG(render)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if err = r.Set(cacheKey, data, time.Hour*24); err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "FALSE")
ctx.SetContentType("image/png")
ctx.SetBody(data)
}
func FrontBodyHandler(ctx *fasthttp.RequestCtx) {
user := ctx.UserValue("user").(string)
download := ctx.QueryArgs().GetBool("download")
scale, err := ctx.QueryArgs().GetUint("scale")
if err != nil {
scale = 4
}
scale = int(math.Max(math.Min(float64(scale), MaxScale), MinScale))
overlay := true
if ctx.QueryArgs().Has("overlay") {
overlay = ctx.QueryArgs().GetBool("overlay")
}
uuid, err := util.GetUUID(r, user)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
cacheKey := fmt.Sprintf("result:frontbody-%d-%t-%s", scale, overlay, uuid)
cache, ok, err := r.GetBytes(cacheKey)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if ok {
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "TRUE")
ctx.SetContentType("image/png")
ctx.SetBody(cache)
return
}
skin, slim, err := util.GetPlayerSkin(r, uuid)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if skin == nil {
skin = util.GetDefaultSkin(slim)
}
render := renders.RenderFrontBody(skin, renders.RenderOptions{
Overlay: overlay,
Slim: slim,
Scale: scale,
})
data, err := util.EncodePNG(render)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if err = r.Set(cacheKey, data, time.Hour*24); err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "FALSE")
ctx.SetContentType("image/png")
ctx.SetBody(data)
}
func BackBodyHandler(ctx *fasthttp.RequestCtx) {
user := ctx.UserValue("user").(string)
download := ctx.QueryArgs().GetBool("download")
scale, err := ctx.QueryArgs().GetUint("scale")
if err != nil {
scale = 4
}
scale = int(math.Max(math.Min(float64(scale), MaxScale), MinScale))
overlay := true
if ctx.QueryArgs().Has("overlay") {
overlay = ctx.QueryArgs().GetBool("overlay")
}
uuid, err := util.GetUUID(r, user)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
cacheKey := fmt.Sprintf("result:backbody-%d-%t-%s", scale, overlay, uuid)
cache, ok, err := r.GetBytes(cacheKey)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if ok {
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "TRUE")
ctx.SetContentType("image/png")
ctx.SetBody(cache)
return
}
skin, slim, err := util.GetPlayerSkin(r, uuid)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if skin == nil {
skin = util.GetDefaultSkin(slim)
}
render := renders.RenderBackBody(skin, renders.RenderOptions{
Overlay: overlay,
Slim: slim,
Scale: scale,
})
data, err := util.EncodePNG(render)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if err = r.Set(cacheKey, data, time.Hour*24); err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "FALSE")
ctx.SetContentType("image/png")
ctx.SetBody(data)
}
func LeftBodyHandler(ctx *fasthttp.RequestCtx) {
user := ctx.UserValue("user").(string)
download := ctx.QueryArgs().GetBool("download")
scale, err := ctx.QueryArgs().GetUint("scale")
if err != nil {
scale = 4
}
scale = int(math.Max(math.Min(float64(scale), MaxScale), MinScale))
overlay := true
if ctx.QueryArgs().Has("overlay") {
overlay = ctx.QueryArgs().GetBool("overlay")
}
uuid, err := util.GetUUID(r, user)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
cacheKey := fmt.Sprintf("result:leftbody-%d-%t-%s", scale, overlay, uuid)
cache, ok, err := r.GetBytes(cacheKey)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if ok {
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "TRUE")
ctx.SetContentType("image/png")
ctx.SetBody(cache)
return
}
skin, slim, err := util.GetPlayerSkin(r, uuid)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if skin == nil {
skin = util.GetDefaultSkin(slim)
}
render := renders.RenderLeftBody(skin, renders.RenderOptions{
Overlay: overlay,
Slim: slim,
Scale: scale,
})
data, err := util.EncodePNG(render)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if err = r.Set(cacheKey, data, time.Hour*24); err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "FALSE")
ctx.SetContentType("image/png")
ctx.SetBody(data)
}
func RightBodyHandler(ctx *fasthttp.RequestCtx) {
user := ctx.UserValue("user").(string)
download := ctx.QueryArgs().GetBool("download")
scale, err := ctx.QueryArgs().GetUint("scale")
if err != nil {
scale = 4
}
scale = int(math.Max(math.Min(float64(scale), MaxScale), MinScale))
overlay := true
if ctx.QueryArgs().Has("overlay") {
overlay = ctx.QueryArgs().GetBool("overlay")
}
uuid, err := util.GetUUID(r, user)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
cacheKey := fmt.Sprintf("result:rightbody-%d-%t-%s", scale, overlay, uuid)
cache, ok, err := r.GetBytes(cacheKey)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if ok {
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "TRUE")
ctx.SetContentType("image/png")
ctx.SetBody(cache)
return
}
skin, slim, err := util.GetPlayerSkin(r, uuid)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if skin == nil {
skin = util.GetDefaultSkin(slim)
}
render := renders.RenderRightBody(skin, renders.RenderOptions{
Overlay: overlay,
Slim: slim,
Scale: scale,
})
data, err := util.EncodePNG(render)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if err = r.Set(cacheKey, data, time.Hour*24); err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "FALSE")
ctx.SetContentType("image/png")
ctx.SetBody(data)
}

118
src/routes/face.go Normal file
View File

@@ -0,0 +1,118 @@
package routes
import (
"fmt"
"log"
"main/src/util"
"main/src/util/renders"
"math"
"net/http"
"time"
"github.com/valyala/fasthttp"
)
func FaceHandler(ctx *fasthttp.RequestCtx) {
user := ctx.UserValue("user").(string)
download := ctx.QueryArgs().GetBool("download")
scale, err := ctx.QueryArgs().GetUint("scale")
if err != nil {
scale = 4
}
scale = int(math.Max(math.Min(float64(scale), MaxScale), MinScale))
overlay := true
if ctx.QueryArgs().Has("overlay") {
overlay = ctx.QueryArgs().GetBool("overlay")
}
uuid, err := util.GetUUID(r, user)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
cacheKey := fmt.Sprintf("result:face-%d-%t-%s", scale, overlay, uuid)
cache, ok, err := r.GetBytes(cacheKey)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if ok {
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "TRUE")
ctx.SetContentType("image/png")
ctx.SetBody(cache)
return
}
skin, slim, err := util.GetPlayerSkin(r, uuid)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if skin == nil {
skin = util.GetDefaultSkin(slim)
}
render := renders.RenderFace(skin, renders.RenderOptions{
Overlay: overlay,
Slim: slim,
Scale: scale,
})
data, err := util.EncodePNG(render)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if err = r.Set(cacheKey, data, time.Hour*24); err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "FALSE")
ctx.SetContentType("image/png")
ctx.SetBody(data)
}

118
src/routes/head.go Normal file
View File

@@ -0,0 +1,118 @@
package routes
import (
"fmt"
"log"
"main/src/util"
"main/src/util/renders"
"math"
"net/http"
"time"
"github.com/valyala/fasthttp"
)
func HeadHandler(ctx *fasthttp.RequestCtx) {
user := ctx.UserValue("user").(string)
download := ctx.QueryArgs().GetBool("download")
scale, err := ctx.QueryArgs().GetUint("scale")
if err != nil {
scale = 4
}
scale = int(math.Max(math.Min(float64(scale), MaxScale), MinScale))
overlay := true
if ctx.QueryArgs().Has("overlay") {
overlay = ctx.QueryArgs().GetBool("overlay")
}
uuid, err := util.GetUUID(r, user)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
cacheKey := fmt.Sprintf("result:head-%d-%t-%s", scale, overlay, uuid)
cache, ok, err := r.GetBytes(cacheKey)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if ok {
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "TRUE")
ctx.SetContentType("image/png")
ctx.SetBody(cache)
return
}
skin, slim, err := util.GetPlayerSkin(r, uuid)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if skin == nil {
skin = util.GetDefaultSkin(slim)
}
render := renders.RenderHead(skin, renders.RenderOptions{
Overlay: overlay,
Slim: slim,
Scale: scale,
})
data, err := util.EncodePNG(render)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if err = r.Set(cacheKey, data, time.Hour*24); err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.Response.Header.Set("X-Cache-Hit", "FALSE")
ctx.SetContentType("image/png")
ctx.SetBody(data)
}

17
src/routes/init.go Normal file
View File

@@ -0,0 +1,17 @@
package routes
import "main/src/redis"
var (
r *redis.Redis
)
const (
MaxScale float64 = 64.0
MaxScaleFullBody float64 = 32.0
MinScale float64 = 1.0
)
func InitRoutes(red *redis.Redis) {
r = red
}

9
src/routes/ping.go Normal file
View File

@@ -0,0 +1,9 @@
package routes
import (
"github.com/valyala/fasthttp"
)
func PingHandler(ctx *fasthttp.RequestCtx) {
ctx.SetBodyString("Pong!")
}

60
src/routes/skin.go Normal file
View File

@@ -0,0 +1,60 @@
package routes
import (
"fmt"
"log"
"main/src/util"
"net/http"
"github.com/valyala/fasthttp"
)
func SkinHandler(ctx *fasthttp.RequestCtx) {
user := ctx.UserValue("user").(string)
download := ctx.QueryArgs().GetBool("download")
uuid, err := util.GetUUID(r, user)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
skin, slim, err := util.GetPlayerSkin(r, uuid)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if skin == nil {
skin = util.GetDefaultSkin(slim)
}
data, err := util.EncodePNG(skin)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
if download {
ctx.Response.Header.Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s.png"`, user))
}
ctx.SetContentType("image/png")
ctx.SetBody(data)
}

26
src/routes/uuid.go Normal file
View File

@@ -0,0 +1,26 @@
package routes
import (
"log"
"main/src/util"
"net/http"
"github.com/valyala/fasthttp"
)
func UUIDHandler(ctx *fasthttp.RequestCtx) {
user := ctx.UserValue("user").(string)
uuid, err := util.GetUUID(r, user)
if err != nil {
log.Println(err)
ctx.SetStatusCode(http.StatusInternalServerError)
ctx.SetBodyString(http.StatusText(http.StatusInternalServerError))
return
}
ctx.SetBodyString(uuid)
}

BIN
src/util/alex.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

17
src/util/image.go Normal file
View File

@@ -0,0 +1,17 @@
package util
import (
"bytes"
"image"
"image/png"
)
func EncodePNG(img image.Image) ([]byte, error) {
buf := &bytes.Buffer{}
if err := png.Encode(buf, img); err != nil {
return nil, err
}
return buf.Bytes(), nil
}

5
src/util/init.go Normal file
View File

@@ -0,0 +1,5 @@
package util
import "os"
var Debug = os.Getenv("DEBUG") == "true"

View File

@@ -0,0 +1,59 @@
package renders
import (
"image"
)
func RenderBackBody(skin *image.NRGBA, opts RenderOptions) *image.NRGBA {
slimOffset := GetSlimOffset(opts.Slim)
var (
backHead *image.NRGBA = RemoveTransparency(Extract(skin, 24, 8, 8, 8))
backTorso *image.NRGBA = RemoveTransparency(Extract(skin, 32, 20, 8, 12))
backLeftArm *image.NRGBA = nil
backRightArm *image.NRGBA = RemoveTransparency(Extract(skin, 52-slimOffset, 20, 4-slimOffset, 12))
backLeftLeg *image.NRGBA = nil
backRightLeg *image.NRGBA = RemoveTransparency(Extract(skin, 12, 20, 4, 12))
)
if IsOldSkin(skin) {
backLeftArm = FlipHorizontal(backRightArm)
backLeftLeg = FlipHorizontal(backRightLeg)
} else {
backLeftArm = RemoveTransparency(Extract(skin, 44-slimOffset, 52, 4-slimOffset, 12))
backLeftLeg = RemoveTransparency(Extract(skin, 28, 52, 4, 12))
if opts.Overlay {
overlaySkin := FixTransparency(skin)
backHead = Composite(backHead, Extract(overlaySkin, 56, 8, 8, 8), 0, 0)
backTorso = Composite(backTorso, Extract(overlaySkin, 32, 36, 8, 12), 0, 0)
backLeftArm = Composite(backLeftArm, Extract(overlaySkin, 60-slimOffset, 52, 4-slimOffset, 64), 0, 0)
backRightArm = Composite(backRightArm, Extract(overlaySkin, 52-slimOffset, 36, 4-slimOffset, 48), 0, 0)
backLeftLeg = Composite(backLeftLeg, Extract(overlaySkin, 12, 52, 8, 64), 0, 0)
backRightLeg = Composite(backRightLeg, Extract(overlaySkin, 12, 36, 8, 48), 0, 0)
}
}
output := image.NewNRGBA(image.Rect(0, 0, 16, 32))
// Face
output = Composite(output, backHead, 4, 0)
// Torso
output = Composite(output, backTorso, 4, 8)
// Left Arm
output = Composite(output, backLeftArm, slimOffset, 8)
// Right Arm
output = Composite(output, backRightArm, 12, 8)
// Left Leg
output = Composite(output, backLeftLeg, 4, 20)
// Right Leg
output = Composite(output, backRightLeg, 8, 20)
return Scale(output, opts.Scale)
}

90
src/util/renders/body.go Normal file
View File

@@ -0,0 +1,90 @@
package renders
import "image"
func RenderBody(skin *image.NRGBA, opts RenderOptions) *image.NRGBA {
scale := float64(opts.Scale)
slimOffset := GetSlimOffset(opts.Slim)
output := image.NewNRGBA(image.Rect(0, 0, 20*opts.Scale, 45*opts.Scale+int(scale*(1.0/16.0))))
var (
frontHead *image.NRGBA = RemoveTransparency(Extract(skin, 8, 8, 8, 8))
topHead *image.NRGBA = RemoveTransparency(Extract(skin, 8, 0, 8, 8))
rightHead *image.NRGBA = RemoveTransparency(Extract(skin, 0, 8, 8, 8))
frontTorso *image.NRGBA = RemoveTransparency(Extract(skin, 20, 20, 8, 12))
frontLeftArm *image.NRGBA = nil
topLeftArm *image.NRGBA = nil
frontRightArm *image.NRGBA = RemoveTransparency(Extract(skin, 44, 20, 4-slimOffset, 12))
topRightArm *image.NRGBA = RemoveTransparency(Extract(skin, 44, 16, 4-slimOffset, 4))
rightRightArm *image.NRGBA = RemoveTransparency(Extract(skin, 40, 20, 4, 12))
frontLeftLeg *image.NRGBA = nil
frontRightLeg *image.NRGBA = RemoveTransparency(Extract(skin, 4, 20, 4, 12))
rightRightLeg *image.NRGBA = RemoveTransparency(Extract(skin, 0, 20, 4, 12))
)
if IsOldSkin(skin) {
frontLeftArm = FlipHorizontal(frontRightArm)
topLeftArm = FlipHorizontal(topRightArm)
frontLeftLeg = FlipHorizontal(frontRightLeg)
} else {
frontLeftArm = RemoveTransparency(Extract(skin, 36, 52, 4-slimOffset, 12))
topLeftArm = RemoveTransparency(Extract(skin, 36, 48, 4-slimOffset, 4))
frontLeftLeg = RemoveTransparency(Extract(skin, 20, 52, 4, 12))
if opts.Overlay {
overlaySkin := FixTransparency(skin)
frontHead = Composite(frontHead, Extract(overlaySkin, 40, 8, 8, 8), 0, 0)
topHead = Composite(topHead, Extract(overlaySkin, 40, 0, 8, 8), 0, 0)
rightHead = Composite(rightHead, Extract(overlaySkin, 32, 8, 8, 8), 0, 0)
frontTorso = Composite(frontTorso, Extract(overlaySkin, 20, 36, 8, 12), 0, 0)
frontLeftArm = Composite(frontLeftArm, Extract(overlaySkin, 52, 52, 4-slimOffset, 64), 0, 0)
topLeftArm = Composite(topLeftArm, Extract(overlaySkin, 52, 48, 4-slimOffset, 4), 0, 0)
frontRightArm = Composite(frontRightArm, Extract(overlaySkin, 44, 36, 4-slimOffset, 48), 0, 0)
topRightArm = Composite(topRightArm, Extract(overlaySkin, 44, 48, 4-slimOffset, 4), 0, 0)
rightRightArm = Composite(rightRightArm, Extract(overlaySkin, 40, 36, 4, 12), 0, 0)
frontLeftLeg = Composite(frontLeftLeg, Extract(overlaySkin, 4, 52, 4, 12), 0, 0)
frontRightLeg = Composite(frontRightLeg, Extract(overlaySkin, 4, 36, 4, 12), 0, 0)
rightRightLeg = Composite(rightRightLeg, Extract(overlaySkin, 0, 36, 4, 12), 0, 0)
}
}
// Right Side of Right Leg
output = CompositeTransform(output, Scale(rightRightLeg, opts.Scale), TransformRight, 4*scale, 23*scale)
// Front of Right Leg
output = CompositeTransform(output, Scale(frontRightLeg, opts.Scale), TransformForward, 8*scale, 31*scale)
// Front of Left Leg
output = CompositeTransform(output, Scale(frontLeftLeg, opts.Scale), TransformForward, 12*scale, 31*scale)
// Front of Torso
output = CompositeTransform(output, Scale(frontTorso, opts.Scale), TransformForward, 8*scale, 19*scale)
// Front of Right Arm
output = CompositeTransform(output, Scale(frontRightArm, opts.Scale), TransformForward, float64(4+slimOffset)*scale, 19*scale-1)
// Front of Left Arm
output = CompositeTransform(output, Scale(frontLeftArm, opts.Scale), TransformForward, 16*scale, 21*scale-1)
// Top of Left Arm
output = CompositeTransform(output, Scale(topLeftArm, opts.Scale), TransformUp, -5*scale, 17*scale)
// Right Side of Right Arm
output = CompositeTransform(output, Scale(rightRightArm, opts.Scale), TransformRight, float64(slimOffset)*scale, float64(15-slimOffset)*scale)
// Top of Right Arm
output = CompositeTransform(output, Scale(topRightArm, opts.Scale), TransformUp, float64(-15+slimOffset)*scale, 15*scale)
// Front of Head
output = CompositeTransform(output, Scale(frontHead, opts.Scale), TransformForward, 10*scale, 13*scale-1)
// Top of Head
output = CompositeTransform(output, Scale(topHead, opts.Scale), TransformUp, -3*scale, 5*scale)
// Right Side of Head
output = CompositeTransform(output, Scale(rightHead, opts.Scale), TransformRight, 2*scale, 3*scale)
return output
}

13
src/util/renders/face.go Normal file
View File

@@ -0,0 +1,13 @@
package renders
import "image"
func RenderFace(skin *image.NRGBA, opts RenderOptions) *image.NRGBA {
output := RemoveTransparency(Extract(skin, 8, 8, 8, 8))
if opts.Overlay && !IsOldSkin(skin) {
output = Composite(output, Extract(skin, 40, 8, 8, 8), 0, 0)
}
return Scale(output, opts.Scale)
}

View File

@@ -0,0 +1,59 @@
package renders
import (
"image"
)
func RenderFrontBody(skin *image.NRGBA, opts RenderOptions) *image.NRGBA {
slimOffset := GetSlimOffset(opts.Slim)
var (
frontHead *image.NRGBA = RemoveTransparency(Extract(skin, 8, 8, 8, 8))
frontTorso *image.NRGBA = RemoveTransparency(Extract(skin, 20, 20, 8, 12))
leftArm *image.NRGBA = nil
rightArm *image.NRGBA = RemoveTransparency(Extract(skin, 44, 20, 4-slimOffset, 12))
leftLeg *image.NRGBA = nil
rightLeg *image.NRGBA = RemoveTransparency(Extract(skin, 4, 20, 4, 12))
)
if IsOldSkin(skin) {
leftArm = FlipHorizontal(rightArm)
leftLeg = FlipHorizontal(rightLeg)
} else {
leftArm = RemoveTransparency(Extract(skin, 36, 52, 4-slimOffset, 12))
leftLeg = RemoveTransparency(Extract(skin, 20, 52, 4, 12))
if opts.Overlay {
overlaySkin := FixTransparency(skin)
frontHead = Composite(frontHead, Extract(overlaySkin, 40, 8, 8, 8), 0, 0)
frontTorso = Composite(frontTorso, Extract(overlaySkin, 20, 36, 8, 12), 0, 0)
leftArm = Composite(leftArm, Extract(overlaySkin, 52, 52, 4-slimOffset, 64), 0, 0)
rightArm = Composite(rightArm, Extract(overlaySkin, 44, 36, 4-slimOffset, 48), 0, 0)
leftLeg = Composite(leftLeg, Extract(overlaySkin, 4, 52, 4, 12), 0, 0)
rightLeg = Composite(rightLeg, Extract(overlaySkin, 4, 36, 4, 12), 0, 0)
}
}
output := image.NewNRGBA(image.Rect(0, 0, 16, 32))
// Face
output = Composite(output, frontHead, 4, 0)
// Torso
output = Composite(output, frontTorso, 4, 8)
// Left Arm
output = Composite(output, leftArm, 12, 8)
// Right Arm
output = Composite(output, rightArm, slimOffset, 8)
// Left Leg
output = Composite(output, leftLeg, 8, 20)
// Right Leg
output = Composite(output, rightLeg, 4, 20)
return Scale(output, opts.Scale)
}

33
src/util/renders/head.go Normal file
View File

@@ -0,0 +1,33 @@
package renders
import "image"
func RenderHead(skin *image.NRGBA, opts RenderOptions) *image.NRGBA {
scale := float64(opts.Scale)
output := image.NewNRGBA(image.Rect(0, 0, 16*opts.Scale, 19*opts.Scale-int(scale/2.0)-1))
var (
frontHead *image.NRGBA = RemoveTransparency(Extract(skin, 8, 8, 8, 8))
topHead *image.NRGBA = RemoveTransparency(Extract(skin, 8, 0, 8, 8))
rightHead *image.NRGBA = RemoveTransparency(Extract(skin, 0, 8, 8, 8))
)
if opts.Overlay && !IsOldSkin(skin) {
overlaySkin := FixTransparency(skin)
frontHead = Composite(frontHead, Extract(overlaySkin, 40, 8, 8, 8), 0, 0)
topHead = Composite(topHead, Extract(overlaySkin, 40, 0, 8, 8), 0, 0)
rightHead = Composite(rightHead, Extract(overlaySkin, 32, 8, 8, 8), 0, 0)
}
// Front Head
output = CompositeTransform(output, Scale(frontHead, opts.Scale), TransformForward, 8*scale, 12*scale-1)
// Top Head
output = CompositeTransform(output, Scale(topHead, opts.Scale), TransformUp, -4*scale, 4*scale)
// Right Head
output = CompositeTransform(output, Scale(rightHead, opts.Scale), TransformRight, 0, 4*scale)
return output
}

View File

@@ -0,0 +1,44 @@
package renders
import (
"image"
)
func RenderLeftBody(skin *image.NRGBA, opts RenderOptions) *image.NRGBA {
slimOffset := GetSlimOffset(opts.Slim)
var (
leftHead *image.NRGBA = RemoveTransparency(Extract(skin, 24, 8, 8, 8))
leftLeftArm *image.NRGBA = nil
leftLeftLeg *image.NRGBA = nil
)
if IsOldSkin(skin) {
leftLeftArm = FlipHorizontal(RemoveTransparency(Extract(skin, 40, 20, 4, 12)))
leftLeftLeg = FlipHorizontal(RemoveTransparency(Extract(skin, 0, 20, 4, 12)))
} else {
leftLeftArm = RemoveTransparency(Extract(skin, 40-slimOffset, 52, 4, 12))
leftLeftLeg = RemoveTransparency(Extract(skin, 24, 52, 4, 12))
if opts.Overlay {
overlaySkin := FixTransparency(skin)
leftHead = Composite(leftHead, Extract(overlaySkin, 48, 8, 8, 8), 0, 0)
leftLeftArm = Composite(leftLeftArm, Extract(overlaySkin, 56-slimOffset, 52, 4, 12), 0, 0)
leftLeftLeg = Composite(leftLeftLeg, Extract(overlaySkin, 8, 52, 4, 12), 0, 0)
}
}
output := image.NewNRGBA(image.Rect(0, 0, 8, 32))
// Left Head
output = Composite(output, leftHead, 0, 0)
// Left Arm
output = Composite(output, leftLeftArm, 2, 8)
// Left Leg
output = Composite(output, leftLeftLeg, 2, 20)
return Scale(output, opts.Scale)
}

View File

@@ -0,0 +1,90 @@
package matrix
import "math"
// Credit: https://github.com/fogleman/gg
type Matrix struct {
XX, YX, XY, YY, X0, Y0 float64
}
func Identity() Matrix {
return Matrix{
1, 0,
0, 1,
0, 0,
}
}
func Translate(x, y float64) Matrix {
return Matrix{
1, 0,
0, 1,
x, y,
}
}
func Scale(x, y float64) Matrix {
return Matrix{
x, 0,
0, y,
0, 0,
}
}
func Rotate(angle float64) Matrix {
c := math.Cos(angle)
s := math.Sin(angle)
return Matrix{
c, s,
-s, c,
0, 0,
}
}
func Shear(x, y float64) Matrix {
return Matrix{
1, y,
x, 1,
0, 0,
}
}
func (a Matrix) Multiply(b Matrix) Matrix {
return Matrix{
a.XX*b.XX + a.YX*b.XY,
a.XX*b.YX + a.YX*b.YY,
a.XY*b.XX + a.YY*b.XY,
a.XY*b.YX + a.YY*b.YY,
a.X0*b.XX + a.Y0*b.XY + b.X0,
a.X0*b.YX + a.Y0*b.YY + b.Y0,
}
}
func (a Matrix) TransformVector(x, y float64) (tx, ty float64) {
tx = a.XX*x + a.XY*y
ty = a.YX*x + a.YY*y
return
}
func (a Matrix) TransformPoint(x, y float64) (tx, ty float64) {
tx = a.XX*x + a.XY*y + a.X0
ty = a.YX*x + a.YY*y + a.Y0
return
}
func (a Matrix) Translate(x, y float64) Matrix {
return Translate(x, y).Multiply(a)
}
func (a Matrix) Scale(x, y float64) Matrix {
return Scale(x, y).Multiply(a)
}
func (a Matrix) Rotate(angle float64) Matrix {
return Rotate(angle).Multiply(a)
}
func (a Matrix) Shear(x, y float64) Matrix {
return Shear(x, y).Multiply(a)
}

View File

@@ -0,0 +1,7 @@
package renders
type RenderOptions struct {
Scale int
Overlay bool
Slim bool
}

View File

@@ -0,0 +1,34 @@
package renders
import (
"image"
)
func RenderRightBody(skin *image.NRGBA, opts RenderOptions) *image.NRGBA {
var (
rightHead *image.NRGBA = RemoveTransparency(Extract(skin, 0, 8, 8, 8))
rightRightArm *image.NRGBA = RemoveTransparency(Extract(skin, 40, 20, 4, 12))
rightRightLeg *image.NRGBA = RemoveTransparency(Extract(skin, 0, 20, 4, 12))
)
if opts.Overlay && !IsOldSkin(skin) {
overlaySkin := FixTransparency(skin)
rightHead = Composite(rightHead, Extract(overlaySkin, 32, 8, 8, 8), 0, 0)
rightRightArm = Composite(rightRightArm, Extract(overlaySkin, 40, 36, 4, 12), 0, 0)
rightRightLeg = Composite(rightRightLeg, Extract(overlaySkin, 0, 36, 4, 12), 0, 0)
}
output := image.NewNRGBA(image.Rect(0, 0, 8, 32))
// Right Head
output = Composite(output, rightHead, 0, 0)
// Right Arm
output = Composite(output, rightRightArm, 2, 8)
// Right Leg
output = Composite(output, rightRightLeg, 2, 20)
return Scale(output, opts.Scale)
}

164
src/util/renders/util.go Normal file
View File

@@ -0,0 +1,164 @@
package renders
import (
"image"
"image/draw"
"main/src/util/renders/matrix"
drw "golang.org/x/image/draw"
"golang.org/x/image/math/f64"
)
var (
SkewA float64 = 26.0 / 45.0
SkewB float64 = SkewA * 2.0
TransformForward matrix.Matrix = matrix.Matrix{
XX: 1, YX: -SkewA,
XY: 0, YY: SkewB,
X0: 0, Y0: SkewA,
}
TransformUp matrix.Matrix = matrix.Matrix{
XX: 1, YX: -SkewA,
XY: 1, YY: SkewA,
X0: 0, Y0: 0,
}
TransformRight matrix.Matrix = matrix.Matrix{
XX: 1, YX: SkewA,
XY: 0, YY: SkewB,
X0: 0, Y0: 0,
}
)
func Extract(img *image.NRGBA, x, y, width, height int) *image.NRGBA {
output := image.NewNRGBA(image.Rect(0, 0, width, height))
draw.Draw(output, output.Bounds(), img, image.Pt(x, y), draw.Src)
return output
}
func Scale(img *image.NRGBA, scale int) *image.NRGBA {
if scale == 1 {
return img
}
bounds := img.Bounds().Max
output := image.NewNRGBA(image.Rect(0, 0, bounds.X*scale, bounds.Y*scale))
for x := 0; x < bounds.X; x++ {
for y := 0; y < bounds.Y; y++ {
color := img.At(x, y)
for sx := 0; sx < scale; sx++ {
for sy := 0; sy < scale; sy++ {
output.Set(x*scale+sx, y*scale+sy, color)
}
}
}
}
return output
}
func RemoveTransparency(img *image.NRGBA) *image.NRGBA {
output := image.NewNRGBA(img.Bounds())
for i, l := 0, len(img.Pix); i < l; i += 4 {
output.Pix[i] = img.Pix[i]
output.Pix[i+1] = img.Pix[i+1]
output.Pix[i+2] = img.Pix[i+2]
output.Pix[i+3] = 255
}
return output
}
func IsOldSkin(img *image.NRGBA) bool {
return img.Bounds().Max.Y < 64
}
func Composite(bottom, top *image.NRGBA, x, y int) *image.NRGBA {
output := image.NewNRGBA(bottom.Bounds())
topBounds := top.Bounds().Max
draw.Draw(output, bottom.Bounds(), bottom, image.Pt(0, 0), draw.Src)
draw.Draw(output, image.Rect(0, 0, topBounds.X+x, topBounds.Y+y), top, image.Pt(-x, -y), draw.Over)
return output
}
func FlipHorizontal(img *image.NRGBA) *image.NRGBA {
data := img.Pix
bounds := img.Bounds()
output := image.NewNRGBA(bounds)
for x := 0; x < bounds.Max.X; x++ {
for y := 0; y < bounds.Max.Y; y++ {
fx := bounds.Max.X - x - 1
fi := fx*4 + y*4*bounds.Max.X
ix := x*4 + y*4*bounds.Max.X
for i := 0; i < 4; i++ {
output.Pix[ix+i] = data[fi+i]
}
}
}
return output
}
func FixTransparency(img *image.NRGBA) *image.NRGBA {
a := img.Pix[0:4]
if a[3] == 0 {
return img
}
output := Clone(img)
for i, l := 0, len(output.Pix); i < l; i += 4 {
if output.Pix[i+0] != a[0] || output.Pix[i+1] != a[1] || output.Pix[i+2] != a[2] || output.Pix[i+3] != a[3] {
continue
}
output.Pix[i+3] = 0
}
return output
}
func Clone(img *image.NRGBA) *image.NRGBA {
bounds := img.Bounds()
output := image.NewNRGBA(bounds)
draw.Draw(output, bounds, img, image.Pt(0, 0), draw.Src)
return output
}
func GetSlimOffset(slim bool) int {
if slim {
return 1
}
return 0
}
func CompositeTransform(bottom, top *image.NRGBA, mat matrix.Matrix, x, y float64) *image.NRGBA {
output := image.NewNRGBA(bottom.Bounds())
draw.Draw(output, bottom.Bounds(), bottom, image.Pt(0, 0), draw.Src)
transformer := drw.NearestNeighbor
fx, fy := float64(x), float64(y)
m := mat.Translate(fx, fy)
transformer.Transform(output, f64.Aff3{m.XX, m.XY, m.X0, m.YX, m.YY, m.Y0}, top, top.Bounds(), draw.Over, nil)
return output
}

47
src/util/skin.go Normal file
View File

@@ -0,0 +1,47 @@
package util
import (
"bytes"
_ "embed"
"image"
"image/draw"
"image/png"
"log"
)
var (
//go:embed steve.png
rawSteveData []byte
//go:embed alex.png
rawAlexData []byte
steveSkin *image.NRGBA = image.NewNRGBA(image.Rect(0, 0, 64, 64))
alexSkin *image.NRGBA = image.NewNRGBA(image.Rect(0, 0, 64, 64))
)
func init() {
rawSteveSkin, err := png.Decode(bytes.NewReader(rawSteveData))
if err != nil {
log.Fatal(err)
}
draw.Draw(steveSkin, rawSteveSkin.Bounds(), rawSteveSkin, image.Pt(0, 0), draw.Src)
rawAlexSkin, err := png.Decode(bytes.NewReader(rawAlexData))
if err != nil {
log.Fatal(err)
}
draw.Draw(alexSkin, rawAlexSkin.Bounds(), rawAlexSkin, image.Pt(0, 0), draw.Src)
}
func GetDefaultSkin(slim bool) *image.NRGBA {
if slim {
return alexSkin
}
return steveSkin
}

BIN
src/util/steve.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

50
src/util/uuid.go Normal file
View File

@@ -0,0 +1,50 @@
package util
import (
"fmt"
"log"
"main/src/redis"
"strings"
)
func GetUUID(r *redis.Redis, value string) (string, error) {
value = strings.ToLower(strings.ReplaceAll(value, "-", ""))
if len(value) == 32 {
return value, nil
}
cache, ok, err := r.GetString(fmt.Sprintf("uuid:%s", value))
if err != nil {
return "", err
}
if ok {
if Debug {
log.Printf("[DEBUG] Retrieved UUID for player %s (%s) from cache\n", value, cache)
}
return cache, nil
}
profile, err := GetProfileByUsername(value)
if err != nil {
return "", err
}
if profile == nil {
return "", nil
}
if err = r.Set(fmt.Sprintf("uuid:%s", value), profile.ID, 0); err != nil {
return "", err
}
if Debug {
log.Printf("[DEBUG] Fetched UUID for player %s (%s) from Mojang\n", profile.Name, profile.ID)
}
return profile.ID, nil
}

243
src/util/yggdrasil.go Normal file
View File

@@ -0,0 +1,243 @@
package util
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"image"
"image/draw"
"io/ioutil"
"log"
"main/src/redis"
"net/http"
"time"
)
type BasicProfile struct {
Name string `json:"name"`
ID string `json:"id"`
}
type Profile struct {
ID string `json:"id"`
Name string `json:"name"`
Properties []struct {
Name string `json:"name"`
Value string `json:"value"`
Signature string `json:"signature"`
} `yaml:"properties"`
}
type Textures struct {
Textures map[string]struct {
URL string `json:"url"`
Metadata struct {
Model string `json:"model"`
} `json:"metadata"`
} `json:"textures"`
}
func GetProfileByUsername(username string) (*BasicProfile, error) {
resp, err := http.Get(fmt.Sprintf("https://api.mojang.com/users/profiles/minecraft/%s", username))
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
if resp.StatusCode == 204 {
return nil, nil
}
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
defer resp.Body.Close()
result := &BasicProfile{}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if err = json.Unmarshal(body, result); err != nil {
return nil, err
}
return result, nil
}
func GetPlayerProfile(uuid string) (*Profile, error) {
resp, err := http.Get(fmt.Sprintf("https://sessionserver.mojang.com/session/minecraft/profile/%s", uuid))
if err != nil {
return nil, err
}
if resp.StatusCode != 200 {
if resp.StatusCode == 404 {
return nil, nil
}
return nil, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
defer resp.Body.Close()
result := &Profile{}
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if err = json.Unmarshal(body, result); err != nil {
return nil, err
}
return result, nil
}
func GetPlayerSkin(r *redis.Redis, uuid string) (*image.NRGBA, bool, error) {
if len(uuid) < 1 {
return GetDefaultSkin(false), false, nil
}
cache, ok, err := r.GetBytes(fmt.Sprintf("skin:%s", uuid))
if err != nil {
return nil, false, err
}
if ok {
slim, err := r.Exists(fmt.Sprintf("slim:%s", uuid))
if err != nil {
return nil, false, err
}
img, format, err := image.Decode(bytes.NewReader(cache))
if err != nil {
return nil, false, err
}
if Debug {
log.Printf("[DEBUG] Retrieved skin for %s from cache\n", uuid)
}
if format != "NRGBA" {
newImage := image.NewNRGBA(img.Bounds())
draw.Draw(newImage, img.Bounds(), img, image.Pt(0, 0), draw.Src)
return newImage, slim, nil
}
return img.(*image.NRGBA), slim, nil
}
profile, err := GetPlayerProfile(uuid)
if err != nil {
return nil, false, err
}
if profile == nil {
return nil, false, nil
}
var value string
for _, property := range profile.Properties {
if property.Name != "textures" {
continue
}
value = property.Value
}
if len(value) < 1 {
return nil, false, nil
}
propertyValue, err := base64.StdEncoding.DecodeString(value)
if err != nil {
return nil, false, err
}
textures := &Textures{}
if err = json.Unmarshal(propertyValue, textures); err != nil {
return nil, false, err
}
skinProperty, ok := textures.Textures["SKIN"]
if !ok {
return nil, false, nil
}
slim := skinProperty.Metadata.Model == "slim"
resp, err := http.Get(skinProperty.URL)
if err != nil {
return nil, false, err
}
if resp.StatusCode != 200 {
if resp.StatusCode == 404 {
return nil, slim, nil
}
return nil, false, fmt.Errorf("unexpected status code: %d", resp.StatusCode)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, false, err
}
img, format, err := image.Decode(bytes.NewReader(body))
if err != nil {
return nil, false, err
}
if slim {
if err = r.Set(fmt.Sprintf("slim:%s", uuid), "true", time.Hour*24); err != nil {
return nil, false, err
}
} else {
if err = r.Delete(fmt.Sprintf("slim:%s", uuid)); err != nil {
return nil, false, err
}
}
if err = r.Set(fmt.Sprintf("skin:%s", uuid), body, time.Hour*24); err != nil {
return nil, false, err
}
if Debug {
log.Printf("[DEBUG] Fetched skin for %s from Mojang\n", uuid)
}
if format != "NRGBA" {
newImage := image.NewNRGBA(img.Bounds())
draw.Draw(newImage, img.Bounds(), img, image.Pt(0, 0), draw.Src)
return newImage, slim, nil
}
return img.(*image.NRGBA), slim, nil
}