Compare commits

..

71 Commits

Author SHA1 Message Date
Alicia
178b5263d5 Update clan.go 2019-02-25 21:19:07 +00:00
Alicia
21d9cf3fae Update clan.go 2019-02-25 21:13:50 +00:00
Alicia
d7d592a2bd Update clan.go 2019-02-25 21:12:06 +00:00
Alicia
43bb674197 Update clan.go 2019-02-25 21:09:44 +00:00
Alicia
bd1b959836 adaq 2019-02-25 21:04:55 +00:00
Alicia
303b248408 Update clan.go 2019-02-25 20:57:06 +00:00
Alicia
1dabbe6b8c Update clan.go 2019-02-25 20:55:59 +00:00
Alicia
2e3c779330 Update clan.go 2019-02-24 14:56:50 +00:00
Alicia
3f08657c4d yea 2019-02-24 14:56:23 +00:00
Alicia
95754bffef czcz 2019-02-24 14:41:10 +00:00
Alicia
950340a04d add clan info to api 2019-02-24 14:37:51 +00:00
Alicia
e5b83bb11c Update clan.go 2019-02-24 14:29:19 +00:00
Alicia
2b02e0eaea Update user.go 2019-02-24 14:25:24 +00:00
Alicia
261c1549ed Update clan.go 2019-02-24 14:24:30 +00:00
Alicia
7b6bf4f562 add clans to api 2019-02-24 14:23:54 +00:00
Alicia
6f0df0a994 oops 2019-02-24 11:30:43 +00:00
Alicia
9f388f032c Forgot to update ranks 2019-02-24 11:26:46 +00:00
Alicia
53c06bd94f Update user.go 2019-02-24 00:38:51 +00:00
Alicia
a2916a6045 Update user.go 2019-02-24 00:37:52 +00:00
Alicia
13b6017e37 Update user.go 2019-02-24 00:36:31 +00:00
Alicia
47d0c75345 add rx and ap calls to api 2019-02-24 00:35:04 +00:00
Alicia
5f8eb862dd users.privileges 2019-02-23 14:22:28 +00:00
Alicia
df6cbafb00 dadadada 2019-02-23 14:21:31 +00:00
Alicia
43c63e57b3 ffafafa 2019-02-23 14:13:27 +00:00
Alicia
0c7b815edd crazy 2019-02-23 14:11:21 +00:00
Alicia
f6bbeec56e forgot to do these 2019-02-23 14:10:04 +00:00
Alicia
21646d8db7 Add relaxboard and autoboard to api 2019-02-23 14:06:24 +00:00
Alicia
b444bf15dd final error fixing 2019-02-23 13:14:37 +00:00
Alicia
5fc84bd914 fix schiavo error and changing rippleapi to api 2019-02-23 13:11:47 +00:00
Alicia
5b78c99b04 Allow import straight from github 2019-02-23 13:09:10 +00:00
Alicia
9c44c15e8a loL 2019-02-03 13:23:56 +00:00
Alicia
e1ed11d49f now we're cooking with gas 2019-02-03 13:21:31 +00:00
Alicia
69123c57a6 Didnt happen 2019-02-03 13:07:54 +00:00
Alicia
0de2f2afc0 Brian 2019-02-03 13:06:43 +00:00
Alicia
147274ebcb All 3 in 1 2019-02-03 12:59:47 +00:00
Alicia
333ca2743d Add rx and ap 2019-02-03 12:49:32 +00:00
qewc
2eda6c7aff
user score ap 2019-02-03 12:45:37 +00:00
qewc
133b744bd2
Make users scores relax 2019-02-03 12:45:15 +00:00
qewc
a0c1da8c70
Add other playmode to api 2019-02-03 12:44:15 +00:00
Morgan Bazalgette
50ffa4e066 forbid empty querying scores 2018-07-19 15:58:35 +02:00
Morgan Bazalgette
daf10b5d71 memes 2018-07-19 15:52:19 +02:00
Morgan Bazalgette
21e3939b36 how do we not have querying by score id??? 2018-07-19 15:43:58 +02:00
Morgan Bazalgette
4470ca2e63
Add support for scores_removed 2018-06-21 22:18:48 +02:00
Morgan Bazalgette
334c409e9e
Explain why you shouldn't design APIs like Ripple's in the README 2018-06-02 20:43:11 +02:00
Morgan Bazalgette
7e531b4ff4
Restrict/lock/ban/change privs via API 2018-05-20 18:57:27 +02:00
Morgan Bazalgette
e7a15cc9bc
add POST /scores/reports 2018-05-03 22:28:38 +02:00
Morgan Bazalgette
5ed6601359
Remove 'Username change' note, because that is already handled by pep.py 2018-03-06 21:26:23 +01:00
Morgan Bazalgette
b35dd9aebf
add user score wipe
i also forgot to add agplwarning in the vendor folder haha
2018-02-25 11:30:46 +01:00
Morgan Bazalgette
741b1e0b9f
Require users to agree to license before starting the API 2018-02-04 11:54:35 +01:00
Morgan Bazalgette
77ba8aee78
lolol i forgot this 2018-01-23 22:45:59 +01:00
Morgan Bazalgette
a1eb970382 add API endpoint to retrieve user achievements 2018-01-21 21:21:46 +01:00
Morgan Bazalgette
39078d00a3 on /api/v1/scores, make users with UserManager not see scores by restricted users 2018-01-02 12:30:32 +01:00
Morgan Bazalgette
3130863456
custom rap logs 2017-12-09 09:36:00 +01:00
Morgan Bazalgette
982b9ab9f8
use coalesce rather than notes directly 2017-12-08 15:40:45 +01:00
Morgan Bazalgette
0cb01f6067
show email when token has manageusers 2017-11-21 15:53:23 +01:00
Morgan Bazalgette
8d92df534c
make /users/full show CM notes and ban date when token has PrivilegeManageUser 2017-11-20 14:33:58 +01:00
Morgan Bazalgette
366418f025
log username/country changes 2017-11-18 16:49:49 +01:00
Morgan Bazalgette
c1e892336c
create POST /api/v1/users/edit
now i need to make the docs for it kill me
2017-11-18 16:28:59 +01:00
Morgan Bazalgette
6dde2086ac
We shall never forget about #ilbagdellennepì
add support for taiko pp
2017-09-18 21:38:33 +02:00
Morgan Bazalgette
77093ebef7 add Content-Type: json to peppy methods 2017-09-03 14:35:23 +02:00
Morgan Bazalgette
73f4a888c5
Allow IN for beatmap_id, beatmapset_id, beatmap_md5 2017-08-09 23:45:45 +02:00
Morgan Bazalgette
b7c00722de
implement subscribe_mp_complete_match 2017-08-09 12:46:50 +02:00
Morgan Bazalgette
6925ce4c6e
Remove deprecated API methods 2017-07-26 19:17:25 +02:00
Morgan Bazalgette
2535a03c5f
Revert "Vendor update"
This reverts commit e5f062ee91.
2017-07-25 15:09:02 +02:00
Morgan Bazalgette
e5f062ee91
Vendor update 2017-07-25 14:58:07 +02:00
Morgan Bazalgette
8ebe5f6a02
Require client to specify explicitly in websockets whether restricted users should be seen
This is only allowed to those having the user privilege AdminPrivilegeManageUsers, having being identified by the API AND having sent a message of type set_restricted_visibility stating specifically in the data that they want to get info also about restricted users.
This also includes some more information in the new_scores, such as the username and userid of the user who submitted the score.
2017-07-25 14:49:14 +02:00
Morgan Bazalgette
60d48df46d
Merge branch 'oauth2' 2017-07-25 10:41:09 +02:00
Morgan Bazalgette
a409231ca0
Some whitespace fixes 2017-07-25 10:39:37 +02:00
Morgan Bazalgette
6352f752ca
Add AdminPrivilegeCaker 2017-07-23 22:38:27 +02:00
Morgan Bazalgette
c078e20ac5 Pagination and filer by ID for GET /tokens 2017-07-01 21:37:25 +02:00
Morgan Bazalgette
9be90df7bd ping/pong 2017-06-27 00:33:21 +02:00
52 changed files with 2951 additions and 260 deletions

View File

@ -2,5 +2,19 @@
This is the source code for Ripple's API.
- Origin: https://git.zxq.co/ripple/rippleapi
- Mirror: https://github.com/osuripple/api
- Origin: https://git.github.com/osuyozora/api
- Mirror: https://github.com/osuyozora/api
## Note to fellow developers: this is not how you do it!
The API is crammed with terrible design. First of all, it is not RESTful, and as you'll come to learn, designing an API in a RESTful manner is good because it helps to create consistent design (across your API and other APIs). It also quite simplifies many other things:
* In the API, to get a specific item, you need to do e.g. `/users?id=1009`. It's much more useful to have these in the URL path directly (`/users/1009`) for a number of reasons:
* It simplifies checks (`/users/scores?id=1009` will require a check to see if an ID is present. `/users/:id/scores` doesn't really need a check, because `/users/scores` won't match)
* It gives a "feel" of hierarchy
* There is no multiple ways of addressing a specific user. There is a single way: IDs. In the Ripple API, you can specify an username instead of an ID to get a specific user, but this is prone to failure in the event of the user changing the username, whereas an ID cannot (should not) change.
* You can show error codes to the user using HTTP status codes. This way, you can present the resource to the user without any wrapper (such as an object giving an "ok" field or, like in the API, a `code` parameter), so the user can likely reuse other parts for error handling that they already use for other http requests.
* GET merely shows a resource, is cacheable and "idempotent". This helps debugging (repeating the same request twice will yield the same result, unless of course the data changes otherwise), caching (you can answer with Cache-Control headers, which browsers understand).
The not-making-it-RESTful was the biggest sin of the API. In itself, the API was a step into the right direction (it is MUCH better than the official osu! API), but nowhere close to how an API actually is, ideally. If you are building an API, I won't recommend you a book, but instead I will recommend you to see what [GitHub](https://developer.github.com/v3/) does, as they will have probably faced most problems that you have, and provided an answer already. If you're unsure, check other APIs: Discord, Slack, Twitter, Stripe, to name a few.

View File

