Skip to content

Commit

Permalink
fixed friendship ui user profile
Browse files Browse the repository at this point in the history
  • Loading branch information
singharaj-usai committed Oct 23, 2024
1 parent 1d15ebb commit abba4d2
Show file tree
Hide file tree
Showing 5 changed files with 166 additions and 74 deletions.
6 changes: 1 addition & 5 deletions client/html/pages/home/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -120,11 +120,7 @@
<h3 class="panel-title" id="profile-username"></h3>
</div>
<div class="panel-body text-center">
<img
src="https://kids.kiddle.co/images/6/6e/Roblox_Default_Male_Avatar.png"
alt="Profile Image"
class="profile-image"
/>
<div id="avatar-container" class="mb-3"></div>
</div>
</div>
</div>
Expand Down
92 changes: 72 additions & 20 deletions client/js/home.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ $(document).ready(function () {
},
success: function (response) {
$('#profile-username').text(`Welcome, ${username}`);
loadUserAvatar();
fetchUserBlurb();
fetchFriendsList();
fetchAndDisplayGames();
Expand Down Expand Up @@ -44,6 +45,70 @@ $(document).ready(function () {
});
}

function loadUserAvatar() {
const token = localStorage.getItem('token');
const userId = localStorage.getItem('userId');

if (!token || !userId) {
console.error('Missing token or userId');
return;
}

$.ajax({
url: '/api/avatar',
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
'Cache-Control': 'no-cache'
},
success: function(response) {
console.log('Avatar data received:', response);
if (response && response.avatarRender && response.avatarRender.shirt) {
const avatarHtml = `
<img src="${response.avatarRender.shirt}"
alt="User Avatar"
class="img-responsive center-block"
style="max-width: 197px; height: auto;"
onerror="this.onerror=null; console.error('Failed to load avatar image:', this.src);">
`;
$('#avatar-container').html(avatarHtml);
} else {
$('#avatar-container').html(`
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">My Avatar</h3>
</div>
<div class="panel-body text-center">
<p>No avatar configured yet.</p>
<a href="/avatar" class="btn btn-primary">Create Avatar</a>
</div>
</div>
`);
}
},
error: function(xhr, status, error) {
console.error('Error loading avatar:', {
error: error,
status: status,
response: xhr.responseText,
userId: userId
});
$('#avatar-container').html(`
<div class="panel panel-danger">
<div class="panel-heading">
<h3 class="panel-title">Error Loading Avatar</h3>
</div>
<div class="panel-body text-center">
<p>Unable to load avatar. Please try again later.</p>
<a href="/avatar" class="btn btn-primary">Go to Avatar Page</a>
</div>
</div>
`);
}
});
}

