Merge branch 'master' into kd-live

This commit is contained in:
2023-08-29 18:41:22 +09:00
10 changed files with 796 additions and 272 deletions

View File

@ -2,9 +2,7 @@ package core
import (
"bytes"
"crypto/md5"
"encoding/binary"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
@ -27,7 +25,6 @@ import (
)
type FileDocumentDesc struct {
Service string `bson:"service" json:"service"`
Key string `bson:"key" json:"key"`
Src string `bson:"src" json:"src"`
Link string `bson:"link" json:"link"`
@ -110,11 +107,6 @@ var seq = uint32(0)
func (caller apiCaller) uploadAPI(w http.ResponseWriter, r *http.Request) error {
if r.Method == "PUT" {
servicename := r.FormValue("service")
hasher := md5.New()
hasher.Write([]byte(servicename))
subfolder := hex.EncodeToString(hasher.Sum(nil))[:8]
infile, header, err := r.FormFile("file")
if err != nil {
w.WriteHeader(http.StatusBadRequest)
@ -130,17 +122,16 @@ func (caller apiCaller) uploadAPI(w http.ResponseWriter, r *http.Request) error
var b [5]byte
binary.BigEndian.PutUint32(b[0:4], uint32(time.Now().Unix()))
b[4] = byte(atomic.AddUint32(&seq, 1) % 255)
rf := hex.EncodeToString(b[1:])
newidstr := subfolder + rf
newidbt, _ := hex.DecodeString(newidstr)
newidobj := primitive.NewObjectID()
copy(newidobj[:], newidbt[:8])
newidobj := primitive.NewObjectID()
copy(newidobj[:], b[1:])
rf := newidobj.Hex()
var link string
if extract {
link = path.Join("static", subfolder, rf)
link = path.Join("static", rf)
} else {
link = path.Join("static", subfolder, rf, header.Filename)
link = path.Join("static", rf, header.Filename)
}
newdoc := FileDocumentDesc{
@ -151,12 +142,10 @@ func (caller apiCaller) uploadAPI(w http.ResponseWriter, r *http.Request) error
Link: link,
Desc: desc,
Key: rf,
Service: servicename,
}
_, _, err = caller.mg.mongoClient.UpsertOne(CollectionFile, bson.M{
"_id": newidobj,
"service": servicename,
"key": rf,
"_id": newidobj,
"key": rf,
}, newdoc)
if err == nil {
@ -169,44 +158,81 @@ func (caller apiCaller) uploadAPI(w http.ResponseWriter, r *http.Request) error
return nil
}
func (caller apiCaller) whitelistAPI(w http.ResponseWriter, r *http.Request) error {
func (caller apiCaller) blockAPI(w http.ResponseWriter, r *http.Request) error {
mg := caller.mg
if r.Method == "GET" {
// if !caller.isAdminOrValidToken() {
// logger.Println("whitelistAPI failed. not vaild user :", r.Method, caller.userinfo)
// w.WriteHeader(http.StatusUnauthorized)
// return nil
// }
enc := json.NewEncoder(w)
enc.Encode(mg.bl.all())
} else if r.Method == "PUT" {
body, _ := io.ReadAll(r.Body)
all, err := mg.mongoClient.All(CollectionWhitelist)
var bipl blockinfoWithStringId
if err := json.Unmarshal(body, &bipl); err != nil {
return err
}
accid, err := primitive.ObjectIDFromHex(bipl.StrId)
if err != nil {
return err
}
if len(all) > 0 {
var notexp []primitive.M
for _, v := range all {
if _, exp := v["_ts"]; !exp {
notexp = append(notexp, v)
}
}
allraw, _ := json.Marshal(notexp)
w.Write(allraw)
bi := blockinfo{
Start: primitive.NewDateTimeFromTime(time.Unix(bipl.StartUnix, 0)),
End: primitive.NewDateTimeFromTime(time.Unix(bipl.EndUnix, 0)),
Reason: bipl.Reason,
}
logger.Println("bi :", accid, bi)
_, _, err = mg.mongoClient.Update(CollectionBlock, bson.M{
"_id": accid,
}, bson.M{
"$set": &bi,
}, options.Update().SetUpsert(true))
if err != nil {
return err
}
} else if r.Method == "DELETE" {
id := r.URL.Query().Get("id")
if len(id) == 0 {
return errors.New("id param is missing")
}
idobj, err := primitive.ObjectIDFromHex(id)
if err != nil {
return err
}
_, _, err = mg.mongoClient.Update(CollectionBlock, bson.M{
"_id": idobj,
}, bson.M{
"$currentDate": bson.M{
"_ts": bson.M{"$type": "date"},
},
}, options.Update().SetUpsert(false))
if err != nil {
return err
}
mg.mongoClient.Delete(CollectionAuth, bson.M{"_id": idobj})
}
return nil
}
func (caller apiCaller) whitelistAPI(w http.ResponseWriter, r *http.Request) error {
mg := caller.mg
if r.Method == "GET" {
enc := json.NewEncoder(w)
enc.Encode(mg.wl.all())
} else if r.Method == "PUT" {
body, _ := io.ReadAll(r.Body)
var member whitelistmember
if err := json.Unmarshal(body, &member); err != nil {
return err
}
// if !caller.isAdminOrValidToken() {
// logger.Println("whitelistAPI failed. not vaild user :", r.Method, caller.userinfo)
// w.WriteHeader(http.StatusUnauthorized)
// return nil
// }
member.Expired = 0
member.ExpiredAt = 0
_, _, err := mg.mongoClient.Update(CollectionWhitelist, bson.M{
"_id": primitive.NewObjectID(),
@ -260,7 +286,7 @@ func (caller apiCaller) serviceAPI(w http.ResponseWriter, r *http.Request) error
atomic.StorePointer(&mg.serviceptr, unsafe.Pointer(&newService))
}
w.Write(mg.service().divisionsSerialized)
w.Write(mg.service().serviceSerialized)
} else if r.Method == "POST" {
body, _ := io.ReadAll(r.Body)
var service serviceDescription
@ -319,6 +345,38 @@ func (caller apiCaller) maintenanceAPI(w http.ResponseWriter, r *http.Request) e
return nil
}
func (caller apiCaller) couponAPI(w http.ResponseWriter, r *http.Request) error {
switch r.Method {
case "PUT":
// 쿠폰 생성
logger.Println("begin generateCoupons")
generateCoupons(caller.mg.mongoClient, w, r)
case "POST":
// TODO : 쿠폰 사용
// 쿠폰 사용 표시 해주고 내용을 응답
logger.Println("begin useCoupon")
useCoupon(caller.mg.mongoClient, w, r)
case "GET":
// 쿠폰 조회
if r.Form.Has("code") {
// 쿠폰 코드 조회
logger.Println("begin queryCoupon")
queryCoupon(caller.mg.mongoClient, w, r)
} else if r.Form.Has("name") {
// 쿠폰 코드 다운
logger.Println("begin downloadCoupons")
downloadCoupons(caller.mg.mongoClient, w, r)
} else {
// 쿠폰 이름 목록
logger.Println("begin listAllCouponNames")
listAllCouponNames(caller.mg.mongoClient, w, r)
}
}
return nil
}
var errApiTokenMissing = errors.New("mg-x-api-token is missing")
func (caller apiCaller) configAPI(w http.ResponseWriter, r *http.Request) error {
@ -359,6 +417,8 @@ func (mg *Maingate) api(w http.ResponseWriter, r *http.Request) {
r.Body.Close()
}()
r.ParseMultipartForm(32 << 20)
var userinfo map[string]any
if !*devflag {
@ -439,6 +499,10 @@ func (mg *Maingate) api(w http.ResponseWriter, r *http.Request) {
err = caller.maintenanceAPI(w, r)
} else if strings.HasSuffix(r.URL.Path, "/files") {
err = caller.filesAPI(w, r)
} else if strings.HasSuffix(r.URL.Path, "/block") {
err = caller.blockAPI(w, r)
} else if strings.HasSuffix(r.URL.Path, "/coupon") {
err = caller.couponAPI(w, r)
}
if err != nil {