Golang aTalk-server-common.IntToBytes类(方法)实例源码

下面列出了Golang aTalk-server-common.IntToBytes 类(方法)源码代码实例,从而了解它的用法。

作者:happyEg    项目:aTal   
func GroupMsgRecordController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("message")
	var messages []models.Message
	var oldTime time.Time

	now := time.Now().Unix()

	//只返回3天以内的聊天记录
	if msg.GetMsgTime() < now-(TimeLimit*24*3600) {
		oldTime = time.Unix(now-(TimeLimit*24*3600), 0)
	} else {
		oldTime = time.Unix(msg.GetMsgTime(), 0)
	}

	// 每次获取一定条数的群消息
	err := collection.Find(bson.M{"group_id": msg.Group.GetId(), "send_time": bson.M{"gte": oldTime}}).
		Sort("-send_time").Limit(OnceRequent).Skip(int(MsgCount[msg.Group.GetId()])).All(&messages)
	if err != nil {
		Logger.Error("group msgRecord failed:", err)
		common.CommonResultReturn(conn, "groupMsgRecordResult", msg.GetMsgTypeId(), 1)
		return
	}

	//统计需要的偏移量
	MsgCount[msg.Group.GetId()] = MsgCount[msg.Group.GetId()] + OnceRequent

	for _, v := range messages {
		msgUser := &protocol.User{}
		send := &protocol.SendMessage{}
		msgUser.Username = &v.Sender
		send.Receiver = &v.Receiver
		msgType := protocol.Mode(v.MsgType)
		send.Type = &msgType
		send.Msg = &v.Msg
		sendTime := v.MsgTime.Unix()
		send.MsgTime = &sendTime
		returnMsg := &protocol.WMessage{
			MsgType:   proto.String("groupMsgRecordResult"),
			MsgTypeId: msg.MsgTypeId,
			StataCode: proto.Int32(0),
			SendMsg:   send,
			UserInfo:  msgUser,
		}

		buffer, err := proto.Marshal(returnMsg)
		if err != nil {
			Logger.Warn("protobuf marshal failed: ", err)
			continue
		}
		newbuffer := append(common.IntToBytes(len(buffer)), buffer...)
		switch conn.(type) {
		case net.Conn:
			_, err = conn.(net.Conn).Write(newbuffer)
			common.CheckErr(err)
		case websocket.Conn:
			_, err = conn.(*websocket.Conn).Write(newbuffer)
			common.CheckErr(err)
		}
	}
}

作者:happyEg    项目:aTal   
func write(conn *net.TCPConn) {

	n := protocol.Mode(5)
	reg := &protocol.WMessage{
		MsgType:   proto.String("sendMsg"),
		MsgTypeId: proto.Int32(8),
		UserInfo: &protocol.User{
			Username: proto.String("jim"),
			//Password: proto.String("123456"),
		},
		SendMsg: &protocol.SendMessage{
			Receiver: proto.String("zhang"),
			MsgType:  &n,
			Msg:      proto.String("吃了吗?"),
		},
	}
	buf, err := proto.Marshal(reg)
	if err != nil {
		fmt.Println("failed: %s\n", err)
		return
	}
	fmt.Println("buf: ", len(buf))
	length := len(buf)
	buffer := append(common.IntToBytes(length), buf...)
	conn.Write(buffer)
	//return buffer
	//conn.Write(common.IntToBytes(length))
}

作者:happyEg    项目:aTal   
//处理未读的群聊信息
func HandleGroupUnreadMsg(conn interface{}, value *models.Message, user *models.User) {

	//根据群组找其所在的群组的聊天消息
	var messages []models.Message
	collection := (common.DBMongo).C("message")
	nowTime := time.Now()

	//查找用户上次退出和此次登陆时的未读消息
	err := collection.Find(bson.M{"group_id": value.GroupId, "send_time": bson.M{"$gte": user.LogoutTime, "$lte": nowTime}}).
		Sort("-send_time").Limit(PullCount).All(&messages)

	//未读消息的数量
	num, err := collection.Find(bson.M{"sender": value.Sender, "group_id": value.GroupId, "receiver": value.Receiver,
		"send_time": bson.M{"$gte": user.LogoutTime, "$lte": nowTime}}).Sort("-send_time").Limit(PullCount).Count()
	if err != nil {
		Logger.Error("get unread single msg failed: ", err)
		return
	}

	MsgCount[value.GroupId] = num

	//循环推送查找到的每一条未读消息
	for _, v := range messages {
		msgUser := &protocol.User{}
		msgUser.Username = &v.Sender

		group := &protocol.Groups{}
		group.Id = &v.GroupId

		send := &protocol.SendMessage{}
		msgType := protocol.Mode(v.MsgType)
		send.Type = &msgType
		send.Msg = &v.Msg
		sendtime := v.MsgTime.Unix()
		send.MsgTime = &sendtime
		returnMsg := &protocol.WMessage{
			MsgType: proto.String("groupMsgResult"),
			//MsgTypeId: proto.Int32(16),
			StataCode: proto.Int32(0),
			SendMsg:   send,
			UserInfo:  msgUser,
		}

		buffer, err := proto.Marshal(returnMsg)
		if err != nil {
			Logger.Warn("protobuf marshal failed: ", err)
			return
		}
		newbuffer := append(common.IntToBytes(len(buffer)), buffer...)
		switch conn.(type) {
		case net.Conn:
			_, err = conn.(net.Conn).Write(newbuffer)
			common.CheckErr(err)
		case websocket.Conn:
			_, err = conn.(*websocket.Conn).Write(newbuffer)
			common.CheckErr(err)
		}
	}
}

