Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions backend/data/follows.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,16 @@ def follow(follower: User, followee: User):
pass


def unfollow(follower: User, followee: User):
with db_cursor() as cur:
cur.execute(
"DELETE FROM follows WHERE follower = %(follower_id)s AND followee = %(followee_id)s",
dict(
follower_id=follower.id,
followee_id=followee.id,
),
)

def get_followed_usernames(follower: User) -> List[str]:
"""get_followed_usernames returns a list of usernames followee follows."""
with db_cursor() as cur:
Expand Down
23 changes: 22 additions & 1 deletion backend/endpoints.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import Dict, Union
from data import blooms
from data.follows import follow, get_followed_usernames, get_inverse_followed_usernames
from data.follows import follow,unfollow, get_followed_usernames, get_inverse_followed_usernames
from data.users import (
UserRegistrationError,
get_suggested_follows,
Expand Down Expand Up @@ -149,6 +149,27 @@ def do_follow():
}
)

@jwt_required()
def do_unfollow():
type_check_error = verify_request_fields({"unfollow_username": str})
if type_check_error is not None:
return type_check_error

current_user = get_current_user()

unfollow_username = request.json["unfollow_username"]
unfollow_user = get_user(unfollow_username)
if unfollow_user is None:
return make_response(
(f"Cannot unfollow {unfollow_username} - user does not exist", 404)
)

unfollow(current_user, unfollow_user)
return jsonify(
{
"success": True,
}
)

