Skip to content

Commit

Permalink
started to add real time activity notify
Browse files Browse the repository at this point in the history
  • Loading branch information
tomyRomero committed Dec 10, 2023
1 parent 2f4ba3e commit 976d7ea
Show file tree
Hide file tree
Showing 16 changed files with 379 additions and 109 deletions.
4 changes: 3 additions & 1 deletion app/(root)/activity/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ async function Page() {

updateOnlineStatus(user.id, true);
const activity = await fetchLikesAndCommentsByUser(user.id, 5);
console.log("Activity: ", activity)

function getLastUserId(likes: string) {
// Split the string using commas and filter out empty strings
Expand All @@ -39,6 +38,8 @@ async function Page() {
}
}

console.log("Activity: ", activity)

return (
<>
<h1 className='head-text text-black'>Notifications</h1>
Expand Down Expand Up @@ -72,6 +73,7 @@ async function Page() {
}
content = {activity.content}
title = {activity.title}
read_status = {activity.read_status}
/>
))}
</>
Expand Down
8 changes: 1 addition & 7 deletions app/(root)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,6 @@ export default async function RootLayout({
const dateA = new Date(lastMessageA.timestamp);
const dateB = new Date(lastMessageB.timestamp);

console.log("Timestamp A: ", lastMessageA.timestamp);
console.log("Date A: ", dateA);

console.log("Timestamp B: ", lastMessageB.timestamp);
console.log("Date B: ", dateB);

// Compare the dates (descending order, latest time first)
//@ts-ignore
return dateB - dateA;
Expand Down Expand Up @@ -75,7 +69,7 @@ export default async function RootLayout({
<html lang='en'>
<body className={inter.className}>
<AppProvider>
<Topbar />
<Topbar user={data.dbUser}/>
<main className='flex flex-row'>
<LeftSidebar user={data.dbUser}/>
<section className='main-container'>
Expand Down
2 changes: 1 addition & 1 deletion app/globals.css
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@
@apply sticky left-0 top-0 z-20 flex h-screen w-fit flex-col justify-between overflow-auto border-r border-r-slate-300 bg-black pb-2 pt-20 max-md:hidden;
}
.leftsidebar_link {
@apply relative flex justify-start gap-4 rounded-xl p-2.5;
@apply relative flex justify-start gap-4 rounded-xl p-2.5 max-lg:gap-1 max-lg:justify-center;
}
.pagination {
@apply mt-10 flex w-full items-center justify-center gap-5;
Expand Down
30 changes: 6 additions & 24 deletions components/cards/ChatLogs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getImageData } from "@/lib/s3";
import pusherClient from "@/lib/pusher";
import { getChatBySenderAndReceiver, revalData } from "@/lib/actions/chat.actions";
import { useAppContext } from "@/lib/AppContext";
import { useRouter } from "next/navigation";


interface Chat {
chatRead : boolean;
Expand All @@ -25,30 +25,15 @@ interface Chat {

const ChatLogs = ({ chatRead, senderID, receiverID, chatMessages, receiverPicture, chatName, isHome , path} : Chat) => {

const {globalMessages, setGlobalMessages, setReadMessages, readMessages, refresh, setRefresh} = useAppContext();
const {globalMessages, setGlobalMessages, setReadMessages, readMessages, pusherChannel} = useAppContext();

const [chatPicture, setChatPicture] = useState("/assets/imgloader.svg")
const [isMe, setIsMe] = useState(false);
const [messages, setMessages] = useState(chatMessages);
const [read, setRead] = useState(true)

var pusher = pusherClient;
const router = useRouter();

useEffect( ()=> {

if(path === "/" || path === "/create-post" || path === "/activity" || path === "/search" || path.startsWith("/profile"))
{
if(refresh)
{
setRefresh(false)
router.refresh();
}
}else if(path === "/chat")
{
setRefresh(true)
}

const getImage = async () => {
let imgResult = "/assets/profile.svg"

Expand All @@ -66,8 +51,6 @@ const ChatLogs = ({ chatRead, senderID, receiverID, chatMessages, receiverPictur

useEffect( ()=> {

console.log("Right Bar Set Read active:")

const lastIndex = messages[ messages.length - 1]
const lastMessageSender = lastIndex.sender

Expand All @@ -91,7 +74,7 @@ const ChatLogs = ({ chatRead, senderID, receiverID, chatMessages, receiverPictur

useEffect(() => {
try {
const channel = pusher.subscribe('sparks');
const channel = pusherChannel

channel.bind('message', (data: any) => {
revalData(path)
Expand All @@ -114,10 +97,9 @@ const ChatLogs = ({ chatRead, senderID, receiverID, chatMessages, receiverPictur
});

// Clean up on component unmount
return () => {
channel.unbind('message');
pusher.unsubscribe('chats');
};
// return () => {
// channel.unbind('message');
// };

} catch (error) {
console.error(error);
Expand Down
7 changes: 7 additions & 0 deletions components/cards/Post.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { getImageData } from "@/lib/s3";
import { addLikeToPost, removeLikeFromPost } from "@/lib/actions/post.actions";
import DeletePost from "../forms/DeletePost";
import { fetchUser } from "@/lib/actions/user.actions";
import { useAppContext } from "@/lib/AppContext";

interface Props {
id: string;
Expand Down Expand Up @@ -44,6 +45,7 @@ function Post({
title
}: Props) {


const isInsideLikes = () => {
// Split the comma-separated string into an array
const userIdsArray = likes.split(',');
Expand All @@ -68,6 +70,8 @@ function Post({
const [numLikes, setNumLikes] = useState(filterLikes())
const [contentImg, setContentImg] = useState('/assets/postloader.svg')

const {setNewLike, newLike} = useAppContext();

useEffect(() => {
const loadProfile = async () => {
try {
Expand Down Expand Up @@ -159,6 +163,9 @@ function Post({
} else {
await addLikeToPost(id, currentUserId);
setNumLikes(prevNumLikes => prevNumLikes + 1);

//Adjust global state for notifactions
setNewLike(!newLike)
}

// After a short delay (e.g., 500ms)
Expand Down
13 changes: 4 additions & 9 deletions components/forms/Chat.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:

var pusher = pusherClient;

const { globalMessages, setGlobalMessages, readMessages, setReadMessages, setRefresh} = useAppContext();
const { globalMessages, setGlobalMessages, readMessages, setReadMessages, pusherChannel} = useAppContext();

useEffect(() => {
try {

const channel = pusher.subscribe('sparks');
const channel = pusherChannel

// Handle the event for updating the online status
channel.bind('updateOnlineStatus', (data: any) => {
Expand Down Expand Up @@ -96,10 +96,7 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:
// Filter and update the messages based on the data received
console.log('Received updateReadStatus event:', data);

setReadMessages(true);

// Check if the current user is the sender of the message

if(data.sender === userID && data.receiver === receiver)
{
setRead(true);
Expand All @@ -112,13 +109,12 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:
channel.unbind('message');
channel.unbind('updateReadStatus');
channel.unbind('updateOnlineStatus');
pusher.unsubscribe('chats');
};

} catch (error) {
console.error(error);
}
}, [chatMessages, setMessages, readMessages, setReadMessages, loading, setLoading]);
}, [chatMessages, setMessages,loading, setLoading]);

useEffect ( ()=> {

Expand All @@ -130,6 +126,7 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:
if(lastMessage.sender !== userID)
{
const read = await markChatAsRead(receiver, userID, messages, pathname);
setReadMessages(!readMessages);
}

}
Expand All @@ -144,8 +141,6 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:

useEffect( ()=> {

setRefresh(true);

//Check To See If Chat Was Read Already
if(messages.length > 0)
{
Expand Down
9 changes: 8 additions & 1 deletion components/forms/Comment.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { Button } from "../ui/button";
import { CommentValdiation } from "@/lib/validations/post";
import { addCommentToPost } from "@/lib/actions/post.actions";
import { getImageData } from "@/lib/s3";
import { AppProvider, useAppContext } from "@/lib/AppContext";

interface Props {
postId: string;
Expand All @@ -37,6 +38,8 @@ function Comment({ postId, currentUserImg, currentUserId, parentId }: Props) {
const [backLoading, setBackLoading] = useState(false)
const router = useRouter();

const {newComment, setNewComment} = useAppContext();

useEffect( () => {
const load = async () => {
try{
Expand Down Expand Up @@ -72,14 +75,18 @@ function Comment({ postId, currentUserImg, currentUserId, parentId }: Props) {

const onSubmit = async (values: z.infer<typeof CommentValdiation>) => {
setLoading(true)
await addCommentToPost(
const added = await addCommentToPost(
postId,
values.comment,
currentUserId,
pathname,
currentUserImg,
);

if(added){
setNewComment(!newComment)
}

form.reset();
setLoading(false)
};
Expand Down
11 changes: 10 additions & 1 deletion components/shared/Activity.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,11 @@ interface Props {
time: string;
content: string;
title: string;
read_status: boolean | null;
}


const Activity = ({idpost, authorUsername, authorImage, activityKey, parentid, type, likes, time, content, title} : Props) => {
const Activity = ({idpost, authorUsername, authorImage, activityKey, parentid, type, likes, time, content, title, read_status} : Props) => {
const [img, setImg] = useState("/assets/imgloader.svg");
const [parentContent, setParentContent] = useState('')

Expand Down Expand Up @@ -160,6 +161,14 @@ const Activity = ({idpost, authorUsername, authorImage, activityKey, parentid, t
)}
<span>{` at ${reformatDateString(time)}`}</span>
</p>
{ read_status && (
<Image
src={"/assets/alert.svg"}
alt={"alert"}
width={20}
height={20}
/>
)}
</article>
</Link>
</>
Expand Down
60 changes: 60 additions & 0 deletions components/shared/BottomBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,56 @@ import { bottombarLinks } from "@/constants";
import Link from "next/link";
import Image from "next/image";
import { usePathname, useRouter } from 'next/navigation'
import { useState, useEffect } from "react";
import { useAppContext } from "@/lib/AppContext";
import { doesPostBelongToUser } from "@/lib/actions/user.actions";

function Bottombar({user} : any)
{
const pathname = usePathname();
const [activity, setActivity] = useState(false)

const { globalMessages, setGlobalMessages, readMessages, setReadMessages, pusherChannel, newComment, setNewComment, newLike, setNewLike} = useAppContext();
const channel = pusherChannel

useEffect( ()=> {
try {
//Look for realtime events on new notifactions from activity
channel.bind('comment', async (data: any) => {

// Handle new comment received from Pusher

const myPost = await doesPostBelongToUser(data.postId, user.id)

if(myPost)
{
setActivity(true);
}

});

} catch (error) {
console.error(error);
}

}, [newComment, setNewComment])

useEffect(()=> {

//Look for Real time updates of Likes
channel.bind('like', async (data: any) => {

// Handle new comment received from Pusher

const myPost = await doesPostBelongToUser(data.postId, user.id)

if(myPost)
{
setActivity(true);
}
});

}, [newLike, setNewLike])

return(
<section className="bottombar">
Expand All @@ -18,21 +64,35 @@ function Bottombar({user} : any)
|| pathname === link.route;

return(

<Link
href={`${link.route === '/profile' ? `/profile/${user.id}` : `${link.route}`}`}
key={link.label}
className={`bottombar_link ${ isActive && 'bg-primary-500'}`}
>
<div className={`${activity ? 'flex' : ''}`}>
<Image
src={link.imgURL}
alt={link.label}
width={24}
height={24}
/>

{activity && link.label === "Activity" && (
<Image
src={"/assets/alert.svg"}
alt={"alert"}
width={20}
height={20}
/>
)}
</div>

<p className="text-subtle-medium text-light-1 max-sm:hidden">
{link.label.split(/\s+/)[0]}

</p>

</Link>
)}
)}
Expand Down
Loading

0 comments on commit 976d7ea

Please sign in to comment.