作者:happyEg    项目:aTal   
func GetGroupInfoController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("group")
	collectionUser := common.DBMongo.C("user")
	var group models.Group
	var members = make([]*protocol.Friend, 0)
	err := collection.Find(bson.M{"_id": msg.Group.GetId()}).All(&group)
	if err != nil {
		Logger.Error("group info:", err)
		common.CommonResultReturn(conn, "groupInfoResult", msg.GetMsgTypeId(), 1)
		return
	}

	for _, v := range group.Members {
		member := &protocol.Friend{}
		var user models.User
		member.Username = &v.Name
		member.Remark = &v.Remark
		err := collectionUser.Find(bson.M{"user_name": v.Name}).Select(bson.M{"profile_photoid": true}).One(&user)
		if err != nil {
			Logger.Error("group info: ", err)
			common.CommonResultReturn(conn, "groupInfoResult", msg.GetMsgTypeId(), 1)
			return
		}
		//好友头像
		member.ProfilePhotoid = &user.ProfilePhotoid
		members = append(members, member)
	}
	returnMsg := &protocol.WMessage{
		MsgType:   proto.String("groupInfoResult"),
		MsgTypeId: msg.MsgTypeId,
		StataCode: proto.Int32(0),
		Group: &protocol.Groups{
			Id:          proto.String(group.Id.String()),
			GroupName:   proto.String(group.GroupName),
			Owner:       proto.String(group.Owner),
			Description: proto.String(group.Description),
			GroupMember: members,
		},
	}
	buffer, err := proto.Marshal(returnMsg)
	if err != nil {
		Logger.Error("get friendinfo:", err)
		common.CommonResultReturn(conn, "groupInfoResult", msg.GetMsgTypeId(), 1)
		return
	}
	newbuffer := append(common.IntToBytes(len(buffer)), buffer...)
	switch conn.(type) {
	case net.Conn:
		_, err = conn.(net.Conn).Write(newbuffer)
		common.CheckErr(err)
	case websocket.Conn:
		_, err = conn.(*websocket.Conn).Write(newbuffer)
		common.CheckErr(err)
	}
	return
}

作者:happyEg    项目:aTal   
func SendMsgController(conn interface{}, msg *protocol.WMessage) {
	collectionUser := common.DBMongo.C("user")
	collection := common.DBMongo.C("message")

	//好友之间消息的转发

	//判断两者是不是好友
	n, err := collectionUser.Find(bson.M{"user_name": msg.UserInfo.GetUsername(), "friends.name": msg.SendMsg.GetReceiver()}).Count()
	if err != nil {
		common.CommonResultReturn(conn, "sendMsgResult", msg.GetMsgTypeId(), 2)
		Logger.Error("send msg:", err)
		return
	}

	if n != 0 {
		nowTime := time.Now()
		log.Println("time:", nowTime)
		time := nowTime.Unix()
		msg.SendMsg.MsgTime = &time
		buffer, err := proto.Marshal(msg)
		if err != nil {
			common.CommonResultReturn(conn, "sendMsgResult", msg.GetMsgTypeId(), 2)
			Logger.Warn("protobuf marshal failed: ", err)
			return
		}
		newbuffer := append(common.IntToBytes(len(buffer)), buffer...)
		if OnlineCheck(msg.SendMsg.GetReceiver()) {
			switch (UserMap[msg.SendMsg.GetReceiver()]).(type) {
			case net.Conn:
				_, err = (UserMap[msg.SendMsg.GetReceiver()]).(net.Conn).Write(newbuffer)
				common.CheckErr(err)
			case websocket.Conn:
				_, err = (UserMap[msg.SendMsg.GetReceiver()]).(*websocket.Conn).Write(newbuffer)
				common.CheckErr(err)
			}
		}
		common.CommonResultReturn(conn, "sendMsgResult", msg.GetMsgTypeId(), 0)
		var message models.Message
		message.Id = bson.NewObjectId()
		message.Sender = msg.UserInfo.GetUsername()
		message.MsgType = int32(msg.SendMsg.GetType())
		message.Receiver = msg.SendMsg.GetReceiver()
		message.Msg = msg.SendMsg.GetMsg()
		message.MsgTime = nowTime

		err = collection.Insert(&message)
		if err != nil {
			Logger.Error("insert message: ", err)
			log.Println("message: ", err)
		}

	} else {
		common.CommonResultReturn(conn, "sendMsgResult", msg.GetMsgTypeId(), 1)
	}
}