@jwt_required()
def send_bloom():
Expand Down
2 changes: 2 additions & 0 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from data.users import lookup_user
from endpoints import (
do_follow,
do_unfollow,
get_bloom,
hashtag,
home_timeline,
Expand Down Expand Up @@ -54,6 +55,7 @@ def main():
app.add_url_rule("/profile", view_func=self_profile)
app.add_url_rule("/profile/<profile_username>", view_func=other_profile)
app.add_url_rule("/follow", methods=["POST"], view_func=do_follow)
app.add_url_rule("/unfollow", methods=["POST"], view_func=do_unfollow)
app.add_url_rule("/suggested-follows/<limit_str>", view_func=suggested_follows)

app.add_url_rule("/bloom", methods=["POST"], view_func=send_bloom)
Expand Down
44 changes: 32 additions & 12 deletions front-end/components/profile.mjs
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import {apiService} from "../index.mjs";
import { apiService } from "../index.mjs";

/**
* Create a profile component
* @param {string} template - The ID of the template to clone
* @param {Object} profileData - The profile data to display
* @returns {DocumentFragment} - The profile UI
*/
function createProfile(template, {profileData, whoToFollow, isLoggedIn}) {
function createProfile(template, { profileData, whoToFollow, isLoggedIn }) {
if (!template || !profileData) return;
const profileElement = document
.getElementById(template)
Expand All @@ -15,26 +15,37 @@ function createProfile(template, {profileData, whoToFollow, isLoggedIn}) {
const usernameEl = profileElement.querySelector("[data-username]");
const bloomCountEl = profileElement.querySelector("[data-bloom-count]");
const followingCountEl = profileElement.querySelector(
"[data-following-count]"
"[data-following-count]",
);
const followerCountEl = profileElement.querySelector("[data-follower-count]");
const followButtonEl = profileElement.querySelector("[data-action='follow']");
const whoToFollowContainer = profileElement.querySelector(".profile__who-to-follow");
// Populate with data
const whoToFollowContainer = profileElement.querySelector(
".profile__who-to-follow",
);

usernameEl.querySelector("h2").textContent = profileData.username || "";
usernameEl.setAttribute("href", `/profile/${profileData.username}`);
bloomCountEl.textContent = profileData.total_blooms || 0;
followerCountEl.textContent = profileData.followers?.length || 0;
followingCountEl.textContent = profileData.follows?.length || 0;
followButtonEl.setAttribute("data-username", profileData.username || "");
followButtonEl.hidden = profileData.is_self || profileData.is_following;
followButtonEl.addEventListener("click", handleFollow);
if (!isLoggedIn) {
followButtonEl.style.display = "none";

if (followButtonEl) {
followButtonEl.setAttribute("data-username", profileData.username || "");
followButtonEl.hidden = profileData.is_self || !isLoggedIn;

if (profileData.is_following) {
followButtonEl.textContent = "Unfollow";
followButtonEl.addEventListener("click", handleUnfollow);
} else {
followButtonEl.textContent = "Follow";
followButtonEl.addEventListener("click", handleFollow);
}
}

if (whoToFollow.length > 0) {
const whoToFollowList = whoToFollowContainer.querySelector("[data-who-to-follow]");
const whoToFollowList = whoToFollowContainer.querySelector(
"[data-who-to-follow]",
);
const whoToFollowTemplate = document.querySelector("#who-to-follow-chip");
for (const userToFollow of whoToFollow) {
const wtfElement = whoToFollowTemplate.content.cloneNode(true);
Expand Down Expand Up @@ -66,4 +77,13 @@ async function handleFollow(event) {
await apiService.getWhoToFollow();
}

export {createProfile, handleFollow};
async function handleUnfollow(event) {
const button = event.target;
const username = button.getAttribute("data-username");
if (!username) return;

await apiService.unfollowUser(username);
await apiService.getWhoToFollow();
}

export { createProfile, handleFollow, handleUnfollow };
67 changes: 33 additions & 34 deletions front-end/lib/api.mjs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import {state} from "../index.mjs";
import {handleErrorDialog} from "../components/error.mjs";
import { state } from "../index.mjs";
import { handleErrorDialog } from "../components/error.mjs";

// === ABOUT THE STATE
// state gives you these two functions only
Expand All @@ -20,13 +20,13 @@ async function _apiRequest(endpoint, options = {}) {
const defaultOptions = {
headers: {
"Content-Type": "application/json",
...(token ? {Authorization: `Bearer ${token}`} : {}),
...(token ? { Authorization: `Bearer ${token}` } : {}),
},
mode: "cors",
credentials: "include",
};

const fetchOptions = {...defaultOptions, ...options};
const fetchOptions = { ...defaultOptions, ...options };
const url = endpoint.startsWith("http") ? endpoint : `${baseUrl}${endpoint}`;

try {
Expand All @@ -35,7 +35,7 @@ async function _apiRequest(endpoint, options = {}) {
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
const error = new Error(
errorData.message || `API error: ${response.status}`
errorData.message || `API error: ${response.status}`,
);
error.status = response.status;

Expand All @@ -54,7 +54,7 @@ async function _apiRequest(endpoint, options = {}) {
const contentType = response.headers.get("content-type");
return contentType?.includes("application/json")
? await response.json()
: {success: true};
: { success: true };
} catch (error) {
if (!error.status) {
// Only handle network errors here, response errors are handled above
Expand All @@ -70,19 +70,19 @@ function _updateProfile(username, profileData) {
const index = profiles.findIndex((p) => p.username === username);

if (index !== -1) {
profiles[index] = {...profiles[index], ...profileData};
profiles[index] = { ...profiles[index], ...profileData };
} else {
profiles.push({username, ...profileData});
profiles.push({ username, ...profileData });
}
state.updateState({profiles});
state.updateState({ profiles });
}

// ====== AUTH methods
async function login(username, password) {
try {
const data = await _apiRequest("/login", {
method: "POST",
body: JSON.stringify({username, password}),
body: JSON.stringify({ username, password }),
});

if (data.success && data.token) {
Expand All @@ -96,20 +96,20 @@ async function login(username, password) {

return data;
} catch (error) {
return {success: false};
return { success: false };
}
}

async function getWhoToFollow() {
try {
const usernamesToFollow = await _apiRequest("/suggested-follows/3");

state.updateState({whoToFollow: usernamesToFollow});
state.updateState({ whoToFollow: usernamesToFollow });

return usernamesToFollow;
} catch (error) {
// Error already handled by _apiRequest
state.updateState({usernamesToFollow: []});
state.updateState({ usernamesToFollow: [] });
return [];
}
}
Expand All @@ -118,7 +118,7 @@ async function signup(username, password) {
try {
const data = await _apiRequest("/register", {
method: "POST",
body: JSON.stringify({username, password}),
body: JSON.stringify({ username, password }),
});

if (data.success && data.token) {
Expand All @@ -132,20 +132,20 @@ async function signup(username, password) {

return data;
} catch (error) {
return {success: false};
return { success: false };
}
}

function logout() {
state.destroyState();
return {success: true};
return { success: true };
}

// ===== BLOOM methods
async function getBloom(bloomId) {
const endpoint = `/bloom/${bloomId}`;
const bloom = await _apiRequest(endpoint);
state.updateState({singleBloomToShow: bloom});
state.updateState({ singleBloomToShow: bloom });
return bloom;
}

Expand All @@ -156,18 +156,18 @@ async function getBlooms(username) {
const blooms = await _apiRequest(endpoint);

if (username) {
_updateProfile(username, {blooms});
_updateProfile(username, { blooms });
} else {
state.updateState({timelineBlooms: blooms});
state.updateState({ timelineBlooms: blooms });
}

return blooms;
} catch (error) {
// Error already handled by _apiRequest
if (username) {
_updateProfile(username, {blooms: []});
_updateProfile(username, { blooms: [] });
} else {
state.updateState({timelineBlooms: []});
state.updateState({ timelineBlooms: [] });
}
return [];
}
Expand All @@ -189,15 +189,15 @@ async function getBloomsByHashtag(hashtag) {
return blooms;
} catch (error) {
// Error already handled by _apiRequest
return {success: false};
return { success: false };
}
}

async function postBloom(content) {
try {
const data = await _apiRequest("/bloom", {
method: "POST",
body: JSON.stringify({content}),
body: JSON.stringify({ content }),
});

if (data.success) {
Expand All @@ -208,7 +208,7 @@ async function postBloom(content) {
return data;
} catch (error) {
// Error already handled by _apiRequest
return {success: false};
return { success: false };
}
}

Expand All @@ -225,24 +225,24 @@ async function getProfile(username) {
const currentUsername = profileData.username;
const fullProfileData = await _apiRequest(`/profile/${currentUsername}`);
_updateProfile(currentUsername, fullProfileData);
state.updateState({currentUser: currentUsername, isLoggedIn: true});
state.updateState({ currentUser: currentUsername, isLoggedIn: true });
}

return profileData;
} catch (error) {
// Error already handled by _apiRequest
if (!username) {
state.updateState({isLoggedIn: false, currentUser: null});
state.updateState({ isLoggedIn: false, currentUser: null });
}
return {success: false};
return { success: false };
}
}

async function followUser(username) {
try {
const data = await _apiRequest("/follow", {
method: "POST",
body: JSON.stringify({follow_username: username}),
body: JSON.stringify({ follow_username: username }),
});

if (data.success) {
Expand All @@ -255,18 +255,18 @@ async function followUser(username) {

return data;
} catch (error) {
return {success: false};
return { success: false };
}
}

async function unfollowUser(username) {
try {
const data = await _apiRequest(`/unfollow/${username}`, {
const data = await _apiRequest("/unfollow", {
method: "POST",
body: JSON.stringify({ unfollow_username: username }), // Send object in body
});

if (data.success) {
// Update both the unfollowed user's profile and the current user's profile
await Promise.all([
getProfile(username),
getProfile(state.currentUser),
Expand All @@ -276,8 +276,7 @@ async function unfollowUser(username) {

return data;
} catch (error) {
// Error already handled by _apiRequest
return {success: false};
return { success: false };
}
}

Expand All @@ -300,4 +299,4 @@ const apiService = {
getWhoToFollow,
};

export {apiService};
export { apiService };