Example #1
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)
}
Example #2
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
}
Example #3
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)
}
Example #4
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)
}
Example #5
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
}