作者:happyEg    项目:aTal   
func sendfile(conn *net.TCPConn) {
	buff := make([]byte, 1024)
	fd, err := os.Open("./123.jpg")
	common.CheckErr(err)
	defer fd.Close()

	fdinfo, err := fd.Stat()
	fmt.Println("这个文件的大小为:", fiinfo.Size(), "字节")
	m := protocol.Mode_FILE
	sendfile := &protocol.WMessage{
		MsgType:   proto.String("sendfile"),
		MsgTypeId: proto.Int32(8),
		SendMsg: &protocol.SendMessage{
			Receiver: proto.String("zhang"),
			MsgType:  &m,
			File:     proto.String("123.jpg"),
			FileSize: proto.Int64(fdinfo.Size()),
		},
	}
	n := protocol.Mode_FILE
	for {
		num, err := fd.Read(buff)
		if err != nil && err != io.EOF {
			panic(err)
		}

		if num == 0 {
			break
		}

		reg := &protocol.WMessage{
			MsgType:   proto.String("sendfile"),
			MsgTypeId: proto.Int32(8),
			UserInfo: &protocol.User{
				Username: proto.String("jim"),
			},
			SendMsg: &protocol.SendMessage{
				Receiver: proto.String("zhang"),
				MsgType:  &n,
				File:     proto.String(buff[:num]),
			},
		}
		buf, err := proto.Marshal(reg)
		if err != nil {
			fmt.Println("failed: %s\n", err)
			return
		}
		fmt.Println("buf: ", len(buf))
		length := len(buf)
		buffer := append(common.IntToBytes(length), buf...)
		conn.Write(buffer)
	}
}

作者:happyEg    项目:aTal   
func GetFriendInfoController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("user")
	var user models.User
	n, err := collection.Find(bson.M{"user_name": ConnMap[conn], "friends.name": msg.UserInfo.GetUsername()}).Count()
	if err != nil {
		Logger.Error("get friendinfo:", err)
		common.CommonResultReturn(conn, "friendInfoResult", msg.GetMsgTypeId(), 2)
		return
	}
	if n == 0 {
		common.CommonResultReturn(conn, "friendInfoResult", msg.GetMsgTypeId(), 1)
		return
	}
	err = collection.Find(bson.M{"user_name": msg.UserInfo.GetUsername()}).One(&user)
	if err != nil {
		Logger.Error("get friendinfo:", err)
		common.CommonResultReturn(conn, "friendInfoResult", msg.GetMsgTypeId(), 2)
		return
	}

	userInfo := &protocol.User{}
	userInfo = common.DataToProto(&user)
	returnMsg := &protocol.WMessage{
		MsgType:   proto.String("friendInfoResult"),
		MsgTypeId: proto.Int32(msg.GetMsgTypeId()),
		StataCode: proto.Int32(0),
		UserInfo:  userInfo,
	}

	buffer, err := proto.Marshal(returnMsg)
	if err != nil {
		Logger.Error("get friendinfo:", err)
		common.CommonResultReturn(conn, "friendInfoResult", msg.GetMsgTypeId(), 2)
		return
	}

	newbuffer := append(common.IntToBytes(len(buffer)), buffer...)
	switch conn.(type) {
	case net.Conn:
		_, err = conn.(net.Conn).Write(newbuffer)
		common.CheckErr(err)
	case websocket.Conn:
		_, err = conn.(*websocket.Conn).Write(newbuffer)
		common.CheckErr(err)
	}

	return
}

作者:happyEg    项目:aTal   
func SearchUserController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("user")
	var user []models.User
	var searchUser = make([]*protocol.Friend, 0)

	friend := msg.Friends[0].GetUsername()

	//模糊查询用户,并返回全部查找到的好友信息
	err := collection.Find(bson.M{"user_name": bson.M{"$regex": friend, "$options": 'i'}}).
		Select(bson.M{"user_name": true, "gender": true, "profile_photoid": true}).Limit(10).All(&user)
	if err != nil {
		Logger.Error("select user info: ", err)
		common.CommonResultReturn(conn, "searchUserResult", msg.GetMsgTypeId(), 1)
		return
	}
	for _, v := range user {
		friend := &protocol.Friend{}
		friend.Username = &v.UserName
		sex := protocol.Gender(v.Gender)
		friend.Sex = &sex
		friend.ProfilePhotoid = &v.ProfilePhotoid
		searchUser = append(searchUser, friend)
	}

	ReturnMsg := &protocol.WMessage{
		MsgType:   proto.String("searchUserResult"),
		MsgTypeId: msg.MsgTypeId,
		StataCode: proto.Int32(0),
		Friends:   searchUser,
	}
	buffer, err := proto.Marshal(ReturnMsg)
	if err != nil {
		common.CommonResultReturn(conn, "searchUserResult", msg.GetMsgTypeId(), 1)
		Logger.Warn("protobuf marshal failed: ", err)
		return
	}
	length := len(buffer)
	newbuffer := append(common.IntToBytes(length), buffer...)
	switch conn.(type) {
	case net.Conn:
		_, err = conn.(net.Conn).Write(newbuffer)
		common.CheckErr(err)
	case websocket.Conn:
		_, err = conn.(*websocket.Conn).Write(newbuffer)
		common.CheckErr(err)
	}
}

作者:happyEg    项目:aTal   
func zhanBaoWrite(conn *net.TCPConn) {

	login := &protocol.WMessage{
		MsgType:   proto.String("login"),
		MsgTypeId: proto.Int32(1),
		UserInfo: &protocol.User{
			Username: proto.String("jim"),
			Password: proto.String("123456"),
		},
	}
	loginbuf, err := proto.Marshal(login)
	if err != nil {
		fmt.Println("failed: %s\n", err)
		return
	}
	loginlength := len(loginbuf)
	loginbuffer := append(common.IntToBytes(loginlength), loginbuf...)
	conn.Write(loginbuffer)
}