@ -9,7 +9,7 @@ import (
"unsafe"
"github.com/valyala/fasthttp"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
// Method wraps an API method to a HandlerFunc.

View File

@ -7,7 +7,7 @@ import (
"github.com/jmoiron/sqlx"
"github.com/thehowl/go-osuapi"
"github.com/valyala/fasthttp"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
// GetBeatmap retrieves general beatmap information.

View File

@ -7,7 +7,7 @@ import (
"github.com/jmoiron/sqlx"
"github.com/valyala/fasthttp"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
var modes = []string{"std", "taiko", "ctb", "mania"}
@ -27,7 +27,7 @@ func genmodei(m string) int {
}
func rankable(m string) bool {
x := genmodei(m)
return x == 0 || x == 3
return x != 2
}
func genUser(c *fasthttp.RequestCtx, db *sqlx.DB) (string, string) {

View File

@ -5,7 +5,7 @@ import (
"strconv"
"strings"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
"github.com/jmoiron/sqlx"
"github.com/valyala/fasthttp"

View File

@ -13,7 +13,7 @@ import (
"github.com/valyala/fasthttp"
"gopkg.in/redis.v5"
"zxq.co/ripple/ocl"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
// R is a redis client.

View File

@ -7,7 +7,7 @@ import (
"github.com/jmoiron/sqlx"
"github.com/valyala/fasthttp"
"gopkg.in/thehowl/go-osuapi.v1"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
"zxq.co/x/getrank"
)

View File

@ -10,6 +10,8 @@ func PeppyMethod(a func(c *fasthttp.RequestCtx, db *sqlx.DB)) fasthttp.RequestHa
return func(c *fasthttp.RequestCtx) {
doggo.Incr("requests.peppy", nil, 1)
c.Response.Header.Add("Content-Type", "application/json; charset=utf-8")
// I have no idea how, but I manged to accidentally string the first 4
// letters of the alphabet into a single function call.
a(c, db)

View File

@ -9,7 +9,7 @@ import (
"github.com/buaazp/fasthttprouter"
"github.com/jmoiron/sqlx"
"github.com/valyala/fasthttp"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
type router struct {

View File

@ -2,18 +2,19 @@ package app
import (
"fmt"
"time"
"github.com/DataDog/datadog-go/statsd"
fhr "github.com/buaazp/fasthttprouter"
"github.com/getsentry/raven-go"
"github.com/jmoiron/sqlx"
"gopkg.in/redis.v5"
"zxq.co/ripple/rippleapi/app/internals"
"zxq.co/ripple/rippleapi/app/peppy"
"zxq.co/ripple/rippleapi/app/v1"
"zxq.co/ripple/rippleapi/app/websockets"
"zxq.co/ripple/rippleapi/common"
)
"github.com/osuyozora/api/app/internals"
"github.com/osuyozora/api/app/peppy"
"github.com/osuyozora/api/app/v1"
"github.com/osuyozora/api/app/websockets"
"github.com/osuyozora/api/common"
)
var (
db *sqlx.DB
@ -67,6 +68,9 @@ func Start(conf common.Conf, dbO *sqlx.DB) *fhr.Router {
// start websocket
websockets.Start(red, db)
// start load achievements
go v1.LoadAchievementsEvery(db, time.Minute*10)
// peppyapi
{
r.Peppy("/api/get_user", peppy.GetUser)
@ -79,10 +83,6 @@ func Start(conf common.Conf, dbO *sqlx.DB) *fhr.Router {
// v1 API
{
// These require an user to pass the password in cleartext and are
// as such really insecure.
//r.POSTMethod("/api/v1/tokens", v1.TokenNewPOST)
//r.POSTMethod("/api/v1/tokens/new", v1.TokenNewPOST)
r.POSTMethod("/api/v1/tokens/self/delete", v1.TokenSelfDeletePOST)
// Auth-free API endpoints (public data)
@ -91,14 +91,25 @@ func Start(conf common.Conf, dbO *sqlx.DB) *fhr.Router {
r.Method("/api/v1/users", v1.UsersGET)
r.Method("/api/v1/users/whatid", v1.UserWhatsTheIDGET)
r.Method("/api/v1/users/full", v1.UserFullGET)
r.Method("/api/v1/users/rx/full", v1.UserFullGETRx)
r.Method("/api/v1/users/ap/full", v1.UserFullGETAp)
r.Method("/api/v1/users/achievements", v1.UserAchievementsGET)
r.Method("/api/v1/users/userpage", v1.UserUserpageGET)
r.Method("/api/v1/users/lookup", v1.UserLookupGET)
r.Method("/api/v1/users/scores/best", v1.UserScoresBestGET)
r.Method("/api/v1/users/scores/recent", v1.UserScoresRecentGET)
r.Method("/api/v1/badges", v1.BadgesGET)
r.Method("/api/v1/badges/members", v1.BadgeMembersGET)
r.Method("/api/v1/clans", v1.ClansGET)
r.Method("/api/v1/clans/members", v1.ClanMembersGET)
r.Method("/api/v1/clans/stats", v1.TotalClanStatsGET)
r.Method("/api/v1/clans/stats/all", v1.AllClanStatsGET)
r.Method("/api/v1/clans/getinvite", v1.ClanInviteGET)
r.Method("/api/v1/clans/isclan", v1.IsInClanGET)
r.Method("/api/v1/beatmaps", v1.BeatmapGET)
r.Method("/api/v1/leaderboard", v1.LeaderboardGET)
r.Method("/api/v1/relaxboard", v1.LeaderboardRxGET)
r.Method("/api/v1/autoboard", v1.LeaderboardApGET)
r.Method("/api/v1/tokens", v1.TokenGET)
r.Method("/api/v1/users/self", v1.UserSelfGET)
r.Method("/api/v1/tokens/self", v1.TokenSelfGET)
@ -106,6 +117,12 @@ func Start(conf common.Conf, dbO *sqlx.DB) *fhr.Router {
r.Method("/api/v1/scores", v1.ScoresGET)
r.Method("/api/v1/beatmaps/rank_requests/status", v1.BeatmapRankRequestsStatusGET)
// Other leaderboard memes
r.Method("/api/v1/users/scores/relax/best", v1.UserScoresBestRelaxGET)
r.Method("/api/v1/users/scores/relax/recent", v1.UserScoresRecentRelaxGET)
r.Method("/api/v1/users/scores/ap/best", v1.UserScoresBestAPGET)
r.Method("/api/v1/users/scores/ap/recent", v1.UserScoresRecentAPGET)
// ReadConfidential privilege required
r.Method("/api/v1/friends", v1.FriendsGET, common.PrivilegeReadConfidential)
r.Method("/api/v1/friends/with", v1.FriendsWithGET, common.PrivilegeReadConfidential)
@ -120,19 +137,24 @@ func Start(conf common.Conf, dbO *sqlx.DB) *fhr.Router {
r.POSTMethod("/api/v1/users/self/userpage", v1.UserSelfUserpagePOST, common.PrivilegeWrite)
r.POSTMethod("/api/v1/beatmaps/rank_requests", v1.BeatmapRankRequestsSubmitPOST, common.PrivilegeWrite)
// Admin: RAP
r.POSTMethod("/api/v1/rap/log", v1.RAPLogPOST)
// Admin: beatmap
r.POSTMethod("/api/v1/beatmaps/set_status", v1.BeatmapSetStatusPOST, common.PrivilegeBeatmap)
r.Method("/api/v1/beatmaps/ranked_frozen_full", v1.BeatmapRankedFrozenFullGET, common.PrivilegeBeatmap)
// Admin: user managing
r.POSTMethod("/api/v1/users/manage/set_allowed", v1.UserManageSetAllowedPOST, common.PrivilegeManageUser)
r.POSTMethod("/api/v1/users/edit", v1.UserEditPOST, common.PrivilegeManageUser)
r.POSTMethod("/api/v1/users/wipe", v1.WipeUserPOST, common.PrivilegeManageUser)
r.POSTMethod("/api/v1/scores/reports", v1.ScoreReportPOST, common.PrivilegeManageUser)
// M E T A
// E T "wow thats so meta"
// T E -- the one who said "wow thats so meta"
// A T E M
r.Method("/api/v1/meta/restart", v1.MetaRestartGET, common.PrivilegeAPIMeta)
r.Method("/api/v1/meta/kill", v1.MetaKillGET, common.PrivilegeAPIMeta)
r.Method("/api/v1/meta/up_since", v1.MetaUpSinceGET, common.PrivilegeAPIMeta)
r.Method("/api/v1/meta/update", v1.MetaUpdateGET, common.PrivilegeAPIMeta)

View File

@ -5,11 +5,10 @@ import (
"crypto/sha256"
"database/sql"
"fmt"
"strings"
"time"
"github.com/jmoiron/sqlx"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
// GetTokenFull retrieves an user ID and their token privileges knowing their API token.
@ -87,7 +86,7 @@ func tokenUpdater(db *sqlx.DB) {
}
}
// BearerToken parses a Token guiven in the Authorization header, with the
// BearerToken parses a Token given in the Authorization header, with the
// Bearer prefix.
func BearerToken(token string, db *sqlx.DB) (common.Token, bool) {
var x struct {
@ -107,20 +106,7 @@ func BearerToken(token string, db *sqlx.DB) (common.Token, bool) {
t.UserID = x.Extra
t.Value = token
t.UserPrivileges = common.UserPrivileges(privs)
t.TokenPrivileges = oauthPrivileges(x.Scope).CanOnly(t.UserPrivileges)
t.TokenPrivileges = common.OAuthPrivileges(x.Scope).CanOnly(t.UserPrivileges)
return t, true
}
var privilegeMap = map[string]common.Privileges{
"read_confidential": common.PrivilegeReadConfidential,
"write": common.PrivilegeWrite,
}
func oauthPrivileges(scopes string) common.Privileges {
var p common.Privileges
for _, x := range strings.Split(scopes, " ") {
p |= privilegeMap[x]
}
return p
}

View File

@ -4,7 +4,7 @@ import (
"encoding/json"
"github.com/valyala/fasthttp"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
type response404 struct {

View File

@ -3,7 +3,7 @@ package v1
import (
"database/sql"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
type singleBadge struct {

View File

@ -3,7 +3,7 @@ package v1
import (
"database/sql"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
type difficulty struct {
@ -129,12 +129,13 @@ func getMultipleBeatmaps(md common.MethodData) common.CodeMessager {
Default: "id DESC",
Table: "beatmaps",
})
pm := md.Ctx.Request.URI().QueryArgs().PeekMulti
where := common.
Where("beatmap_id = ?", md.Query("bb")).
Where("beatmapset_id = ?", md.Query("s")).
Where("song_name = ?", md.Query("song_name")).
Where("beatmap_md5 = ?", md.Query("md5")).
Where("ranked_status_freezed = ?", md.Query("ranked_status_frozen"), "0", "1")
Where("ranked_status_freezed = ?", md.Query("ranked_status_frozen"), "0", "1").
In("beatmap_id", pm("bb")...).
In("beatmapset_id", pm("s")...).
In("beatmap_md5", pm("md5")...)
rows, err := md.DB.Query(baseBeatmapSelect+
where.Clause+" "+sort+" "+

View File

@ -6,8 +6,8 @@ import (
"strconv"
"time"
"zxq.co/ripple/rippleapi/common"
"zxq.co/ripple/rippleapi/limit"
"github.com/osuyozora/api/common"
"github.com/osuyozora/api/limit"
)
type rankRequestsStatusResponse struct {

View File

@ -10,7 +10,7 @@ import (
"strings"
"time"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
// This basically proxies requests from Medium's API and is used on Ripple's

465
app/v1/clan.go Normal file
View File

@ -0,0 +1,465 @@
package v1
import (
"database/sql"
"github.com/osuyozora/api/common"
"sort"
"fmt"
"strconv"
)
type singleClan struct {
ID int `json:"id,omitempty"`
Name string `json:"name"`
Description string `json:"description"`
Tag string `json:"tag"`
Icon string `json:"icon"`
}
type multiClanData struct {
common.ResponseBase
Clans []singleClan `json:"clans"`
}
// clansGET retrieves all the clans on this ripple instance.
func ClansGET(md common.MethodData) common.CodeMessager {
var (
r multiClanData
rows *sql.Rows
err error
)
if md.Query("id") != "" {
rows, err = md.DB.Query("SELECT id, name, description, tag, icon FROM clans WHERE id = ? LIMIT 1", md.Query("id"))
} else {
rows, err = md.DB.Query("SELECT id, name, description, tag, icon FROM clans " + common.Paginate(md.Query("p"), md.Query("l"), 50))
}
if err != nil {
md.Err(err)
return Err500
}
defer rows.Close()
for rows.Next() {
nc := singleClan{}
err = rows.Scan(&nc.ID, &nc.Name, &nc.Description, &nc.Tag, &nc.Icon)
if err != nil {
md.Err(err)
}
r.Clans = append(r.Clans, nc)
}
if err := rows.Err(); err != nil {
md.Err(err)
}
r.ResponseBase.Code = 200
return r
}
type clanMembersData struct {
common.ResponseBase
Members []userNotFullResponseLmao `json:"members"`
}
// get total stats of clan. later.
type totalStats struct {
common.ResponseBase
ClanID int `json:"id"`
ChosenMode modeData `json:"chosen_mode"`
Rank int `json:"rank"`
}
type clanLbSingle struct {
ID int `json:"id,omitempty"`
Name string `json:"name"`
Description string `json:"description"`
Tag string `json:"tag"`
Icon string `json:"icon"`
ChosenMode modeData `json:"chosen_mode"`
Rank int `json:"rank"`
}
type megaStats struct {
common.ResponseBase
Clans []clanLbSingle `json:"clans"`
}
func AllClanStatsGET(md common.MethodData) common.CodeMessager {
var (
r megaStats
rows *sql.Rows
err error
)
rows, err = md.DB.Query("SELECT id, name, description, icon FROM clans")
if err != nil {
fmt.Println("lol")
md.Err(err)
}
defer rows.Close()
for rows.Next() {
nc := clanLbSingle{}
err = rows.Scan(&nc.ID, &nc.Name, &nc.Description, &nc.Icon)
if err != nil {
md.Err(err)
}
nc.ChosenMode.PP = 0
r.Clans = append(r.Clans, nc)
}
if err := rows.Err(); err != nil {
fmt.Println("lol 2")
md.Err(err)
}
r.ResponseBase.Code = 200
// anyone who ever looks into this, yes, i need to kill myself. ~Flame
m, brr := strconv.ParseInt(string(md.Query("m")[19]), 10, 64)
if brr != nil {
fmt.Println("lol 3")
fmt.Println(brr)
m = 0
}
n := "std"
if m == 1 {
n = "taiko"
} else if m == 2 {
n = "ctb"
} else if m == 3 {
n = "mania"
} else {
n = "std"
}
fmt.Println(n)
for i := 0; i < len(r.Clans); i++ {
var members clanMembersData
rid := r.Clans[i].ID
err := md.DB.Select(&members.Members, `SELECT users.id, users.username, users.register_datetime, users.privileges,
latest_activity, users_stats.username_aka,
users_stats.country, users_stats.user_color,
users_stats.ranked_score_std, users_stats.total_score_std, users_stats.pp_std, users_stats.playcount_std, users_stats.replays_watched_std, users_stats.total_hits_std,
users_stats.ranked_score_taiko, users_stats.total_score_taiko, users_stats.pp_taiko, users_stats.playcount_taiko, users_stats.replays_watched_taiko, users_stats.total_hits_taiko,
users_stats.ranked_score_ctb, users_stats.total_score_ctb, users_stats.pp_ctb, users_stats.playcount_ctb, users_stats.replays_watched_ctb, users_stats.total_hits_ctb,
users_stats.ranked_score_mania, users_stats.total_score_mania, users_stats.pp_mania, users_stats.playcount_mania, users_stats.replays_watched_mania, users_stats.total_hits_mania
FROM user_clans uc
INNER JOIN users
ON users.id = uc.user
INNER JOIN users_stats ON users_stats.id = uc.user
WHERE clan = ? AND privileges & 1 = 1
`, rid)
if err != nil {
fmt.Println("lol 4")
fmt.Println(err)
}
members.Code = 200
if n == "std" {
fmt.Printf("%v", r.Clans)
for u := 0; u < len(members.Members); u++ {
r.Clans[i].ChosenMode.PP = r.Clans[i].ChosenMode.PP + members.Members[u].PpStd
r.Clans[i].ChosenMode.RankedScore = r.Clans[i].ChosenMode.RankedScore + members.Members[u].RankedScoreStd
r.Clans[i].ChosenMode.TotalScore = r.Clans[i].ChosenMode.TotalScore + members.Members[u].TotalScoreStd
r.Clans[i].ChosenMode.PlayCount = r.Clans[i].ChosenMode.PlayCount + members.Members[u].PlaycountStd
}
} else if n == "taiko" {
for u := 0; u < len(members.Members); u++ {
r.Clans[i].ChosenMode.PP = r.Clans[i].ChosenMode.PP + members.Members[u].PpTaiko
r.Clans[i].ChosenMode.RankedScore = r.Clans[i].ChosenMode.RankedScore + members.Members[u].RankedScoreTaiko
r.Clans[i].ChosenMode.TotalScore = r.Clans[i].ChosenMode.TotalScore + members.Members[u].TotalScoreTaiko
r.Clans[i].ChosenMode.PlayCount = r.Clans[i].ChosenMode.PlayCount + members.Members[u].PlaycountTaiko
}
} else if n == "ctb" {
for u := 0; u < len(members.Members); u++ {
r.Clans[i].ChosenMode.PP = r.Clans[i].ChosenMode.PP + members.Members[u].PpCtb
r.Clans[i].ChosenMode.RankedScore = r.Clans[i].ChosenMode.RankedScore + members.Members[u].RankedScoreCtb
r.Clans[i].ChosenMode.TotalScore = r.Clans[i].ChosenMode.TotalScore + members.Members[u].TotalScoreCtb
r.Clans[i].ChosenMode.PlayCount = r.Clans[i].ChosenMode.PlayCount + members.Members[u].PlaycountCtb
}
} else if n == "mania" {
for u := 0; u < len(members.Members); u++ {
r.Clans[i].ChosenMode.PP = r.Clans[i].ChosenMode.PP + members.Members[u].PpMania
r.Clans[i].ChosenMode.RankedScore = r.Clans[i].ChosenMode.RankedScore + members.Members[u].RankedScoreMania
r.Clans[i].ChosenMode.TotalScore = r.Clans[i].ChosenMode.TotalScore + members.Members[u].TotalScoreMania
r.Clans[i].ChosenMode.PlayCount = r.Clans[i].ChosenMode.PlayCount + members.Members[u].PlaycountMania
}
}
r.Clans[i].ChosenMode.PP = (r.Clans[i].ChosenMode.PP / (len(members.Members) + 1))
}
sort.Slice(r.Clans, func(i, j int) bool {
return r.Clans[i].ChosenMode.PP > r.Clans[j].ChosenMode.PP
})
for i := 0; i < len(r.Clans); i++ {
r.Clans[i].Rank = i+1
}
return r
}
func TotalClanStatsGET(md common.MethodData) common.CodeMessager {
var (
r megaStats
rows *sql.Rows
err error
)
rows, err = md.DB.Query("SELECT id, name, description, icon FROM clans")
if err != nil {
md.Err(err)
return Err500
}
defer rows.Close()
for rows.Next() {
nc := clanLbSingle{}
err = rows.Scan(&nc.ID, &nc.Name, &nc.Description, &nc.Icon)
if err != nil {
md.Err(err)
}
nc.ChosenMode.PP = 0
r.Clans = append(r.Clans, nc)
}
if err := rows.Err(); err != nil {
md.Err(err)
}
r.ResponseBase.Code = 200
id := common.Int(md.Query("id"))
if id == 0 {
return ErrMissingField("id")
}
//RETARD CODE HAHAAAA
m, brr := strconv.ParseInt(string(md.Query("m")[11]), 10, 64)
if brr != nil {
fmt.Println(brr)
}
n := "std"
if m == 1 {
n = "taiko"
} else if m == 2 {
n = "ctb"
} else if m == 3 {
n = "mania"
} else {
n = "std"
}
fmt.Println(n)
for i := 0; i < len(r.Clans); i++ {
var members clanMembersData
rid := r.Clans[i].ID
err := md.DB.Select(&members.Members, `SELECT users.id, users.username, users.register_datetime, users.privileges,
latest_activity, users_stats.username_aka,
users_stats.country, users_stats.user_color,
users_stats.ranked_score_std, users_stats.total_score_std, users_stats.pp_std, users_stats.playcount_std, users_stats.replays_watched_std, users_stats.total_hits_std,
users_stats.ranked_score_taiko, users_stats.total_score_taiko, users_stats.pp_taiko, users_stats.playcount_taiko, users_stats.replays_watched_taiko, users_stats.total_hits_taiko,
users_stats.ranked_score_ctb, users_stats.total_score_ctb, users_stats.pp_ctb, users_stats.playcount_ctb, users_stats.replays_watched_ctb, users_stats.total_hits_ctb,
users_stats.ranked_score_mania, users_stats.total_score_mania, users_stats.pp_mania, users_stats.playcount_mania, users_stats.replays_watched_mania, users_stats.total_hits_mania
FROM user_clans uc
INNER JOIN users
ON users.id = uc.user
INNER JOIN users_stats ON users_stats.id = uc.user
WHERE clan = ? AND privileges & 1 = 1
`, rid)
if err != nil {
fmt.Println(err)
}
members.Code = 200
if n == "std" {
for u := 0; u < len(members.Members); u++ {
r.Clans[i].ChosenMode.PP = r.Clans[i].ChosenMode.PP + members.Members[u].PpStd
r.Clans[i].ChosenMode.RankedScore = r.Clans[i].ChosenMode.RankedScore + members.Members[u].RankedScoreStd
r.Clans[i].ChosenMode.TotalScore = r.Clans[i].ChosenMode.TotalScore + members.Members[u].TotalScoreStd
r.Clans[i].ChosenMode.PlayCount = r.Clans[i].ChosenMode.PlayCount + members.Members[u].PlaycountStd
r.Clans[i].ChosenMode.ReplaysWatched = r.Clans[i].ChosenMode.ReplaysWatched + members.Members[u].ReplaysWatchedStd
r.Clans[i].ChosenMode.TotalHits = r.Clans[i].ChosenMode.TotalHits + members.Members[u].TotalHitsStd
}
} else if n == "taiko" {
for u := 0; u < len(members.Members); u++ {
r.Clans[i].ChosenMode.PP = r.Clans[i].ChosenMode.PP + members.Members[u].PpTaiko
r.Clans[i].ChosenMode.RankedScore = r.Clans[i].ChosenMode.RankedScore + members.Members[u].RankedScoreTaiko
r.Clans[i].ChosenMode.TotalScore = r.Clans[i].ChosenMode.TotalScore + members.Members[u].TotalScoreTaiko
r.Clans[i].ChosenMode.PlayCount = r.Clans[i].ChosenMode.PlayCount + members.Members[u].PlaycountTaiko
r.Clans[i].ChosenMode.ReplaysWatched = r.Clans[i].ChosenMode.ReplaysWatched + members.Members[u].ReplaysWatchedTaiko
r.Clans[i].ChosenMode.TotalHits = r.Clans[i].ChosenMode.TotalHits + members.Members[u].TotalHitsTaiko
}
} else if n == "ctb" {
for u := 0; u < len(members.Members); u++ {
r.Clans[i].ChosenMode.PP = r.Clans[i].ChosenMode.PP + members.Members[u].PpCtb
r.Clans[i].ChosenMode.RankedScore = r.Clans[i].ChosenMode.RankedScore + members.Members[u].RankedScoreCtb
r.Clans[i].ChosenMode.TotalScore = r.Clans[i].ChosenMode.TotalScore + members.Members[u].TotalScoreCtb
r.Clans[i].ChosenMode.PlayCount = r.Clans[i].ChosenMode.PlayCount + members.Members[u].PlaycountCtb
r.Clans[i].ChosenMode.ReplaysWatched = r.Clans[i].ChosenMode.ReplaysWatched + members.Members[u].ReplaysWatchedCtb
r.Clans[i].ChosenMode.TotalHits = r.Clans[i].ChosenMode.TotalHits + members.Members[u].TotalHitsStd
}
} else if n == "mania" {
for u := 0; u < len(members.Members); u++ {
r.Clans[i].ChosenMode.PP = r.Clans[i].ChosenMode.PP + members.Members[u].PpMania
r.Clans[i].ChosenMode.RankedScore = r.Clans[i].ChosenMode.RankedScore + members.Members[u].RankedScoreMania
r.Clans[i].ChosenMode.TotalScore = r.Clans[i].ChosenMode.TotalScore + members.Members[u].TotalScoreMania
r.Clans[i].ChosenMode.PlayCount = r.Clans[i].ChosenMode.PlayCount + members.Members[u].PlaycountMania
r.Clans[i].ChosenMode.ReplaysWatched = r.Clans[i].ChosenMode.ReplaysWatched + members.Members[u].ReplaysWatchedMania
r.Clans[i].ChosenMode.TotalHits = r.Clans[i].ChosenMode.TotalHits + members.Members[u].TotalHitsMania
}
}
r.Clans[i].ChosenMode.PP = (r.Clans[i].ChosenMode.PP / (len(members.Members) + 1))
}
sort.Slice(r.Clans, func(i, j int) bool {
return r.Clans[i].ChosenMode.PP > r.Clans[j].ChosenMode.PP
})
for i := 0; i < len(r.Clans); i++ {
r.Clans[i].Rank = i+1
}
b := totalStats{}
for i := 0; i < len(r.Clans); i++ {
if r.Clans[i].ID == id {
b.ClanID = id
b.ChosenMode.PP = r.Clans[i].ChosenMode.PP
b.ChosenMode.RankedScore = r.Clans[i].ChosenMode.RankedScore
b.ChosenMode.TotalScore = r.Clans[i].ChosenMode.TotalScore
b.ChosenMode.PlayCount = r.Clans[i].ChosenMode.PlayCount
b.ChosenMode.ReplaysWatched = r.Clans[i].ChosenMode.ReplaysWatched
b.ChosenMode.TotalHits = r.Clans[i].ChosenMode.TotalHits
b.Rank = r.Clans[i].Rank
b.Code = 200
}
}
return b
}
type isClanData struct {
Clan int `json:"clan"`
User int `json:"user"`
Perms int `json:"perms"`
}
type isClan struct {
common.ResponseBase
Clan isClanData `json:"clan"`
}
func IsInClanGET(md common.MethodData) common.CodeMessager {
ui := md.Query("uid")
if ui == "0" {
return ErrMissingField("uid")
}
var r isClan
rows, err := md.DB.Query("SELECT user, clan, perms FROM user_clans WHERE user = ?", ui)
if err != nil {
md.Err(err)
return Err500
}
defer rows.Close()
for rows.Next() {
nc := isClanData{}
err = rows.Scan(&nc.User, &nc.Clan, &nc.Perms)
if err != nil {
md.Err(err)
}
r.Clan = nc
}
if err := rows.Err(); err != nil {
md.Err(err)
}
r.ResponseBase.Code = 200
return r
}
type imRetarded struct {
common.ResponseBase
Invite string `json:"invite"`
}
func ClanInviteGET(md common.MethodData) common.CodeMessager {
// big perms check lol ok
n := common.Int(md.Query("id"))
var r imRetarded
var clan int
// get user clan, then get invite
md.DB.QueryRow("SELECT clan FROM user_clans WHERE user = ? LIMIT 1", n).Scan(&clan)
row := md.DB.QueryRow("SELECT invite FROM clans_invites WHERE clan = ? LIMIT 1", clan).Scan(&r.Invite)
if row != nil {
fmt.Println(row)
}
return r
}
// ClanMembersGET retrieves the people who are in a certain clan.
func ClanMembersGET(md common.MethodData) common.CodeMessager {
i := common.Int(md.Query("id"))
if i == 0 {
return ErrMissingField("id")
}
r := common.Int(md.Query("r"))
if r == 0 {
var members clanMembersData
err := md.DB.Select(&members.Members, `SELECT users.id, users.username, users.register_datetime, users.privileges,
latest_activity, users_stats.username_aka,
users_stats.country, users_stats.user_color,
users_stats.ranked_score_std, users_stats.total_score_std, users_stats.pp_std, users_stats.playcount_std, users_stats.replays_watched_std, users_stats.total_hits_std,
users_stats.ranked_score_taiko, users_stats.total_score_taiko, users_stats.pp_taiko, users_stats.playcount_taiko, users_stats.replays_watched_taiko, users_stats.total_hits_taiko
FROM user_clans uc
INNER JOIN users
ON users.id = uc.user
INNER JOIN users_stats ON users_stats.id = uc.user
WHERE clan = ?
ORDER BY id ASC `, i)
if err != nil {
md.Err(err)
return Err500
}
members.Code = 200
return members
} else {
var members clanMembersData
err := md.DB.Select(&members.Members, `SELECT users.id, users.username, users.register_datetime, users.privileges,
latest_activity, users_stats.username_aka,
users_stats.country, users_stats.user_color,
users_stats.ranked_score_std, users_stats.total_score_std, users_stats.pp_std, users_stats.playcount_std, users_stats.replays_watched_std,
users_stats.ranked_score_taiko, users_stats.total_score_taiko, users_stats.pp_taiko, users_stats.playcount_taiko, users_stats.replays_watched_taiko
FROM user_clans uc
INNER JOIN users
ON users.id = uc.user
INNER JOIN users_stats ON users_stats.id = uc.user
WHERE clan = ? AND perms = ?
ORDER BY id ASC `, i, r)
if err != nil {
md.Err(err)
return Err500
}
members.Code = 200
return members
}
}

View File

@ -3,7 +3,7 @@ package v1
import (
"strings"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
// Boilerplate errors

View File

@ -3,7 +3,7 @@ package v1
import (
"database/sql"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
type friendData struct {

View File

@ -10,7 +10,7 @@ import (
redis "gopkg.in/redis.v5"
"zxq.co/ripple/ocl"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
type leaderboardUser struct {
@ -39,6 +39,36 @@ FROM users
INNER JOIN users_stats ON users_stats.id = users.id
WHERE users.id IN (?)
`
const lbUserQueryRx = `
SELECT
users.id, users.username, users.register_datetime, users.privileges, users.latest_activity,
users_stats.username_aka, users_stats.country,
users_stats.play_style, users_stats.favourite_mode,
users_stats.ranked_score_%[1]s_rx, users_stats.total_score_%[1]s_rx, users_stats.playcount_%[1]s_rx,
users_stats.replays_watched_%[1]s, users_stats.total_hits_%[1]s,
users_stats.avg_accuracy_%[1]s_rx, users_stats.pp_%[1]s_rx
FROM users
INNER JOIN users_stats ON users_stats.id = users.id
WHERE users.id IN (?)
`
const lbUserQueryAp = `
SELECT
users.id, users.username, users.register_datetime, users.privileges, users.latest_activity,
users_stats.username_aka, users_stats.country,
users_stats.play_style, users_stats.favourite_mode,
users_stats.ranked_score_%[1]s_ap, users_stats.total_score_%[1]s_ap, users_stats.playcount_%[1]s_ap,
users_stats.replays_watched_%[1]s, users_stats.total_hits_%[1]s,
users_stats.avg_accuracy_%[1]s_ap, users_stats.pp_%[1]s_auto
FROM users
INNER JOIN users_stats ON users_stats.id = users.id
WHERE users.id IN (?) AND users.privileges >= 3
`
// LeaderboardGET gets the leaderboard.
func LeaderboardGET(md common.MethodData) common.CodeMessager {
@ -119,3 +149,147 @@ func _position(r *redis.Client, key string, user int) *int {
x := int(res.Val()) + 1
return &x
}
// LeaderboardGET gets the leaderboard.
func LeaderboardRxGET(md common.MethodData) common.CodeMessager {
m := getMode(md.Query("mode"))
// md.Query.Country
p := common.Int(md.Query("p")) - 1
if p < 0 {
p = 0
}
l := common.InString(1, md.Query("l"), 500, 50)
key := "ripple:leaderboard_relax:" + m
if md.Query("country") != "" {
key += ":" + md.Query("country")
}
results, err := md.R.ZRevRange(key, int64(p*l), int64(p*l+l-1)).Result()
if err != nil {
md.Err(err)
return Err500
}
var resp leaderboardResponse
resp.Code = 200
if len(results) == 0 {
return resp
}
query := fmt.Sprintf(lbUserQueryRx+` ORDER BY users_stats.pp_%[1]s_rx DESC, users_stats.ranked_score_%[1]s_rx DESC`, m)
query, params, _ := sqlx.In(query, results)
rows, err := md.DB.Query(query, params...)
if err != nil {
md.Err(err)
return Err500
}
for rows.Next() {
var u leaderboardUser
err := rows.Scan(
&u.ID, &u.Username, &u.RegisteredOn, &u.Privileges, &u.LatestActivity,
&u.UsernameAKA, &u.Country, &u.PlayStyle, &u.FavouriteMode,
&u.ChosenMode.RankedScore, &u.ChosenMode.TotalScore, &u.ChosenMode.PlayCount,
&u.ChosenMode.ReplaysWatched, &u.ChosenMode.TotalHits,
&u.ChosenMode.Accuracy, &u.ChosenMode.PP,
)
if err != nil {
md.Err(err)
continue
}
u.ChosenMode.Level = ocl.GetLevelPrecise(int64(u.ChosenMode.TotalScore))
if i := leaderboardPositionRx(md.R, m, u.ID); i != nil {
u.ChosenMode.GlobalLeaderboardRank = i
}
if i := countryPositionRx(md.R, m, u.ID, u.Country); i != nil {
u.ChosenMode.CountryLeaderboardRank = i
}
resp.Users = append(resp.Users, u)
}
return resp
}
// LeaderboardGET gets the leaderboard.
func LeaderboardApGET(md common.MethodData) common.CodeMessager {
m := getMode(md.Query("mode"))
// md.Query.Country
p := common.Int(md.Query("p")) - 1
if p < 0 {
p = 0
}
l := common.InString(1, md.Query("l"), 500, 50)
key := "ripple:leaderboard_auto:" + m
if md.Query("country") != "" {
key += ":" + md.Query("country")
}
results, err := md.R.ZRevRange(key, int64(p*l), int64(p*l+l-1)).Result()
if err != nil {
md.Err(err)
return Err500
}
var resp leaderboardResponse
resp.Code = 200
if len(results) == 0 {
return resp
}
query := fmt.Sprintf(lbUserQueryAp+` ORDER BY users_stats.pp_%[1]s_auto DESC, users_stats.ranked_score_%[1]s_ap DESC`, m)
query, params, _ := sqlx.In(query, results)
rows, err := md.DB.Query(query, params...)
if err != nil {
md.Err(err)
return Err500
}
for rows.Next() {
var u leaderboardUser
err := rows.Scan(
&u.ID, &u.Username, &u.RegisteredOn, &u.Privileges, &u.LatestActivity,
&u.UsernameAKA, &u.Country, &u.PlayStyle, &u.FavouriteMode,
&u.ChosenMode.RankedScore, &u.ChosenMode.TotalScore, &u.ChosenMode.PlayCount,
&u.ChosenMode.ReplaysWatched, &u.ChosenMode.TotalHits,
&u.ChosenMode.Accuracy, &u.ChosenMode.PP,
)
if err != nil {
md.Err(err)
continue
}
u.ChosenMode.Level = ocl.GetLevelPrecise(int64(u.ChosenMode.TotalScore))
if i := leaderboardPositionAp(md.R, m, u.ID); i != nil {
u.ChosenMode.GlobalLeaderboardRank = i
}
if i := countryPositionAp(md.R, m, u.ID, u.Country); i != nil {
u.ChosenMode.CountryLeaderboardRank = i
}
resp.Users = append(resp.Users, u)
}
return resp
}
func leaderboardPositionRx(r *redis.Client, mode string, user int) *int {
return _position(r, "ripple:leaderboard_relax:"+mode, user)
}
func countryPositionRx(r *redis.Client, mode string, user int, country string) *int {
return _position(r, "ripple:leaderboard_relax:"+mode+":"+strings.ToLower(country), user)
}
func leaderboardPositionAp(r *redis.Client, mode string, user int) *int {
return _position(r, "ripple:leaderboard_auto:"+mode, user)
}
func countryPositionAp(r *redis.Client, mode string, user int, country string) *int {
return _position(r, "ripple:leaderboard_auto:"+mode+":"+strings.ToLower(country), user)
}

View File

@ -1,9 +1,15 @@
package v1
import (
"database/sql"
"encoding/json"
"fmt"
"strconv"
"strings"
"time"
"zxq.co/ripple/rippleapi/common"
redis "gopkg.in/redis.v5"
"github.com/osuyozora/api/common"
)
type setAllowedData struct {
@ -13,7 +19,7 @@ type setAllowedData struct {
// UserManageSetAllowedPOST allows to set the allowed status of an user.
func UserManageSetAllowedPOST(md common.MethodData) common.CodeMessager {
data := setAllowedData{}
var data setAllowedData
if err := md.Unmarshal(&data); err != nil {
return ErrBadJSON
}
@ -34,6 +40,7 @@ func UserManageSetAllowedPOST(md common.MethodData) common.CodeMessager {
md.Err(err)
return Err500
}
rapLog(md, fmt.Sprintf("changed UserID:%d's allowed to %d. This was done using the API's terrible ManageSetAllowed.", data.UserID, data.Allowed))
go fixPrivileges(data.UserID, md.DB)
query := `
SELECT users.id, users.username, register_datetime, privileges,
@ -46,3 +53,249 @@ WHERE users.id=?
LIMIT 1`
return userPutsSingle(md, md.DB.QueryRowx(query, data.UserID))
}
type userEditData struct {
ID int `json:"id"`
Username *string `json:"username"`
UsernameAKA *string `json:"username_aka"`
Privileges *uint64 `json:"privileges"`
Country *string `json:"country"`
SilenceInfo *silenceInfo `json:"silence_info"`
ResetUserpage bool `json:"reset_userpage"`
//ResetAvatar bool `json:"reset_avatar"`
}
var privChangeList = [...]string{
"banned",
"locked",
"restricted",
"removed all restrictions on",
}
// UserEditPOST allows to edit an user's information.
func UserEditPOST(md common.MethodData) common.CodeMessager {
var data userEditData
if err := md.Unmarshal(&data); err != nil {
fmt.Println(err)
return ErrBadJSON
}
if data.ID == 0 {
return common.SimpleResponse(404, "That user could not be found")
}
var prevUser struct {
Username string
Privileges uint64
}
err := md.DB.Get(&prevUser, "SELECT username, privileges FROM users WHERE id = ? LIMIT 1", data.ID)
switch err {
case nil: // carry on
case sql.ErrNoRows:
return common.SimpleResponse(404, "That user could not be found")
default:
md.Err(err)
return Err500
}
const initQuery = "UPDATE users SET\n"
q := initQuery
var args []interface{}
// totally did not realise I had to update some fields in users_stats as well
// and just copy pasting the above code by prefixing "stats" to every
// variable
const statsInitQuery = "UPDATE users_stats SET\n"
statsQ := statsInitQuery
var statsArgs []interface{}
if common.UserPrivileges(prevUser.Privileges)&common.AdminPrivilegeManageUsers != 0 &&
data.ID != md.User.UserID {
return common.SimpleResponse(403, "Can't edit that user")
}
var isBanned bool
if data.Privileges != nil {
// If we want to modify privileges other than Normal/Public, we need to have
// the right privilege ourselves and AdminManageUsers won't suffice.
if (*data.Privileges&^3) != (prevUser.Privileges&^3) &&
md.User.UserPrivileges&common.AdminPrivilegeManagePrivilege == 0 {
return common.SimpleResponse(403, "Can't modify user privileges without AdminManagePrivileges")
}
q += "privileges = ?,\n"
args = append(args, *data.Privileges)
// UserPublic became 0, so banned or restricted
const uPublic = uint64(common.UserPrivilegePublic)
if *data.Privileges&uPublic == 0 && prevUser.Privileges&uPublic != 0 {
q += "ban_datetime = ?,\n"
args = append(args, time.Now().Unix())
isBanned = true
}
// If we modified other privileges apart from Normal and Public, we use a generic
// "changed user's privileges". Otherwise, we are more descriptive.
if *data.Privileges^prevUser.Privileges > 3 {
rapLog(md, fmt.Sprintf("has changed %s's privileges", prevUser.Username))
} else {
rapLog(md, fmt.Sprintf("has %s %s", privChangeList[*data.Privileges&3], prevUser.Username))
}
}
if data.Username != nil {
if strings.Contains(*data.Username, " ") && strings.Contains(*data.Username, "_") {
return common.SimpleResponse(400, "Mixed spaces and underscores")
}
if usernameAvailable(md, *data.Username, data.ID) {
return common.SimpleResponse(409, "User with that username exists")
}
jsonData, _ := json.Marshal(struct {
UserID int `json:"userID"`
NewUsername string `json:"newUsername"`
}{data.ID, *data.Username})
md.R.Publish("peppy:change_username", string(jsonData))
}
if data.UsernameAKA != nil {
statsQ += "username_aka = ?,\n"
statsArgs = append(statsArgs, *data.UsernameAKA)
}
if data.Country != nil {
statsQ += "country = ?,\n"
statsArgs = append(statsArgs, *data.Country)
rapLog(md, fmt.Sprintf("has changed %s country to %s", prevUser.Username, *data.Country))
appendToUserNotes(md, "country changed to "+*data.Country, data.ID)
}
if data.SilenceInfo != nil && md.User.UserPrivileges&common.AdminPrivilegeSilenceUsers != 0 {
q += "silence_end = ?, silence_reason = ?,\n"
args = append(args, time.Time(data.SilenceInfo.End).Unix(), data.SilenceInfo.Reason)
}
if data.ResetUserpage {
statsQ += "userpage_content = '',\n"
}
if q != initQuery {
q = q[:len(q)-2] + " WHERE id = ? LIMIT 1"
args = append(args, data.ID)
_, err = md.DB.Exec(q, args...)
if err != nil {
md.Err(err)
return Err500
}
}
if statsQ != statsInitQuery {
statsQ = statsQ[:len(statsQ)-2] + " WHERE id = ? LIMIT 1"
statsArgs = append(statsArgs, data.ID)
_, err = md.DB.Exec(statsQ, statsArgs...)
if err != nil {
md.Err(err)
return Err500
}
}
if isBanned {
if err := updateBanBancho(md.R, data.ID); err != nil {
md.Err(err)
return Err500
}
}
rapLog(md, fmt.Sprintf("has updated user %s", prevUser.Username))
return userPutsSingle(md, md.DB.QueryRowx(userFields+" WHERE users.id = ? LIMIT 1", data.ID))
}
func updateBanBancho(r *redis.Client, user int) error {
return r.Publish("peppy:ban", strconv.Itoa(user)).Err()
}
type wipeUserData struct {
ID int `json:"id"`
Modes []int `json:"modes"`
}
// WipeUserPOST wipes an user's scores.
func WipeUserPOST(md common.MethodData) common.CodeMessager {
var data wipeUserData
if err := md.Unmarshal(&data); err != nil {
return ErrBadJSON
}
if data.ID == 0 {
return ErrMissingField("id")
}
if len(data.Modes) == 0 {
return ErrMissingField("modes")
}
var userData struct {
Username string
Privileges uint64
}
err := md.DB.Get(&userData, "SELECT username, privileges FROM users WHERE id = ?", data.ID)
switch err {
case sql.ErrNoRows:
return common.SimpleResponse(404, "That user could not be found!")
case nil: // carry on
default:
md.Err(err)
return Err500
}
if common.UserPrivileges(userData.Privileges)&common.AdminPrivilegeManageUsers != 0 {
return common.SimpleResponse(403, "Can't edit that user")
}
tx, err := md.DB.Beginx()
if err != nil {
md.Err(err)
return Err500
}
for _, mode := range data.Modes {
if mode < 0 || mode > 3 {
continue
}
_, err = tx.Exec("INSERT INTO scores_removed SELECT * FROM scores WHERE userid = ? AND play_mode = ?", data.ID, mode)
if err != nil {
md.Err(err)
}
_, err = tx.Exec("DELETE FROM scores WHERE userid = ? AND play_mode = ?", data.ID, mode)
if err != nil {
md.Err(err)
}
_, err = tx.Exec(strings.Replace(
`UPDATE users_stats SET total_score_MODE = 0, ranked_score_MODE = 0, replays_watched_MODE = 0,
playcount_MODE = 0, avg_accuracy_MODE = 0, total_hits_MODE = 0, level_MODE = 0, pp_MODE = 0
WHERE id = ?`, "MODE", modesToReadable[mode], -1,
), data.ID)
if err != nil {
md.Err(err)
}
}
if err = tx.Commit(); err != nil {
md.Err(err)
return Err500
}
rapLog(md, fmt.Sprintf("has wiped %s's account", userData.Username))
return userPutsSingle(md, md.DB.QueryRowx(userFields+" WHERE users.id = ? LIMIT 1", data.ID))
}
func appendToUserNotes(md common.MethodData, message string, user int) {
message = "\n[" + time.Now().Format("2006-01-02 15:04:05") + "] API: " + message
_, err := md.DB.Exec("UPDATE users SET notes = CONCAT(COALESCE(notes, ''), ?) WHERE id = ?",
message, user)
if err != nil {
md.Err(err)
}
}
func usernameAvailable(md common.MethodData, u string, userID int) (r bool) {
err := md.DB.QueryRow("SELECT EXISTS(SELECT 1 FROM users WHERE username_safe = ? AND id != ?)", common.SafeUsername(u), userID).Scan(&r)
if err != nil && err != sql.ErrNoRows {
md.Err(err)
}
return
}

View File

@ -5,7 +5,6 @@
package v1
import (
"fmt"
"io"
"io/ioutil"
"log"
@ -14,7 +13,7 @@ import (
"syscall"
"time"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
// MetaRestartGET restarts the API with Zero Downtime™.
@ -30,26 +29,6 @@ func MetaRestartGET(md common.MethodData) common.CodeMessager {
return common.SimpleResponse(200, "brb")
}
// MetaKillGET kills the API process. NOTE TO EVERYONE: NEVER. EVER. USE IN PROD.
// Mainly created because I couldn't bother to fire up a terminal, do htop and kill the API each time.
func MetaKillGET(md common.MethodData) common.CodeMessager {
proc, err := os.FindProcess(syscall.Getpid())
if err != nil {
return common.SimpleResponse(500, "couldn't find process. what the fuck?")
}
const form = "02/01/2006"
r := common.ResponseBase{
Code: 200,
Message: fmt.Sprintf("RIP ripple API %s - %s", upSince.Format(form), time.Now().Format(form)),
}
// yes
go func() {
time.Sleep(time.Second)
proc.Kill()
}()
return r
}
var upSince = time.Now()
type metaUpSinceResponse struct {

View File

@ -5,7 +5,7 @@ package v1
import (
"time"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
// MetaRestartGET restarts the API with Zero Downtime™.

View File

@ -4,7 +4,7 @@ import (
"math/rand"
"time"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
var rn = rand.New(rand.NewSource(time.Now().UnixNano()))

87
app/v1/rap.go Normal file
View File

@ -0,0 +1,87 @@
package v1
import (
"fmt"
"time"
"github.com/osuyozora/api/common"
)
type rapLogData struct {
Through string `json:"through"`
Text string `json:"text"`
}
type rapLogMessage struct {
rapLogData
Author int `json:"author"`
CreatedAt time.Time `json:"created_at"`
}
type rapLogResponse struct {
common.ResponseBase
rapLogMessage
}
// RAPLogPOST creates a new entry in the RAP logs
func RAPLogPOST(md common.MethodData) common.CodeMessager {
if md.User.UserPrivileges&common.AdminPrivilegeAccessRAP == 0 {
return common.SimpleResponse(403, "Got lost, kiddo?")
}
var d rapLogData
if err := md.Unmarshal(&d); err != nil {
fmt.Println(err)
return ErrBadJSON
}
if d.Text == "" {
return ErrMissingField("text")
}
if d.Through == "" {
ua := string(md.Ctx.UserAgent())
if len(ua) > 20 {
ua = ua[:20] + "…"
}
d.Through = "API"
if ua != "" {
d.Through += " (" + ua + ")"
}
}
if len(d.Through) > 30 {
d.Through = d.Through[:30]
}
created := time.Now()
_, err := md.DB.Exec("INSERT INTO rap_logs(userid, text, datetime, through) VALUES (?, ?, ?, ?)",
md.User.UserID, d.Text, created.Unix(), d.Through)
if err != nil {
md.Err(err)
return Err500
}
var resp rapLogResponse
resp.rapLogData = d
resp.Author = md.User.UserID
resp.CreatedAt = created.Truncate(time.Second)
resp.Code = 200
return resp
}
func rapLog(md common.MethodData, message string) {
ua := string(md.Ctx.UserAgent())
if len(ua) > 20 {
ua = ua[:20] + "…"
}
through := "API"
if ua != "" {
through += " (" + ua + ")"
}
_, err := md.DB.Exec("INSERT INTO rap_logs(userid, text, datetime, through) VALUES (?, ?, ?, ?)",
md.User.UserID, message, time.Now().Unix(), through)
if err != nil {
md.Err(err)
}
}

View File

@ -2,12 +2,13 @@ package v1
import (
"database/sql"
"encoding/json"
"fmt"
"strconv"
"strings"
"gopkg.in/thehowl/go-osuapi.v1"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
"zxq.co/x/getrank"
)
@ -48,14 +49,16 @@ type scoresResponse struct {
// ScoresGET retrieves the top scores for a certain beatmap.
func ScoresGET(md common.MethodData) common.CodeMessager {
var (
beatmapMD5 string
r scoresResponse
where = new(common.WhereClause)
r scoresResponse
)
pm := md.Ctx.Request.URI().QueryArgs().PeekMulti
switch {
case md.Query("md5") != "":
beatmapMD5 = md.Query("md5")
where.In("beatmap_md5", pm("md5")...)
case md.Query("b") != "":
err := md.DB.Get(&beatmapMD5, "SELECT beatmap_md5 FROM beatmaps WHERE beatmap_id = ? LIMIT 1", md.Query("b"))
var md5 string
err := md.DB.Get(&md5, "SELECT beatmap_md5 FROM beatmaps WHERE beatmap_id = ? LIMIT 1", md.Query("b"))
switch {
case err == sql.ErrNoRows:
r.Code = 200
@ -64,15 +67,22 @@ func ScoresGET(md common.MethodData) common.CodeMessager {
md.Err(err)
return Err500
}
default:
return ErrMissingField("md5|b")
where.Where("beatmap_md5 = ?", md5)
}
where.In("scores.id", pm("id")...)
sort := common.Sort(md, common.SortConfiguration{
Default: "scores.pp DESC, scores.score DESC",
Table: "scores",
Allowed: []string{"pp", "score", "accuracy", "id"},
})
if where.Clause == "" {
return ErrMissingField("must specify at least one queried item")
}
where.Where(` scores.completed = '3' AND `+md.User.OnlyUserPublic(false)+` `+
genModeClause(md)+` `+sort+common.Paginate(md.Query("p"), md.Query("l"), 100), "FIF")
where.Params = where.Params[:len(where.Params)-1]
rows, err := md.DB.Query(`
SELECT
@ -88,9 +98,7 @@ SELECT
FROM scores
INNER JOIN users ON users.id = scores.userid
INNER JOIN users_stats ON users_stats.id = scores.userid
WHERE scores.beatmap_md5 = ? AND scores.completed = '3' AND `+md.User.OnlyUserPublic(true)+
` `+genModeClause(md)+`
`+sort+common.Paginate(md.Query("p"), md.Query("l"), 100), beatmapMD5)
`+where.Clause, where.Params...)
if err != nil {
md.Err(err)
return Err500
@ -131,6 +139,111 @@ WHERE scores.beatmap_md5 = ? AND scores.completed = '3' AND `+md.User.OnlyUserPu
return r
}
type scoreReportData struct {
ScoreID int `json:"score_id"`
Data json.RawMessage `json:"data"`
Anticheat string `json:"anticheat"`
Severity float32 `json:"severity"`
}
type scoreReport struct {
ID int `json:"id"`
scoreReportData
}
type scoreReportResponse struct {
common.ResponseBase
scoreReport
}
// ScoreReportPOST creates a new report for a score
func ScoreReportPOST(md common.MethodData) common.CodeMessager {
var data scoreReportData
err := md.Unmarshal(&data)
if err != nil {
return ErrBadJSON
}
// Check if there are any missing fields
var missingFields []string
if data.ScoreID == 0 {
missingFields = append(missingFields, "score_id")
}
if data.Anticheat == "" {
missingFields = append(missingFields, "anticheat")
}
if len(missingFields) > 0 {
return ErrMissingField(missingFields...)
}
tx, err := md.DB.Beginx()
if err != nil {
md.Err(err)
return Err500
}
// Get anticheat ID
var id int
err = tx.Get(&id, "SELECT id FROM anticheats WHERE name = ? LIMIT 1", data.Anticheat)
switch err {
case nil: // carry on
case sql.ErrNoRows:
// Create anticheat!
res, err := tx.Exec("INSERT INTO anticheats (name) VALUES (?);", data.Anticheat)
if err != nil {
md.Err(err)
return Err500
}
lid, err := res.LastInsertId()
if err != nil {
md.Err(err)
return Err500
}
id = int(lid)
default:
md.Err(err)
return Err500
}
d := sql.NullString{String: string(data.Data), Valid: true}
if d.String == "null" || d.String == `""` ||
d.String == "[]" || d.String == "{}" || d.String == "0" {
d.Valid = false
}
res, err := tx.Exec("INSERT INTO anticheat_reports (score_id, anticheat_id, data, severity) VALUES (?, ?, ?, ?)",
data.ScoreID, id, d, data.Severity)
if err != nil {
md.Err(err)
return Err500
}
lid, err := res.LastInsertId()
if err != nil {
md.Err(err)
return Err500
}
err = tx.Commit()
if err != nil {
md.Err(err)
return Err500
}
if !d.Valid {
data.Data = json.RawMessage("null")
}
repData := scoreReportResponse{
scoreReport: scoreReport{
ID: int(lid),
scoreReportData: data,
},
}
repData.Code = 200
return repData
}
func getMode(m string) string {
switch m {
case "1":
@ -154,3 +267,25 @@ func genModeClause(md common.MethodData) string {
}
return modeClause
}
func genModeClauseRx(md common.MethodData) string {
var modeClause string
if md.Query("mode") != "" {
m, err := strconv.Atoi(md.Query("mode"))
if err == nil && m >= 0 && m <= 3 {
modeClause = fmt.Sprintf("AND scores_relax.play_mode = '%d'", m)
}
}
return modeClause
}
func genModeClauseAp(md common.MethodData) string {
var modeClause string
if md.Query("mode") != "" {
m, err := strconv.Atoi(md.Query("mode"))
if err == nil && m >= 0 && m <= 3 {
modeClause = fmt.Sprintf("AND scores_auto.play_mode = '%d'", m)
}
}
return modeClause
}

View File

@ -3,7 +3,7 @@ package v1
import (
"strings"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
"zxq.co/ripple/semantic-icons-ugc"
)

View File

@ -3,7 +3,6 @@ package v1
import (
"crypto/md5"
"crypto/sha256"
"database/sql"
"encoding/json"
"errors"
"fmt"
@ -12,131 +11,10 @@ import (
"github.com/jmoiron/sqlx"
"golang.org/x/crypto/bcrypt"
"zxq.co/ripple/rippleapi/common"
"zxq.co/ripple/rippleapi/limit"
"github.com/osuyozora/api/common"
"zxq.co/ripple/schiavolib"
)
type tokenNewInData struct {
// either username or userid must be given in the request.
// if none is given, the request is trashed.
Username string `json:"username"`
UserID int `json:"id"`
Password string `json:"password"`
Privileges int `json:"privileges"`
Description string `json:"description"`
}
type tokenNewResponse struct {
common.ResponseBase
Username string `json:"username"`
ID int `json:"id"`
Privileges int `json:"privileges"`
Token string `json:"token,omitempty"`
Banned bool `json:"banned"`
}
// TokenNewPOST is the handler for POST /token/new.
func TokenNewPOST(md common.MethodData) common.CodeMessager {
var r tokenNewResponse
data := tokenNewInData{}
err := md.Unmarshal(&data)
if err != nil {
return ErrBadJSON
}
md.Doggo.Incr("tokens.new", nil, 1)
var miss []string
if data.Username == "" && data.UserID == 0 {
miss = append(miss, "username|id")
}
if data.Password == "" {
miss = append(miss, "password")
}
if len(miss) != 0 {
return ErrMissingField(miss...)
}
var q *sql.Row
const base = "SELECT id, username, privileges, password_md5, password_version, privileges FROM users "
if data.UserID != 0 {
q = md.DB.QueryRow(base+"WHERE id = ? LIMIT 1", data.UserID)
} else {
q = md.DB.QueryRow(base+"WHERE username = ? LIMIT 1", common.SafeUsername(data.Username))
}
var (
rank int
pw string
pwVersion int
privilegesRaw uint64
)
err = q.Scan(&r.ID, &r.Username, &rank, &pw, &pwVersion, &privilegesRaw)
switch {
case err == sql.ErrNoRows:
return common.SimpleResponse(404, "No user with that username/id was found.")
case err != nil:
md.Err(err)
return Err500
}
privileges := common.UserPrivileges(privilegesRaw)
if !limit.NonBlockingRequest(fmt.Sprintf("loginattempt:%d:%s", r.ID, md.ClientIP()), 5) {
return common.SimpleResponse(429, "You've made too many login attempts. Try again later.")
}
if pwVersion == 1 {
return common.SimpleResponse(418, "That user still has a password in version 1. Unfortunately, in order for the API to check for the password to be OK, the user has to first log in through the website.")
}
if err := bcrypt.CompareHashAndPassword([]byte(pw), []byte(fmt.Sprintf("%x", md5.Sum([]byte(data.Password))))); err != nil {
if err == bcrypt.ErrMismatchedHashAndPassword {
return common.SimpleResponse(403, "That password doesn't match!")
}
md.Err(err)
return Err500
}
const want = (common.UserPrivilegePublic | common.UserPrivilegeNormal)
if (privileges & want) != want {
r.Code = 402
r.Message = "That user is banned."
r.Banned = true
return r
}
r.Privileges = int(common.Privileges(data.Privileges).CanOnly(privileges))
var (
tokenStr string
tokenMD5 string
)
for {
tokenStr = common.RandomString(32)
tokenMD5 = fmt.Sprintf("%x", md5.Sum([]byte(tokenStr)))
r.Token = tokenStr
var id int
err := md.DB.QueryRow("SELECT id FROM tokens WHERE token=? LIMIT 1", tokenMD5).Scan(&id)
if err == sql.ErrNoRows {
break
}
if err != nil {
md.Err(err)
return Err500
}
}
_, err = md.DB.Exec("INSERT INTO tokens(user, privileges, description, token, private, last_updated) VALUES (?, ?, ?, ?, '0', ?)",
r.ID, r.Privileges, data.Description, tokenMD5, time.Now().Unix())
if err != nil {
md.Err(err)
return Err500
}
r.Code = 200
return r
}
// TokenSelfDeletePOST deletes the token the user is connecting with.
func TokenSelfDeletePOST(md common.MethodData) common.CodeMessager {
if md.ID() == 0 {
@ -170,7 +48,13 @@ type tokenResponse struct {
// TokenGET retrieves a list listing all the user's public tokens.
func TokenGET(md common.MethodData) common.CodeMessager {
rows, err := md.DB.Query("SELECT id, privileges, description, last_updated FROM tokens WHERE user = ? AND private = '0' "+common.Paginate(md.Query("p"), md.Query("l"), 50), md.ID())
wc := common.Where("user = ? AND private = 0", strconv.Itoa(md.ID()))
if md.Query("id") != "" {
wc.Where("id = ?", md.Query("id"))
}
rows, err := md.DB.Query("SELECT id, privileges, description, last_updated FROM tokens "+
wc.Clause+common.Paginate(md.Query("p"), md.Query("l"), 50), wc.Params...)
if err != nil {
return Err500
}

View File

@ -9,7 +9,7 @@ import (
"github.com/jmoiron/sqlx"
"zxq.co/ripple/ocl"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
type userData struct {
@ -29,6 +29,44 @@ FROM users
INNER JOIN users_stats
ON users.id=users_stats.id
`
type userNotFullResponseLmao struct {
Id int `json:"id"`
Username string `json:"username"`
UsernameAKA string `json:"username_aka"`
RegisteredOn common.UnixTimestamp `json:"registered_on"`
Privileges uint64 `json:"privileges"`
LatestActivity common.UnixTimestamp `json:"latest_activity"`
Country string `json:"country"`
UserColor string `json:"user_color"`
RankedScoreStd uint64 `json:"ranked_score_std"`
TotalScoreStd uint64 `json:"total_score_std"`
PlaycountStd int `json:"playcount_std"`
ReplaysWatchedStd int `json:"replays_watched_std"`
TotalHitsStd int `json:"total_hits_std"`
PpStd int `json:"pp_std"`
RankedScoreTaiko uint64 `json:"ranked_score_taiko"`
TotalScoreTaiko uint64 `json:"total_score_taiko"`
PlaycountTaiko int `json:"playcount_taiko"`
ReplaysWatchedTaiko int `json:"replays_watched_taiko"`
TotalHitsTaiko int `json:"total_hits_taiko"`
PpTaiko int `json:"pp_taiko"`
RankedScoreCtb uint64 `json:"ranked_score_ctb"`
TotalScoreCtb uint64 `json:"total_score_ctb"`
PlaycountCtb int `json:"playcount_ctb"`
ReplaysWatchedCtb int `json:"replays_watched_ctb"`
TotalHitsCtb int `json:"total_hits_ctb"`
PpCtb int `json:"pp_ctb"`
RankedScoreMania uint64 `json:"ranked_score_mania"`
TotalScoreMania uint64 `json:"total_score_mania"`
PlaycountMania int `json:"playcount_mania"`
ReplaysWatchedMania int `json:"replays_watched_mania"`
TotalHitsMania int `json:"total_hits_mania"`
PpMania int `json:"pp_mania"`
// STD clappedModeData `json:"std"`
// Taiko clappedModeData `json:"taiko"`
// CTB clappedModeData `json:"ctb"`
// Mania clappedModeData `json:"mania"`
}
// UsersGET is the API handler for GET /users
func UsersGET(md common.MethodData) common.CodeMessager {
@ -185,25 +223,31 @@ type modeData struct {
GlobalLeaderboardRank *int `json:"global_leaderboard_rank"`
CountryLeaderboardRank *int `json:"country_leaderboard_rank"`
}
type userFullResponse struct {
common.ResponseBase
userData
STD modeData `json:"std"`
Taiko modeData `json:"taiko"`
CTB modeData `json:"ctb"`
Mania modeData `json:"mania"`
PlayStyle int `json:"play_style"`
FavouriteMode int `json:"favourite_mode"`
Badges []singleBadge `json:"badges"`
CustomBadge *singleBadge `json:"custom_badge"`
SilenceInfo silenceInfo `json:"silence_info"`
STD modeData `json:"std"`
Taiko modeData `json:"taiko"`
CTB modeData `json:"ctb"`
Mania modeData `json:"mania"`
PlayStyle int `json:"play_style"`
FavouriteMode int `json:"favourite_mode"`
Badges []singleBadge `json:"badges"`
Clan singleClan `json:"clan"`
CustomBadge *singleBadge `json:"custom_badge"`
SilenceInfo silenceInfo `json:"silence_info"`
CMNotes *string `json:"cm_notes,omitempty"`
BanDate *common.UnixTimestamp `json:"ban_date,omitempty"`
Email string `json:"email,omitempty"`
}
type silenceInfo struct {
Reason string `json:"reason"`
End common.UnixTimestamp `json:"end"`
}
// UserFullGET gets all of an user's information, with one exception: their userpage.
// Rx gets all of an user's information, with one exception: their userpage.
func UserFullGET(md common.MethodData) common.CodeMessager {
shouldRet, whereClause, param := whereClauseUser(md, "users")
if shouldRet != nil {
@ -236,7 +280,8 @@ SELECT
users_stats.replays_watched_mania, users_stats.total_hits_mania,
users_stats.avg_accuracy_mania, users_stats.pp_mania,
users.silence_reason, users.silence_end
users.silence_reason, users.silence_end,
users.notes, users.ban_datetime, users.email
FROM users
LEFT JOIN users_stats
@ -276,6 +321,7 @@ LIMIT 1
&r.Mania.Accuracy, &r.Mania.PP,
&r.SilenceInfo.Reason, &r.SilenceInfo.End,
&r.CMNotes, &r.BanDate, &r.Email,
)
switch {
case err == sql.ErrNoRows:
@ -317,6 +363,306 @@ LIMIT 1
r.Badges = append(r.Badges, badge)
}
if md.User.TokenPrivileges&common.PrivilegeManageUser == 0 {
r.CMNotes = nil
r.BanDate = nil
r.Email = ""
}
rows, err = md.DB.Query("SELECT c.id, c.name, c.description, c.tag, c.icon FROM user_clans uc "+
"LEFT JOIN clans c ON uc.clan = c.id WHERE user = ?", r.ID)
if err != nil {
md.Err(err)
}
for rows.Next() {
var clan singleClan
err = rows.Scan(&clan.ID, &clan.Name, &clan.Description, &clan.Tag, &clan.Icon)
if err != nil {
md.Err(err)
continue
}
r.Clan = clan
}
r.Code = 200
return r
}
func UserFullGETRx(md common.MethodData) common.CodeMessager {
shouldRet, whereClause, param := whereClauseUser(md, "users")
if shouldRet != nil {
return *shouldRet
}
// Hellest query I've ever done.
query := `
SELECT
users.id, users.username, users.register_datetime, users.privileges, users.latest_activity,
users_stats.username_aka, users_stats.country, users_stats.play_style, users_stats.favourite_mode,
users_stats.custom_badge_icon, users_stats.custom_badge_name, users_stats.can_custom_badge,
users_stats.show_custom_badge,
users_stats.ranked_score_std_rx, users_stats.total_score_std_rx, users_stats.playcount_std_rx,
users_stats.replays_watched_std, users_stats.total_hits_std,
users_stats.avg_accuracy_std_rx, users_stats.pp_std_rx,
users_stats.ranked_score_taiko_rx, users_stats.total_score_taiko_rx, users_stats.playcount_taiko_rx,
users_stats.replays_watched_taiko, users_stats.total_hits_taiko,
users_stats.avg_accuracy_taiko_rx, users_stats.pp_taiko_rx,
users_stats.ranked_score_ctb_rx, users_stats.total_score_ctb_rx, users_stats.playcount_ctb_rx,
users_stats.replays_watched_ctb, users_stats.total_hits_ctb,
users_stats.avg_accuracy_ctb_rx, users_stats.pp_ctb_rx,
users_stats.ranked_score_mania, users_stats.total_score_mania, users_stats.playcount_mania,
users_stats.replays_watched_mania, users_stats.total_hits_mania,
users_stats.avg_accuracy_mania, users_stats.pp_mania,
users.silence_reason, users.silence_end,
users.notes, users.ban_datetime, users.email
FROM users
LEFT JOIN users_stats
ON users.id=users_stats.id
WHERE ` + whereClause + ` AND ` + md.User.OnlyUserPublic(true) + `
LIMIT 1
`
// Fuck.
r := userFullResponse{}
var (
b singleBadge
can bool
show bool
)
err := md.DB.QueryRow(query, param).Scan(
&r.ID, &r.Username, &r.RegisteredOn, &r.Privileges, &r.LatestActivity,
&r.UsernameAKA, &r.Country,
&r.PlayStyle, &r.FavouriteMode,
&b.Icon, &b.Name, &can, &show,
&r.STD.RankedScore, &r.STD.TotalScore, &r.STD.PlayCount,
&r.STD.ReplaysWatched, &r.STD.TotalHits,
&r.STD.Accuracy, &r.STD.PP,
&r.Taiko.RankedScore, &r.Taiko.TotalScore, &r.Taiko.PlayCount,
&r.Taiko.ReplaysWatched, &r.Taiko.TotalHits,
&r.Taiko.Accuracy, &r.Taiko.PP,
&r.CTB.RankedScore, &r.CTB.TotalScore, &r.CTB.PlayCount,
&r.CTB.ReplaysWatched, &r.CTB.TotalHits,
&r.CTB.Accuracy, &r.CTB.PP,
&r.Mania.RankedScore, &r.Mania.TotalScore, &r.Mania.PlayCount,
&r.Mania.ReplaysWatched, &r.Mania.TotalHits,
&r.Mania.Accuracy, &r.Mania.PP,
&r.SilenceInfo.Reason, &r.SilenceInfo.End,
&r.CMNotes, &r.BanDate, &r.Email,
)
switch {
case err == sql.ErrNoRows:
return common.SimpleResponse(404, "That user could not be found!")
case err != nil:
md.Err(err)
return Err500
}
can = can && show && common.UserPrivileges(r.Privileges)&common.UserPrivilegeDonor > 0
if can && (b.Name != "" || b.Icon != "") {
r.CustomBadge = &b
}
for modeID, m := range [...]*modeData{&r.STD, &r.Taiko, &r.CTB, &r.Mania} {
m.Level = ocl.GetLevelPrecise(int64(m.TotalScore))
if i := leaderboardPositionRx(md.R, modesToReadable[modeID], r.ID); i != nil {
m.GlobalLeaderboardRank = i
}
if i := countryPositionRx(md.R, modesToReadable[modeID], r.ID, r.Country); i != nil {
m.CountryLeaderboardRank = i
}
}
rows, err := md.DB.Query("SELECT b.id, b.name, b.icon FROM user_badges ub "+
"LEFT JOIN badges b ON ub.badge = b.id WHERE user = ?", r.ID)
if err != nil {
md.Err(err)
}
for rows.Next() {
var badge singleBadge
err := rows.Scan(&badge.ID, &badge.Name, &badge.Icon)
if err != nil {
md.Err(err)
continue
}
r.Badges = append(r.Badges, badge)
}
if md.User.TokenPrivileges&common.PrivilegeManageUser == 0 {
r.CMNotes = nil
r.BanDate = nil
r.Email = ""
}
rows, err = md.DB.Query("SELECT c.id, c.name, c.description, c.tag, c.icon FROM user_clans uc "+
"LEFT JOIN clans c ON uc.clan = c.id WHERE user = ?", r.ID)
if err != nil {
md.Err(err)
}
for rows.Next() {
var clan singleClan
err = rows.Scan(&clan.ID, &clan.Name, &clan.Description, &clan.Tag, &clan.Icon)
if err != nil {
md.Err(err)
continue
}
r.Clan = clan
}
r.Code = 200
return r
}
func UserFullGETAp(md common.MethodData) common.CodeMessager {
shouldRet, whereClause, param := whereClauseUser(md, "users")
if shouldRet != nil {
return *shouldRet
}
// Hellest query I've ever done.
query := `
SELECT
users.id, users.username, users.register_datetime, users.privileges, users.latest_activity,
users_stats.username_aka, users_stats.country, users_stats.play_style, users_stats.favourite_mode,
users_stats.custom_badge_icon, users_stats.custom_badge_name, users_stats.can_custom_badge,
users_stats.show_custom_badge,
users_stats.ranked_score_std_ap, users_stats.total_score_std, users_stats.playcount_std_ap,
users_stats.replays_watched_std, users_stats.total_hits_std,
users_stats.avg_accuracy_std_ap, users_stats.pp_std_auto,
users_stats.ranked_score_taiko_ap, users_stats.total_score_taiko, users_stats.playcount_taiko_ap,
users_stats.replays_watched_taiko, users_stats.total_hits_taiko,
users_stats.avg_accuracy_taiko_ap, users_stats.pp_taiko_auto,
users_stats.ranked_score_ctb_ap, users_stats.total_score_ctb, users_stats.playcount_ctb_ap,
users_stats.replays_watched_ctb, users_stats.total_hits_ctb,
users_stats.avg_accuracy_ctb_ap, users_stats.pp_ctb_auto,
users_stats.ranked_score_mania, users_stats.total_score_mania, users_stats.playcount_mania,
users_stats.replays_watched_mania, users_stats.total_hits_mania,
users_stats.avg_accuracy_mania, users_stats.pp_mania,
users.silence_reason, users.silence_end,
users.notes, users.ban_datetime, users.email
FROM users
LEFT JOIN users_stats
ON users.id=users_stats.id
WHERE ` + whereClause + ` AND ` + md.User.OnlyUserPublic(true) + `
LIMIT 1
`
// Fuck.
r := userFullResponse{}
var (
b singleBadge
can bool
show bool
)
err := md.DB.QueryRow(query, param).Scan(
&r.ID, &r.Username, &r.RegisteredOn, &r.Privileges, &r.LatestActivity,
&r.UsernameAKA, &r.Country,
&r.PlayStyle, &r.FavouriteMode,
&b.Icon, &b.Name, &can, &show,
&r.STD.RankedScore, &r.STD.TotalScore, &r.STD.PlayCount,
&r.STD.ReplaysWatched, &r.STD.TotalHits,
&r.STD.Accuracy, &r.STD.PP,
&r.Taiko.RankedScore, &r.Taiko.TotalScore, &r.Taiko.PlayCount,
&r.Taiko.ReplaysWatched, &r.Taiko.TotalHits,
&r.Taiko.Accuracy, &r.Taiko.PP,
&r.CTB.RankedScore, &r.CTB.TotalScore, &r.CTB.PlayCount,
&r.CTB.ReplaysWatched, &r.CTB.TotalHits,
&r.CTB.Accuracy, &r.CTB.PP,
&r.Mania.RankedScore, &r.Mania.TotalScore, &r.Mania.PlayCount,
&r.Mania.ReplaysWatched, &r.Mania.TotalHits,
&r.Mania.Accuracy, &r.Mania.PP,
&r.SilenceInfo.Reason, &r.SilenceInfo.End,
&r.CMNotes, &r.BanDate, &r.Email,
)
switch {
case err == sql.ErrNoRows:
return common.SimpleResponse(404, "That user could not be found!")
case err != nil:
md.Err(err)
return Err500
}
can = can && show && common.UserPrivileges(r.Privileges)&common.UserPrivilegeDonor > 0
if can && (b.Name != "" || b.Icon != "") {
r.CustomBadge = &b
}
for modeID, m := range [...]*modeData{&r.STD, &r.Taiko, &r.CTB, &r.Mania} {
m.Level = ocl.GetLevelPrecise(int64(m.TotalScore))
if i := leaderboardPositionAp(md.R, modesToReadable[modeID], r.ID); i != nil {
m.GlobalLeaderboardRank = i
}
if i := countryPositionAp(md.R, modesToReadable[modeID], r.ID, r.Country); i != nil {
m.CountryLeaderboardRank = i
}
}
rows, err := md.DB.Query("SELECT b.id, b.name, b.icon FROM user_badges ub "+
"LEFT JOIN badges b ON ub.badge = b.id WHERE user = ?", r.ID)
if err != nil {
md.Err(err)
}
for rows.Next() {
var badge singleBadge
err := rows.Scan(&badge.ID, &badge.Name, &badge.Icon)
if err != nil {
md.Err(err)
continue
}
r.Badges = append(r.Badges, badge)
}
if md.User.TokenPrivileges&common.PrivilegeManageUser == 0 {
r.CMNotes = nil
r.BanDate = nil
r.Email = ""
}
rows, err = md.DB.Query("SELECT c.id, c.name, c.description, c.tag, c.icon FROM user_clans uc "+
"LEFT JOIN clans c ON uc.clan = c.id WHERE user = ?", r.ID)
if err != nil {
md.Err(err)
}
for rows.Next() {
var clan singleClan
err = rows.Scan(&clan.ID, &clan.Name, &clan.Description, &clan.Tag, &clan.Icon)
if err != nil {
md.Err(err)
continue
}
r.Clan = clan
}
r.Code = 200
return r
}

View File

@ -0,0 +1,84 @@
package v1
import (
"database/sql"
"fmt"
"time"
"github.com/jmoiron/sqlx"
"github.com/osuyozora/api/common"
)
// Achievement represents an achievement in the database.
type Achievement struct {
ID int `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Icon string `json:"icon"`
}
// LoadAchievementsEvery reloads the achievements in the database every given
// amount of time.
func LoadAchievementsEvery(db *sqlx.DB, d time.Duration) {
for {
achievs = nil
err := db.Select(&achievs,
"SELECT id, name, description, icon FROM achievements ORDER BY id ASC")
if err != nil {
fmt.Println("LoadAchievements error", err)
common.GenericError(err)
}
time.Sleep(d)
}
}
var achievs []Achievement
type userAchievement struct {
Achievement
Achieved bool `json:"achieved"`
}
type userAchievementsResponse struct {
common.ResponseBase
Achievements []userAchievement `json:"achievements"`
}
// UserAchievementsGET handles requests for retrieving the achievements of a
// given user.
func UserAchievementsGET(md common.MethodData) common.CodeMessager {
shouldRet, whereClause, param := whereClauseUser(md, "users")
if shouldRet != nil {
return *shouldRet
}
var ids []int
err := md.DB.Select(&ids, `SELECT ua.achievement_id FROM users_achievements ua
INNER JOIN users ON users.id = ua.user_id
WHERE `+whereClause+` ORDER BY ua.achievement_id ASC`, param)
switch {
case err == sql.ErrNoRows:
return common.SimpleResponse(404, "No such user!")
case err != nil:
md.Err(err)
return Err500
}
all := md.HasQuery("all")
resp := userAchievementsResponse{Achievements: make([]userAchievement, 0, len(achievs))}
for _, ach := range achievs {
achieved := inInt(ach.ID, ids)
if all || achieved {
resp.Achievements = append(resp.Achievements, userAchievement{ach, achieved})
}
}
resp.Code = 200
return resp
}
func inInt(i int, js []int) bool {
for _, j := range js {
if i == j {
return true
}
}
return false
}

View File

@ -5,7 +5,7 @@ import (
"strings"
"gopkg.in/thehowl/go-osuapi.v1"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
"zxq.co/x/getrank"
)
@ -46,8 +46,8 @@ func UserScoresBestGET(md common.MethodData) common.CodeMessager {
return *cm
}
mc := genModeClause(md)
// Do not print 0pp scores on std
if getMode(md.Query("mode")) == "std" {
// For all modes that have PP, we leave out 0 PP scores.
if getMode(md.Query("mode")) != "ctb" {
mc += " AND scores.pp > 0"
}
return scoresPuts(md, fmt.Sprintf(

127
app/v1/user_scores_ap.go Normal file
View File

@ -0,0 +1,127 @@
package v1
import (
"fmt"
"strings"
"gopkg.in/thehowl/go-osuapi.v1"
"github.com/osuyozora/api/common"
"zxq.co/x/getrank"
)
type userScoreAuto struct {
Score
Beatmap beatmap `json:"beatmap"`
}
type userScoresResponseAuto struct {
common.ResponseBase
Scores []userScoreAuto `json:"scores"`
}
const userScoreSelectBaseAp = `
SELECT
scores_auto.id, scores_auto.beatmap_md5, scores_auto.score,
scores_auto.max_combo, scores_auto.full_combo, scores_auto.mods,
scores_auto.300_count, scores_auto.100_count, scores_auto.50_count,
scores_auto.gekis_count, scores_auto.katus_count, scores_auto.misses_count,
scores_auto.time, scores_auto.play_mode, scores_auto.accuracy, scores_auto.pp,
scores_auto.completed,
beatmaps.beatmap_id, beatmaps.beatmapset_id, beatmaps.beatmap_md5,
beatmaps.song_name, beatmaps.ar, beatmaps.od, beatmaps.difficulty_std,
beatmaps.difficulty_taiko, beatmaps.difficulty_ctb, beatmaps.difficulty_mania,
beatmaps.max_combo, beatmaps.hit_length, beatmaps.ranked,
beatmaps.ranked_status_freezed, beatmaps.latest_update
FROM scores_auto
INNER JOIN beatmaps ON beatmaps.beatmap_md5 = scores_auto.beatmap_md5
INNER JOIN users ON users.id = scores_auto.userid
`
// UserScoresBestGET retrieves the best scores of an user, sorted by PP if
// mode is standard and sorted by ranked score otherwise.
func UserScoresBestAPGET(md common.MethodData) common.CodeMessager {
cm, wc, param := whereClauseUser(md, "users")
if cm != nil {
return *cm
}
mc := genModeClauseAp(md)
// For all modes that have PP, we leave out 0 PP scores_auto.
if getMode(md.Query("mode")) != "ctb" {
mc += " AND scores_auto.pp > 0"
}
return scoresPutsAp(md, fmt.Sprintf(
`WHERE
scores_auto.completed = '3'
AND %s
%s
AND `+md.User.OnlyUserPublic(true)+`
ORDER BY scores_auto.pp DESC, scores_auto.score DESC %s`,
wc, mc, common.Paginate(md.Query("p"), md.Query("l"), 100),
), param)
}
// UserScoresRecentGET retrieves an user's latest scores_auto.
func UserScoresRecentAPGET(md common.MethodData) common.CodeMessager {
cm, wc, param := whereClauseUser(md, "users")
if cm != nil {
return *cm
}
return scoresPutsAp(md, fmt.Sprintf(
`WHERE
%s
%s
AND `+md.User.OnlyUserPublic(true)+`
ORDER BY scores_auto.id DESC %s`,
wc, genModeClauseAp(md), common.Paginate(md.Query("p"), md.Query("l"), 100),
), param)
}
func scoresPutsAp(md common.MethodData, whereClause string, params ...interface{}) common.CodeMessager {
rows, err := md.DB.Query(userScoreSelectBaseAp+whereClause, params...)
if err != nil {
md.Err(err)
return Err500
}
var scores []userScoreAuto
for rows.Next() {
var (
us userScoreAuto
b beatmap
)
err = rows.Scan(
&us.ID, &us.BeatmapMD5, &us.Score.Score,
&us.MaxCombo, &us.FullCombo, &us.Mods,
&us.Count300, &us.Count100, &us.Count50,
&us.CountGeki, &us.CountKatu, &us.CountMiss,
&us.Time, &us.PlayMode, &us.Accuracy, &us.PP,
&us.Completed,
&b.BeatmapID, &b.BeatmapsetID, &b.BeatmapMD5,
&b.SongName, &b.AR, &b.OD, &b.Diff2.STD,
&b.Diff2.Taiko, &b.Diff2.CTB, &b.Diff2.Mania,
&b.MaxCombo, &b.HitLength, &b.Ranked,
&b.RankedStatusFrozen, &b.LatestUpdate,
)
if err != nil {
md.Err(err)
return Err500
}
b.Difficulty = b.Diff2.STD
us.Beatmap = b
us.Rank = strings.ToUpper(getrank.GetRank(
osuapi.Mode(us.PlayMode),
osuapi.Mods(us.Mods),
us.Accuracy,
us.Count300,
us.Count100,
us.Count50,
us.CountMiss,
))
scores = append(scores, us)
}
r := userScoresResponseAuto{}
r.Code = 200
r.Scores = scores
return r
}

127
app/v1/user_scores_relax.go Normal file
View File

@ -0,0 +1,127 @@
package v1
import (
"fmt"
"strings"
"gopkg.in/thehowl/go-osuapi.v1"
"github.com/osuyozora/api/common"
"zxq.co/x/getrank"
)
type userScoreRx struct {
Score
Beatmap beatmap `json:"beatmap"`
}
type userScoresResponseRx struct {
common.ResponseBase
Scores []userScoreRx `json:"scores"`
}
const userScoreSelectBaseRelax = `
SELECT
scores_relax.id, scores_relax.beatmap_md5, scores_relax.score,
scores_relax.max_combo, scores_relax.full_combo, scores_relax.mods,
scores_relax.300_count, scores_relax.100_count, scores_relax.50_count,
scores_relax.gekis_count, scores_relax.katus_count, scores_relax.misses_count,
scores_relax.time, scores_relax.play_mode, scores_relax.accuracy, scores_relax.pp,
scores_relax.completed,
beatmaps.beatmap_id, beatmaps.beatmapset_id, beatmaps.beatmap_md5,
beatmaps.song_name, beatmaps.ar, beatmaps.od, beatmaps.difficulty_std,
beatmaps.difficulty_taiko, beatmaps.difficulty_ctb, beatmaps.difficulty_mania,
beatmaps.max_combo, beatmaps.hit_length, beatmaps.ranked,
beatmaps.ranked_status_freezed, beatmaps.latest_update
FROM scores_relax
INNER JOIN beatmaps ON beatmaps.beatmap_md5 = scores_relax.beatmap_md5
INNER JOIN users ON users.id = scores_relax.userid
`
// UserScoresBestGET retrieves the best scores of an user, sorted by PP if
// mode is standard and sorted by ranked score otherwise.
func UserScoresBestRelaxGET(md common.MethodData) common.CodeMessager {
cm, wc, param := whereClauseUser(md, "users")
if cm != nil {
return *cm
}
mc := genModeClauseRx(md)
// For all modes that have PP, we leave out 0 PP scores_relax.
if getMode(md.Query("mode")) != "ctb" {
mc += " AND scores_relax.pp > 0"
}
return scoresPutsRx(md, fmt.Sprintf(
`WHERE
scores_relax.completed = '3'
AND %s
%s
AND `+md.User.OnlyUserPublic(true)+`
ORDER BY scores_relax.pp DESC, scores_relax.score DESC %s`,
wc, mc, common.Paginate(md.Query("p"), md.Query("l"), 100),
), param)
}
// UserScoresRecentGET retrieves an user's latest scores_relax.
func UserScoresRecentRelaxGET(md common.MethodData) common.CodeMessager {
cm, wc, param := whereClauseUser(md, "users")
if cm != nil {
return *cm
}
return scoresPutsRx(md, fmt.Sprintf(
`WHERE
%s
%s
AND `+md.User.OnlyUserPublic(true)+`
ORDER BY scores_relax.id DESC %s`,
wc, genModeClauseRx(md), common.Paginate(md.Query("p"), md.Query("l"), 100),
), param)
}
func scoresPutsRx(md common.MethodData, whereClause string, params ...interface{}) common.CodeMessager {
rows, err := md.DB.Query(userScoreSelectBaseRelax+whereClause, params...)
if err != nil {
md.Err(err)
return Err500
}
var scores []userScoreRx
for rows.Next() {
var (
us userScoreRx
b beatmap
)
err = rows.Scan(
&us.ID, &us.BeatmapMD5, &us.Score.Score,
&us.MaxCombo, &us.FullCombo, &us.Mods,
&us.Count300, &us.Count100, &us.Count50,
&us.CountGeki, &us.CountKatu, &us.CountMiss,
&us.Time, &us.PlayMode, &us.Accuracy, &us.PP,
&us.Completed,
&b.BeatmapID, &b.BeatmapsetID, &b.BeatmapMD5,
&b.SongName, &b.AR, &b.OD, &b.Diff2.STD,
&b.Diff2.Taiko, &b.Diff2.CTB, &b.Diff2.Mania,
&b.MaxCombo, &b.HitLength, &b.Ranked,
&b.RankedStatusFrozen, &b.LatestUpdate,
)
if err != nil {
md.Err(err)
return Err500
}
b.Difficulty = b.Diff2.STD
us.Beatmap = b
us.Rank = strings.ToUpper(getrank.GetRank(
osuapi.Mode(us.PlayMode),
osuapi.Mods(us.Mods),
us.Accuracy,
us.Count300,
us.Count100,
us.Count50,
us.CountMiss,
))
scores = append(scores, us)
}
r := userScoresResponseRx{}
r.Code = 200
r.Scores = scores
return r
}

101
app/websockets/identify.go Normal file
View File

@ -0,0 +1,101 @@
package websockets
import (
"crypto/md5"
"crypto/sha256"
"encoding/json"
"fmt"
"database/sql"
"github.com/osuyozora/api/common"
)
type websocketUser struct {
ID int `json:"id"`
Username string `json:"username"`
UserPrivileges uint64 `json:"user_privileges"`
TokenPrivileges uint64 `json:"token_privileges"`
ApplicationID *string `json:"application_id"`
}
type identifyMessage struct {
Token string `json:"token"`
IsBearer bool `json:"is_bearer"`
}
// Identify sets the identity of the user.
func Identify(c *conn, message incomingMessage) {
var idMsg identifyMessage
err := json.Unmarshal(message.Data, &idMsg)
if err != nil {
c.WriteJSON(TypeInvalidMessage, err.Error())
return
}
var wsu websocketUser
if idMsg.IsBearer {
err = getBearerToken(idMsg.Token, &wsu)
} else {
err = db.Get(&wsu, `
SELECT
t.user as id, t.privileges as token_privileges,
u.username, u.privileges as user_privileges
FROM tokens t
INNER JOIN users u ON t.user = u.id
WHERE t.token = ?`, fmt.Sprintf("%x", md5.Sum([]byte(idMsg.Token))))
}
switch err {
case nil:
break
case sql.ErrNoRows:
c.WriteJSON(TypeNotFound, nil)
return
default:
common.WSErr(err)
c.WriteJSON(TypeUnexpectedError, nil)
return
}
wsu.TokenPrivileges = uint64(
common.Privileges(wsu.TokenPrivileges).CanOnly(
common.UserPrivileges(wsu.UserPrivileges),
),
)
c.Mtx.Lock()
c.User = &wsu
c.Mtx.Unlock()
c.WriteJSON(TypeIdentified, wsu)
}
func getBearerToken(token string, wsu *websocketUser) error {
var x struct {
Client string
Scope string
Extra int
}
err := db.Get(&x, "SELECT client, scope, extra FROM osin_access WHERE access_token = ? LIMIT 1", fmt.Sprintf("%x", sha256.Sum256([]byte(token))))
if err != nil {
return err
}
var userInfo struct {
Username string
Privileges uint64
}
err = db.Get(&userInfo, "SELECT username, privileges FROM users WHERE id = ? LIMIT 1", x.Extra)
if err != nil {
return err
}
wsu.ApplicationID = &x.Client
wsu.ID = x.Extra
wsu.Username = userInfo.Username
wsu.UserPrivileges = userInfo.Privileges
wsu.TokenPrivileges = uint64(common.OAuthPrivileges(x.Scope))
return nil
}

View File

@ -26,6 +26,8 @@ func handler(rawConn *websocket.Conn) {
rawConn,
sync.Mutex{},
step | uint64(time.Now().UnixNano()<<10),
false,
nil,
}
c.WriteJSON(TypeConnected, nil)
@ -47,14 +49,18 @@ func handler(rawConn *websocket.Conn) {
c.WriteJSON(TypeInvalidMessage, "invalid message type")
continue
}
f(c, i)
if f != nil {
f(c, i)
}
}
}
type conn struct {
Conn *websocket.Conn
Mtx sync.Mutex
ID uint64
Conn *websocket.Conn
Mtx sync.Mutex
ID uint64
RestrictedVisible bool
User *websocketUser
}
func (c *conn) WriteJSON(t string, data interface{}) error {
@ -65,22 +71,41 @@ func (c *conn) WriteJSON(t string, data interface{}) error {
}
var messageHandler = map[string]func(c *conn, message incomingMessage){
TypeSubscribeScores: SubscribeScores,
TypeSubscribeScores: SubscribeScores,
TypeSubscribeMultiMatches: SubscribeMultiMatches,
TypeSetRestrictedVisibility: SetRestrictedVisibility,
TypeIdentify: Identify,
TypePing: pingHandler,
}
// Server Message Types
const (
TypeConnected = "connected"
TypeInvalidMessage = "invalid_message_type"
TypeSubscribedToScores = "subscribed_to_scores"
TypeNewScore = "new_score"
TypeConnected = "connected"
TypeInvalidMessage = "invalid_message_type"
TypeUnexpectedError = "unexpected_error"
TypeNotFound = "not_found"
TypeSubscribedToScores = "subscribed_to_scores"
TypeNewScore = "new_score"
TypeSubscribedToMultiMatches = "subscribed_mp_complete_match"
TypeNewMatch = "new_completed_match"
TypeIdentified = "identified"
TypeRestrictedVisibilitySet = "restricted_visibility_set"
TypePong = "pong"
)
// Client Message Types
const (
TypeSubscribeScores = "subscribe_scores"
TypeSubscribeScores = "subscribe_scores"
TypeSubscribeMultiMatches = "subscribe_mp_complete_match"
TypeIdentify = "identify"
TypeSetRestrictedVisibility = "set_restricted_visibility"
TypePing = "ping"
)
func pingHandler(c *conn, message incomingMessage) {
c.WriteJSON(TypePong, nil)
}
// Message is the wrapped information for a message sent to the client.
type Message struct {
Type string `json:"type"`

57
app/websockets/multi.go Normal file
View File

@ -0,0 +1,57 @@
package websockets
import (
"encoding/json"
"fmt"
"sync"
)
// SubscribeMultiMatches subscribes to receiving information from completed
// games in multiplayer matches.
func SubscribeMultiMatches(c *conn, message incomingMessage) {
multiSubscriptionsMtx.Lock()
var found bool
for _, el := range multiSubscriptions {
if el.ID == c.ID {
found = true
break
}
}
// if it was not found, we need to add it
if !found {
multiSubscriptions = append(multiSubscriptions, c)
}
multiSubscriptionsMtx.Unlock()
c.WriteJSON(TypeSubscribedToMultiMatches, nil)
}
var multiSubscriptions []*conn
var multiSubscriptionsMtx = new(sync.RWMutex)
func matchRetriever() {
ps, err := red.Subscribe("api:mp_complete_match")
if err != nil {
fmt.Println(err)
}
for {
msg, err := ps.ReceiveMessage()
if err != nil {
fmt.Println(err.Error())
return
}
go handleNewMultiGame(msg.Payload)
}
}
func handleNewMultiGame(payload string) {
defer catchPanic()
multiSubscriptionsMtx.RLock()
cp := make([]*conn, len(multiSubscriptions))
copy(cp, multiSubscriptions)
multiSubscriptionsMtx.RUnlock()
for _, el := range cp {
el.WriteJSON(TypeNewMatch, json.RawMessage(payload))
}
}

View File

@ -0,0 +1,31 @@
package websockets
import (
"encoding/json"
"github.com/osuyozora/api/common"
)
// SetRestrictedVisibility sets whether the information of restricted users
// can be seen.
func SetRestrictedVisibility(c *conn, message incomingMessage) {
var visibility bool
err := json.Unmarshal(message.Data, &visibility)
if err != nil {
c.WriteJSON(TypeInvalidMessage, err.Error())
return
}
var userIsManager bool
if c.User != nil && (c.User.UserPrivileges&uint64(common.AdminPrivilegeManageUsers) > 0) {
userIsManager = true
}
c.Mtx.Lock()
visibility = visibility && userIsManager
c.RestrictedVisible = visibility
c.Mtx.Unlock()
c.WriteJSON(TypeRestrictedVisibilitySet, visibility)
}

View File

@ -7,7 +7,8 @@ import (
"sync"
"gopkg.in/thehowl/go-osuapi.v1"
"zxq.co/ripple/rippleapi/app/v1"
"github.com/osuyozora/api/app/v1"
"github.com/osuyozora/api/common"
"zxq.co/x/getrank"
)
@ -69,9 +70,21 @@ func scoreRetriever() {
}
}
type scoreUser struct {
UserID int `json:"id"`
Username string `json:"username"`
Privileges uint64 `json:"privileges"`
}
type score struct {
v1.Score
UserID int `json:"user_id"`
scoreUser
}
type scoreJSON struct {
v1.Score
UserID int `json:"user_id"`
User scoreUser `json:"user"`
}
func handleNewScore(id string) {
@ -79,10 +92,13 @@ func handleNewScore(id string) {
var s score
err := db.Get(&s, `
SELECT
id, beatmap_md5, score, max_combo, full_combo, mods,
300_count, 100_count, 50_count, gekis_count, katus_count, misses_count,
time, play_mode, accuracy, pp, completed, userid AS user_id
FROM scores WHERE id = ?`, id)
s.id, s.beatmap_md5, s.score, s.max_combo, s.full_combo, s.mods,
s.300_count, s.100_count, s.50_count, s.gekis_count, s.katus_count, s.misses_count,
s.time, s.play_mode, s.accuracy, s.pp, s.completed, s.userid AS user_id,
u.username, u.privileges
FROM scores s
INNER JOIN users u ON s.userid = u.id
WHERE s.id = ?`, id)
if err != nil {
fmt.Println(err)
return
@ -96,21 +112,32 @@ FROM scores WHERE id = ?`, id)
s.Count50,
s.CountMiss,
))
sj := scoreJSON{
Score: s.Score,
UserID: s.UserID,
User: s.scoreUser,
}
scoreSubscriptionsMtx.RLock()
cp := make([]scoreSubscription, len(scoreSubscriptions))
copy(cp, scoreSubscriptions)
scoreSubscriptionsMtx.RUnlock()
for _, el := range cp {
if len(el.Users) > 0 && !scoreUserValid(el.Users, s) {
if len(el.Users) > 0 && !scoreUserValid(el.Users, sj) {
continue
}
el.Conn.WriteJSON(TypeNewScore, s)
if sj.User.Privileges&3 != 3 && !el.Conn.RestrictedVisible {
continue
}
el.Conn.WriteJSON(TypeNewScore, sj)
}
}
func scoreUserValid(users []subscribeScoresUser, s score) bool {
func scoreUserValid(users []subscribeScoresUser, s scoreJSON) bool {
for _, u := range users {
if u.User == s.UserID {
if len(u.Modes) > 0 {
@ -136,7 +163,11 @@ func inModes(modes []int, i int) bool {
func catchPanic() {
r := recover()
if r != nil {
fmt.Println(r)
// TODO: sentry
switch r := r.(type) {
case error:
common.WSErr(r)
default:
fmt.Println("PANIC", r)
}
}
}

View File

@ -16,6 +16,7 @@ func Start(r *redis.Client, _db *sqlx.DB) error {
red = r
db = _db
go scoreRetriever()
go matchRetriever()
return nil
}
@ -29,4 +30,13 @@ func cleanup(connID uint64) {
}
}
scoreSubscriptionsMtx.Unlock()
multiSubscriptionsMtx.Lock()
for idx, el := range multiSubscriptions {
if el.ID == connID {
multiSubscriptions[idx] = multiSubscriptions[len(multiSubscriptions)-1]
multiSubscriptions = multiSubscriptions[:len(multiSubscriptions)-1]
break
}
}
multiSubscriptionsMtx.Unlock()
}

View File

@ -10,7 +10,7 @@ import (
"strings"
"time"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
"github.com/jmoiron/sqlx"
"gopkg.in/thehowl/go-osuapi.v1"
)

View File

@ -5,7 +5,7 @@ import (
"errors"
"time"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
"gopkg.in/thehowl/go-osuapi.v1"
)

View File

@ -70,6 +70,18 @@ func Err(c *fasthttp.RequestCtx, err error) {
_err(err, tags, nil, c)
}
// WSErr is the error function for errors happening in the websockets.
func WSErr(err error) {
_err(err, map[string]string{
"endpoint": "/api/v1/ws",
}, nil, nil)
}
// GenericError is just an error. Can't make a good description.
func GenericError(err error) {
_err(err, nil, nil, nil)
}
func _err(err error, tags map[string]string, user *raven.User, c *fasthttp.RequestCtx) {
if RavenClient == nil {
fmt.Println("ERROR!!!!")
@ -78,7 +90,7 @@ func _err(err error, tags map[string]string, user *raven.User, c *fasthttp.Reque
}
// Create stacktrace
st := raven.NewStacktrace(0, 3, []string{"zxq.co/ripple", "git.zxq.co/ripple"})
st := raven.NewStacktrace(0, 3, []string{"github.com/osuYozora", "git.github.com/osuYozora"})
ifaces := []raven.Interface{st, generateRavenHTTP(c)}
if user != nil {
@ -93,6 +105,10 @@ func _err(err error, tags map[string]string, user *raven.User, c *fasthttp.Reque
}
func generateRavenHTTP(ctx *fasthttp.RequestCtx) *raven.Http {
if ctx == nil {
return nil
}
// build uri
uri := ctx.URI()
// safe to use b2s because a new string gets allocated eventually for

View File

@ -77,3 +77,18 @@ func (p Privileges) CanOnly(userPrivs UserPrivileges) Privileges {
}
return Privileges(newPrivilege)
}
var privilegeMap = map[string]Privileges{
"read_confidential": PrivilegeReadConfidential,
"write": PrivilegeWrite,
}
// OAuthPrivileges returns the equivalent in Privileges of a space-separated
// list of scopes.
func OAuthPrivileges(scopes string) Privileges {
var p Privileges
for _, x := range strings.Split(scopes, " ") {
p |= privilegeMap[x]
}
return p
}

View File

@ -26,6 +26,7 @@ const (
AdminPrivilegeKickUsers
UserPrivilegePendingVerification
UserPrivilegeTournamentStaff
AdminPrivilegeCaker
)
// UserPrivileges represents a bitwise enum of the privileges of an user.

13
main.go
View File

@ -6,9 +6,10 @@ import (
"strings"
"syscall"
"zxq.co/ripple/rippleapi/app"
"zxq.co/ripple/rippleapi/beatmapget"
"zxq.co/ripple/rippleapi/common"
"zxq.co/ripple/agplwarning"
"github.com/osuyozora/api/app"
"github.com/osuyozora/api/beatmapget"
"github.com/osuyozora/api/common"
"zxq.co/ripple/schiavolib"
// Golint pls dont break balls
_ "github.com/go-sql-driver/mysql"
@ -30,6 +31,11 @@ func init() {
var db *sqlx.DB
func main() {
err := agplwarning.Warn("ripple", "Ripple API")
if err != nil {
fmt.Println(err)
}
fmt.Print("Ripple API")
if Version != "" {
fmt.Print("; git commit hash: ", Version)
@ -51,7 +57,6 @@ func main() {
conf.DSN += c + "parseTime=true&charset=utf8mb4,utf8&collation=utf8mb4_general_ci"
}
var err error
db, err = sqlx.Open(conf.DatabaseType, conf.DSN)
if err != nil {
schiavo.Bunker.Send(err.Error())

View File

@ -10,7 +10,7 @@ import (
"github.com/rcrowley/goagain"
"github.com/valyala/fasthttp"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
"zxq.co/ripple/schiavolib"
)

View File

@ -10,7 +10,7 @@ import (
"net"
"github.com/valyala/fasthttp"
"zxq.co/ripple/rippleapi/common"
"github.com/osuyozora/api/common"
)
func startuato(hn fasthttp.RequestHandler) {

View File

@ -286,7 +286,7 @@ func (c *Client) Timing(name string, value time.Duration, tags []string, rate fl
}
// TimeInMilliseconds sends timing information in milliseconds.
// It is flushed by statsd with percentiles, mean and other info (https://github.com/etsy/statsd/blob/master/docs/metric_types.md#timing)
// It is flushed by statsd with percentiles, mean and other info (.com/etsy/statsd/blob/master/docs/metric_types.md#timing)
func (c *Client) TimeInMilliseconds(name string, value float64, tags []string, rate float64) error {
stat := fmt.Sprintf("%f|ms", value)
return c.send(name, stat, tags, rate)

8
vendor/vendor.json vendored
View File

@ -182,6 +182,12 @@
"revision": "77ef7867f23cd52e80dcf97e62447d3b36b1d26a",
"revisionTime": "2016-10-17T20:25:41Z"
},
{
"checksumSHA1": "vTjp3tQOr8z8CNjZWwPzgR+t2qQ=",
"path": "zxq.co/ripple/agplwarning",
"revision": "d3a3d0ee424fcb0bd09a651354c1735285f59f8c",
"revisionTime": "2018-02-04T10:46:38Z"
},
{
"checksumSHA1": "SI9tgNMlnMhxP7t6cAGuDjvoAHg=",
"path": "zxq.co/ripple/ocl",
@ -207,5 +213,5 @@
"revisionTime": "2017-04-18T18:31:09Z"
}
],
"rootPath": "zxq.co/ripple/rippleapi"
"rootPath": "github.com/osuyozora/api"
}

620
vendor/zxq.co/ripple/agplwarning/LICENSE vendored Normal file
View File

@ -0,0 +1,620 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS

View File

@ -0,0 +1,5 @@
# agplwarning
Show a warning in your Go programs regarding the use of AGPL software.
[![asciicast](https://asciinema.org/a/rUolzFDQebbWMPcaSgRQRTBEC.png)](https://asciinema.org/a/rUolzFDQebbWMPcaSgRQRTBEC)

View File

@ -0,0 +1,82 @@
package agplwarning
import (
"bufio"
"fmt"
"os"
"os/user"
"strings"
)
var pages = [...]string{
`This is a friendly reminder that the GNU AGPL adds an additional clause to
the standard GNU GPL, which is that you MUST distribute the source code for the
software once you publish it on the web.
This is not to be considered professional legal advice. For further
information, refer to the LICENSE file which contains the whole license, or ask
your lawyer. If you did not receive a copy of the LICENSE file with this
software, you can refer to the online version:
https://www.gnu.org/licenses/agpl-3.0.html`,
`In order to comply with the license, should you have made any modification
to the original copy of the software, which should contain a link to the
source code, however minor it is, you are under the legal obligation to provide
the source code once you publish the software on the Web.
Another obligation is that of stating your changes. This is usually done by
cloning the original git repository of the project and stating your changes
through the creation of commits, which allow us to determine when a specific
change was done.`,
`Furthermore, all the original clauses of the GNU General Public License
are kept intact, which means you have the obligation to
* Keep the AGPL License, without possibility of sublicensing the software
or making it available under any other more liberal license.
* Keep the copyright notice of the original authors
Failure to do so will result in a request to follow the License, and
repeated violation of the license could result in a legal fight.`,
`For more information on the FSF and software freedom, refer to:
* What is free software? https://www.gnu.org/philosophy/free-sw.html
* Free Software Is Even More Important Now
https://www.gnu.org/philosophy/free-software-even-more-important.html
* The GNU operating system https://www.gnu.org
* The Free Software Foundation https://www.fsf.org
Thank you for reading this and following our license terms.`,
}
// Warn shows a warning about the GNU Affero General Public License the first
// time the software is run. The state is saved in
// ~/.config/[namespace]_license_agreed.
func Warn(namespace, projectName string) error {
usr, err := user.Current()
if err != nil {
return fmt.Errorf("initialization of agplwarning failed: %v", err)
}
if err := os.MkdirAll(usr.HomeDir+"/.config", 0755); err != nil {
return fmt.Errorf("can't create config dir: %v", err)
}
agreedFilename := usr.HomeDir + "/.config/" + namespace + "_license_agreed"
if _, err := os.Stat(agreedFilename); !os.IsNotExist(err) {
return err
}
reader := bufio.NewReader(os.Stdin)
// file does not exist. Show warning.
fmt.Printf(" %s, and most/all software related to %s,\n"+
"is licensed under the GNU Affero General Public License.\n\n", projectName, namespace)
for _, page := range pages {
fmt.Println(" " + page)
fmt.Println("\nPress Enter to continue")
_, err := reader.ReadString('\n')
if err != nil {
return err
}
}
fmt.Println("Please write 'I agree' to accept the terms of the license.")
res, err := reader.ReadString('\n')
if err != nil || !strings.Contains(strings.ToLower(res), "i agree") {
fmt.Println("License not agreed. Quitting.")
os.Exit(1)
}
f, err := os.Create(agreedFilename)
if err != nil {
return fmt.Errorf("couldn't save read status: %v", err)
}
return f.Close()
}