Skip to content

Commit

Permalink
real time notifcations
Browse files Browse the repository at this point in the history
  • Loading branch information
tomyRomero committed Dec 8, 2023
1 parent 7762945 commit 916014a
Show file tree
Hide file tree
Showing 15 changed files with 226 additions and 27 deletions.
2 changes: 2 additions & 0 deletions app/(root)/activity/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { fetchUser } from "@/lib/actions/user.actions";
import { fetchPostById} from "@/lib/actions/post.actions";
import { fetchLikesAndCommentsByUser } from "@/lib/actions/user.actions";
import Activity from "@/components/shared/Activity";
import { updateOnlineStatus } from "@/lib/actions/chat.actions";

async function Page() {
const user = await currentUser();
Expand All @@ -12,6 +13,7 @@ async function Page() {
const userInfo = await fetchUser(user.id);
if (!userInfo?.onboarded) redirect("/onboarding");

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

Expand Down
4 changes: 3 additions & 1 deletion app/(root)/chat/[id]/page.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Chat from "@/components/forms/Chat";
import { getChatBySenderAndReceiver } from "@/lib/actions/chat.actions";
import { getChatBySenderAndReceiver, updateOnlineStatus } from "@/lib/actions/chat.actions";
import { fetchUser } from "@/lib/actions/user.actions";
import { currentUser } from "@clerk/nextjs";

Expand All @@ -10,6 +10,8 @@ const page = async ({ params }: { params: { id: string } }) => {

const dbUser = await fetchUser(params.id)

updateOnlineStatus(user.id, true);

//user would then use its ID and the ID of the searchParams to get the chat that belongs to those two
//Chat data would look a little like this.
let chatData = {
Expand Down
4 changes: 3 additions & 1 deletion app/(root)/chat/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { fetchUser, fetchUsers } from "@/lib/actions/user.actions";
import { currentUser } from "@clerk/nextjs";
import { redirect } from "next/navigation";
import HorizontalScroll from "@/components/shared/HorizontalScroll";
import { getChatsWithUsersByUserId } from "@/lib/actions/chat.actions";
import { getChatsWithUsersByUserId, updateOnlineStatus } from "@/lib/actions/chat.actions";
import ChatLogs from "@/components/cards/ChatLogs";

async function Page({
Expand All @@ -18,6 +18,8 @@ async function Page({
const userInfo = await fetchUser(user.id);
if (!userInfo?.onboarded) redirect("/onboarding");

updateOnlineStatus(user.id, true);

const result = await fetchUsers({
userId: user.id,
searchString: searchParams.q,
Expand Down
3 changes: 3 additions & 0 deletions app/(root)/create-post/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { postTabs } from "@/constants";
import Image from "next/image";
import Studio from "@/components/studio/Studio";
import { updateOnlineStatus } from "@/lib/actions/chat.actions";


const page = async () => {
Expand All @@ -14,6 +15,8 @@ const page = async () => {
const userInfo = await fetchUser(user.id);
if (!userInfo?.onboarded) redirect("/onboarding");

updateOnlineStatus(user.id, true);

return (
<section>
<h1 className="head_text text-center blue_gradient">Spark Studio </h1>
Expand Down
9 changes: 8 additions & 1 deletion app/(root)/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ import RightBar from "@/components/shared/RightBar";
import { fetchUser } from "@/lib/actions/user.actions";
import { getChatsWithUsersByUserId, updateOnlineStatus } from "@/lib/actions/chat.actions";

//Global State
import { AppProvider } from "@/lib/AppContext";

const inter = Inter({ subsets: ["latin"] });

export const metadata: Metadata = {
Expand Down Expand Up @@ -71,8 +74,8 @@ export default async function RootLayout({
>
<html lang='en'>
<body className={inter.className}>
<AppProvider>
<Topbar />

<main className='flex flex-row'>
<LeftSidebar user={data.dbUser}/>
<section className='main-container'>
Expand All @@ -81,8 +84,12 @@ export default async function RootLayout({
<RightBar chats={data.chats} />
</main>
<Bottombar user={data.dbUser} />
</AppProvider>
</body>
</html>
</ClerkProvider>
);
}



3 changes: 3 additions & 0 deletions app/(root)/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { currentUser } from "@clerk/nextjs";
import { fetchUser } from "@/lib/actions/user.actions";
import { redirect, useRouter } from "next/navigation";
import Pagination from "@/components/shared/Pagination";
import { updateOnlineStatus } from "@/lib/actions/chat.actions";

async function Home({
searchParams,
Expand All @@ -21,6 +22,8 @@ async function Home({
10,
)

updateOnlineStatus(user.id, true);

return (
<>
<h1 className='head-text text-left text-black'>Recent Sparks...</h1>
Expand Down
5 changes: 3 additions & 2 deletions app/(root)/post/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,19 @@ import Post from "@/components/cards/Post";

import { fetchUser } from "@/lib/actions/user.actions";
import { fetchPostById } from "@/lib/actions/post.actions";
import { updateOnlineStatus } from "@/lib/actions/chat.actions";

export const revalidate = 0;

async function page({ params }: { params: { id: string } }) {
if (!params.id) return null;


console.log("PARAMS ID:", params.id)

const user = await currentUser();
if (!user) return null;

updateOnlineStatus(user.id, true);

const userInfo = await fetchUser(user.id);
if (!userInfo?.onboarded) redirect("/onboarding");

Expand Down
2 changes: 2 additions & 0 deletions app/(root)/profile/[id]/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import CommentsTab from "@/components/shared/CommentsTab";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { fetchUser } from "@/lib/actions/user.actions";
import LikedTab from "@/components/shared/LikedTab";
import { updateOnlineStatus } from "@/lib/actions/chat.actions";

async function Page({ params }: { params: { id: string } }) {
const user = await currentUser();
Expand All @@ -16,6 +17,7 @@ async function Page({ params }: { params: { id: string } }) {
const userInfo = await fetchUser(params.id);
if (!userInfo?.onboarded) redirect("/onboarding");

updateOnlineStatus(user.id, true);


return (
Expand Down
3 changes: 3 additions & 0 deletions app/(root)/search/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import Searchbar from "@/components/shared/Searchbar";
import Pagination from "@/components/shared/Pagination";

import { fetchUser, fetchUsers } from "@/lib/actions/user.actions";
import { updateOnlineStatus } from "@/lib/actions/chat.actions";

async function Page({
searchParams,
Expand All @@ -15,6 +16,8 @@ async function Page({
const user = await currentUser();
if (!user) return null;

updateOnlineStatus(user.id, true);

const userInfo = await fetchUser(user.id);
if (!userInfo?.onboarded) redirect("/onboarding");

Expand Down
32 changes: 15 additions & 17 deletions components/cards/ChatLogs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { useEffect, useState } from "react";
import { getImageData } from "@/lib/s3";
import pusherClient from "@/lib/pusher";
import { getChatBySenderAndReceiver, revalData } from "@/lib/actions/chat.actions";
import { useAppContext } from "@/lib/AppContext";

interface Chat {
chatRead : boolean;
Expand All @@ -22,6 +23,9 @@ interface Chat {
}

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

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

const [chatPicture, setChatPicture] = useState("/assets/imgloader.svg")
const [isMe, setIsMe] = useState(false);
const [messages, setMessages] = useState(chatMessages);
Expand All @@ -46,6 +50,9 @@ 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 @@ -59,32 +66,31 @@ const ChatLogs = ({ chatRead, senderID, receiverID, chatMessages, receiverPictur
const updateRead = async ()=> {
const chat = await getChatBySenderAndReceiver(receiverID, senderID);
const readStatus = chat.read_status
console.log("Read Status: " , readStatus)
setRead(readStatus)

}

updateRead();

}, [messages])
}, [messages , setRead, setReadMessages])

useEffect(() => {
try {
console.log("Chat Logs Ran")
const channel = pusher.subscribe('sparks');

channel.bind('message', (data: any) => {
revalData(path)
// Handle new message received from Pusher
// Update the state with the new message if the sender ID and reciever ID match
setGlobalMessages((prevGlobalMessages: any) => [...prevGlobalMessages, data]);

console.log("MESSAGE DATA: ", data)

if(data.sender === senderID && data.receiver === receiverID || data.sender === receiverID && data.receiver === senderID)
{
setMessages((prevMessages) => [...prevMessages, data]);

const newArr = [...messages, data]
console.log("New Message", newArr)


if(data.sender !== senderID)
{
setRead(false);
Expand All @@ -102,7 +108,7 @@ const ChatLogs = ({ chatRead, senderID, receiverID, chatMessages, receiverPictur
} catch (error) {
console.error(error);
}
}, [messages, setMessages]);
}, [messages, setMessages, globalMessages, setGlobalMessages]);

const getLastText = () => {
const lastIndex = messages[messages.length - 1]
Expand Down Expand Up @@ -164,11 +170,7 @@ const ChatLogs = ({ chatRead, senderID, receiverID, chatMessages, receiverPictur

{isHome && (
<div className={`ml-auto text-black ${!read && !isMe ? 'font-bold' : ''}`}>
<div className="text-left">
{/* Date */}
{getLastTime().split(' ')[0]}
</div>
<div className="text-left">
<div>
{/* Time */}
{getLastTime().split(' ')[1]}{' '}
{getLastTime().split(' ')[2]} {/* AM/PM */}
Expand All @@ -180,11 +182,7 @@ const ChatLogs = ({ chatRead, senderID, receiverID, chatMessages, receiverPictur

{!isHome && (
<div className={`ml-auto text-black ${!read && !isMe ? 'font-bold' : ''}`}>
<div className="text-right">
{/* Date */}
{getLastTime().split(' ')[0]}
</div>
<div className="text-right">
<div >
{/* Time */}
{getLastTime().split(' ')[1]}{' '}
{getLastTime().split(' ')[2]} {/* AM/PM */}
Expand Down
18 changes: 13 additions & 5 deletions components/forms/Chat.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
"use client"

import Link from "next/link"
import Image from "next/image"
import { useState, useEffect, useRef} from "react";
import { useForm } from "react-hook-form";
import { boolean, z } from "zod";
import { z } from "zod";
import {
Form,
FormControl,
Expand All @@ -22,6 +21,7 @@ import { usePathname, useRouter } from "next/navigation";
import { getImageData } from "@/lib/s3";
import pusherClient from "@/lib/pusher";
import { getDateTime } from "@/lib/utils";
import { useAppContext } from "@/lib/AppContext";

interface chat{
chatPicture: string;
Expand Down Expand Up @@ -51,6 +51,8 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:

var pusher = pusherClient;

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

useEffect(() => {
try {
const channel = pusher.subscribe('sparks');
Expand All @@ -72,12 +74,13 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:
// Handle new message received from Pusher

// Update the state with the new message if the sender ID and reciever ID match
console.log("MESSAGE DATA: ", data)

setGlobalMessages((prevGlobalMessages: any) => [...prevGlobalMessages, data]);

if(data.sender === userID && data.receiver === receiver || data.sender === receiver && data.receiver === userID)
{
setRead(false);

setMessages((prevMessages) => [...prevMessages, data]);
const newArr = [...messages, data]
console.log("New Message", newArr)
Expand All @@ -91,6 +94,8 @@ 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)
Expand All @@ -111,7 +116,7 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:
} catch (error) {
console.error(error);
}
}, [chatMessages, setMessages]);
}, [chatMessages, setMessages, readMessages, setReadMessages, loading, setLoading]);

useEffect ( ()=> {

Expand All @@ -136,7 +141,9 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:
}, [read])

useEffect( ()=> {


//Check To See If Chat Was Read Already
if(messages.length > 0)
{
const lastMessage = messages[messages.length - 1]
Expand All @@ -148,6 +155,7 @@ const Chat = ({chatPicture, chatName, chatMessages, userID, receiver , isRead}:

}

//Load Chat Image
const loadChatImage = async ()=> {
let imgResult = "/assets/profile.svg"

Expand Down
Loading

0 comments on commit 916014a

Please sign in to comment.