func loginHandlerV2(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, form loginFormV2) { user := &models.Account{} if exists, _ := models.CheckUserExists(form.Id, form.Type); !exists { writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.AuthError, "该用户还未注册")) return } user.FindPass(form.Id, form.Type, Md5(form.Password)) if len(user.Id) == 0 { writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.AuthError)) return } if user.TimeLimit < 0 { writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.AuthError, "账户已禁用")) return } token := Uuid() + "-" + strconv.FormatInt(time.Now().AddDate(0, 0, 30).Unix(), 10) redis.SetOnlineUser(token, user.Id) data := map[string]interface{}{ "access_token": token, "userid": user.Id, //"last_login_time": user.LastLogin.Unix(), } writeResponse(request.RequestURI, resp, data, nil) }
func userInfoHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, p Parameter) { user := &models.Account{} form := p.(getInfoForm) if find, err := user.FindByUserid(form.Userid); !find { if err == nil { err = errors.NewError(errors.NotExistsError) } writeResponse(request.RequestURI, resp, nil, err) return } info := convertUser(user, redis) //info.Pet = userPet(info.Props.Level) info.ScoreRank, _ = user.PropIndex("score", user.Props.Score) if uid := redis.OnlineUser(p.TokenId()); len(uid) > 0 { relation := redis.Relationship(uid, user.Id) switch relation { case models.RelFriend: info.Relation = "FRIENDS" case models.RelFollowing: info.Relation = "ATTENTION" case models.RelFollower: info.Relation = "FANS" case models.RelBlacklist: info.Relation = "DEFRIEND" } } writeResponse(request.RequestURI, resp, info, nil) }
func setGroupHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(setGroupForm) group := &models.Group{ Gid: form.Id, Name: form.Name, Profile: form.Profile, Desc: form.Desc, Creator: user.Id, Time: time.Now(), } if form.Address.String() != "" { group.Addr = &form.Address loc := models.Addr2Loc(form.Address) group.Loc = &loc } var err error if len(form.Id) == 0 { err = group.Save() if err == nil { redis.JoinGroup(user.Id, group.Gid, true) } } else { err = group.Update() } writeResponse(request.RequestURI, resp, map[string]string{"group_id": group.Gid}, err) }
func regHandlerV2(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, form regFormV2) { exists, err := models.CheckUserExists(form.Id, form.Type) if err != nil { writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.DbError)) return } if exists { writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.UserExistError)) return } dbw, err := getNewWallet() if err != nil { writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.DbError, "创建钱包失败")) return } user := &models.Account{ Role: form.Type, Password: Md5(form.Password), Nickname: form.Nickname, Profile: form.Profile, Gender: form.Gender, Birth: form.Birthday, Wallet: *dbw, RegTime: time.Now(), } switch form.Type { case models.AccountPhone: user.Phone = form.Id case models.AccountWeibo: user.Weibo = form.Id case models.AccountEmail: fallthrough default: user.Email = form.Id } if err := user.Save(); err != nil { writeResponse(request.RequestURI, resp, nil, err) return } token := Uuid() + "-" + strconv.FormatInt(time.Now().AddDate(0, 0, 30).Unix(), 10) data := map[string]string{"access_token": token, "userid": user.Id} writeResponse(request.RequestURI, resp, data, nil) redis.LogRegister(user.Id, form.Type) redis.SetOnlineUser(token, user.Id) // ws push //regNotice(user.Id, redis) }
func checkTokenHandler(c martini.Context, p Parameter, redis *models.RedisLogger, r *http.Request, w http.ResponseWriter) { uid := redis.OnlineUser(p.TokenId()) if len(uid) == 0 { writeResponse(r.RequestURI, w, nil, errors.NewError(errors.AccessError)) } fmt.Println("===", p.TokenId(), uid) c.Map(&models.Account{Id: uid}) }
func blacklistHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(relationshipForm) redis.SetRelationship(user.Id, form.Userids, models.RelBlacklist, form.Blacklist) writeResponse(request.RequestURI, resp, map[string]interface{}{"ExpEffect": Awards{}}, nil) }
/* func (this loginForm) getUserId() string { return this.Userid } */ func weiboLogin(uid, password string, redis *models.RedisLogger) (bool, *models.Account, error) { user := &models.Account{} exists, err := user.FindByWeibo(strings.ToLower(uid)) if err != nil { return false, nil, err } p := Md5(password) registered := user.RegTime.Unix() > 0 if registered { if user.Password != p { user.SetPassword(p) } return false, user, nil } weiboUser, err := GetWeiboUserInfo(uid, password) if err != nil { return false, nil, err } user.Nickname = weiboUser.ScreenName if find, _ := user.Exists("nickname"); find { user.Nickname = "wb_" + user.Nickname } user.Password = p if !strings.HasPrefix(weiboUser.Gender, "f") { user.Gender = "male" } else { user.Gender = "female" } user.Weibo = uid user.Url = weiboUser.Url user.Profile = weiboUser.Avatar //user.Addr = &models.Address{Desc: weiboUser.Location} user.About = weiboUser.Description user.Role = models.AccountWeibo user.RegTime = time.Now() dbw, err := getNewWallet() if err != nil { return true, nil, err } user.Wallet = *dbw if !exists { if err := user.Save(); err != nil { return true, nil, err } } redis.LogRegister(user.Id, user.Role) // ws push regNotice(user.Id, redis) return true, user, nil }
func userAuthRequestHandler(r *http.Request, w http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(authRequestForm) err := user.SetAuthInfo(form.Type, form.Images, form.Desc) redis.AddAuthCoach(user.Id) writeResponse(r.RequestURI, w, nil, err) }
func logoutHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { redis.DelOnlineUser(p.TokenId()) if len(user.Devs) > 0 { user.RmDevice(user.Devs[0]) } writeResponse(request.RequestURI, resp, nil, nil) }
func checkToken(r *models.RedisLogger, t string) (valid bool, err error) { uid := r.OnlineUser(t) if len(uid) == 0 { err = errors.NewError(errors.AccessError) valid = false return } valid = true return }
func friendCountHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, user *models.Account) { follows, followers, friends, blacklist := redis.FriendCount(user.Id) respData := map[string]int{ "friend_count": friends, "attention_count": follows, "fans_count": followers, "defriend_count": blacklist, } writeResponse(request.RequestURI, resp, respData, nil) }
func getQiniuTokenHandler(r *http.Request, w http.ResponseWriter, redis *models.RedisLogger) { token := redis.GetQiniuUpToken() //log.Println(token) if len(token) == 0 { token = uptoken("test") redis.SetQiniuUpToken(token) } writeResponse(r.RequestURI, w, map[string]string{"token": token}, nil) }
func articleNewsHandler(r *http.Request, w http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(articleNewsForm) followings := redis.Friends(models.RelFollowing, user.Id) //followings = append(followings, user.Id) // self included //fmt.Println(followings) count, err := models.NewArticles(followings, form.Id) writeResponse(r.RequestURI, w, bson.M{"count": count}, err) }
func retentionHandler(w http.ResponseWriter, redis *models.RedisLogger, form retentionForm) { if ok, err := checkToken(redis, form.Token); !ok { writeResponse(w, err) return } date := time.Now() if form.Date > 0 { date = time.Unix(form.Date, 0) } r := redis.Retention(date) writeResponse(w, map[string]interface{}{"retention": r}) }
func taskReferralsHandler(r *http.Request, w http.ResponseWriter, redis *models.RedisLogger, user *models.Account) { if user.Taskid > len(models.NewTasks) { writeResponse(r.RequestURI, w, nil, errors.NewError(errors.AccessError)) return } task := models.NewTasks[user.Taskid] excludes := redis.TaskSharers() friends := redis.Friends(models.RelFriend, user.Id) excludes = append(excludes, user.Id) excludes = append(excludes, friends...) users, _ := user.TaskReferrals(task.Type, excludes) var referrals []*referral for i, _ := range users { ref := &referral{ Userid: users[i].Id, Nickname: users[i].Nickname, Profile: users[i].Profile, Gender: users[i].Gender, Images: users[i].Photos, Birthday: users[i].Birth, Lastlog: users[i].LastLogin.Unix(), Location: users[i].Loc, } if users[i].Ratios.RunRecv > 0 { ref.RunRatio = float32(users[i].Ratios.RunAccept) / float32(users[i].Ratios.RunRecv) } if users[i].Ratios.PostRecv > 0 { ref.PostRatio = float32(users[i].Ratios.PostAccept) / float32(users[i].Ratios.PostRecv) } if users[i].Ratios.PKRecv > 0 { ref.PkRatio = float32(users[i].Ratios.PKAccept) / float32(users[i].Ratios.PKRecv) } if task.Type == models.TaskRunning || task.Type == models.TaskGame { rec, _ := users[i].LastRecord("run") ref.LastId = rec.Id.Hex() ref.LastTime = rec.PubTime.Unix() } else if task.Type == models.TaskPost { article := users[i].LatestArticle() ref.LastId = article.Id.Hex() ref.LastTime = article.PubTime.Unix() } referrals = append(referrals, ref) } respData := map[string]interface{}{"referrals": referrals} writeResponse(r.RequestURI, w, respData, nil) }
func regNotice(uid string, redis *models.RedisLogger) { notice := &models.Event{ Type: models.EventWallet, Time: time.Now().Unix(), Data: models.EventData{ Type: models.EventTx, Id: uid, From: uid, Body: []models.MsgBody{ {Type: "rule", Content: "1"}, }, }, } redis.Notice(notice.Bytes()) }
func socialListHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, form socialListForm) { user := &models.Account{Id: form.Userid} var ids []string switch form.Type { case "FRIENDS": ids = redis.Friends(models.RelFriend, user.Id) case "ATTENTION": ids = redis.Friends(models.RelFollowing, user.Id) case "FANS": ids = redis.Friends(models.RelFollower, user.Id) case "DEFRIEND": ids = redis.Friends(models.RelBlacklist, user.Id) case "WEIBO": ids = redis.Friends("weibo", user.Id) } users, err := models.Users(ids, &form.Paging) if err != nil { writeResponse(request.RequestURI, resp, nil, err) return } lb := make([]leaderboardResp, len(users)) for i, _ := range users { lb[i].Userid = users[i].Id lb[i].Score = users[i].Props.Score lb[i].Level = users[i].Level() lb[i].Profile = users[i].Profile lb[i].Nickname = users[i].Nickname lb[i].Gender = users[i].Gender lb[i].LastLog = users[i].LastLogin.Unix() lb[i].Birth = users[i].Birth lb[i].Location = users[i].Loc lb[i].Phone = users[i].Phone lb[i].Actor = users[i].Actor } respData := map[string]interface{}{ "members_list": lb, "page_frist_id": form.Paging.First, "page_last_id": form.Paging.Last, } writeResponse(request.RequestURI, resp, respData, nil) return }
func articlePostHandler(w http.ResponseWriter, redis *models.RedisLogger, form postForm) { uid := redis.OnlineUser(form.Token) if len(uid) == 0 { writeResponse(w, errors.NewError(errors.AccessError)) return } user := &models.Account{Id: uid} article := &models.Article{ Parent: form.Id, Author: form.Author, PubTime: time.Now(), //Tags: []string{form.Tags}, } switch v := form.Tags.(type) { case string: article.Tags = []string{v} case []string: article.Tags = v } if len(article.Tags) == 0 { article.Tags = []string{"SPORT_LOG"} } if len(form.Author) == 0 { article.Author = user.Id } article.Content = form.Contents article.Title = form.Title article.Images = form.Image if len(article.Images) > 0 { article.Image = article.Images[0] } /* article.Contents = append(article.Contents, models.Segment{ContentType: "TEXT", ContentText: form.Contents}) */ if err := article.Save(); err != nil { writeResponse(w, err) return } writeResponse(w, map[string]string{"article_id": article.Id.Hex()}) }
func taskAuthListHandler(r *http.Request, w http.ResponseWriter, redis *models.RedisLogger, form taskAuthListForm) { userid := redis.OnlineUser(form.Token) if len(userid) == 0 { writeResponse(w, errors.NewError(errors.AccessError)) return } pass := make([]bool, len(form.Auths)) for i, _ := range form.Auths { taskAuthFunc(userid, &form.Auths[i], redis) pass[i] = form.Auths[i].Pass } writeResponse(w, map[string][]bool{"pass": pass}) }
func loginHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, form loginForm) { user := &models.Account{} var err error var reg bool token := Uuid() + "-" + strconv.FormatInt(time.Now().AddDate(0, 0, 30).Unix(), 10) switch form.Type { case "weibo": reg, user, err = weiboLogin(form.Userid, form.Password, redis) case "weixin": writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.UnimplementedError)) return case "usrpass": fallthrough default: var find bool if find, err = user.FindByUserPass(strings.ToLower(form.Userid), Md5(form.Password)); !find { if err == nil { err = errors.NewError(errors.AuthError) } } } if err != nil { writeResponse(request.RequestURI, resp, nil, err) return } if user.TimeLimit < 0 { writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.AuthError, "账户已禁用")) return } redis.SetOnlineUser(token, user.Id) data := map[string]interface{}{ "access_token": token, "userid": user.Id, "register": reg, "last_login_time": user.LastLogin.Unix(), "ExpEffect": Awards{}, } writeResponse(request.RequestURI, resp, data, nil) }
func taskAuthHandler(r *http.Request, w http.ResponseWriter, redis *models.RedisLogger, form taskAuthForm) { userid := redis.OnlineUser(form.Token) if len(userid) == 0 { writeResponse(w, errors.NewError(errors.AccessError)) return } a := &taskAuth{ Userid: form.Userid, Id: form.Id, Pass: form.Pass, Reason: form.Reason, } if err := taskAuthFunc(userid, a, redis); err != nil { writeResponse(w, err) return } writeResponse(w, map[string]bool{"pass": form.Pass}) }
func importContactsHandler(r *http.Request, w http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(importContactsForm) var result []*userJsonStruct users, _ := models.FindUsersByPhones(form.Contacts) ids := redis.Friends(models.RelFollowing, user.Id) for j, _ := range users { i := 0 for ; i < len(ids); i++ { if users[j].Id == ids[i] || users[j].Id == user.Id { break } } if i >= len(ids) { result = append(result, convertUser(&users[j], redis)) } } writeResponse(r.RequestURI, w, map[string]interface{}{"users": result}, nil) }
func recvHeartHandler(r *http.Request, w http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(recvHeartForm) // ws push event := &models.Event{ Type: models.EventSystem, Time: time.Now().Unix(), Data: models.EventData{ Type: models.EventRecvHeart, Id: user.Id, From: user.Id, To: form.Sender, Body: []models.MsgBody{ {Type: "userid", Content: user.Id}, }, }, } awards := Awards{} if form.Accept { redis.SetRelationship(user.Id, []string{form.Sender}, models.RelFriend, true) event.Save() redis.PubMsg(models.EventSystem, form.Sender, event.Bytes()) awards.Wealth = 1 * models.Satoshi GiveAwards(user, awards, redis) } redis.SetHeartRecv(user.Id, false) writeResponse(r.RequestURI, w, map[string]interface{}{"ExpEffect": awards}, nil) }
func registerHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, form userRegForm) { user := &models.Account{} t := "" if phone, _ := strconv.ParseUint(form.Email, 10, 64); phone > 0 { user.Phone = form.Email t = models.AccountPhone } else { user.Email = strings.ToLower(form.Email) t = models.AccountEmail } if exists, _ := user.Exists(t); exists { writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.UserExistError)) return } //user.Nickname = form.Nickname user.Password = Md5(form.Password) user.Role = t user.RegTime = time.Now() dbw, err := getNewWallet() if err != nil { writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.DbError, "wallet: "+err.Error())) return } user.Wallet = *dbw if err := user.Save(); err != nil { writeResponse(request.RequestURI, resp, nil, err) } else { token := Uuid() + "-" + strconv.FormatInt(time.Now().AddDate(0, 0, 30).Unix(), 10) data := map[string]string{"access_token": token, "userid": user.Id} writeResponse(request.RequestURI, resp, data, nil) redis.LogRegister(user.Id, t) redis.SetOnlineUser(token, user.Id) // ws push regNotice(user.Id, redis) } }
func joinGroupHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(joinGroupForm) redis.JoinGroup(user.Id, form.Gid, !form.Leave) writeResponse(request.RequestURI, resp, nil, nil) event := &models.Event{ Type: "message", Data: models.EventData{ From: user.Id, To: form.Gid, }, } if !form.Leave { event.Data.Type = "subscribe" } else { event.Data.Type = "unsubscribe" } redis.PubMsg(event.Data.Type, user.Id, event.Bytes()) }
func articleInfoHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(articleInfoForm) article := &models.Article{} if find, err := article.FindById(form.Id); !find { if err == nil { err = errors.NewError(errors.NotExistsError) } writeResponse(request.RequestURI, resp, nil, err) return } event := &models.Event{} //event.Data.Type = models.EventThumb event.Data.Id = article.Id.Hex() event.Data.To = user.Id event.Clear() // clear all events about this article u := &models.Account{} u.FindByUserid(article.Author) author := convertUser(u, redis) jsonStruct := convertArticle(user, article, author) jsonStruct.Relation = redis.Relationship(user.Id, article.Author) switch jsonStruct.Relation { case models.RelFriend: jsonStruct.Relation = "FRIENDS" case models.RelFollowing: jsonStruct.Relation = "ATTENTION" case models.RelFollower: jsonStruct.Relation = "FANS" case models.RelBlacklist: jsonStruct.Relation = "DEFRIEND" } writeResponse(request.RequestURI, resp, jsonStruct, nil) }
func GiveAwards(user *models.Account, awards Awards, redis *models.RedisLogger) error { if awards.Level < 0 || awards.Score < 0 { panic("invalid level or score") } if _, err := sendCoin(user.Wallet.Addr, awards.Wealth); err != nil { return err } redis.SendCoins(user.Id, awards.Wealth) err := user.UpdateProps(models.Props{ Physical: awards.Physical, Literal: awards.Literal, Mental: awards.Mental, //Wealth: awards.Wealth, Score: awards.Score, //Level: awards.Level, }) if err != nil { return err } if lvl := models.Score2Level(user.Props.Score + awards.Score); lvl > user.Level() { // ws push event := &models.Event{ Type: models.EventNotice, Time: time.Now().Unix(), Data: models.EventData{ Type: models.EventLevelUP, To: user.Id, }, } event.Save() redis.PubMsg(event.Type, event.Data.To, event.Bytes()) } return nil }
func followHandler(request *http.Request, resp http.ResponseWriter, client *ApnClient, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(relationshipForm) for _, peer := range form.Userids { if redis.Relationship(peer, user.Id) == models.RelBlacklist { writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.DbError, "对方已屏蔽了你!")) return } } redis.SetRelationship(user.Id, form.Userids, models.RelFollowing, form.Follow) writeResponse(request.RequestURI, resp, map[string]interface{}{"ExpEffect": Awards{}}, nil) for _, userid := range form.Userids { u := &models.Account{} u.FindByUserid(userid) event := &models.Event{ Type: models.EventMsg, Time: time.Now().Unix(), Data: models.EventData{ Type: models.EventSub, Id: user.Id + "-" + u.Id, From: user.Id, To: u.Id, Body: []models.MsgBody{ {Type: "nikename", Content: user.Nickname}, {Type: "image", Content: user.Profile}, }, }, } if form.Follow { /* if err := event.Save(); err == nil { redis.IncrEventCount(u.Id, event.Data.Type, 1) } */ event.Upsert() event.Data.Body = append(event.Data.Body, models.MsgBody{Type: "new_count", Content: "1"}) redis.PubMsg(models.EventMsg, u.Id, event.Bytes()) // apple push if u.Push { go sendApn(client, user.Nickname+"关注了你!", u.EventCount("", ""), u.Devs...) } } else { //count := u.DelEvent(models.EventSub, user.Id, user.Id, u.Id) //redis.IncrEventCount(u.Id, models.EventSub, -count) event.Delete() } } }
func recommendHandler(r *http.Request, w http.ResponseWriter, redis *models.RedisLogger, user *models.Account, p Parameter) { form := p.(recommendForm) excludes := redis.Friends(models.RelFollowing, user.Id) excludes = append(excludes, redis.Friends(models.RelBlacklist, user.Id)...) users, _ := user.Recommend(excludes) var list []*leaderboardResp for i, _ := range users { if users[i].Id == user.Id { continue } rel := redis.Relationship(user.Id, users[i].Id) if rel == models.RelFollowing || rel == models.RelFriend { continue } lb := &leaderboardResp{ Userid: users[i].Id, Score: users[i].Props.Score, Level: users[i].Level(), Profile: users[i].Profile, Nickname: users[i].Nickname, Gender: users[i].Gender, LastLog: users[i].LastLogin.Unix(), Birth: users[i].Birth, Location: users[i].Loc, Addr: users[i].LocAddr, Phone: users[i].Phone, Actor: users[i].Actor, } lb.Distance, _ = redis.RecStats(users[i].Id) lb.Status = users[i].LatestArticle().Title list = append(list, lb) } respData := map[string]interface{}{ "members_list": list, "page_frist_id": form.Paging.First, "page_last_id": form.Paging.Last, } writeResponse(r.RequestURI, w, respData, nil) }
func adminLoginHandler(w http.ResponseWriter, redis *models.RedisLogger, form jsgenLoginForm) { user := &models.Account{} log.Println(form.Username, form.Password) h := md5.New() io.WriteString(h, form.Password) pwd := fmt.Sprintf("%x", h.Sum(nil)) find := false var err error if find, err = user.FindByUserPass(strings.ToLower(form.Username), pwd); !find { if err == nil { err = AuthError } else { err = DbError } } if err != nil { writeResponse(w, false, nil, nil, err) return } redis.LogLogin(user.Id) info := &User{ Id: user.Id, Name: user.Nickname, Nickname: user.Nickname, Email: "", Locked: user.TimeLimit != 0, Social: social{}, Sex: user.Gender, Role: 1, Avatar: user.Profile, Desc: user.About, Date: user.RegTime.Unix() * 1000, Score: user.Score, ReadTime: 0, LastLogin: user.LastLogin.Unix() * 1000, FollowList: redis.Friends(models.RelFollowing, user.Id), TagsList: []string{}, Articles: user.ArticleCount(), Collections: 0, MarkList: []int{}, Unread: []string{}, ReceiveList: []string{}, SendList: []string{}, } info.Follow, info.Fans, _, _ = redis.FriendCount(user.Id) writeResponse(w, true, info, nil, nil) }