Skip to content

Commit

Permalink
Changes made in part14
Browse files Browse the repository at this point in the history
  • Loading branch information
YuriyNasretdinov committed Jul 27, 2016
1 parent d15a679 commit bdada29
Show file tree
Hide file tree
Showing 9 changed files with 172 additions and 60 deletions.
37 changes: 35 additions & 2 deletions db/db.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,9 @@ var (
AddToTimelineStmt *sql.Stmt

// Users
GetUsersListStmt *sql.Stmt
GetFriendsList *sql.Stmt
GetUsersListStmt *sql.Stmt
GetFriendsList *sql.Stmt
GetFriendsRequestList *sql.Stmt

// Friends
AddFriendsRequestStmt *sql.Stmt
Expand Down Expand Up @@ -66,6 +67,7 @@ func InitStmts() {
LoginStmt = prepareStmt(Db, "SELECT id, password, name FROM socialuser WHERE email = $1")
RegisterStmt = prepareStmt(Db, "INSERT INTO socialuser(email, password, name) VALUES($1, $2, $3) RETURNING id")
GetFriendsList = prepareStmt(Db, `SELECT friend_user_id FROM friend WHERE user_id = $1 AND request_accepted = true`)
GetFriendsRequestList = prepareStmt(Db, `SELECT friend_user_id FROM friend WHERE user_id = $1 AND request_accepted = false`)

GetMessagesStmt = prepareStmt(Db, `SELECT id, message, ts, is_out
FROM messages
Expand Down Expand Up @@ -174,3 +176,34 @@ func GetCityInfoByName(name string) (*City, error) {
}
return res, nil
}

func GetUserFriends(userId uint64) (userIds []uint64, err error) {
return getUsersByStmt(userId, GetFriendsList)
}

func GetUserFriendsRequests(userId uint64) (userIds []uint64, err error) {
return getUsersByStmt(userId, GetFriendsRequestList)
}

func getUsersByStmt(userId uint64, stmt *sql.Stmt) (userIds []uint64, err error) {
res, err := stmt.Query(userId)
if err != nil {
return
}

defer res.Close()

userIds = make([]uint64, 0)

for res.Next() {
var uid uint64
if err = res.Scan(&uid); err != nil {
log.Println(err.Error())
return
}

userIds = append(userIds, uid)
}

return
}
63 changes: 32 additions & 31 deletions handlers/handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -135,13 +135,19 @@ func (ctx *WebsocketCtx) ProcessGetFriends(req *protocol.RequestGetFriends) prot
return &protocol.ResponseError{UserMsg: "Limit must be greater than 0"}
}

friendUserIds, err := getUserFriends(ctx.UserId)
friendUserIds, err := db.GetUserFriends(ctx.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get friends", Err: err}
}

friendRequestUserIds, err := db.GetUserFriendsRequests(ctx.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get friends", Err: err}
}

reply := new(protocol.ReplyGetFriends)
reply.Users = make([]protocol.JSUserInfo, 0)
reply.FriendRequests = make([]protocol.JSUserInfo, 0)

friendUserIdsStr := make([]string, 0)

Expand All @@ -151,6 +157,12 @@ func (ctx *WebsocketCtx) ProcessGetFriends(req *protocol.RequestGetFriends) prot
friendUserIdsStr = append(friendUserIdsStr, userIdStr)
}

for _, userId := range friendRequestUserIds {
userIdStr := fmt.Sprint(userId)
reply.FriendRequests = append(reply.FriendRequests, protocol.JSUserInfo{Id: userIdStr})
friendUserIdsStr = append(friendUserIdsStr, userIdStr)
}

userNames, err := db.GetUserNames(friendUserIdsStr)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get friends", Err: err}
Expand All @@ -160,6 +172,10 @@ func (ctx *WebsocketCtx) ProcessGetFriends(req *protocol.RequestGetFriends) prot
reply.Users[i].Name = userNames[user.Id]
}

for i, user := range reply.FriendRequests {
reply.FriendRequests[i].Name = userNames[user.Id]
}

return reply
}

Expand Down Expand Up @@ -250,29 +266,6 @@ func (ctx *WebsocketCtx) ProcessSendMessage(req *protocol.RequestSendMessage) pr
return reply
}

func getUserFriends(userId uint64) (userIds []uint64, err error) {
res, err := db.GetFriendsList.Query(userId)
if err != nil {
return
}

defer res.Close()

userIds = make([]uint64, 0)

for res.Next() {
var uid uint64
if err = res.Scan(&uid); err != nil {
log.Println(err.Error())
return
}

userIds = append(userIds, uid)
}

return
}

func (ctx *WebsocketCtx) ProcessAddToTimeline(req *protocol.RequestAddToTimeline) protocol.Reply {
var (
err error
Expand All @@ -283,7 +276,7 @@ func (ctx *WebsocketCtx) ProcessAddToTimeline(req *protocol.RequestAddToTimeline
return &protocol.ResponseError{UserMsg: "Text must not be empty"}
}

userIds, err := getUserFriends(ctx.UserId)
userIds, err := db.GetUserFriends(ctx.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get user ids", Err: err}
}
Expand Down Expand Up @@ -394,7 +387,7 @@ func (ctx *WebsocketCtx) ProcessGetMessagesUsers(req *protocol.RequestGetMessage
userIds = append(userIds, userId)
}

friendIds, err := getUserFriends(ctx.UserId)
friendIds, err := db.GetUserFriends(ctx.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get users list for messages", Err: err}
}
Expand Down Expand Up @@ -424,6 +417,18 @@ func (ctx *WebsocketCtx) ProcessGetMessagesUsers(req *protocol.RequestGetMessage
func (ctx *WebsocketCtx) ProcessGetProfile(req *protocol.RequestGetProfile) protocol.Reply {
reply := new(protocol.ReplyGetProfile)

userIdStr := fmt.Sprint(req.UserId)
userNames, err := db.GetUserNames([]string{userIdStr})
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get user profile", Err: err}
}

if len(userNames) == 0 {
return &protocol.ResponseError{UserMsg: "No such user", Err: err}
}

reply.Name = userNames[userIdStr]

row, err := db.GetProfileStmt.Query(req.UserId)
if err != nil {
return &protocol.ResponseError{UserMsg: "Could not get user profile", Err: err}
Expand All @@ -432,11 +437,7 @@ func (ctx *WebsocketCtx) ProcessGetProfile(req *protocol.RequestGetProfile) prot

var birthdate time.Time
if !row.Next() {
if req.Required {
return &protocol.ResponseError{UserMsg: "No such user", Err: err}
} else {
return reply
}
return reply
}

err = row.Scan(&reply.Name, &birthdate, &reply.Sex, &reply.Description, &reply.CityId, &reply.FamilyPosition)
Expand Down
18 changes: 17 additions & 1 deletion main.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,23 @@ func passwordHash(password string) string {
return fmt.Sprintf("%x:%x", sh.Sum(nil), md.Sum(nil))
}

func serveAuthPage(info *session.SessionInfo, w http.ResponseWriter) {
func serveAuthPage(sessionInfo *session.SessionInfo, w http.ResponseWriter) {
info := new(struct {
session.SessionInfo
FriendsRequestsCount int
})

info.Id = sessionInfo.Id
info.Name = sessionInfo.Name
info.FriendsRequestsCount = 0

friendsReqs, err := db.GetUserFriendsRequests(sessionInfo.Id)
if err != nil {
log.Println("Could not get friends requests: ", err.Error())
} else {
info.FriendsRequestsCount = len(friendsReqs)
}

if err := authTpl.Execute(w, info); err != nil {
fmt.Println("Could not render template: " + err.Error())
}
Expand Down
6 changes: 3 additions & 3 deletions protocol/protocol.go
Original file line number Diff line number Diff line change
Expand Up @@ -128,8 +128,7 @@ type (
}

RequestGetProfile struct {
UserId uint64 `json:",string"`
Required bool
UserId uint64 `json:",string"`
}

RequestUpdateProfile struct {
Expand All @@ -155,7 +154,8 @@ type (

ReplyGetFriends struct {
BaseReply
Users []JSUserInfo
Users []JSUserInfo
FriendRequests []JSUserInfo
}

ReplyGetMessagesUsers struct {
Expand Down
3 changes: 2 additions & 1 deletion static/auth.html
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
<li><a href="/timeline/" id="timeline_link">Timeline</a></li>
<li><a href="/profile/" id="profile_link">Profile</a></li>
<li><a href="/messages/" id="messages_link">Messages</a></li>
<li><a href="/friends/" id="friends_link">Friends</a></li>
<li><a href="/friends/" id="friends_link">Friends<span id="friends_badge" style="display: none;"></span></a></li>
<li><a href="/users_list/" id="users_list_link">Users</a></li>
</ul>
<div class="login_info"><span id="status"></span> Logged in as <b>{{.Name}}</b> [<a href="/logout">logout</a>]</div>
Expand Down Expand Up @@ -66,6 +66,7 @@
<script type="text/javascript" src="/static/js/profile.js"></script>
<script>
var ourUserId = "{{.Id}}";
var friendsRequestsCount = parseInt("{{.FriendsRequestsCount}}");
setWebsocketConnection();
setUpPage();
</script>
Expand Down
13 changes: 13 additions & 0 deletions static/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -274,3 +274,16 @@ body{
left: 0;
z-index: 1001;
}

.add_friends_link {
color: green;
padding-right: 5px;
}

#friends_badge {
background: green;
color: white;
padding: 2px;
margin-left: 3px;
border-radius: 3px;
}
89 changes: 68 additions & 21 deletions static/js/friends.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,31 @@ function requestAddFriendCallback(ev) {
var friend_id = el.id.replace('add_friend_link_', '')

sendReq("REQUEST_ADD_FRIEND", {FriendId: friend_id}, function (reply) {
el.parentNode.innerHTML = 'request to ' + el.innerHTML + ' has been sent'
el.parentNode.innerHTML = 'request to ' + el.dataName + ' has been sent'
})

return false
}

function redrawFriendsRequestCount() {
var el = document.getElementById('friends_badge')
if (friendsRequestsCount > 0) {
el.innerHTML = friendsRequestsCount
el.style.display = ''
} else {
el.style.display = 'none'
}
}

function confirmFriendshipCallback(ev) {
var el = ev.target
var friend_id = el.id.replace('confirm_friend_link_', '')

sendReq("REQUEST_CONFIRM_FRIENDSHIP", {FriendId: friend_id}, function (reply) {
el.parentNode.innerHTML = 'friendship confirmed'

friendsRequestsCount--
redrawFriendsRequestCount()
})

return false
Expand All @@ -37,12 +50,49 @@ function confirmFriendshipCallback(ev) {
function loadFriends() {
sendReq("REQUEST_GET_FRIENDS", {Limit: 50}, function (reply) {
var el = document.getElementById('friends')
el.innerHTML = '<b>Friends:</b><hr/>'
var friends, i, r, div, a

el.innerHTML = ''

friendsRequestsCount = reply.FriendRequests.length
redrawFriendsRequestCount()

if (friendsRequestsCount > 0) {
var b = document.createElement('b')
b.appendChild(document.createTextNode('Friends requests:'))
el.appendChild(b)
el.appendChild(document.createElement('hr'))

friends = reply.FriendRequests
for (i = 0; i < friends.length; i++) {
r = friends[i]
div = document.createElement('div')
div.appendChild(document.createTextNode(r.Name + ' '))

a = document.createElement('a')
a.title = 'Confirm add to friends'
a.href = '#confirm_friend_' + r.Id
a.id = 'confirm_friend_link_' + r.Id
a.appendChild(document.createTextNode('(confirm friendship)'))

addEv(a, 'click', confirmFriendshipCallback)

div.appendChild(a)
el.appendChild(div)
}

var friends = reply.Users
for (var i = 0; i < friends.length; i++) {
var r = friends[i]
var div = document.createElement('div')
el.appendChild(document.createElement('br'))
}

b = document.createElement('b')
b.appendChild(document.createTextNode('Friends:'))
el.appendChild(b)
el.appendChild(document.createElement('hr'))

friends = reply.Users
for (i = 0; i < friends.length; i++) {
r = friends[i]
div = document.createElement('div')
div.appendChild(document.createTextNode(r.Name))
el.appendChild(div)
}
Expand All @@ -52,7 +102,7 @@ function loadFriends() {
function loadUsersList() {
sendReq("REQUEST_GET_USERS_LIST", {Limit: 50}, function (reply) {
var el = document.getElementById('users_list')
el.innerHTML = '<b>Add to friends:</b><hr/>'
el.innerHTML = '<b>Users:</b><hr/>'

var users = reply.Users
for (var i = 0; i < users.length; i++) {
Expand All @@ -62,30 +112,27 @@ function loadUsersList() {

ulItem.className = 'users_list_item'

aItem = document.createElement('a')
aItem.href = '/profile/' + r.Id
addEv(aItem, 'click', function(ev) { changeLocation('Profile', ev.target.href); return false })
aItem.appendChild(document.createTextNode(r.Name + ' '))
ulItem.appendChild(aItem)

if (!r.IsFriend) {
aItem = document.createElement('a')
aItem.title = 'Add to friends'
aItem.className = 'add_friends_link'
aItem.href = '#add_friend_' + r.Id
aItem.id = 'add_friend_link_' + r.Id
aItem.appendChild(document.createTextNode(r.Name))

aItem.dataName = r.Name
aItem.appendChild(document.createTextNode('+'))
addEv(aItem, 'click', requestAddFriendCallback)

ulItem.appendChild(aItem)
} else if (r.FriendshipConfirmed) {
ulItem.appendChild(document.createTextNode(r.Name + ' (friend)'))
ulItem.appendChild(document.createTextNode('(friend)'))
} else {
ulItem.appendChild(document.createTextNode(r.Name + ' '))

aItem = document.createElement('a')
aItem.title = 'Confirm add to friends'
aItem.href = '#confirm_friend_' + r.Id
aItem.id = 'confirm_friend_link_' + r.Id
aItem.appendChild(document.createTextNode('(confirm friendship)'))

addEv(aItem, 'click', confirmFriendshipCallback)

ulItem.appendChild(aItem)
ulItem.appendChild(document.createTextNode('(wants to become friend)'))
}

el.appendChild(ulItem)
Expand Down
Loading

0 comments on commit bdada29

Please sign in to comment.