예제 #1
0
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)
}
예제 #2
0
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})
}
예제 #3
0
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
}
예제 #4
0
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()})
}
예제 #5
0
파일: task.go 프로젝트: shevilangle/sports
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})
}
예제 #6
0
파일: task.go 프로젝트: shevilangle/sports
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})
}
예제 #7
0
파일: push.go 프로젝트: shevilangle/sports
func wsPushHandler(request *http.Request, resp http.ResponseWriter, redisLogger *models.RedisLogger) {
	conn, err := upgrader.Upgrade(resp, request, nil)
	if err != nil {
		conn.WriteJSON(errors.NewError(errors.HttpError, err.Error()))
		return
	}
	defer conn.Close()

	r := wsAuthResp{}
	var auth wsAuth
	conn.ReadJSON(&auth)

	//log.Println("check token:", auth.Token)
	if !checkTokenValid(auth.Token) {
		//log.Println("check token valid")
		redisLogger.DelOnlineUser(auth.Token)
		conn.WriteJSON(r)
		return
	}

	uid := redisLogger.OnlineUser(auth.Token)

	user := &models.Account{}
	if find, _ := user.FindByUserid(uid); !find || user.TimeLimit < 0 {
		r.TimeLimit = user.TimeLimit
		conn.WriteJSON(r)
		return
	}

	//redisLogger.LogLogin(user.Id)

	days := user.LoginDays
	loginCount := user.LoginCount + 1
	d := nowDate()
	if user.LastLogin.Unix() < d.Unix() { // check wether first time login of one day
		days++
		if user.LastLogin.Unix() < d.Unix()-24*3600 {
			days = 1
		}
		loginCount = 1
	}
	//fmt.Println(uid, "loginCount", loginCount)
	user.SetLastLogin(days, loginCount, time.Now())

	r.Userid = uid
	r.LastLog = user.LastLogin.Unix()
	r.LoginCount = loginCount

	if err := conn.WriteJSON(r); err != nil {
		return
	}

	if len(uid) == 0 {
		return
	}

	redisLogger.LogVisitor(user.Id)
	psc := redisLogger.PubSub(user.Id)

	go func(conn *websocket.Conn) {
		//wg.Add(1)
		//defer log.Println("ws thread closed")
		//defer wg.Done()
		redisLogger.SetOnline(user.Id, user.Actor, true, 0)
		start := time.Now()

		defer psc.Close()

		for {
			event := &models.Event{}
			err := conn.ReadJSON(event)
			if err != nil {
				//log.Println(err)

				dur := int64(time.Since(start) / time.Second)
				redisLogger.SetOnline(user.Id, user.Actor, false, dur)
				user.UpdateStat(models.StatOnlineTime, dur)
				return
			}
			//log.Println("recv msg:", event.Type)
			switch event.Type {
			case models.EventMsg:
				m := &models.Message{
					From: event.Data.From,
					To:   event.Data.To,
					Body: event.Data.Body,
					Time: time.Now(),
				}
				if event.Data.Type == models.EventChat || event.Data.Type == models.EventGChat {
					m.Type = event.Data.Type
					m.Save()
					event.Data.Id = m.Id.Hex()
					event.Time = m.Time.Unix()

					redisLogger.PubMsg(m.Type, m.To, event.Bytes())
				}
			case models.EventStatus:
				//fmt.Println(user.Id, event.Data.Body)
				switch event.Data.Type {
				case "loc":
					var lat, lng float64
					var locaddr string
					for _, body := range event.Data.Body {
						switch body.Type {
						case "latlng":
							//log.Println("latlng:", body.Content)
							loc := strings.Split(body.Content, ",")
							if len(loc) != 2 {
								break
							}
							lat, _ = strconv.ParseFloat(loc[0], 64)
							lng, _ = strconv.ParseFloat(loc[1], 64)
						case "locaddr":
							//log.Println("locaddr:", body.Content)
							locaddr = body.Content
						}
					}
					user.UpdateLocation(models.Location{Lat: lat, Lng: lng}, locaddr)
				case "device":
					for _, body := range event.Data.Body {
						switch body.Type {
						case "token":
							token := body.Content
							//log.Println("device token:", token)
							user.AddDevice(token)
						}
					}
				}

			default:
				log.Println("unhandled message type:", event.Type)
			}
		}
	}(conn)

	for {
		switch v := psc.Receive().(type) {
		case redis.Message:
			//log.Printf("%s: message: %s\n", v.Channel, v.Data)
			event := &models.Event{}
			if err := json.Unmarshal(v.Data, event); err != nil {
				log.Println("parse push message error:", err)
				continue
			}

			// subscribe group
			if event.Data.Type == models.EventSub && event.Data.From == user.Id {
				if err := redisLogger.Subscribe(psc, event.Data.To); err != nil {
					log.Println(err)
				}
				continue
			}
			// unsubscribe group
			if event.Data.Type == models.EventUnsub && event.Data.From == user.Id {
				if err := redisLogger.Unsubscribe(psc, event.Data.To); err != nil {
					log.Println(err)
				}
				continue
			}

			if err := conn.WriteMessage(websocket.TextMessage, v.Data); err != nil {
				log.Println(err)
				return
			}
		case redis.Subscription:
			//log.Printf("%s: %s %d\n", v.Channel, v.Kind, v.Count)
		case error:
			//log.Println(v)
			return
		}
	}
}
예제 #8
0
파일: file.go 프로젝트: shevilangle/sports
func fileUploadHandler(request *http.Request, resp http.ResponseWriter,
	redis *models.RedisLogger /*, user *models.Account*/, form fileUploadForm) {
	user := &models.Account{}

	if len(form.Token) > 0 {
		id := redis.OnlineUser(form.Token)
		if find, _ := user.FindByUserid(id); !find {
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.NotFoundError))
			return
		}
	}

	var file models.File

	filedata, header, err := request.FormFile("filedata")
	if err != nil {
		log.Println(err)
		writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.FileNotFoundError))
		return
	}

	if form.Width > 0 || form.Height > 0 {
		img, _, err := image.Decode(filedata)
		if err != nil {
			log.Println(err)
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.InvalidFileError))
			return
		}

		fid, err := Weedfs.Master().AssignN(2)
		if err != nil {
			log.Println(err)
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.FileUploadError))
			return
		}
		file.Fid = fid

		thumbnail := resize.Thumbnail(uint(form.Width), uint(form.Height), img, resize.MitchellNetravali)
		vol, err := Weedfs.Volume(fid, "")
		if err != nil {
			log.Println(err)
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.FileUploadError))
			return
		}

		buf := &bytes.Buffer{}
		if err := jpeg.Encode(buf, thumbnail, nil); err != nil {
			log.Println(err)
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.FileUploadError))
			return
		}

		length, err := vol.Upload(fid, 0, header.Filename, "image/jpeg", buf)
		if err != nil {
			log.Println(err)
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.FileUploadError))
			return
		}
		file.Length = length

		filedata.Seek(0, 0)
		if _, err := vol.Upload(fid, 1, header.Filename, header.Header.Get("Content-Type"), filedata); err != nil {
			log.Println(err)
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.FileUploadError))
			return
		}
	} else {
		fid, length, err := Weedfs.Master().Submit(header.Filename, header.Header.Get("Content-Type"), filedata)
		if err != nil {
			writeResponse(request.RequestURI, resp, nil, errors.NewError(errors.FileUploadError))
			return
		}
		//log.Println(fid, length, header.Filename, header.Header.Get("Content-Type"))

		file.Fid = fid
		file.Length = length
	}

	filedata.Seek(0, 0)

	file.Name = header.Filename
	file.ContentType = header.Header.Get("Content-Type")
	file.Md5 = FileMd5(filedata)
	file.Owner = user.Id
	file.UploadDate = time.Now()
	if err := file.Save(); err != nil {
		writeResponse(request.RequestURI, resp, nil, err)
		return
	}

	url, _, _ := Weedfs.GetUrl(file.Fid)
	respData := map[string]interface{}{"fileid": file.Fid, "fileurl": url}

	writeResponse(request.RequestURI, resp, respData, nil)
}