作者:happyEg    项目:aTal   
func write(conn *net.TCPConn) {
	reg := &protocol.WMessage{
		MsgType:   proto.String("register"),
		MsgTypeId: proto.Int32(1),
		UserInfo: &protocol.User{
			Username: proto.String("zhang"),
			Password: proto.String("123456"),
		},
	}
	buf, err := proto.Marshal(reg)
	if err != nil {
		fmt.Println("failed: %s\n", err)
		return
	}
	fmt.Println("buf: ", len(buf))
	length := len(buf)
	buffer := append(common.IntToBytes(length), buf...)
	conn.Write(buffer)
	//return buffer
	//conn.Write(common.IntToBytes(length))
}

作者:happyEg    项目:aTal   
func write(conn *net.TCPConn) {
	reg := &protocol.WMessage{
		MsgType:   proto.String("modifyInfo"),
		MsgTypeId: proto.Int32(3),
		UserInfo: &protocol.User{
			Username: proto.String("jim"),
			RealName: proto.String("张三"),
			Age:      proto.Int32(20),
		},
	}
	buf, err := proto.Marshal(reg)
	if err != nil {
		fmt.Println("failed: %s\n", err)
		return
	}
	fmt.Println("buf: ", len(buf))
	length := len(buf)
	buffer := append(common.IntToBytes(length), buf...)
	conn.Write(buffer)
	//return buffer
	//conn.Write(common.IntToBytes(length))
}

作者:happyEg    项目:aTal   
func addFriendWrite(conn *net.TCPConn) {

	n := protocol.Mode(2)
	reg := &protocol.WMessage{
		MsgType:   proto.String("sendFriendRequest"),
		MsgTypeId: proto.Int32(1),
		System:    proto.String("IOS"),
		AddFriend: &protocol.AddFriendRequest{
			Sender:   proto.String("jim"),
			Modes:    &n,
			Receiver: proto.String("jj"),
		},
	}
	buf, err := proto.Marshal(reg)
	if err != nil {
		fmt.Println("failed: %s\n", err)
		return
	}
	fmt.Println("buf: ", len(buf))
	length := len(buf)
	buffer := append(common.IntToBytes(length), buf...)
	conn.Write(buffer)
}

作者:happyEg    项目:aTal   
//获取所有好友
func GetAllFriendController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("user")
	var user models.User
	var friends = make([]*protocol.Friend, 0)

	//获取和用户相关联的所有好友
	err := collection.Find(bson.M{"user_name": msg.UserInfo.GetUsername()}).Select(bson.M{"friends": true, "_id": false}).One(&user)
	if err != nil {
		Logger.Error("select friends: ", err)
		common.CommonResultReturn(conn, "allFriendsResult", msg.GetMsgTypeId(), 2)
		return
	}

	//把好友循环写入好友数组中发送给请求者
	for _, v := range user.Friends {
		friend := &protocol.Friend{}
		var user models.User

		friend.Username = &v.Name
		friend.Remark = &v.Remark
		err := collection.Find(bson.M{"user_name": v.Name}).Select(bson.M{"profile_photoid": true, "_id": false}).One(&user)
		if err != nil {
			Logger.Error("select friend failed: ", err)
			common.CommonResultReturn(conn, "allFriendsResult", msg.GetMsgTypeId(), 3)
			return
		}

		//好友头像
		friend.ProfilePhotoid = &user.ProfilePhotoid

		//判断该好友是否在线
		if OnlineCheck(v.Name) {
			x := int32(1)
			friend.Online = &x
		} else {
			x := int32(0)
			friend.Online = &x
		}

		friends = append(friends, friend)
	}

	ReturnMsg := &protocol.WMessage{
		MsgType:   proto.String("allFriendsResult"),
		MsgTypeId: msg.MsgTypeId,
		StataCode: proto.Int32(0),
		Friends:   friends,
	}
	buffer, err := proto.Marshal(ReturnMsg)
	if err != nil {
		Logger.Warn("protobuf marshal failed: ", err)
		return
	}
	length := len(buffer)
	newbuffer := append(common.IntToBytes(length), buffer...)
	switch conn.(type) {
	case net.Conn:
		_, err = conn.(net.Conn).Write(newbuffer)
		common.CheckErr(err)
	case websocket.Conn:
		_, err = conn.(*websocket.Conn).Write(newbuffer)
		common.CheckErr(err)
	}
}