function displayBlurb(blurb) {
const blurbHtml = `
<p id="blurb-text">${blurb ? escapeHtml(blurb) : 'No blurb set.'}</p>
Expand Down Expand Up @@ -148,35 +213,22 @@ $(document).ready(function () {
</div>
<div class="panel-body">
<div class="row">
${games
.slice(0, 4)
.map(
(game) => `
${games.slice(0, 4).map((game) => `
<div class="col-md-3 col-sm-6 mb-4">
<div class="thumbnail" style="position: relative;">
${
game.year
? `<span class="badge" style="position: absolute; top: 10px; left: 10px; z-index: 1; background-color: #337ab7;">${game.year}</span>`
: '<span class="badge" style="position: absolute; top: 10px; left: 10px; z-index: 1; background-color: #d9534f;">No Year</span>'
}
${game.year ? `<span class="badge" style="position: absolute; top: 10px; left: 10px; z-index: 1; background-color: #337ab7;">
${game.year}</span>` : '<span class="badge" style="position: absolute; top: 10px; left: 10px; z-index: 1; background-color: #d9534f;">No Year</span>'}
<a href="/game?id=${game._id}">
<img src="${game.thumbnailUrl}" alt="${
game.title
}" class="embed-responsive-item">
<img src="${game.thumbnailUrl}" alt="${game.title}" class="embed-responsive-item">
<div class="caption">
<h4><a href="/game?id=${game._id}">${
game.title
}</a></h4>
<p>Creator: <a href="/user-profile?username=${encodeURIComponent(
game.creator.username
)}">${game.creator.username}</a></p>
<h4><a href="/game?id=${game._id}">${game.title}</a></h4>
<p>Creator: <a href="/user-profile?username=${encodeURIComponent(game.creator.username)}">${game.creator.username}</a></p>
</div>
</a>
</div>
</div>
`
)
.join('')}
).join('')}
</div>
<div class="text-center">
<a href="/games" class="btn btn-primary">View All Games</a>
Expand Down
126 changes: 85 additions & 41 deletions client/js/user-profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,27 @@ $(document).ready(function () {
Authorization: `Bearer ${token}`,
},
success: function (user) {
if (!user || !user.username) {
console.error('Invalid user data received:', user);
$('#user-profile').html('<p>Error: Invalid user data received.</p>');
return;
}
console.log('User profile data received:', user); // Add this line
currentUser = user;
fetchUserStatus(username).then((isOnline) => {
user.isOnline = isOnline;
fetchForumPostCount(user._id).then((postCount) => {
user.forumPostCount = postCount;
displayUserProfile(user);
});
});
document.getElementById('profile-title').textContent = `${user.username}'s Profile - Valkyrie`;
},
updateFriendshipUI({
isFriend: user.isFriend,
friendRequestSent: user.friendRequestSent,
friendRequestReceived: user.friendRequestReceived
});
fetchUserStatus(username).then((isOnline) => {
user.isOnline = isOnline;
fetchForumPostCount(user._id).then((postCount) => {
user.forumPostCount = postCount;
displayUserProfile(user);
});
});
document.getElementById('profile-title').textContent = `${user.username}'s Profile - Valkyrie`;
},
error: function (xhr, status, error) {
console.error('Error fetching user profile:', xhr.responseText);
$('#user-profile').html('<p>Error fetching user profile. Please try again.</p>');
Expand Down Expand Up @@ -77,6 +87,12 @@ $(document).ready(function () {
}

function displayUserProfile(user) {
if (!user || !user.username) {
console.error('Invalid user data:', user);
$('#user-info').html('<div class="alert alert-danger">Error loading user profile. Invalid user data.</div>');
return;
}

console.log('Displaying profile for user:', {
userId: user.userId,
hasAvatarRender: !!user.avatarRender,
Expand Down Expand Up @@ -237,6 +253,9 @@ $(document).ready(function () {
Authorization: `Bearer ${token}`,
},
success: function (response) {
currentUser.isFriend = response.isFriend;
currentUser.friendRequestSent = response.friendRequestSent;
currentUser.friendRequestReceived = response.friendRequestReceived;
displayUserProfile(response);
},
error: function (xhr, status, error) {
Expand All @@ -250,35 +269,39 @@ $(document).ready(function () {
sendAjaxRequest(
'/api/friends/send-friend-request/' + userId,
'POST',
'Friend request sent successfully'
'Friend request sent successfully',
currentUser.username
);
}

function acceptFriendRequest(userId) {
sendAjaxRequest(
'/api/friends/accept-friend-request/' + userId,
'POST',
'Friend request accepted'
'Friend request accepted',
currentUser.username
);
}

function declineFriendRequest(userId) {
sendAjaxRequest(
'/api/friends/decline-friend-request/' + userId,
'POST',
'Friend request declined'
'Friend request declined',
currentUser.username
);
}

function unfriend(userId) {
sendAjaxRequest(
'/api/friends/unfriend/' + userId,
'POST',
'Unfriended successfully'
'Unfriended successfully',
currentUser.username
);
}

function sendAjaxRequest(url, method, successMessage) {
function sendAjaxRequest(url, method, successMessage, userId) {
const token = localStorage.getItem('token');
$.ajax({
url: url,
Expand All @@ -291,19 +314,10 @@ $(document).ready(function () {
checkFriendshipStatus(userId);
},
error: function (xhr, status, error) {
if (
xhr.responseJSON &&
xhr.responseJSON.error ===
'You have already received a friend request from this user'
) {
alert(
'You have already received a friend request from this user. Please check your friend requests.'
);
if (xhr.responseJSON && xhr.responseJSON.error === 'You have already received a friend request from this user') {
alert('You have already received a friend request from this user. Please check your friend requests.');
} else {
alert(
'Error: ' +
(xhr.responseJSON ? xhr.responseJSON.error : 'Unknown error')
);
alert('Error: ' + (xhr.responseJSON ? xhr.responseJSON.error : 'Unknown error'));
}
checkFriendshipStatus(userId);
},
Expand All @@ -315,9 +329,7 @@ $(document).ready(function () {
const blurbContainer = $('#blurb-container');
blurbContainer.html(`
<h4>Edit About Me</h4>
<textarea id="blurb-textarea" class="form-control" rows="3" maxlength="500">${escapeHtml(
currentBlurb || ''
)}</textarea>
<textarea id="blurb-textarea" class="form-control" rows="3" maxlength="500">${escapeHtml(currentBlurb || '')}</textarea>
<p id="char-count">0/500</p>
<button id="save-blurb" class="btn btn-success btn-sm mt-2">Save</button>
<button id="cancel-blurb" class="btn btn-secondary btn-sm mt-2">Cancel</button>
Expand Down Expand Up @@ -645,6 +657,7 @@ $(document).ready(function () {
}

function escapeHtml(unsafe) {
if (!unsafe) return '';
return unsafe
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
Expand All @@ -653,26 +666,57 @@ $(document).ready(function () {
.replace(/'/g, '&#039;');
}

/* function updateFriendshipUI(status) {
function updateFriendshipUI(status) {
let actionButton = '';

// Check if viewing own profile
const profileUsername = $('#profile-username').data('username');
const currentUsername = localStorage.getItem('username');

if (profileUsername === currentUsername) {
return; // Don't show any friendship buttons on own profile
}

if (status.isFriend) {
actionButton = '<button id="unfriend" class="btn btn-warning btn-sm"><i class="fa fa-user-times"></i> Unfriend</button>';
actionButton = `
<button id="unfriend" class="btn btn-warning btn-sm">
<i class="fa fa-user-times"></i> Unfriend
</button>
<button id="message-user" class="btn btn-info btn-sm" style="margin-left: 10px;">
<i class="fa fa-envelope"></i> Message User
</button>
`;
} else if (status.friendRequestReceived) {
actionButton = `
<button id="accept-friend-request" class="btn btn-success btn-sm"><i class="fa fa-check"></i> Accept Friend Request</button>
<button id="decline-friend-request" class="btn btn-danger btn-sm" style="margin-left: 10px;"><i class="fa fa-times"></i> Decline Friend Request</button>
`;
actionButton = `
<button id="accept-friend-request" class="btn btn-success btn-sm">
<i class="fa fa-check"></i> Accept Friend Request
</button>
<button id="decline-friend-request" class="btn btn-danger btn-sm" style="margin-left: 10px;">
<i class="fa fa-times"></i> Decline Friend Request
</button>
`;
} else if (status.friendRequestSent) {
actionButton = '<button class="btn btn-secondary btn-sm" disabled><i class="fa fa-clock-o"></i> Friend Request Sent</button>';
actionButton = `
<button class="btn btn-secondary btn-sm" disabled>
<i class="fa fa-clock-o"></i> Friend Request Sent
</button>
<button id="message-user" class="btn btn-info btn-sm" style="margin-left: 10px;">
<i class="fa fa-envelope"></i> Message User
</button>
`;
} else {
actionButton = `
<button id="send-friend-request" class="btn btn-primary btn-sm"><i class="fa fa-user-plus"></i> Send Friend Request</button>
<button id="message-user" class="btn btn-info btn-sm" style="margin-left: 10px;"><i class="fa fa-envelope"></i> Message User</button>
`;
actionButton = `
<button id="send-friend-request" class="btn btn-primary btn-sm">
<i class="fa fa-user-plus"></i> Send Friend Request
</button>
<button id="message-user" class="btn btn-info btn-sm" style="margin-left: 10px;">
<i class="fa fa-envelope"></i> Message User
</button>
`;
}
$('#action-button-container').html(actionButton);
initFriendActions();
} */
}
});

function formatDate(dateString) {
Expand Down
10 changes: 5 additions & 5 deletions server/functions/api/routes/friends.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,20 +80,20 @@ router.post(

// Add this new route after the existing friend-related routes
router.get(
'/friendship-status/:userId',
'/friendship-status/:username',
authenticateToken,
async (req, res) => {
try {
const currentUser = await User.findById({ userId: req.user.userId });
const currentUser = await User.findOne({ userId: req.user.userId });
const targetUser = await User.findOne({ username: req.params.username });

if (!targetUser) {
return res.status(404).json({ error: 'User not found' });
}

const isFriend = currentUser.friends.includes(targetUser.userId);
const friendRequestSent = targetUser.friendRequests.includes(currentUser.userId);
const friendRequestReceived = currentUser.friendRequests.includes(targetUser.userId);
const isFriend = currentUser.friends.some(id => id.equals(targetUser._id));
const friendRequestSent = targetUser.friendRequests.some(id => id.equals(currentUser._id));
const friendRequestReceived = currentUser.friendRequests.some(id => id.equals(targetUser._id));

res.json({
isFriend,
Expand Down
6 changes: 3 additions & 3 deletions server/functions/api/routes/user.js
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ router.get('/user/:username', authenticateToken, async (req, res) => {
avatarRenderDetails: user.avatarRender
});

const isFriend = currentUser.friends.includes(user.userId);
const friendRequestSent = user.friendRequests.includes(currentUser.userId);
const friendRequestReceived = currentUser.friendRequests.includes(user.userId);
const isFriend = currentUser.friends.some(id => id.equals(user._id));
const friendRequestSent = user.friendRequests.some(id => id.equals(currentUser._id));
const friendRequestReceived = currentUser.friendRequests.some(id => id.equals(user._id));

delete user.friendRequests;
delete user.friends;
Expand Down

0 comments on commit abba4d2

Please sign in to comment.