Example #1
0
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)
}
Example #2
0
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)
}
Example #3
0
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)
}
Example #4
0
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
}
Example #5
0
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)
}
Example #6
0
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)
}
Example #7
0
func articleListHandler(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account, p Parameter) {
	var articles []models.Article
	var err error
	form := p.(articleListForm)

	if len(form.Tag) > 0 {
		_, articles, err = models.GetArticles(form.Tag, &form.Paging, true)
	} else if form.Circle {
		followings := redis.Friends(models.RelFollowing, user.Id)
		followings = append(followings, user.Id) // self included
		_, articles, err = models.GetFollowingsArticles(followings, &form.Paging)
	} else {
		excludes := redis.Friends(models.RelFollowing, user.Id)
		excludes = append(excludes, redis.Friends(models.RelBlacklist, user.Id)...)
		excludes = append(excludes, user.Id)
		recommends, _ := user.Recommend(excludes)
		ids := []string{}
		for i, _ := range recommends {
			ids = append(ids, recommends[i].Id)
		}
		_, articles, err = models.GetRecommendArticles(ids, &form.Paging)
	}

	jsonStructs := make([]*articleJsonStruct, len(articles))
	for i, _ := range articles {
		u := &models.Account{}
		u.FindByUserid(articles[i].Author)
		author := convertUser(u, redis)
		jsonStructs[i] = convertArticle(user, &articles[i], author)
	}

	respData := make(map[string]interface{})
	respData["page_frist_id"] = form.Paging.First
	respData["page_last_id"] = form.Paging.Last
	//respData["page_item_count"] = total
	respData["articles_without_content"] = jsonStructs
	writeResponse(request.RequestURI, resp, respData, err)
}
Example #8
0
func gamelbHandler(r *http.Request, w http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account, p Parameter) {

	form := p.(gamelbForm)
	if form.Index <= 0 {
		form.Index = 0
	}
	if form.Count <= 0 {
		form.Count = 20
	}

	gt := gameType(form.Game)
	var ids []string
	var kvs []models.KV

	switch form.Query {
	case "FRIEND":
		ids = redis.Friends(models.RelFriend, user.Id)
		if len(ids) == 0 {
			break
		}

		ids = append(ids, user.Id)

		if form.Index*form.Count >= len(ids) {
			break
		}

		start := form.Index * form.Count
		end := start + form.Count
		if end > len(ids) {
			end = len(ids)
		}

		scores := redis.UserGameScores(gt, ids...)
		if len(scores) != len(ids) {
			scores = make([]int64, len(ids))
		}

		kvs = make([]models.KV, len(ids))
		for i, _ := range kvs {
			kvs[i].K = ids[i]
			kvs[i].V = scores[i]
			if ids[i] == user.Id {
				kvs[i].V = int64(form.Score)
			}
		}
		sort.Sort(sort.Reverse(models.KVSlice(kvs)))

		kvs = kvs[start:end]
		ids = []string{}
		for _, kv := range kvs {
			ids = append(ids, kv.K)
		}
	case "TOP":
		fallthrough
	default:
		maxScore := 0
		if scores := redis.UserGameScores(gt, user.Id); len(scores) == 1 {
			maxScore = int(scores[0])
		}
		redis.SetGameScore(gt, user.Id, form.Score) // current score
		kvs = redis.GameScores(gt, form.Index*form.Count, form.Count)
		redis.SetGameScore(gt, user.Id, maxScore) // recover max score
		for i, kv := range kvs {
			ids = append(ids, kv.K)
			if kv.K == user.Id {
				kvs[i].V = int64(form.Score)
			}
		}
	}

	var respData struct {
		List []*leaderboardResp `json:"members_list"`
	}

	users, _ := models.FindUsersByIds(1, ids...)
	index := 0
	for _, kv := range kvs {
		for i, _ := range users {
			if users[i].Id == kv.K {
				respData.List = append(respData.List, &leaderboardResp{
					Userid:   users[i].Id,
					Score:    kv.V,
					Rank:     form.Index*form.Count + index + 1,
					Level:    users[i].Level(),
					Profile:  users[i].Profile,
					Nickname: users[i].Nickname,
					Actor:    users[i].Actor,
					Gender:   users[i].Gender,
					LastLog:  users[i].LastGameTime(gt).Unix(),
					Birth:    users[i].Birth,
					Location: users[i].Loc,
					Phone:    users[i].Phone,
				})
				index++

				break
			}
		}
	}

	writeResponse(r.RequestURI, w, respData, nil)
}
Example #9
0
func leaderboardHandler(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account, form leaderboardForm) {
	if form.Paging.Count == 0 {
		form.Paging.Count = models.DefaultPageSize
	}

	start := 0
	stop := 0

	switch form.Type {
	case "FRIEND":
		ids := redis.Friends("friend", user.Id)
		friends, err := models.Users(ids, &form.Paging)
		if err != nil {
			writeResponse(request.RequestURI, resp, nil, err)
			return
		}
		lb := make([]leaderboardResp, len(friends))
		for i, _ := range friends {
			lb[i].Userid = friends[i].Id
			lb[i].Score = friends[i].Props.Score
			lb[i].Level = friends[i].Level()
			lb[i].Profile = friends[i].Profile
			lb[i].Nickname = friends[i].Nickname
			lb[i].Gender = friends[i].Gender
			lb[i].Actor = friends[i].Actor
			lb[i].LastLog = friends[i].LastLogin.Unix()
			lb[i].Birth = friends[i].Birth
			lb[i].Location = friends[i].Loc
			lb[i].Phone = friends[i].Phone
		}

		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

	case "USER_AROUND":
		rank := redis.LBDisRank(form.Info)
		if rank < 0 {
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.NotExistsError, "user not exist"))
			return
		}

		if form.Paging.Count < 0 {
			start = rank
			stop = rank
			break
		}

		start = rank - form.Paging.Count
		if start < 0 {
			start = 0
		}
		stop = rank + form.Paging.Count
	case "TOP":
		fallthrough
	default:
		start, stop = leaderboardPaging(&form.Paging)
	}

	kv := redis.GetDisLB(start, stop)
	ids := make([]string, len(kv))
	for i, _ := range kv {
		ids[i] = kv[i].K
	}

	users, _ := models.FindUsersByIds(0, ids...)

	lb := make([]leaderboardResp, len(kv))
	for i, _ := range kv {
		lb[i].Userid = kv[i].K
		lb[i].Rank = start + i + 1
		lb[i].Score = kv[i].V
		for _, user := range users {
			if user.Id == kv[i].K {
				lb[i].Nickname = user.Nickname
				lb[i].Profile = user.Profile
				break
			}
		}
	}

	page_first := 0
	page_last := 0
	if len(lb) > 0 {
		page_first = lb[0].Rank
		page_last = lb[len(lb)-1].Rank
	}

	respData := map[string]interface{}{
		"members_list":  lb,
		"page_frist_id": strconv.Itoa(page_first),
		"page_last_id":  strconv.Itoa(page_last),
	}
	writeResponse(request.RequestURI, resp, respData, nil)
}
Example #10
0
func getFollowersHandler(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account) {

	writeResponse(request.RequestURI, resp, redis.Friends(models.RelFollower, user.Id), nil)
}
Example #11
0
func gameResultHandler(r *http.Request, w http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account, p Parameter) {

	form := p.(gameResultForm)
	var respData struct {
		Total     []*leaderboardResp `json:"total_list"`
		Friends   []*leaderboardResp `json:"friends_list"`
		Score     int                `json:"total_score"`
		Percent   int                `json:"percent"`
		PerFriend int                `json:"percentFri"`
	}

	if form.Count == 0 {
		form.Count = 3
	}

	gt := gameType(form.Type)
	if scores := redis.UserGameScores(gt, user.Id); len(scores) == 1 {
		respData.Score = int(scores[0])
	}
	redis.SetGameScore(gt, user.Id, form.Score) // current score

	kvs := redis.GameScores(gt, 0, form.Count)
	var ids []string
	for _, kv := range kvs {
		ids = append(ids, kv.K)
	}
	ranks := redis.UserGameRanks(gt, user.Id)

	redis.SetGameScore(gt, user.Id, respData.Score) // recover max score

	n := redis.GameUserCount(gt) - 1
	//log.Println(ranks, n)
	if len(ranks) == 1 && n > 0 && form.Score > 0 {
		respData.Percent = int(float64(n-ranks[0]) / float64(n) * 100.0)
	}

	//log.Println(ids)
	users, _ := models.FindUsersByIds(1, ids...)
	index := 0
	for _, kv := range kvs {
		for i, _ := range users {
			if users[i].Id == kv.K {
				respData.Total = append(respData.Total, &leaderboardResp{
					Userid:   users[i].Id,
					Score:    kv.V,
					Rank:     index + 1,
					Level:    users[i].Level(),
					Profile:  users[i].Profile,
					Nickname: users[i].Nickname,
					Gender:   users[i].Gender,
					LastLog:  users[i].LastGameTime(gt).Unix(),
					Birth:    users[i].Birth,
					Location: users[i].Loc,
					Phone:    users[i].Phone,
					Actor:    users[i].Actor,
				})
				index++

				break
			}
		}
	}

	ids = redis.Friends(models.RelFriend, user.Id)
	if len(ids) > 0 {
		total := len(ids)
		ids = append(ids, user.Id)
		scores := redis.UserGameScores(gt, ids...)

		if len(scores) != len(ids) {
			scores = make([]int64, total)
		}
		kvs = make([]models.KV, total+1)
		for i, _ := range ids {
			kvs[i].K = ids[i]
			kvs[i].V = scores[i]
			if ids[i] == user.Id {
				kvs[i].V = int64(form.Score)
			}
		}

		sort.Sort(sort.Reverse(models.KVSlice(kvs)))
		lb := kvs
		if len(kvs) > 3 {
			kvs = kvs[0:3]
		}
		ids = []string{}
		for _, kv := range kvs {
			ids = append(ids, kv.K)
		}
		users, _ = models.FindUsersByIds(1, ids...)
		index := 0
		rank := 0

		for i, _ := range lb {
			if lb[i].K == user.Id {
				rank = i
				break
			}
		}

		for _, kv := range kvs {
			for i, _ := range users {
				if users[i].Id == kv.K {
					respData.Friends = append(respData.Friends, &leaderboardResp{
						Userid:   users[i].Id,
						Score:    kv.V,
						Rank:     index + 1,
						Level:    users[i].Level(),
						Profile:  users[i].Profile,
						Nickname: users[i].Nickname,
						Gender:   users[i].Gender,
						LastLog:  users[i].LastGameTime(gt).Unix(),
						Birth:    users[i].Birth,
						Location: users[i].Loc,
						Phone:    users[i].Phone,
						Actor:    users[i].Actor,
					})
					index++

					break
				}
			}
		}

		if total > 0 {
			respData.PerFriend = int(float64(total-rank) / float64(total) * 100.0)
		}
	}

	writeResponse(r.RequestURI, w, respData, nil)
}