作者:happyEg    项目:aTal   
func SingleMsgRecordController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("message")
	collectionUser := common.DBMongo.C("user")
	var messages []models.Message
	var user models.User
	var oldTime time.Time

	//返回此用户的登陆时间
	err := collectionUser.Find(bson.M{"user_name": msg.UserInfo.GetUsername()}).Select(bson.M{"login_time": true}).One(&user)
	if err != nil {
		Logger.Error("single msg record:", err)
		common.CommonResultReturn(conn, "msgRecordResult", msg.GetMsgTypeId(), 1)
		return
	}

	now := time.Now().Unix()
	//只返回3天以内的聊天记录
	limitTime := now - TimeLimit*24*3600
	if msg.GetMsgTime() < limitTime {
		oldTime = time.Unix(limitTime, 0)
	} else {
		oldTime = time.Unix(msg.GetMsgTime(), 0)
	}

	//用来接收发发送人给自己的和自己发送给发送人的消息
	var cond = make([]interface{}, 0)
	cond1 := &models.Message{
		Sender:   msg.UserInfo.GetUsername(),
		Receiver: msg.Friends[0].GetUsername(),
	}
	cond = append(cond, cond1)
	cond2 := &models.Message{
		Sender:   msg.Friends[0].GetUsername(),
		Receiver: msg.UserInfo.GetUsername(),
	}
	cond = append(cond, cond2)
	err = collection.Find(bson.M{"$or": cond, "send_time": bson.M{"$gte": oldTime, "lte": user.LoginTime}}).
		Sort("-send_time").Limit(OnceRequent).Skip(int(MsgCount[msg.UserInfo.GetUsername()])).All(&messages)
	if err != nil {
		Logger.Error("msgRecord failed:", err)
		common.CommonResultReturn(conn, "msgRecordResult", msg.GetMsgTypeId(), 1)
		return
	}

	//记录每次需要偏移的值
	MsgCount[msg.UserInfo.GetUsername()] = MsgCount[msg.UserInfo.GetUsername()] + OnceRequent

	//循环把数据发送出去
	for _, v := range messages {
		msgUser := &protocol.User{}
		send := &protocol.SendMessage{}
		msgUser.Username = &v.Sender
		send.Receiver = &v.Receiver
		msgType := protocol.Mode(v.MsgType)
		send.Type = &msgType
		send.Msg = &v.Msg
		sendtime := v.MsgTime.Unix()
		send.MsgTime = &sendtime
		returnMsg := &protocol.WMessage{
			MsgType:   proto.String("msgRecordResult"),
			MsgTypeId: msg.MsgTypeId,
			StataCode: proto.Int32(0),
			SendMsg:   send,
			UserInfo:  msgUser,
		}

		buffer, err := proto.Marshal(returnMsg)
		if err != nil {
			common.CommonResultReturn(conn, "msgRecordResult", msg.GetMsgTypeId(), 1)
			Logger.Warn("protobuf marshal failed: ", err)
			continue
		}
		//fmt.Println("msgRecord: ", returnMsg.String())
		newbuffer := append(common.IntToBytes(len(buffer)), buffer...)
		switch conn.(type) {
		case net.Conn:
			_, err = conn.(net.Conn).Write(newbuffer)
			common.CheckErr(err)
		case websocket.Conn:
			_, err = conn.(*websocket.Conn).Write(newbuffer)
			common.CheckErr(err)
		}
	}
}

作者:happyEg    项目:aTal   
func GroupMsgController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("message")
	collectionGroup := common.DBMongo.C("group")
	var groupMsg models.Message
	var group models.Group
	nowTime := time.Now()

	//判断此成员是否在此群组中
	n, err := collectionGroup.Find(bson.M{"_id": msg.Group.GetId(), "members.name": msg.UserInfo.GetUsername()}).Count()
	if err != nil {
		common.CommonResultReturn(conn, "groupMsgResult", msg.GetMsgTypeId(), 2)
		Logger.Error("count :", err)
		return
	}
	if n == 0 {
		//此用户不在此群组中
		common.CommonResultReturn(conn, "groupMsgResult", msg.GetMsgTypeId(), 1)
		return
	}

	//保存聊天记录到数据库
	groupMsg.Id = bson.NewObjectId()
	groupMsg.Sender = msg.UserInfo.GetUsername()
	groupMsg.GroupId = msg.Group.GetId()
	groupMsg.MsgType = int32(msg.SendMsg.GetType())
	groupMsg.Msg = msg.SendMsg.GetMsg()
	groupMsg.MsgTime = nowTime

	err = collection.Insert(&groupMsg)
	if err != nil {
		Logger.Error("insert group msg:", err)
	}

	//转发群组信息给群内所有人
	//获取群组员
	err = collectionGroup.Find(bson.M{"_id": msg.Group.GetId()}).Select(bson.M{"members": true}).All(&group)
	if err != nil {
		Logger.Error("select group member: ", err)
		common.CommonResultReturn(conn, "groupMsgResult", msg.GetMsgTypeId(), 3)
		return
	}
	common.CommonResultReturn(conn, "groupMsgResult", msg.GetMsgTypeId(), 0)
	//发送人
	user := &protocol.User{}
	user.Username = &groupMsg.Sender

	for _, v := range group.Members {
		//把发送消息的用户排除
		if v.Name == msg.UserInfo.GetUsername() {
			continue
		}
		//把群聊信息保存到数据库
		var message models.Message
		message.Id = bson.NewObjectId()
		message.GroupId = msg.Group.GetId()
		message.Receiver = v.Name
		message.MsgType = int32(msg.SendMsg.GetType())
		message.MsgTime = nowTime
		if collection.Insert(&message) != nil {
			Logger.Error("insert group message:", err)
		}

		//如果此成员在线,给其发送消息
		if OnlineCheck(v.Name) {
			sendMsg := &protocol.SendMessage{}

			sendMsg.Receiver = &v.Name
			sendMsg.Type = msg.SendMsg.Type
			sendMsg.Msg = &groupMsg.Msg
			msgTime := nowTime.Unix()
			sendMsg.MsgTime = &msgTime

			returnMsg := &protocol.WMessage{
				MsgType: proto.String("groupMsgResult"),
				//MsgTypeId: proto.Int32(16),
				StataCode: proto.Int32(0),
				SendMsg:   sendMsg,
				Group: &protocol.Groups{
					Id: proto.String(msg.Group.GetId()),
				},
				UserInfo: user,
			}

			buffer, err := proto.Marshal(returnMsg)
			if err != nil {
				Logger.Warn("protobuf marshal failed: ", err)
				continue
			}
			newbuffer := append(common.IntToBytes(len(buffer)), buffer...)
			switch UserMap[v.Name].(type) {
			case net.Conn:
				_, err = (UserMap[v.Name]).(net.Conn).Write(newbuffer)
				common.CheckErr(err)
			case websocket.Conn:
				_, err = (UserMap[v.Name]).(*websocket.Conn).Write(newbuffer)
				common.CheckErr(err)
			}
		}
	}
}

