Пример #1
0
func newAddrHandler(r *http.Request, w http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account) {

	wal, err := getWallet(user.Wallet.Id, user.Wallet.Key)
	if err != nil {
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.DbError, err.Error()))
		return
	}
	k, err := wal.GenKey("")
	if err != nil {
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.DbError, err.Error()))
		return
	}
	wal.AddKey(k)
	if _, err = saveWallet(user.Wallet.Id, wal); err != nil {
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.DbError, err.Error()))
		return
	}

	user.Wallet.Addrs = append(user.Wallet.Addrs, k.PubKey)
	if err = user.AddWalletAddr(k.PubKey); err != nil {
		writeResponse(r.RequestURI, w, nil, err)
		return
	}

	writeResponse(r.RequestURI, w, k, nil)
}
Пример #2
0
func sendDevHandler(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account, p Parameter) {

	form := p.(sendDevForm)
	err := user.AddDevice(form.Token)
	writeResponse(request.RequestURI, resp, nil, err)
}
Пример #3
0
func setPushHandler(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account, p Parameter) {

	form := p.(setPushForm)
	err := user.SetPush(form.Enabled)
	writeResponse(request.RequestURI, resp, nil, err)
}
Пример #4
0
func setEquipHandler(request *http.Request, resp http.ResponseWriter,
	user *models.Account, p Parameter) {

	form := p.(setEquipForm)
	err := user.SetEquip(form.Equips)
	writeResponse(request.RequestURI, resp, map[string]interface{}{"ExpEffect": Awards{}}, err)
}
Пример #5
0
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)

}
Пример #6
0
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)
}
Пример #7
0
func loadUserHandler(c martini.Context, user *models.Account, redis *models.RedisLogger, r *http.Request, w http.ResponseWriter) {
	if find, err := user.FindByUserid(user.Id); !find {
		if err == nil {
			err = errors.NewError(errors.NotExistsError)
		}
		writeResponse(r.RequestURI, w, nil, err)
		return
	}
}
Пример #8
0
func setPasswordHandler(r *http.Request, w http.ResponseWriter,
	user *models.Account, p Parameter) {
	form := p.(setPasswordForm)

	if user.Password != Md5(form.Old) {
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.PasswordError, "原密码错误"))
		return
	}

	err := user.SetPassword(Md5(form.New))
	writeResponse(r.RequestURI, w, nil, err)
}
Пример #9
0
func setPhotosHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger,
	user *models.Account, p Parameter) {
	form := p.(setPhotosForm)

	awards := Awards{}
	if !user.PhotoSet {
		awards.Wealth = 10 * int64(len(form.Pics)) * models.Satoshi
		awards.Score = 10 * int64(len(form.Pics))
	}
	err := user.AddPhotos(form.Pics)
	GiveAwards(user, awards, redis)
	writeResponse(request.RequestURI, resp, map[string]interface{}{"ExpEffect": awards}, err)
}
Пример #10
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)
}
Пример #11
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)
}
Пример #12
0
func loginAwardsHandler(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account) {

	a := user.LoginAwards
	if (user.LoginDays-1)%7 == 0 || len(a) == 0 {
		a = []int64{}
		startDay := ((user.LoginDays - 1) / 7) * 7
		level := user.Level()
		score := user.Props.Score

		for i := 0; i < 7; i++ {
			awards := loginAwards(startDay+i+1, int(level))
			a = append(a, awards.Wealth, awards.Score)
			score = score + awards.Score
			level = models.Score2Level(score)
		}

		user.SetLoginAwards(a)
	}

	index := (user.LoginDays - 1) % 7
	awards := Awards{Wealth: a[index*2], Score: a[index*2+1]}
	awards.Level = models.Score2Level(user.Props.Score+awards.Score) - user.Level()
	GiveAwards(user, awards, redis)

	loginAwards := []int64{}
	for i := 0; i < 7; i++ {
		loginAwards = append(loginAwards, a[i*2])
	}
	respData := map[string]interface{}{
		"continuous_logined_days": user.LoginDays,
		"login_reward_list":       loginAwards,
	}
	writeResponse(request.RequestURI, resp, respData, nil)
}
Пример #13
0
func searchHandler(r *http.Request, w http.ResponseWriter,
	user *models.Account, form searchForm) {
	users := []models.Account{}
	var err error

	if form.Nearby > 0 {
		form.Paging.Count = 50
		users, err = user.SearchNear(&form.Paging, 50000)
	} else {
		users, err = models.SearchUsers(form.Nickname, &form.Paging)
	}

	var list []*leaderboardResp
	for i, _ := range users {
		if users[i].Id == user.Id {
			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,
			Phone:    users[i].Phone,
			Actor:    users[i].Actor,
		}
		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, err)
}
Пример #14
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)
}
Пример #15
0
func purchaseListHandler(r *http.Request, w http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account, p Parameter) {
	form := p.(purchaseListForm)

	_, txs, _ := user.Txs(&form.Paging)

	list := []*purchaseStruct{}
	for _, tx := range txs {
		list = append(list, &purchaseStruct{
			Coins: tx.Coins,
			Value: tx.Value,
			Time:  tx.Time.Unix(),
		})
	}

	respData := map[string]interface{}{
		"payCoinList":   list,
		"page_frist_id": form.Paging.First,
		"page_last_id":  form.Paging.Last,
	}
	writeResponse(r.RequestURI, w, respData, nil)
}
Пример #16
0
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
}
Пример #17
0
func userRanksHandler(r *http.Request, w http.ResponseWriter,
	user *models.Account) {
	var ranks struct {
		Userid         string `json:"userid"`
		ScoreRank      int    `json:"score_rank"`
		PhysiqueRank   int    `json:"physique_rank"`
		LiteratureRank int    `json:"literature_rank"`
		MagicRank      int    `json:"magic_rank"`
	}

	//log.Println(user.Props)
	ranks.Userid = user.Id
	ranks.ScoreRank, _ = user.PropIndex("score", user.Props.Score)
	ranks.PhysiqueRank, _ = user.PropIndex("physique", user.Props.Physical)
	ranks.LiteratureRank, _ = user.PropIndex("literature", user.Props.Literal)
	ranks.MagicRank, _ = user.PropIndex("magic", user.Props.Mental)

	writeResponse(r.RequestURI, w, ranks, nil)
}
Пример #18
0
func getTasksHandler(r *http.Request, w http.ResponseWriter, user *models.Account) {

	/*
		tasklist := user.Tasks

		week := len(tasklist.Completed) / 7
		if week > 0 && len(tasklist.Completed)%7 == 0 &&
			tasklist.Last.After(now.BeginningOfWeek()) {
			week -= 1
		}
		list := make([]models.Task, 7)
		if week*7+7 <= len(models.Tasks)+1 {
			copy(list, models.Tasks[week*7:week*7+7])
		}
		for i, _ := range list {
			list[i].Status = tasklist.TaskStatus(list[i].Id)
			if list[i].Type == models.TaskGame && list[i].Status == "FINISH" {
				rec := &models.Record{Uid: user.Id}
				rec.FindByTask(list[i].Id)
				if rec.Game != nil {
					list[i].Desc = fmt.Sprintf("你在%s游戏中得了%d分",
						rec.Game.Name, rec.Game.Score)
				}
			}
		}
	*/
	count, _ := user.TaskRecordCount("", models.StatusFinish)
	week := count / 7

	var target, actual int

	last, _ := user.LastTaskRecord()
	// all weekly tasks are completed
	if week > 0 && count%7 == 0 && last.AuthTime.After(now.BeginningOfWeek()) {
		week -= 1
	}
	//log.Println("week", week)
	tasks := make([]models.Task, 7)
	if week*7+7 <= len(models.Tasks) {
		copy(tasks, models.Tasks[week*7:week*7+7])
	}

	for i, task := range tasks {
		tasks[i].Status = models.StatusNormal
		record := &models.Record{Uid: user.Id}

		if find, _ := record.FindByTask(task.Id); find {
			tasks[i].Status = record.Status
		}
		if task.Type == models.TaskGame && task.Status == models.StatusFinish &&
			record.Game != nil {
			tasks[i].Result = fmt.Sprintf("你在%s游戏中得了%d分",
				record.Game.Name, record.Game.Score)
		}
		if task.Type == models.TaskRunning {
			target += task.Distance
			if tasks[i].Status == models.StatusFinish && record.Sport != nil {
				actual += record.Sport.Distance
			}
		}
	}
	//log.Println(tasks)
	//random := rand.New(rand.NewSource(time.Now().Unix()))
	respData := map[string]interface{}{
		"week_id":              week + 1,
		"task_list":            tasks,
		"task_target_distance": target,
		"task_actual_distance": actual,
		//"week_desc": tips[random.Int()%len(tips)],
	}

	writeResponse(r.RequestURI, w, respData, nil)
}
Пример #19
0
func newArticleHandler(request *http.Request, resp http.ResponseWriter,
	client *ApnClient, redis *models.RedisLogger, user *models.Account, p Parameter) {
	form := p.(newArticleForm)

	article := &models.Article{
		Author:   user.Id,
		Contents: form.Contents,
		PubTime:  time.Now(),
		Parent:   form.Parent,
		//Tags:     form.Tags,
		Loc:  form.Location,
		Type: form.Type,
	}
	article.Title, article.Images = articleCover(form.Contents)
	if len(article.Images) > 0 {
		article.Image = article.Images[0]
	}
	/*
		if len(article.Tags) == 0 {
			article.Tags = []string{"SPORT_LOG"}
		}
	*/

	awards := Awards{}
	parent := &models.Article{}
	if len(form.Parent) > 0 {
		if find, err := parent.FindById(form.Parent); !find {
			e := errors.NewError(errors.NotExistsError, "文章不存在!")
			if err != nil {
				e = errors.NewError(errors.DbError)
			}
			writeResponse(request.RequestURI, resp, nil, e)
			return
		}

		if redis.Relationship(parent.Author, user.Id) == models.RelBlacklist {
			writeResponse(request.RequestURI, resp, nil,
				errors.NewError(errors.AccessError, "对方屏蔽了你!"))
			return
		}

		awards = Awards{Literal: 1 + user.Level(), Score: 1 + user.Level()}
	} else {
		if user.Stat != nil && user.Stat.LastArticleTime < nowDate().Unix() {
			awards = Awards{Literal: 2 + user.Level(), Wealth: 2 * models.Satoshi, Score: 2 + user.Level()}
		}
		user.UpdateStat(models.StatLastArticleTime, time.Now().Unix())
	}

	if article.Type == models.ArticleRecord {
		article.Coaches = []string{user.Id}
	}

	if article.Type == models.ArticleCoach {
		if parent.Author != user.Id &&
			user.Actor != models.ActorCoach && user.Actor != models.ActorAdmin {
			writeResponse(request.RequestURI, resp, nil,
				errors.NewError(errors.AccessError))
			return
		}

		if err := article.Save(); err != nil {
			log.Println(err)
			writeResponse(request.RequestURI, resp, nil, err)
			return
		}

		// ws push
		event := &models.Event{
			Type: models.EventArticle,
			Time: time.Now().Unix(),
			Data: models.EventData{
				Type: models.EventCoach,
				Id:   parent.Id.Hex(),
				From: user.Id,
				//To:   parent.Author,
				Body: []models.MsgBody{
					{Type: "total_count", Content: strconv.Itoa(parent.CoachReviewCount + 1)},
					{Type: "image", Content: user.Profile},
				},
			},
		}

		for _, coach := range parent.Coaches {
			if coach == user.Id {
				continue
			}
			event.Data.To = coach
			event.Save()
			redis.PubMsg(models.EventArticle, coach, event.Bytes())
		}

		respData := map[string]interface{}{
			"ExpEffect": Awards{},
		}
		writeResponse(request.RequestURI, resp, respData, nil)
		return
	}

	if err := article.Save(); err != nil {
		log.Println(err)
		writeResponse(request.RequestURI, resp, nil, err)
		return
	}
	t := ""
	stat := models.StatArticles
	if len(form.Parent) > 0 {
		t = models.ArticleComment
		stat = models.StatComments
	}
	redis.AddPost(user.Id, t, 1)
	user.UpdateStat(stat, 1)

	if err := GiveAwards(user, awards, redis); err != nil {
		log.Println(err)
		writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.DbError))
		return
	}

	// comment
	if len(form.Parent) > 0 && parent.Author != user.Id {
		//u := &models.User{Id: parent.Author}
		author := &models.Account{}
		author.FindByUserid(parent.Author)

		// ws push
		event := &models.Event{
			Type: models.EventArticle,
			Time: time.Now().Unix(),
			Data: models.EventData{
				Type: models.EventComment,
				Id:   parent.Id.Hex(),
				From: user.Id,
				To:   parent.Author,
				Body: []models.MsgBody{
					{Type: "total_count", Content: strconv.Itoa(parent.ReviewCount + 1)},
					{Type: "image", Content: parent.Image},
				},
			},
		}
		/*
			if err := event.Save(); err == nil {
				redis.IncrEventCount(parent.Author, event.Data.Type, 1)
			}
		*/
		event.Save()

		event.Data.Body = append(event.Data.Body,
			models.MsgBody{Type: "new_count",
				Content: strconv.Itoa(models.EventCount(event.Data.Type, event.Data.Id, event.Data.To))})
		redis.PubMsg(models.EventArticle, parent.Author, event.Bytes())
		// apple push
		if author.Push {
			go sendApn(client, user.Nickname+"评论了你的主题!", author.EventCount("", ""), author.Devs...)
		}
	}

	respData := map[string]interface{}{
		//"articles_without_content": convertArticle(article),
		"ExpEffect": awards,
	}
	writeResponse(request.RequestURI, resp, respData, nil)
}
Пример #20
0
func convertUser(user *models.Account, redis *models.RedisLogger) *userJsonStruct {
	info := &userJsonStruct{
		Userid:   user.Id,
		Nickname: user.Nickname,
		Email:    user.Email,
		Phone:    user.Phone,
		Type:     user.Role,
		About:    user.About,
		Profile:  user.Profile,
		RegTime:  user.RegTime.Unix(),
		Height:   user.Height,
		Weight:   user.Weight,
		Birth:    user.Birth,
		Actor:    user.Actor,
		Location: user.Loc,
		Addr:     user.LocAddr,

		Sign:        user.Sign,
		Emotion:     user.Emotion,
		Profession:  user.Profession,
		Hometown:    user.Hometown,
		OftenAppear: user.Oftenappear,
		Hobby:       user.Hobby,

		//Rank:   userRank(user.Level),
		Online: redis.IsOnline(user.Id),
		Gender: user.Gender,
		//Follows:   len(redis.Follows(user.Id)),
		//Followers: len(redis.Followers(user.Id)),
		Posts: user.ArticleCount(),

		//Props: redis.UserProps(user.Id),
		Props: models.Props{
			Physical: user.Props.Physical,
			Literal:  user.Props.Literal,
			Mental:   user.Props.Mental,
			Wealth:   redis.GetCoins(user.Id),
			Score:    user.Props.Score,
			Level:    user.Level(),
		},

		Photos:     user.Photos,
		CoverImage: user.CoverImage,

		Wallet:  user.Wallet.Addr,
		LastLog: user.LastLogin.Unix(),
		Setinfo: user.Setinfo,
		Ban:     user.TimeLimit,
		Auth:    user.Auth,
	}

	balance, _ := getBalance(user.Wallet.Addrs)
	var wealth int64
	if balance != nil {
		for _, b := range balance.Addrs {
			wealth += (b.Confirmed + b.Unconfirmed)
		}
	}
	info.Props.Wealth = wealth

	info.Follows, info.Followers, _, _ = redis.FriendCount(user.Id)

	/*
		if user.Privilege == 5 {
			info.Actor = "coach"
		} else if user.Privilege == 10 {
			info.Actor = "admin"
		}

			if user.Addr != nil {
				info.Addr = user.Addr.String()
			}
	*/

	if user.Equips != nil {
		info.Equips = *user.Equips
	}

	if info.Auth != nil {
		if info.Auth.IdCard == nil {
			info.Auth.IdCard = info.Auth.IdCardTmp
		}
		if info.Auth.Cert == nil {
			info.Auth.Cert = info.Auth.CertTmp
		}
		if info.Auth.Record == nil {
			info.Auth.Record = info.Auth.RecordTmp
		}
	}

	return info
}
Пример #21
0
func getTaskHandler(r *http.Request, w http.ResponseWriter,
	user *models.Account, p Parameter) {
	form := p.(getTaskForm)

	tid := user.Taskid
	status := user.TaskStatus

	if tid == 0 {
		rec, _ := user.LastTaskRecord2()
		tid = int(rec.Task + 1) // next task
		status = rec.Status
		if status == "" {
			status = models.StatusNormal
		}
		user.UpdateTask(tid, status)
	}

	if status == "" {
		status = models.StatusNormal
	}

	if form.Next {
		if status == models.StatusFinish {
			tid++
		}
		if status == models.StatusFinish || status == models.StatusUnFinish {
			status = models.StatusNormal
		}

		user.UpdateTask(tid, status)
	}

	if tid > len(models.NewTasks) {
		writeResponse(r.RequestURI, w, nil, nil)
	}

	task := models.NewTasks[tid-1]
	task.Status = status

	config := &models.Config{}
	config.Find()
	if task.Index < len(config.Videos) {
		video := config.Videos[task.Index]
		task.Video = video.Url
		/*
			if len(video.Desc) > 0 {
				task.Desc = video.Desc
			}
		*/
	}

	var stat struct {
		Distance int `json:"distance"`
		Run      int `json:"run"`
		Article  int `json:"article"`
		Game     int `json:"game"`
	}

	stat.Article, _ = user.TaskRecordCount("post", models.StatusFinish)
	stat.Game, _ = user.TaskRecordCount("game", models.StatusFinish)
	records, _ := user.TaskRecords("run")
	stat.Run = len(records)
	for i, _ := range records {
		stat.Distance += records[i].Sport.Distance
	}

	respData := map[string]interface{}{
		"task": task,
		"stat": stat,
	}
	writeResponse(r.RequestURI, w, respData, nil)
}
Пример #22
0
func taskShareHandler(r *http.Request, w http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account, p Parameter) {
	form := p.(taskShareForm)

	if form.TaskId > len(models.NewTasks) {
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.AccessError))
		return
	}

	//task := models.NewTasks[form.TaskId]
	// ws push
	event := &models.Event{
		Type: models.EventSystem,
		Time: time.Now().Unix(),
		Data: models.EventData{
			//Type: models.EventRunShare,
			Id:   user.Id,
			From: user.Id,
			To:   form.Userid,
		},
	}

	switch form.Type {
	case models.TaskRunning:
		record, _ := user.LastRecord("run")
		latlng := strconv.FormatFloat(form.Lat, 'f', 7, 64) + "," +
			strconv.FormatFloat(form.Lng, 'f', 7, 64)
		event.Data.Type = models.EventRunShare
		event.Data.Body = []models.MsgBody{
			{Type: "record_id", Content: record.Id.Hex()},
			{Type: "latlng", Content: latlng},
			{Type: "locaddr", Content: form.Addr},
			{Type: "time", Content: strconv.FormatInt(form.Time, 10)},
			{Type: "addr_image", Content: form.Image},
		}
	case models.TaskPost:
		event.Data.Type = models.EventPostShare
		article := user.LatestArticle()
		event.Data.Body = []models.MsgBody{
			{Type: "article_id", Content: article.Id.Hex()},
		}
	case models.TaskGame:
		record, _ := user.LastRecord("run")
		event.Data.Type = models.EventPKShare
		event.Data.Body = []models.MsgBody{
			{Type: "record_id", Content: record.Id.Hex()},
		}
	default:
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.AccessError))
		return
	}

	event.Save()
	redis.PubMsg(event.Type, event.Data.To, event.Bytes())

	u := &models.Account{Id: form.Userid}
	u.UpdateRatio(form.Type, false)
	redis.SetTaskShare(form.Userid, true)

	if _, err := consumeCoin(user.Wallet.Addr, form.Coin); err == nil {
		redis.ConsumeCoins(user.Id, form.Coin)
	}

	writeResponse(r.RequestURI, w, nil, nil)
}
Пример #23
0
func setProfileHandler(request *http.Request, resp http.ResponseWriter,
	user *models.Account, p Parameter) {
	form := p.(setProfileForm)
	err := user.ChangeProfile(form.ImageId)
	writeResponse(request.RequestURI, resp, map[string]interface{}{"ExpEffect": Awards{}}, err)
}
Пример #24
0
func setInfoHandler(request *http.Request, resp http.ResponseWriter, redis *models.RedisLogger,
	user *models.Account, p Parameter) {

	form := p.(setInfoForm)
	setinfo := &models.SetInfo{
		Phone:    form.UserInfo.Phone,
		Nickname: form.UserInfo.Nickname,
		Height:   form.UserInfo.Height,
		Weight:   form.UserInfo.Weight,
		Birth:    form.UserInfo.Birth,
		Gender:   form.UserInfo.Gender,

		Sign:        form.UserInfo.Sign,
		Emotion:     form.UserInfo.Emotion,
		Profession:  form.UserInfo.Profession,
		Hobby:       form.UserInfo.Hobby,
		Hometown:    form.UserInfo.Hometown,
		OftenAppear: form.UserInfo.OftenAppear,
		CoverImage:  form.UserInfo.CoverImage,

		Setinfo:    user.Setinfo,
		SetinfoAll: user.SetinfoAll,
	}

	addr := &models.Address{
		Country:  form.UserInfo.Country,
		Province: form.UserInfo.Province,
		City:     form.UserInfo.City,
		Area:     form.UserInfo.Area,
		Desc:     form.UserInfo.LocDesc,
	}
	if addr.String() != "" {
		setinfo.Address = addr
	}

	if len(setinfo.Phone) > 0 && setinfo.Phone != user.Phone {
		user.Phone = setinfo.Phone
		//setinfo.Setinfo = false
		if b, _ := user.Exists("phone"); b {
			writeResponse(request.RequestURI, resp, nil,
				errors.NewError(errors.UserExistError, "绑定失败,当前手机号已绑定"))
			return
		}
	}

	if len(setinfo.Nickname) > 0 && setinfo.Nickname != user.Nickname {
		u := &models.Account{}
		if find, _ := u.FindByNickname(setinfo.Nickname); find {
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.UserExistError, "昵称已被占用"))
			return
		}
	}

	awards := Awards{}
	if !user.Setinfo || !user.SetinfoAll {
		ratio := calcInfo(user, setinfo)

		if ratio >= 80 && !user.Setinfo {
			setinfo.Setinfo = true
			awards.Wealth = 30 * models.Satoshi
			awards.Score = 30
		}
		if ratio == 100 && !user.SetinfoAll {
			setinfo.SetinfoAll = true
			awards.Wealth = 50 * models.Satoshi
			awards.Score = 50
		}
	}

	if err := user.SetInfo(setinfo); err != nil {
		writeResponse(request.RequestURI, resp, nil, err)
		return
	}

	GiveAwards(user, awards, redis)

	writeResponse(request.RequestURI, resp, map[string]interface{}{"ExpEffect": awards}, nil)

	user.UpdateAction(ActInfo, nowDate())
	//redis.SetOnlineUser(form.Token, user, false)
}
Пример #25
0
func taskSharedHandler(r *http.Request, w http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account, p Parameter) {
	form := p.(taskSharedForm)

	u := &models.Account{}
	u.FindByUserid(form.Sender)

	// ws push
	event := &models.Event{
		Type: models.EventSystem,
		Time: time.Now().Unix(),
		Data: models.EventData{
			Id:   user.Id,
			From: user.Id,
			To:   form.Sender,
		},
	}

	var article *models.Article

	switch form.Type {
	case models.TaskRunning:
		event.Data.Type = models.EventRunShared
		article = &models.Article{
			Author:  user.Id,
			PubTime: time.Now(),
			Contents: []models.Segment{
				{ContentType: "TEXT", ContentText: "我和" + u.Nickname + "约好一起跑步,有想一起参加的吗?" +
					"\n跑步地点: " + form.Addr +
					"\n跑步时间: " + time.Unix(form.Time, 0).Format("2006-01-02 3:04 PM")},
				{ContentType: "IMAGE", ContentText: form.Image},
			},
		}
	case models.TaskPost:
		article := &models.Article{}
		if find, _ := article.FindById(form.ArticleId); find {
			article.SetThumb(user.Id, true)
		}
		event.Data.Type = models.EventPostShared
	case models.TaskGame:
		event.Data.Type = models.EventPKShared
		result := u.Nickname + " 主动PK " + user.Nickname + "大获全胜。"
		if u.Props.Score < user.Props.Score {
			result = u.Nickname + " 主动PK " + user.Nickname + "大败亏输。"
		}
		article = &models.Article{
			Author:  user.Id,
			Type:    "pk",
			PubTime: time.Now(),
			Contents: []models.Segment{
				{ContentType: "TEXT", ContentText: result},
				{ContentType: "IMAGE", ContentText: form.Image},
			},
		}
	default:
		writeResponse(r.RequestURI, w, nil, errors.NewError(errors.AccessError))
		return
	}

	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())
		user.UpdateRatio(form.Type, true)
		if article != nil {
			article.Save()
		}
		awards.Wealth = 1 * models.Satoshi
		GiveAwards(user, awards, redis)
	}

	redis.SetTaskShare(user.Id, false)

	writeResponse(r.RequestURI, w, map[string]interface{}{"ExpEffect": awards}, nil)
}
Пример #26
0
func delPhotoHandler(request *http.Request, resp http.ResponseWriter,
	user *models.Account, p Parameter) {
	err := user.DelPhoto(p.(delPhotoForm).Photo)
	writeResponse(request.RequestURI, resp, nil, err)
}
Пример #27
0
func newRecordHandler(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account, p Parameter) {

	form := p.(newRecordForm)

	rec := &models.Record{
		Uid:       user.Id,
		Task:      form.Task,
		Type:      form.Record.Type,
		StartTime: time.Unix(form.Record.BeginTime, 0),
		EndTime:   time.Unix(form.Record.EndTime, 0),
		PubTime:   time.Now(),
	}

	awards := Awards{}
	level := user.Level()

	switch form.Record.Type {
	case "post":
		rec.Status = models.StatusFinish
		if form.Task > 0 {
			rec.Coin = (2 + level) * models.Satoshi
			awards = Awards{
				Score:   2 + level,
				Literal: 2 + level,
				Wealth:  rec.Coin,
			}
		} else {
			rec.Coin = 2 * models.Satoshi
			awards = Awards{
				Score:   2,
				Literal: 2,
				Wealth:  rec.Coin,
			}
		}

		GiveAwards(user, awards, redis)

		redis.AddPost(user.Id, "", 1)
		user.UpdateStat(models.StatArticles, 1)
	case "game":
		if form.Task > 0 {
			awards = gameAwards(level, form.Record.GameScore, true)
			//user.AddTask(models.Tasks[form.Task-1].Type, form.Task, nil)
			rec.Status = models.StatusFinish
		} else {
			if form.Record.GameScore >= 100 &&
				user.Stat != nil && user.Stat.LastGameTime < nowDate().Unix() {
				awards = gameAwards(level, form.Record.GameScore, false)
			}
			user.UpdateStat(models.StatLastGameTime, time.Now().Unix())
		}
		GiveAwards(user, awards, redis)

		rec.Game = &models.GameRecord{
			Type:     form.Record.GameType,
			Name:     form.Record.GameName,
			Duration: form.Record.Duration,
			Score:    form.Record.GameScore,
			Magic:    int(awards.Mental),
		}
		rec.Coin = awards.Wealth

		redis.AddGameTime(user.Id, int(form.Record.Duration))
		user.UpdateStat(models.StatGameTime, form.Record.Duration)
		redis.SetGameMaxScore(gameType(rec.Game.Type), user.Id, rec.Game.Score)
		user.SetGameTime(gameType(rec.Game.Type), time.Now())

	case "run":
		if rec.Task > 0 {
			rec.Delete()
		}
		rec.Sport = &models.SportRecord{
			Source:    form.Record.Source,
			Duration:  form.Record.Duration,
			Distance:  form.Record.Distance,
			Weight:    form.Record.Weight,
			Mood:      form.Record.Mood,
			HeartRate: form.Record.HeartRate,
			Pics:      form.Record.Pics,
		}

		if rec.Sport.Weight == 0 {
			rec.Sport.Weight = user.Weight
		}
		// update weight
		if rec.Sport.Weight != user.Weight {
			user.SetInfo(&models.SetInfo{Weight: rec.Sport.Weight})
		}

		if form.Record.Duration > 0 {
			rec.Sport.Speed = float64(form.Record.Distance) / float64(form.Record.Duration)
		}
		rec.Status = models.StatusAuth

		redis.AddRecord(user.Id, 1)
		user.UpdateStat(models.StatRecords, 1)
		/*
			if len(form.Record.Source) > 0 {
				level := user.Level()
				awards = Awards{
					Physical: 30 + level,
					Wealth:   30 * models.Satoshi,
					Score:    30 + level,
				}

				GiveAwards(user, awards, redis)
				redis.UpdateRecLB(user.Id, rec.Sport.Distance, int(rec.Sport.Duration))

				rec.Coin = awards.Wealth
				rec.Status = models.StatusFinish
			}
		*/

	default:
		log.Println("Unknown record type:", form.Record.Type)
	}
	// assign task id
	if rec.Task == 0 {
		rec.Task = rec.PubTime.Unix()
	}
	if err := rec.Save(); err != nil {
		writeResponse(request.RequestURI, resp, nil, err)
		return
	}

	if rec.Type == "run" {
		article := &models.Article{
			Author:  user.Id,
			PubTime: time.Now(),
			Loc:     user.Loc,
			Record:  rec.Id.Hex(),
			Type:    models.ArticleRecord,
		}

		if !form.Public {
			article.Privilege = models.PrivPrivate
		}

		if err := article.Save(); err == nil {
			redis.AddPost(user.Id, "", 1)
			user.UpdateStat(models.StatArticles, 1)
		}
	}

	if form.Task > 0 {
		user.UpdateTask(int(form.Task), rec.Status)
		/*
			if rec.Status == models.StatusFinish {
				// ws push
				event := &models.Event{
					Type: models.EventNotice,
					Time: time.Now().Unix(),
					Data: models.EventData{
						Type: models.EventTaskDone,
						To:   user.Id,
						Body: []models.MsgBody{
							{Type: "task_id", Content: strconv.Itoa(int(form.Task))},
							{Type: "literature_value", Content: strconv.FormatInt(awards.Literal, 10)},
							{Type: "magic_value", Content: strconv.FormatInt(awards.Mental, 10)},
							{Type: "coin_value", Content: strconv.FormatInt(awards.Wealth, 10)},
						},
					},
				}
				event.Save()
				redis.PubMsg(event.Type, event.Data.To, event.Bytes())
			}
		*/
	}

	respData := map[string]interface{}{
		"record_id": rec.Id.Hex(),
		"ExpEffect": awards,
	}
	writeResponse(request.RequestURI, resp, respData, nil)
}
Пример #28
0
func pushStatusHandler(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger, user *models.Account) {

	enabled, err := user.PushEnabled()
	writeResponse(request.RequestURI, resp, map[string]bool{"is_enabled": enabled}, err)
}