2018-01-21 11:17:43 +00:00
|
|
|
package common
|
|
|
|
|
|
|
|
import (
|
2022-02-21 03:32:53 +00:00
|
|
|
"database/sql"
|
2018-01-21 11:17:43 +00:00
|
|
|
|
2022-02-21 03:32:53 +00:00
|
|
|
qgen "github.com/Azareal/Gosora/query_gen"
|
2018-01-21 11:17:43 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
var IPSearch IPSearcher
|
|
|
|
|
|
|
|
type IPSearcher interface {
|
2022-02-21 03:32:53 +00:00
|
|
|
Lookup(ip string) (uids []int, e error)
|
2018-01-21 11:17:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type DefaultIPSearcher struct {
|
2022-02-21 03:32:53 +00:00
|
|
|
searchUsers *sql.Stmt
|
|
|
|
searchTopics *sql.Stmt
|
|
|
|
searchReplies *sql.Stmt
|
|
|
|
searchUsersReplies *sql.Stmt
|
2018-01-21 11:17:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// NewDefaultIPSearcher gives you a new instance of DefaultIPSearcher
|
|
|
|
func NewDefaultIPSearcher() (*DefaultIPSearcher, error) {
|
2022-02-21 03:32:53 +00:00
|
|
|
acc := qgen.NewAcc()
|
|
|
|
uu := "users"
|
|
|
|
q := func(tbl string) *sql.Stmt {
|
|
|
|
return acc.Select(uu).Columns("uid").InQ("uid", acc.Select(tbl).Columns("createdBy").Where("ip=?")).Prepare()
|
|
|
|
}
|
|
|
|
return &DefaultIPSearcher{
|
|
|
|
searchUsers: acc.Select(uu).Columns("uid").Where("last_ip=? OR last_ip LIKE CONCAT('%-',?)").Prepare(),
|
|
|
|
searchTopics: q("topics"),
|
|
|
|
searchReplies: q("replies"),
|
|
|
|
searchUsersReplies: q("users_replies"),
|
|
|
|
}, acc.FirstError()
|
2018-01-21 11:17:43 +00:00
|
|
|
}
|
|
|
|
|
2021-03-24 11:45:18 +00:00
|
|
|
func (s *DefaultIPSearcher) Lookup(ip string) (uids []int, e error) {
|
2022-02-21 03:32:53 +00:00
|
|
|
var uid int
|
|
|
|
reqUserList := make(map[int]bool)
|
|
|
|
runQuery2 := func(rows *sql.Rows, e error) error {
|
|
|
|
if e != nil {
|
|
|
|
return e
|
|
|
|
}
|
|
|
|
defer rows.Close()
|
2018-01-21 11:17:43 +00:00
|
|
|
|
2022-02-21 03:32:53 +00:00
|
|
|
for rows.Next() {
|
|
|
|
if e := rows.Scan(&uid); e != nil {
|
|
|
|
return e
|
|
|
|
}
|
|
|
|
reqUserList[uid] = true
|
|
|
|
}
|
|
|
|
return rows.Err()
|
|
|
|
}
|
|
|
|
runQuery := func(stmt *sql.Stmt) error {
|
|
|
|
return runQuery2(stmt.Query(ip))
|
|
|
|
}
|
2018-01-21 11:17:43 +00:00
|
|
|
|
2022-02-21 03:32:53 +00:00
|
|
|
e = runQuery2(s.searchUsers.Query(ip, ip))
|
|
|
|
if e != nil {
|
|
|
|
return uids, e
|
|
|
|
}
|
|
|
|
e = runQuery(s.searchTopics)
|
|
|
|
if e != nil {
|
|
|
|
return uids, e
|
|
|
|
}
|
|
|
|
e = runQuery(s.searchReplies)
|
|
|
|
if e != nil {
|
|
|
|
return uids, e
|
|
|
|
}
|
|
|
|
e = runQuery(s.searchUsersReplies)
|
|
|
|
if e != nil {
|
|
|
|
return uids, e
|
|
|
|
}
|
2018-01-21 11:17:43 +00:00
|
|
|
|
2022-02-21 03:32:53 +00:00
|
|
|
// Convert the user ID map to a slice, then bulk load the users
|
|
|
|
uids = make([]int, len(reqUserList))
|
|
|
|
var i int
|
|
|
|
for userID := range reqUserList {
|
|
|
|
uids[i] = userID
|
|
|
|
i++
|
|
|
|
}
|
2018-01-21 11:17:43 +00:00
|
|
|
|
2022-02-21 03:32:53 +00:00
|
|
|
return uids, nil
|
2018-01-21 11:17:43 +00:00
|
|
|
}
|