作者:happyEg    项目:aTal   
func GroupModifyController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("group")
	var group models.Group
	var members = make([]*protocol.Friend, 0)
	arr := make(map[string]interface{})

	//判断其是否是群主
	n, err := collection.Find(bson.M{"_id": msg.Group.GetId(), "owner": msg.UserInfo.GetUsername()}).Count()
	if err != nil {
		common.CommonResultReturn(conn, "groupModifyResult", msg.GetMsgTypeId(), 1)
		Logger.Error("select group owner: ", err)
		return
	}

	if n != 0 {
		if msg.Group.GroupName != nil {
			arr["group_name"] = msg.Group.GetGroupName()
		}

		if msg.Group.Description != nil {
			arr["description"] = msg.Group.GetDescription()
		}

		err = collection.Update(bson.M{"_id": msg.Group.GetId()}, bson.M{"$set": arr})
		err = collection.Find(bson.M{"_id": msg.Group.GetId()}).One(&group)
		if err != nil {
			common.CommonResultReturn(conn, "groupModifyResult", msg.GetMsgTypeId(), 2)
			Logger.Error("group info:", err)
			return
		}

		//把群信息及成员信息更新发送给用户
		for _, v := range group.Members {
			member := &protocol.Friend{}
			var user models.User
			member.Username = &v.Name
			member.Remark = &v.Remark

			//获取成员头像
			err := collection.Find(bson.M{"user_name": v.Name}).Select(bson.M{"profile_photoid": true, "_id": false}).One(&user)
			if err != nil {
				common.CommonResultReturn(conn, "groupModifyResult", msg.GetMsgTypeId(), 2)
				Logger.Error("select friend failed: ", err)
				return
			}
			member.ProfilePhotoid = &user.ProfilePhotoid

			members = append(members, member)
		}

		proGroup := &protocol.Groups{}
		num := group.Id.String()
		proGroup.Id = &num
		proGroup.GroupName = &group.GroupName
		proGroup.Owner = &group.Owner
		proGroup.GroupMember = members
		proGroup.Description = &group.Description

		returnMsg := &protocol.WMessage{
			MsgType:   proto.String("groupModifyResult"),
			MsgTypeId: msg.MsgTypeId,
			StataCode: proto.Int32(0),
			Group:     proGroup,
		}

		buffer, err := proto.Marshal(returnMsg)
		if err != nil {
			common.CommonResultReturn(conn, "groupModifyResult", msg.GetMsgTypeId(), 2)
			Logger.Warn("protobuf marshal failed: ", err)
			return
		}
		length := len(buffer)
		newbuffer := append(common.IntToBytes(length), buffer...)
		switch conn.(type) {
		case net.Conn:
			_, err = conn.(net.Conn).Write(newbuffer)
			common.CheckErr(err)
		case websocket.Conn:
			_, err = conn.(*websocket.Conn).Write(newbuffer)
			common.CheckErr(err)
		}

	} else {
		common.CommonResultReturn(conn, "groupModifyResult", msg.GetMsgTypeId(), 1)
	}
}

