Example #1
0
// 获取由用户收藏的link
// @page: 从1开始
func FavoriteLink_ByUser(userId int64, page, pagesize int) []Link {
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	page, pagesize = utils.PageCheck(page, pagesize)

	qi := goku.SqlQueryInfo{}
	qi.Fields = "l.id, l.user_id, l.title, l.context, l.topics, l.vote_up, l.vote_down, l.view_count, l.comment_count, l.create_time"
	qi.Join = " ufl INNER JOIN `link` l ON ufl.link_id=l.id"
	qi.Where = "ufl.user_id=?"
	qi.Params = []interface{}{userId}
	qi.Limit = pagesize
	qi.Offset = pagesize * page
	qi.Order = "ufl.create_time desc"

	rows, err := db.Select("user_favorite_link", qi)
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return nil
	}
	links := make([]Link, 0)
	for rows.Next() {
		link := Link{}
		err = rows.Scan(&link.Id, &link.UserId, &link.Title, &link.Context, &link.Topics,
			&link.VoteUp, &link.VoteDown, &link.ViewCount, &link.CommentCount, &link.CreateTime)
		if err != nil {
			goku.Logger().Errorln(err.Error())
			return nil
		}
		links = append(links, link)
	}

	return links
}
Example #2
0
// userId 取消关注 followId
func User_UnFollow(userId, followId int64) (bool, error) {
	if userId < 1 || followId < 1 {
		return false, errors.New("参数错误")
	}
	if userId == followId {
		return false, errors.New("不能取消关注自己")
	}
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	r, err := db.Delete("user_follow", "`user_id`=? AND `follow_id`=?", userId, followId)
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return false, err
	}

	var afrow int64
	afrow, err = r.RowsAffected()
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return false, err
	}

	if afrow > 0 {
		LinkForUser_UnFollowUser(userId, followId)
		// 更新粉丝数
		User_IncCount(db, userId, "friend_count", -1)
		// 更新关注数
		User_IncCount(db, followId, "follower_count", -1)
		return true, nil
	}
	return false, nil
}
Example #3
0
// 关注好友的最新链接的未读数
func NewestLinkUnread_Friends(userId, lastReadLinkId int64) (int64, error) {
	if userId < 1 {
		return 0, nil
	}

	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	qi := goku.SqlQueryInfo{}
	qi.Where = "`user_id`=? and `link_id`>?"
	qi.Params = []interface{}{userId, lastReadLinkId}
	qi.Fields = "count(*)"
	tableName := LinkForUser_TableName(userId)
	rows, err := db.Select(tableName, qi)
	var unreadCount int64
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return 0, err
	}
	if rows.Next() {
		err = rows.Scan(&unreadCount)
		if err != nil {
			goku.Logger().Errorln(err.Error())
			return 0, err
		}
	}
	return unreadCount, nil
}
Example #4
0
//为别的平台用户写cookie
func setCookieForOtherPlatformUser(userId int64, email string, seconds int, ctx *goku.HttpContext) {
	//注册成功,写cookie
	now := time.Now()
	h := md5.New()
	h.Write([]byte(fmt.Sprintf("%v-%v", email, now.Unix())))
	ticket := fmt.Sprintf("%x_%v", h.Sum(nil), now.Unix())
	expires := now.Add(time.Duration(seconds) * time.Second)
	redisClient := models.GetRedis()
	defer redisClient.Quit()
	err := redisClient.Set(ticket, userId)
	if err != nil {
		goku.Logger().Errorln(err.Error())
	} else {
		_, err = redisClient.Expireat(ticket, expires.Unix())
		if err != nil {
			goku.Logger().Errorln(err.Error())
		}
		c := &http.Cookie{
			Name:     "_glut",
			Value:    ticket,
			Expires:  expires,
			Path:     "/",
			HttpOnly: true,
		}
		ctx.SetCookie(c)
	}
}
Example #5
0
// 获取用户列表.
// @page: 从1开始的页数
// @return: users, total-count, err
func User_GetList(page, pagesize int, order string) ([]User, int64, error) {
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	page, pagesize = utils.PageCheck(page, pagesize)

	qi := goku.SqlQueryInfo{}
	qi.Limit = pagesize
	qi.Offset = pagesize * page
	if order == "" {
		qi.Order = "id desc"
	} else {
		qi.Order = order
	}

	var users []User
	err := db.GetStructs(&users, qi)
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return nil, 0, err
	}

	total, err := db.Count("user", "")
	if err != nil {
		goku.Logger().Errorln(err.Error())
	}
	return users, total, nil
}
Example #6
0
// @page: 从1开始
// @return: comments, total-count, err
func Comment_GetByPage(page, pagesize int, order string) ([]Comment, int64, error) {
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	page, pagesize = utils.PageCheck(page, pagesize)

	qi := goku.SqlQueryInfo{}
	qi.Limit = pagesize
	qi.Offset = page * pagesize
	if order == "" {
		qi.Order = "id desc"
	} else {
		qi.Order = order
	}
	var comments []Comment
	err := db.GetStructs(&comments, qi)
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return nil, 0, err
	}

	total, err := db.Count("comment", "")
	if err != nil {
		goku.Logger().Errorln(err.Error())
	}

	return comments, total, nil
}
Example #7
0
// 获取关注topicId的用户列表
func Topic_GetFollowers(topicId int64, page, pagesize int) ([]User, error) {
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	page, pagesize = utils.PageCheck(page, pagesize)

	qi := goku.SqlQueryInfo{}
	qi.Fields = "u.id, u.name, u.email, u.user_pic"
	qi.Join = " tf INNER JOIN `user` u ON tf.user_id=u.id"
	qi.Where = "tf.topic_id=?"
	qi.Params = []interface{}{topicId}
	qi.Limit = pagesize
	qi.Offset = pagesize * page
	qi.Order = "u.id desc"

	rows, err := db.Select("topic_follow", qi)

	if err != nil {
		goku.Logger().Errorln(err.Error())
		return nil, err
	}
	defer rows.Close()

	users := make([]User, 0)
	for rows.Next() {
		user := User{}
		err = rows.Scan(&user.Id, &user.Name, &user.Email, &user.UserPic)
		if err != nil {
			goku.Logger().Errorln(err.Error())
			return nil, err
		}
		users = append(users, user)
	}
	return users, nil
}
Example #8
0
func Topic_SearchByName(name string) ([]Topic, error) {
	var db *goku.MysqlDB = GetDB()
	// db.Debug = true
	defer db.Close()

	qi := goku.SqlQueryInfo{}
	qi.Fields = "`id`,`name`,`name_lower`,`description`,`pic`,`click_count`,`follower_count`,`link_count`"
	qi.Where = "name_lower LIKE ?"                         //"name_lower LIKE '%" + strings.ToLower(name) + "%'"
	qi.Params = []interface{}{strings.ToLower(name) + "%"} //"%" +
	qi.Limit = 10
	qi.Offset = 0
	qi.Order = "link_count DESC"

	rows, err := db.Select("topic", qi)

	topics := make([]Topic, 0)
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return topics, err
	}

	for rows.Next() {
		topic := Topic{}
		err = rows.Scan(&topic.Id, &topic.Name, &topic.NameLower, &topic.Description, &topic.Pic, &topic.ClickCount, &topic.FollowerCount, &topic.LinkCount)
		if err != nil {
			goku.Logger().Errorln(err.Error())
			return topics, err
		}
		topics = append(topics, topic)
	}

	return topics, nil

}
Example #9
0
// 减少DB操作
// @t: 推送类型, 1:关注的用户, 2:关注的话题
func linkForUser_AddWithDb(db *goku.MysqlDB, userId, linkId int64, t int) error {
	m := map[string]interface{}{
		"user_id":     userId,
		"link_id":     linkId,
		"create_time": time.Now(),
	}
	if t == 1 {
		m["user_count"] = 1
	} else {
		m["topic_count"] = 1
	}

	_, err := db.Insert(LinkForUser_TableName(userId), m)
	if err != nil {
		if strings.Index(err.Error(), "Duplicate entry") > -1 {
			m := map[string]interface{}{}
			if t == 1 {
				m["user_count"] = 1
			} else {
				m["topic_count"] = 1
			}
			_, err = db.Update(LinkForUser_TableName(userId), m, "user_id=? and link_id=?", userId, linkId)
			if err != nil {
				goku.Logger().Errorln(err.Error())
			}
		} else {
			goku.Logger().Errorln(err.Error())
		}
	}
	return err
}
Example #10
0
// 用户userId 取消关注 话题topicId
func Topic_UnFollow(userId, topicId int64) (bool, error) {
	if userId < 1 || topicId < 1 {
		return false, errors.New("参数错误")
	}
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	r, err := db.Delete("topic_follow", "`user_id`=? AND `topic_id`=?", userId, topicId)
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return false, err
	}

	var afrow int64
	afrow, err = r.RowsAffected()
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return false, err
	}

	if afrow > 0 {
		// 取消关注话题成功,将话题的链接从用户的推送列表中移除
		LinkForUser_UnFollowTopic(userId, topicId)
		// 更新用户关注话题的数量
		User_IncCount(db, userId, "ftopic_count", -1)
		// 更新话题的关注用户数
		Topic_IncCount(db, topicId, "follower_count", -1)
		return true, nil
	}
	return false, nil
}
Example #11
0
// 检查 mUserId 与 sUserId 的关系,
// return:
//      @isFollower: sUserId是否关注mUserId
//      @isFollowed: mUserId是否关注sUserId
//      @isFriend: 是否互相关注
func User_CheckRelationship(mUserId, sUserId int64) (isFollower, isFollowed, isFriend bool) {
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	rows, err := db.Query("select * from `user_follow` where `user_id`=? and `follow_id`=? limit 1",
		mUserId, sUserId)
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return
	}
	defer rows.Close()
	if rows.Next() {
		isFollowed = true
	}

	rows1, err1 := db.Query("select * from `user_follow` where `user_id`=? and `follow_id`=? limit 1",
		sUserId, mUserId)
	if err1 != nil {
		goku.Logger().Errorln(err1.Error())
		return
	}
	defer rows1.Close()
	if rows1.Next() {
		isFollower = true
	}

	if isFollowed && isFollower {
		isFriend = true
	}

	return
}
Example #12
0
//模糊搜索用户
func User_SearchByName(name string, ctx *goku.HttpContext) ([]*VUser, error) {
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	qi := goku.SqlQueryInfo{}
	qi.Fields = "`id`,`name`,`email`,`description`,`user_pic`,`friend_count`,`topic_count`,`ftopic_count`,`status`,`follower_count`,`link_count`,`create_time`"
	qi.Where = "name_lower LIKE ?"
	qi.Params = []interface{}{strings.ToLower(name) + "%"}
	qi.Limit = 10
	qi.Offset = 0
	qi.Order = "link_count DESC"

	rows, err := db.Select("user", qi)

	if err != nil {
		goku.Logger().Errorln(err.Error())
		return nil, err
	}

	users := make([]User, 0)
	for rows.Next() {
		user := User{}
		err = rows.Scan(&user.Id, &user.Name, &user.Email, &user.Description, &user.UserPic, &user.FriendCount, &user.TopicCount, &user.FtopicCount, &user.Status, &user.FollowerCount, &user.LinkCount, &user.CreateTime)
		if err != nil {
			goku.Logger().Errorln(err.Error())
			return nil, err
		}
		users = append(users, user)
	}

	return User_ToVUsers(users, ctx), nil

}
Example #13
0
File: user.go Project: t7er/ohlala
// 获取用户关注的话题列表
func User_GetFollowTopics(userId int64, page, pagesize int) ([]Topic, error) {
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	page, pagesize = utils.PageCheck(page, pagesize)

	qi := goku.SqlQueryInfo{}
	qi.Fields = "t.id, t.name, t.description, t.pic"
	qi.Join = " tf INNER JOIN `topic` t ON tf.topic_id=t.id"
	qi.Where = "tf.user_id=?"
	qi.Params = []interface{}{userId}
	qi.Limit = pagesize
	qi.Offset = pagesize * page
	qi.Order = "t.id desc"

	rows, err := db.Select("topic_follow", qi)

	if err != nil {
		goku.Logger().Errorln(err.Error())
		return nil, err
	}
	defer rows.Close()

	topics := make([]Topic, 0)
	for rows.Next() {
		topic := Topic{}
		err = rows.Scan(&topic.Id, &topic.Name, &topic.Description, &topic.Pic)
		if err != nil {
			goku.Logger().Errorln(err.Error())
			return nil, err
		}
		topics = append(topics, topic)
	}
	return topics, nil
}
Example #14
0
func (self *BaseCrawler) saveLink(url, title string) (err error) {
	defer func() {
		if err != nil {
			if strings.Index(err.Error(), "Url已经提交过") > -1 {
				goku.Logger().Logln("Crawler saveLink:", err.Error(), url, title)
			} else {
				goku.Logger().Errorln("Crawler saveLink error:", err.Error(), url, title)
			}
		}
	}()
	idCount := len(self.UserIds)
	if idCount < 1 {
		err = errors.New("no user ids")
		return
	}
	userId := self.UserIds[rand.Int63n(int64(idCount))]
	user := models.User_GetById(userId)
	if user == nil || user.Id < 1 {
		err = errors.New("no selected user")
		return
	}

	if strings.Index(url, "news.dbanotes.net") > 0 {
		return nil
	}
	// 移除多余的字符
	if strings.LastIndex(title, ")") == len(title)-1 && strings.Index(title, " (") > 0 {
		title = title[0:strings.LastIndex(title, " (")]
	}

	topics := []string{}
	ltitle := strings.ToLower(title)
	for i := 0; i < lenTopTopics; i++ {
		if strings.Index(ltitle, topTopics[i].NameLower) > -1 {
			if len(topTopics[i].Name) > 1 {
				topics = append(topics, topTopics[i].Name)
			}
		}
	}

	m := map[string]string{
		"title":   title,
		"context": url,
		"topics":  strings.Join(topics, ","),
	}
	f := forms.CreateLinkSubmitForm()
	f.FillByMap(m)

	success, linkId, errMsg, _ := models.Link_SaveForm(f, user.Id, false)

	if success {
		go controllers.AddLinkForSearch(0, f.CleanValues(), linkId, user.Name) //contextType:0: url, 1:文本   TODO:
	} else {
		err = errors.New(strings.Join(errMsg, ", "))
		return
	}
	return nil
}
Example #15
0
// 保持topic到数据库,同时建立topic与link的关系表
// 如果topic已经存在,则直接建立与link的关联
// 全部成功则返回true
func Topic_SaveTopics(topics string, linkId int64) bool {
	if topics == "" {
		return true
	}
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	success := true
	topicList := strings.Split(topics, ",")
	for _, topic := range topicList {
		topicLower := strings.ToLower(topic)
		t := new(Topic)
		err := db.GetStruct(t, "`name_lower`=?", topic)
		if err != nil {
			goku.Logger().Logln(topic)
			goku.Logger().Errorln(err.Error())
			success = false
			continue
		}
		if t.Id < 1 {
			t.Name = topic
			t.NameLower = topicLower
			_, err = db.InsertStruct(t)
			if err != nil {
				goku.Logger().Errorln(err.Error())
				success = false
				continue
			}
		}
		if t.Id > 0 && linkId > 0 {
			_, err = db.Insert("topic_link", map[string]interface{}{"topic_id": t.Id, "link_id": linkId})
			if err != nil {
				goku.Logger().Errorln(err.Error())
				success = false
			} else {
				// 成功,更新话题的链接数量统计
				Topic_IncCount(db, t.Id, "link_count", 1)

				redisClient := GetRedis()
				defer redisClient.Quit()
				// 加入推送队列
				// 格式: pushtype,topicid,linkid,timestamp
				qv := fmt.Sprintf("%v,%v,%v,%v", LinkForUser_ByTopic, t.Id, linkId, time.Now().Unix())
				_, err = redisClient.Lpush(golink.KEY_LIST_PUSH_TO_USER, qv)
				if err != nil {
					goku.Logger().Errorln(err.Error())
				}
			}
		}
	}
	return success
}
Example #16
0
// 获取收到的评论列表
// @page: 从1开始
// @return: comments, total-count, err
func CommentForUser_GetByPage(userId int64, page, pagesize int, order string) ([]Comment, int64, error) {
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	page, pagesize = utils.PageCheck(page, pagesize)

	qi := goku.SqlQueryInfo{}
	qi.Limit = pagesize
	qi.Offset = page * pagesize
	qi.Where = "cfu.user_id=?"
	qi.Join = " cfu INNER JOIN `comment` c ON cfu.comment_id=c.id"
	qi.Fields = `c.id, c.user_id, c.link_id, c.parent_path, c.children_count, c.top_parent_id,
                c.parent_id, c.deep, c.status, c.content, c.create_time, c.vote_up, c.vote_down, c.reddit_score`

	if order == "" {
		qi.Order = "create_time desc"
	} else {
		qi.Order = order
	}

	qi.Params = []interface{}{userId}
	rows, err := db.Select("comment_for_user", qi)

	if err != nil {
		goku.Logger().Errorln(err.Error())
		return nil, 0, err
	}
	defer rows.Close()
	comments := make([]Comment, 0)
	for rows.Next() {
		c := Comment{}
		err = rows.Scan(&c.Id, &c.UserId, &c.LinkId, &c.ParentPath, &c.ChildrenCount,
			&c.TopParentId, &c.ParentId, &c.Deep, &c.Status, &c.Content,
			&c.CreateTime, &c.VoteUp, &c.VoteDown, &c.RedditScore)
		if err != nil {
			goku.Logger().Errorln(err.Error())
			return nil, 0, err
		}
		comments = append(comments, c)
	}

	total, err := db.Count("comment_for_user", "user_id=?", userId)
	if err != nil {
		goku.Logger().Errorln(err.Error())
	}

	return comments, total, nil
}
Example #17
0
func main() {
	//	fmt.Println("Hello World!")
	rt := &goku.RouteTable{Routes: gomgoweb.Routes}
	s := goku.CreateServer(rt, nil, gomgoweb.Config)
	goku.Logger().Logln("Server start on", s.Addr)
	log.Fatal(s.ListenAndServe())
}
Example #18
0
func GetBandsByGenre(id string) []MyDoc {
	bucket := GetDB()
	defer bucket.Close()
	results, err := bucket.View(gocbweb.DDOC, "by_genre",
		map[string]interface{}{"key": id, "full_set": true, "reduce": false})
	if err != nil {
		goku.Logger().Logln(err)
		os.Exit(1)
	}
	var x []MyDoc
	found := false
	for _, row := range results.Rows {
		for _, already := range x {
			if already.Id == row.ID {
				found = true
				break
			}
		}
		if found == false {
			var band MyDoc
			bucket.Get(row.ID, &band)
			x = append(x, band)
		}
		found = false
	}
	return x
}
Example #19
0
func main() {
	rt := goku.RouteTable{Routes: gomenu1.Routes}
	middlewares := []goku.Middlewarer{}
	s := goku.CreateServer(&rt, middlewares, gomenu1.Config)
	goku.Logger().Logln("Server start on", s.Addr)
	log.Fatal(s.ListenAndServe())
}
Example #20
0
// 加(减)表里面的统计数据
// @table: 要操作数据库表名
// @field: 要修改的字段
// @inc: 要增加或减少的值
func IncCountById(db *goku.MysqlDB, table string, id int64, field string, inc int) (sql.Result, error) {
	r, err := db.Exec(fmt.Sprintf("UPDATE `%s` SET %s=%s+? WHERE id=?;", table, field, field), inc, id)
	if err != nil {
		goku.Logger().Errorln(err.Error())
	}
	return r, err
}
Example #21
0
// 增加链接的点击统计数
func link_incClick(ctx *goku.HttpContext) goku.ActionResulter {
	var success bool
	var errorMsgs string
	id := ctx.Get("id")
	if id == "" {
		errorMsgs = "参数错误"
	} else {
		linkId, err := strconv.ParseInt(id, 10, 64)
		if err == nil && linkId > 0 {
			_, err = models.Link_IncClickCount(linkId, 1)
			if err == nil {
				success = true
			}
		}
		if err != nil {
			goku.Logger().Error(err.Error())
			errorMsgs = err.Error()
		}
	}

	r := map[string]interface{}{
		"success": success,
		"errors":  errorMsgs,
	}
	return ctx.Json(r)
}
Example #22
0
// 获取用户的提醒信息数据
func Remind_ForUser(userId int64) (r RemindInfo, err error) {
	redisClient := GetRedis()
	defer redisClient.Quit()

	key := fmt.Sprintf("rd:%d", userId)
	res, err_ := redisClient.Hgetall(key) //,
	//     remindTypeKey[REMIND_COMMENT],
	//     remindTypeKey[REMIND_FANS],
	// )

	if err_ != nil {
		if err_.Error() != "Nonexisting key" {
			err = err_
			goku.Logger().Errorln(err.Error())
		}
		return
	}
	// fmt.Printf("%s => %s => %s => %+v\n", key,
	//     remindTypeKey[REMIND_COMMENT], remindTypeKey[REMIND_FANS], res.StringMap())

	// // r2 := res.IntArray()
	// // r.Comments = int(r2[0])
	// // r.Fans = int(r2[1])
	r2 := res.StringMap()
	if c, ok := r2[remindTypeKey[REMIND_COMMENT]]; ok {
		r.Comments, _ = strconv.Atoi(c)
	}
	if f, ok := r2[remindTypeKey[REMIND_FANS]]; ok {
		r.Fans, _ = strconv.Atoi(f)
	}
	return
}
Example #23
0
func main() {

	for {
		fmt.Println("entry")
		oneSuccess := false
		emails, err := models.GetEmailForSend()

		if err != nil {
			goku.Logger().Errorln(err.Error())
		} else {
			for _, email := range emails {
				err := sendMail(email)
				if err != nil {
					fmt.Println(err)
					email.SendSuccess = false
				} else {
					fmt.Println("send", email)
					email.SendSuccess = true
					oneSuccess = true
				}
			}
			//更新状态
			if oneSuccess == true && len(emails) > 0 {
				models.UpdateInviteEmailStatus(emails)
				continue
			}
		}

		fmt.Println("sleep")
		time.Sleep(300 * time.Second) // 每5分钟
	}
}
Example #24
0
func main() {
	rt := &goku.RouteTable{Routes: gocbweb.Routes}
	s := goku.CreateServer(rt, nil, gocbweb.Config)
	goku.Logger().Logln("Server start on", s.Addr)
	log.Fatal(s.ListenAndServe())

}
Example #25
0
// 获取由用户发布的评论
// @page: 从1开始
func Comment_ByUser(userId int64, page, pagesize int) []Comment {
	if page < 1 {
		page = 1
	}
	page = page - 1
	if pagesize == 0 {
		pagesize = 20
	}
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	qi := goku.SqlQueryInfo{}
	qi.Limit = pagesize
	qi.Offset = page * pagesize
	qi.Where = "`user_id`=?"
	qi.Params = []interface{}{userId}
	qi.Order = "id desc"
	var comments []Comment
	err := db.GetStructs(&comments, qi)
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return nil
	}
	return comments
}
Example #26
0
func User_RecoverPasswordFor(email string) (err error) {
	u, err := User_GetByEmail(email)
	if err != nil {
		err = errors.New("系统内部发生错误")
		return
	}
	if u == nil {
		err = errors.New("指定邮箱不存在")
		return
	}

	var ur *UserRecovery
	if ur, err = userRecovery_GetActive(u.Id); err == nil {
		if ur == nil {
			ur = newUserRecovery(u.Id)
			ur.Save()
		}
	} else {
		goku.Logger().Errorln(err)
		return
	}

	var recoveryPwdStrategy func(*User, *UserRecovery) error

	recoveryPwdStrategy = user_recoveryPasswordBySendingEmail
	err = recoveryPwdStrategy(u, ur)
	return
}
Example #27
0
// 保存link到数据库,如果成功,则返回link的id
func Link_SaveMap(m map[string]interface{}) int64 {
	var db *goku.MysqlDB = GetDB()
	defer db.Close()
	m["create_time"] = time.Now()
	//新增link默认投票1次,显示的时候默认减一
	m["vote_up"] = 0 //1
	m["reddit_score"] = utils.LinkSortAlgorithm(m["create_time"].(time.Time), int64(0), int64(0))
	m["context_md5"] = utils.MD5_16(strings.ToLower(m["context"].(string)))

	r, err := db.Insert("link", m)
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return 0
	}
	var id int64
	id, err = r.LastInsertId()
	if err != nil {
		goku.Logger().Errorln(err.Error())
		return 0
	}

	if id > 0 {
		uid := m["user_id"].(int64)
		// 更新用户的链接计数
		IncCountById(db, "user", uid, "link_count", 1)
		// 直接推送给自己,自己必须看到
		LinkForUser_Add(uid, id, LinkForUser_ByUser)

		// 存入`tui_link_for_handle` 链接处理队列表
		db.Query("INSERT ignore INTO tui_link_for_handle(link_id,create_time,user_id,insert_time,data_type) VALUES (?, ?, ?, NOW(), ?)",
			id, m["create_time"].(time.Time), uid, 1)

		redisClient := GetRedis()
		defer redisClient.Quit()
		// 加入推送队列
		// 格式: pushtype,userid,linkid,timestamp
		qv := fmt.Sprintf("%v,%v,%v,%v", LinkForUser_ByUser, uid, id, time.Now().Unix())
		_, err = redisClient.Lpush(golink.KEY_LIST_PUSH_TO_USER, qv)
		if err != nil {
			goku.Logger().Errorln(err.Error())
			// return 0
		}

	}

	return id
}
Example #28
0
// 获取属于某用户的link
// @page: 从1开始
// @orderType: 排序类型, hot:热门, hotc:热议, time:最新, vote:投票得分, ctvl:争议
func Link_ForUser(userId int64, orderType string, page, pagesize int) ([]Link, error) {
	var db *goku.MysqlDB = GetDB()
	defer db.Close()

	page, pagesize = utils.PageCheck(page, pagesize)

	qi := goku.SqlQueryInfo{}
	qi.Fields = "l.id, l.user_id, l.title, l.context, l.topics, l.vote_up, l.vote_down, l.view_count, l.click_count, l.comment_count, l.create_time"
	qi.Join = " ul INNER JOIN `link` l ON ul.link_id=l.id"
	qi.Where = "ul.user_id=?"
	qi.Params = []interface{}{userId}
	qi.Limit = pagesize
	qi.Offset = pagesize * page
	switch orderType {
	case golink.ORDER_TYPE_TIME: // 最新
		qi.Order = "l.id desc"
	case golink.ORDER_TYPE_HOTC: // 热议
		qi.Order = "l.comment_count desc, id desc"
	case golink.ORDER_TYPE_CTVL: // 争议
		qi.Order = "l.dispute_score desc, id desc"
	case golink.ORDER_TYPE_VOTE: // 得分
		qi.Order = "l.vote_up desc, id desc"
	default:
		qi.Order = "l.reddit_score desc, id desc"
	}

	rows, err := db.Select(LinkForUser_TableName(userId), qi)

	if err != nil {
		goku.Logger().Errorln(err.Error())
		return nil, err
	}
	defer rows.Close()

	links := make([]Link, 0)
	for rows.Next() {
		link := Link{}
		err = rows.Scan(&link.Id, &link.UserId, &link.Title, &link.Context, &link.Topics,
			&link.VoteUp, &link.VoteDown, &link.ViewCount, &link.ClickCount, &link.CommentCount, &link.CreateTime)
		if err != nil {
			goku.Logger().Errorln(err.Error())
			return nil, err
		}
		links = append(links, link)
	}
	return links, nil
}
Example #29
0
func GetDB() *couchbase.Bucket {
	b, err := couchbase.GetBucket(gocbweb.FULLPOOL, "default", gocbweb.BUCKET)
	if err != nil {
		goku.Logger().Logln(err)
		os.Exit(1)
	}
	return b
}
Example #30
0
// 加(减)用户信息里面的统计数据
// @field: 要修改的字段
// @inc: 要增加或减少的值
func User_IncCount(db *goku.MysqlDB, userid int64, field string, inc int) (sql.Result, error) {
	// m := map[string]interface{}{field: fmt.Sprintf("%v+%v", field, inc)}
	// r, err := db.Update("user", m, "id=?", userid)
	r, err := db.Exec(fmt.Sprintf("UPDATE `user` SET %s=%s+? WHERE id=?;", field, field), inc, userid)
	if err != nil {
		goku.Logger().Errorln(err.Error())
	}
	return r, err
}