Start implementing peppyapi; implement /api/get_user

This commit is contained in:
Howl
2016-05-15 13:57:04 +02:00
parent a939d15779
commit d6f67915c5
5 changed files with 151 additions and 26 deletions

52
app/peppy/common.go Normal file
View File

@@ -0,0 +1,52 @@
package peppy
import (
"database/sql"
"strconv"
"github.com/gin-gonic/gin"
)
func genmode(m string) string {
switch m {
case "1":
m = "taiko"
case "2":
m = "ctb"
case "3":
m = "mania"
default:
m = "std"
}
return m
}
func genUser(c *gin.Context, db *sql.DB) (string, string) {
var whereClause string
var p string
// used in second case of switch
_, err := strconv.Atoi(c.Query("u"))
switch {
// We know for sure that it's an username.
case c.Query("type") == "string":
whereClause = "WHERE users.username = ?"
p = c.Query("u")
// It could be an user ID, so we look for an user with that username first.
case err == nil:
err = db.QueryRow("SELECT id FROM users WHERE username = ? LIMIT 1", c.Query("u")).Scan(&p)
// If there is an error, that means u is an userID.
// If there is none, p will automatically have become the user id retrieved from the database
// in the last query.
if err == sql.ErrNoRows {
p = c.Query("u")
}
whereClause = "WHERE users.id = ?"
// u contains letters, so it's an username.
default:
p = c.Query("u")
whereClause = "WHERE users.username = ?"
}
return whereClause, p
}

View File

@@ -1,2 +1,53 @@
// Package peppy implements the osu! API as defined on the osu-api repository wiki (https://github.com/ppy/osu-api/wiki).
package peppy
import (
"database/sql"
"fmt"
"github.com/gin-gonic/gin"
"github.com/thehowl/go-osuapi"
)
// GetUser retrieves general user information.
func GetUser(c *gin.Context, db *sql.DB) {
if c.Query("u") == "" {
c.JSON(200, []struct{}{})
return
}
var user osuapi.User
whereClause, p := genUser(c, db)
mode := genmode(c.Query("m"))
fmt.Println(whereClause, p)
var display bool
err := db.QueryRow(fmt.Sprintf(
`SELECT
users.id, users.username,
users_stats.playcount_%s, users_stats.ranked_score_%s, users_stats.total_score_%s,
leaderboard_%s.position, users_stats.pp_%s, users_stats.avg_accuracy_%s,
users_stats.country, users_stats.show_country
FROM users
LEFT JOIN users_stats ON users_stats.id = users.id
LEFT JOIN leaderboard_%s ON leaderboard_%s.user = users.id
%s
LIMIT 1`,
mode, mode, mode, mode, mode, mode, mode, mode, whereClause,
), p).Scan(
&user.UserID, &user.Username,
&user.Playcount, &user.RankedScore, &user.TotalScore,
&user.Rank, &user.PP, &user.Accuracy,
&user.Country, &display,
)
if err != nil {
c.JSON(200, []struct{}{})
return
}
if !display {
user.Country = "XX"
}
c.JSON(200, []osuapi.User{user})
}