作者:happyEg    项目:aTal   
func GroupRemarkController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("group")
	var group models.Group

	remark := msg.Friends[0].GetRemark()
	//判断此成员在不在此群中
	n, err := collection.Find(bson.M{"_id": msg.Group.GetId(), "members.name": msg.UserInfo.GetUsername()}).Count()
	if err != nil || n == 0 {
		Logger.Error("group remark:", err)
		common.CommonResultReturn(conn, "groupRemarkResult", msg.GetMsgTypeId(), 1)
		return
	}

	//更新备注
	err = collection.Update(bson.M{"_id": msg.Group.GetId(), "members.name": msg.UserInfo.GetUsername()}, bson.M{"$set": bson.M{"members.remark": remark}})
	err = collection.Find(bson.M{"_id": msg.Group.GetId(), "members.name": msg.UserInfo.GetUsername()}).One(&group)
	if err != nil {
		Logger.Error("group remark:", err)
		common.CommonResultReturn(conn, "groupRemarkResult", msg.GetMsgTypeId(), 2)
		return
	}

	var friends = make([]*protocol.Friend, 0)
	for _, v := range group.Members {
		friend := &protocol.Friend{}
		friend.Username = &v.Name
		friend.Remark = &v.Remark
		friends = append(friends, friend)
	}

	returnMsg := &protocol.WMessage{
		MsgType:   proto.String("groupRemarkResult"),
		MsgTypeId: msg.MsgTypeId,
		StataCode: proto.Int32(0),
		Group: &protocol.Groups{
			Id:          proto.String(group.Id.String()),
			GroupName:   proto.String(group.GroupName),
			Description: proto.String(group.Description),
			Owner:       proto.String(group.Owner),
			GroupMember: friends,
		},
	}

	buffer, err := proto.Marshal(returnMsg)
	if err != nil {
		common.CommonResultReturn(conn, "groupRemarkResult", msg.GetMsgTypeId(), 3)
		Logger.Warn("protobuf marshal failed: ", err)
		return
	}
	length := len(buffer)
	newbuffer := append(common.IntToBytes(length), buffer...)
	switch conn.(type) {
	case net.Conn:
		_, err = conn.(net.Conn).Write(newbuffer)
		common.CheckErr(err)
	case websocket.Conn:
		_, err = conn.(*websocket.Conn).Write(newbuffer)
		common.CheckErr(err)
	}
	return
}

作者:happyEg    项目:aTal   
//添加好友应答
func SendFirendResponseController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("user")
	var user models.User

	//判断需要同意的好友是否存在
	exist, err := collection.Find(bson.M{"user_name": msg.AddFriend.GetReceiver()}).Count()
	if err != nil {
		common.CommonResultReturn(conn, "sendFriendResponse", msg.GetMsgTypeId(), 1)
		Logger.Error("get friend relation:", err)
		return
	}
	if exist != 0 {

		//验证是否已经是其好友
		num, err := collection.Find(bson.M{"user_name": msg.AddFriend.GetSender(), "friends.name": msg.AddFriend.GetReceiver(), "friends.mode": 3}).Count()
		if err != nil {
			Logger.Error("get friend relation:", err)
			return
		}

		//其已经是好友关系
		if num != 0 {
			common.CommonResultReturn(conn, "sendFriendResponse", msg.GetMsgTypeId(), 2)
			return
		}

		//如果同意添加好友,就写入到数据库
		n := int32(msg.AddFriend.GetModes())
		if n == 3 {
			friend := &models.Friend{
				Name: msg.AddFriend.GetReceiver(),
				Mode: 3,
			}
			friend1 := &models.Friend{
				Name: msg.AddFriend.GetSender(),
				Mode: 3,
			}
			err := collection.Update(bson.M{"user_name": msg.AddFriend.GetSender()}, bson.M{"$push": bson.M{"friends": friend}})
			err = collection.Update(bson.M{"user_name": msg.AddFriend.GetReceiver()}, bson.M{"$push": bson.M{"friends": friend1}})
			if err != nil {
				Logger.Error("insert friend relation failed: ", err)
				common.CommonResultReturn(conn, "sendFriendResponse", msg.GetMsgTypeId(), 3)
				return
			}

			//添加好友成功,把好友的信息返回
			err = collection.Find(bson.M{"user_name": msg.AddFriend.GetReceiver()}).One(&user)
			if err != nil {
				Logger.Error("select user info: ", err)
				log.Println("好友内容查找错误")
				return
			}
			msg.UserInfo = common.DataToProto(&user)
			n := int32(0)
			msg.StataCode = &n
			buffer, err := proto.Marshal(msg)
			if err != nil {
				common.CommonResultReturn(conn, "sendFriendResponse", msg.GetMsgTypeId(), 3)
				Logger.Warn("protobuf marshal failed: ", err)
				fmt.Println("failed: %s\n", err)
				return
			}
			length := len(buffer)
			newbuffer := append(common.IntToBytes(length), buffer...)
			switch conn.(type) {
			case net.Conn:
				_, err = conn.(net.Conn).Write(newbuffer)
				common.CheckErr(err)
			case websocket.Conn:
				_, err = conn.(*websocket.Conn).Write(newbuffer)
				common.CheckErr(err)
			}
		}

		//给好友发送通知,来自添加好友的应答
		if OnlineCheck(msg.AddFriend.GetReceiver()) {
			buffer, err := proto.Marshal(msg)
			if err != nil {
				fmt.Println("failed: %s\n", err)
				return
			}
			length := len(buffer)
			newbuffer := append(common.IntToBytes(length), buffer...)
			switch (UserMap[msg.AddFriend.GetReceiver()]).(type) {
			case net.Conn:
				_, err = (UserMap[msg.AddFriend.GetReceiver()]).(net.Conn).Write(newbuffer)
				common.CheckErr(err)
			case websocket.Conn:
				_, err = (UserMap[msg.AddFriend.GetReceiver()]).(*websocket.Conn).Write(newbuffer)
				common.CheckErr(err)
			}
		}
	} else {
		common.CommonResultReturn(conn, "sendFriendResponse", msg.GetMsgTypeId(), 1)
	}
}

