// 获取用户关注的话题列表 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 }
// 获取由用户发布的评论 // @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 }
// 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 }
func User_GetByTicket(ticket string) (*User, error) { redisClient := GetRedis() defer redisClient.Quit() id, err := redisClient.Get(ticket) if err != nil { return nil, err } if id.String() == "" { return nil, nil } var db *goku.MysqlDB = GetDB() defer db.Close() var user *User = new(User) err = db.GetStruct(user, "id=?", id.String()) if err != nil { fmt.Printf("err: %v\n", err) return nil, err } if user.Id > 0 { return user, nil } return nil, nil }
func admin_index(ctx *goku.HttpContext) goku.ActionResulter { var db *goku.MysqlDB = models.GetDB() defer db.Close() linkCount, err := db.Count("link", "") if err != nil { ctx.ViewData["errorMsg"] = err.Error() return ctx.Render("error", nil) } ctx.ViewData["linkCount"] = linkCount userCount, err := db.Count("user", "") if err != nil { ctx.ViewData["errorMsg"] = err.Error() return ctx.Render("error", nil) } ctx.ViewData["userCount"] = userCount topicCount, err := db.Count("topic", "") if err != nil { ctx.ViewData["errorMsg"] = err.Error() return ctx.Render("error", nil) } ctx.ViewData["topicCount"] = topicCount commentCount, err := db.Count("comment", "") if err != nil { ctx.ViewData["errorMsg"] = err.Error() return ctx.Render("error", nil) } ctx.ViewData["commentCount"] = commentCount return ctx.View(nil) }
func User_SaveMap(m map[string]interface{}) (sql.Result, error) { var db *goku.MysqlDB = GetDB() defer db.Close() m["email_lower"] = strings.ToLower(m["email"].(string)) r, err := db.Insert("user", m) return r, err }
// 获取由用户收藏的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 }
//收藏link func SaveUserFavorite(f map[string]interface{}) error { var db *goku.MysqlDB = GetDB() defer db.Close() _, err := db.Insert("user_favorite_link", f) return err }
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 }
// 关注好友的最新链接的未读数 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 }
// 获取关注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 }
// 获取用户列表. // @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 }
// 用户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 }
//模糊搜索用户 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 }
// @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 }
// 检查 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 }
//删除link func DelUserFavorite(userId int64, linkId int64) error { var db *goku.MysqlDB = GetDB() defer db.Close() _, err := db.Delete("user_favorite_link", "`user_id`=? AND `link_id`=?", userId, linkId) return err }
func thirdPartyUser_SearchOneBy(criteria string, values ...interface{}) (u *ThirdPartyUser) { var db *goku.MysqlDB = GetDB() defer db.Close() sql := "SELECT `user_id`, `third_party`, `third_party_user_id`, `third_party_email`, `access_token`, `refresh_token`, `token_expire_time`, `create_time`, `last_active_time`, `avatar_url`, `link` FROM `third_party_user` WHERE " + criteria + " limit 1" thirdPartyUserRow, err := db.Query(sql, values...) if err != nil { return } if thirdPartyUserRow == nil { return } if thirdPartyUserRow.Next() { u = &ThirdPartyUser{} err = thirdPartyUserRow.Scan( &u.UserId, &u.ThirdParty, &u.ThirdPartyUserId, &u.ThirdPartyEmail, &u.AccessToken, &u.RefreshToken, &u.TokenExpireTime, &u.CreateTime, &u.LastActiveTime, &u.AvatarUrl, &u.Link) } if err != nil { u = nil } return }
//获取link和comment的投票记录 func GetVoteRecordByUser(userId int64, page int, pagesize int) { /* sql := `SELECT * FROM ( (SELECT L.id, 'link' AS record_type,LSR.score AS vote_score,LSR.vote_time FROM link_support_record LSR INNER JOIN link L ON LSR.link_id=L.id AND LSR.user_id=1 ORDER BY vote_time DESC LIMIT 0,200) UNION ALL (SELECT C.id,'comment' AS record_type,CSR.score AS vote_score,CSR.vote_time FROM comment_support_record CSR INNER JOIN comment C ON CSR.comment_id=C.id AND CSR.user_id=1 ORDER BY CSR.vote_time DESC LIMIT 0,200))T ORDER BY T.vote_time DESC LIMIT ?,?` */ if page < 1 { page = 1 } page = page - 1 if pagesize == 0 { pagesize = 20 } var db *goku.MysqlDB = GetDB() defer db.Close() //rows, err := db.Query(sql, pagesize * page, pagesize) //if err != nil { //goku.Logger().Errorln(err.Error()) //return nil, err //} }
func GetTodo(id int) (Todo, error) { var db *goku.MysqlDB = GetDB() defer db.Close() var todo Todo = Todo{} err := db.GetStruct(&todo, "id=?", id) return todo, err }
func GetTodoLists() (*[]Todo, error) { var db *goku.MysqlDB = GetDB() defer db.Close() qi := goku.SqlQueryInfo{} qi.Order = "finished asc, id desc" var todos []Todo err := db.GetStructs(&todos, qi) return &todos, err }
func (ur *UserRecovery) Update() (sql.Result, error) { m := make(map[string]interface{}) m["active"] = ur.Active m["recovery_time"] = ur.RecoveryTime var db *goku.MysqlDB = GetDB() defer db.Close() r, err := db.Update("user_recovery", m, "`user_id`=? AND `token`=?", ur.UserId, ur.Token) return r, err }
//更新邀请码 func UpdateIsRegister(invite *RegisterInvite) { if !golink.Invite_Enabled { return } var db *goku.MysqlDB = GetDB() defer db.Close() db.Query("UPDATE `register_invite` SET `is_register`=1 WHERE `Guid`=?", invite.Guid) }
//根据用户关注的话题给它推荐相关的用户 func User_RecommendFromTopic(userId int64) ([]User, error) { iRecommendCount := 10 var db *goku.MysqlDB = GetDB() db.Debug = true defer db.Close() sql := "SELECT `topic_id` FROM `topic_follow` WHERE `user_id`=? ORDER BY `create_time` DESC limit ?" topicRows, topicErr := db.Query(sql, userId, iRecommendCount) if topicErr != nil { return nil, topicErr } topicIds := make([]int64, 0) var topicId int64 for topicRows.Next() { topicErr = topicRows.Scan(&topicId) if topicErr == nil { topicIds = append(topicIds, topicId) } } hashUsers := map[int64]int64{} users := make([]User, 0) tLen := len(topicIds) var uCount int uCount = iRecommendCount / tLen strUserIds := fmt.Sprintf("%d", userId) hashUsers[userId] = userId if tLen > 0 { sql = "SELECT u.`id`,u.`name`,u.`email`,u.`description`,u.`user_pic`,u.`friend_count`,u.`topic_count`,u.`ftopic_count`,u.`status`," + "u.`follower_count`,u.`link_count`,u.`create_time` FROM `tui_link_for_topic_top` tl INNER JOIN `link` l ON " + "tl.`topic_id`=? AND tl.`link_id`=l.`id` AND l.`user_id` NOT IN(?) " + "AND NOT EXISTS(SELECT 1 FROM `user_follow` uf WHERE uf.`user_id`=? AND uf.`follow_id`=l.`user_id`) " + "INNER JOIN `user` u ON u.`id`=l.`user_id` " + "ORDER BY tl.`reddit_score` DESC limit ?" for _, tId := range topicIds { userRows, userErr := db.Query(sql, tId, strUserIds, userId, uCount) if userErr == nil { for userRows.Next() { user := User{} userErr = userRows.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 userErr == nil && hashUsers[userId] <= 0 { users = append(users, user) strUserIds += fmt.Sprintf(",%d", user.Id) hashUsers[user.Id] = user.Id } } } } } //fmt.Print(users) return users, nil }
// 更新话题的图片地址(只存相对路径) func Topic_UpdatePic(id int64, pic string) (sql.Result, error) { var db *goku.MysqlDB = GetDB() defer db.Close() m := map[string]interface{}{"pic": pic} r, err := db.Update("topic", m, "id=?", id) if err != nil { goku.Logger().Errorln(err.Error()) } return r, err }
func Comment_DelById(id int64) error { var db *goku.MysqlDB = GetDB() defer db.Close() _, err := db.Query("UPDATE `comment` SET status=2 WHERE id=?", id) if err != nil { goku.Logger().Errorln(err.Error()) return err } return nil }
// 保持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 }
func Topic_GetTops(page, pagesize int) ([]Topic, error) { var db *goku.MysqlDB = GetDB() defer db.Close() qi := goku.SqlQueryInfo{} qi.Order = "link_count desc" var topics []Topic err := db.GetStructs(&topics, qi) if err != nil { goku.Logger().Errorln(err.Error()) } return topics, err }
//更新发送的邀请email状态 func UpdateInviteEmailStatus(emails []*EmailInvite) { var db *goku.MysqlDB = GetDB() defer db.Close() for _, email := range emails { if email.SendSuccess == true { db.Query("UPDATE register_invite SET is_send=1 WHERE guid=?", email.Guid) } else { db.Query("UPDATE register_invite SET fail_count=fail_count+1 WHERE guid=?", email.Guid) } } }
func (ur *UserRecovery) Save() (sql.Result, error) { var db *goku.MysqlDB = GetDB() defer db.Close() m := make(map[string]interface{}) m["user_id"] = ur.UserId m["token"] = ur.Token m["active"] = ur.Active m["create_time"] = ur.CreateTime m["recovery_time"] = ur.RecoveryTime r, err := db.Insert("user_recovery", m) return r, err }