作者:happyEg    项目:aTal   
//创建群组
func GroupCreateController(conn interface{}, msg *protocol.WMessage) {
	collection := common.DBMongo.C("group")
	collectionUser := common.DBMongo.C("user")
	var group models.Group
	var members = make([]*protocol.Friend, 0)

	group.Id = bson.NewObjectId()
	group.Owner = msg.UserInfo.GetUsername()
	group.GroupName = msg.Group.GetGroupName()
	group.Description = msg.Group.GetDescription()
	for k, v := range msg.Group.GetGroupMember() {
		group.Members[k].Name = v.GetUsername()
	}
	//把新创建的组加入到数据库
	err := collection.Insert(&group)
	if err != nil {
		Logger.Error("group create:", err)
		common.CommonResultReturn(conn, "groupCreateResult", msg.GetMsgTypeId(), 1)
		return
	}

	for _, v := range group.Members {
		member := &protocol.Friend{}
		var user models.User
		member.Username = &v.Name
		member.Remark = &v.Remark
		err := collectionUser.Find(bson.M{"user_name": v.Name}).Select(bson.M{"profile_photoid": true}).One(&user)
		if err != nil {
			Logger.Error("group create:", err)
			common.CommonResultReturn(conn, "groupCreateResult", msg.GetMsgTypeId(), 1)
			return
		}

		//好友头像
		member.ProfilePhotoid = &user.ProfilePhotoid
		members = append(members, member)
	}
	//把群信息返回给创建者
	returnMsg := &protocol.WMessage{
		MsgType:   proto.String("groupCreateResult"),
		MsgTypeId: msg.MsgTypeId,
		StataCode: proto.Int32(0),
		Group: &protocol.Groups{
			Id:          proto.String(group.Id.String()),
			GroupName:   proto.String(group.GroupName),
			Description: proto.String(group.Description),
			Owner:       proto.String(group.Owner),
			GroupMember: members,
		},
	}

	buffer, err := proto.Marshal(returnMsg)
	if err != nil {
		Logger.Warn("protobuf marshal failed: ", err)
		common.CommonResultReturn(conn, "groupCreateResult", msg.GetMsgTypeId(), 1)
		fmt.Println("failed: ", err)
		return
	}
	length := len(buffer)
	newbuffer := append(common.IntToBytes(length), buffer...)
	switch conn.(type) {
	case net.Conn:
		_, err = conn.(net.Conn).Write(newbuffer)
		common.CheckErr(err)
	case websocket.Conn:
		_, err = conn.(*websocket.Conn).Write(newbuffer)
		common.CheckErr(err)
	}

	return

}

作者:happyEg    项目:aTal   
func SendFile(conn interface{}, msg *protocol.WMessage) {

	//判断接收方是否在线
	if !OnlineCheck(msg.SendMsg.GetReceiver()) {
		common.CommonResultReturn(conn, "fileResult", msg.GetMsgTypeId(), 1)
		return
	}

	FileMark = msg.GetMsgTypeId()
	//是否同意接收文件
	now := time.Now().Unix()
	msg.SendMsg.MsgTime = &now
	if FileSytle == 0 && int32(msg.SendMsg.GetType()) == 2 {
		fileType := "fileResult"
		msg.MsgType = &fileType
		buffer, err := proto.Marshal(msg)
		if err != nil {
			common.CommonResultReturn(conn, "fileResult", FileMark, 2)
			Logger.Error("sendfile:", err)
			return
		}
		newbuffer := append(common.IntToBytes(len(buffer)), buffer...)
		switch (UserMap[msg.SendMsg.GetReceiver()]).(type) {
		case net.Conn:
			_, err = (UserMap[msg.SendMsg.GetReceiver()]).(net.Conn).Write(newbuffer)
			common.CheckErr(err)
		case websocket.Conn:
			_, err = (UserMap[msg.SendMsg.GetReceiver()]).(*websocket.Conn).Write(newbuffer)
			common.CheckErr(err)
		}
		return
	}

	// if FileSytle == 2 {
	// 	//接收文件名
	// 	fd, err := os.OpenFile("./uploads/"+msg.UserInfo.GetUsername()+"/"+msg.SendMsg.GetMsg(), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	// 	if err != nil {
	// 		common.CommonResultReturn(conn, "fileResult", msg.GetMsgTypeId(), 2)
	// 		Logger.Error("send file", err.Error())
	// 		return
	// 	}
	// 	defer fd.Close()

	// 	//写文件
	// 	_, err = fd.Write(msg.SendMsg.GetFile())
	//给接收方发送文件内容
	buffer, err := proto.Marshal(msg)
	if err != nil {
		common.CommonResultReturn(conn, "fileResult", msg.GetMsgTypeId(), 3)
		Logger.Warn("protobuf marshal failed: ", err)
		return
	}
	newbuffer := append(common.IntToBytes(len(buffer)), buffer...)
	switch (UserMap[msg.SendMsg.GetReceiver()]).(type) {
	case net.Conn:
		_, err = (UserMap[msg.SendMsg.GetReceiver()]).(net.Conn).Write(newbuffer)
		common.CheckErr(err)
	case websocket.Conn:
		_, err = (UserMap[msg.SendMsg.GetReceiver()]).(*websocket.Conn).Write(newbuffer)
		common.CheckErr(err)
	}
}


问题


面经


文章

微信
公众号

扫码关注公众号