Skip to content

Commit

Permalink
finished acivity alerts
Browse files Browse the repository at this point in the history
  • Loading branch information
tomyRomero committed Dec 11, 2023
1 parent 976d7ea commit 45f7b93
Show file tree
Hide file tree
Showing 7 changed files with 102 additions and 19 deletions.
2 changes: 0 additions & 2 deletions app/(root)/activity/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,6 @@ async function Page() {
}
}

console.log("Activity: ", activity)

return (
<>
<h1 className='head-text text-black'>Notifications</h1>
Expand Down
45 changes: 39 additions & 6 deletions components/shared/Activity.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
"use client"

import React from 'react'
import Image from 'next/image'
import Link from 'next/link'
import Image from 'next/image'
import { useRouter } from 'next/navigation'
import { getImageData } from '@/lib/s3'
import { useEffect, useState } from 'react'
import { fetchUser } from '@/lib/actions/user.actions'
import { fetchPostById } from '@/lib/actions/post.actions'
import { fetchPostById, updatePostReadStatus } from '@/lib/actions/post.actions'
import { useAppContext } from '@/lib/AppContext'

interface Props {
parentid: string
Expand All @@ -26,6 +27,10 @@ interface 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('')
const [loading, setLoading] = useState(false);
const router = useRouter();

const {readActivity, setReadActivity} = useAppContext();

const filterLikes = () => {
// Remove trailing comma and split the string by commas
Expand Down Expand Up @@ -90,7 +95,6 @@ const Activity = ({idpost, authorUsername, authorImage, activityKey, parentid, t

let imgResult = '/assets/profile.svg';

console.log("Client Author Image:", loadImg)
if (loadImg.startsWith('user')) {
const res = await getImageData(loadImg);
imgResult = res;
Expand Down Expand Up @@ -121,10 +125,27 @@ const Activity = ({idpost, authorUsername, authorImage, activityKey, parentid, t
}
, [])

const goToActivity = async (event: React.MouseEvent<HTMLAnchorElement>) => {
setLoading(true)
event.preventDefault();
const clearActivity = await updatePostReadStatus(idpost)

if(clearActivity)
{
router.push(`/post/${parentid? parentid: idpost}`)
setReadActivity(!readActivity)
}else{
alert("Something happened and the Notifaction was Deleted")
}
}
useEffect (()=> {
router.refresh()
},[readActivity, setReadActivity] )

return (
<>
<Link key={activityKey} href={`/post/${parentid? parentid: idpost}`}>
<article className='activity-card hover:bg-cyan-500'>
<Link key={activityKey} href={`/post/${parentid? parentid: idpost}`} onClick= {goToActivity}>
<article className={`activity-card hover:bg-cyan-500 ${ loading ? "hidden" : ""}`}>
<Image
src={img}
alt='user_logo'
Expand Down Expand Up @@ -169,7 +190,19 @@ const Activity = ({idpost, authorUsername, authorImage, activityKey, parentid, t
height={20}
/>
)}

</article>


<article className={`activity-card hover:bg-cyan-500 ${ loading ? "" : "hidden"}`}>
<Image
src={"/assets/postloader.svg"}
alt={"loading animation"}
width={40}
height={20}
/>
</article>

</Link>
</>
)
Expand Down
25 changes: 22 additions & 3 deletions components/shared/LeftBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import Image from "next/image";
import { usePathname, useRouter } from 'next/navigation'
import { SignOutButton, SignedIn, currentUser } from "@clerk/nextjs";
import { useEffect, useState } from "react";
import { fetchUser, doesPostBelongToUser } from "@/lib/actions/user.actions";
import { fetchUser, doesPostBelongToUser, fetchLikesAndCommentsByUser } from "@/lib/actions/user.actions";
import { getImageData } from "@/lib/s3";
import { getChatBySenderAndReceiver, getChatsWithUsersByUserId } from "@/lib/actions/chat.actions";
import pusherClient from "@/lib/pusher";
Expand All @@ -19,7 +19,7 @@ function LeftSidebar({user} : any)
const [noti, setNoti] = useState(false);
const [activity, setActivity] = useState(false);

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

const router = useRouter();
const pathname = usePathname();
Expand Down Expand Up @@ -70,6 +70,22 @@ function LeftSidebar({user} : any)
}
};

const getAcivityAtStartUp = async () => {
const activity = await fetchLikesAndCommentsByUser(user.id, 5);

console.log("Left Bar Activity: ", activity)

// Check if any Activity has read_status === 1
const hasUnreadPost = activity.some(activity => activity.read_status === 1);

if(hasUnreadPost)
{
setActivity(true)
}else{
setActivity(false)
}
}

useEffect( ()=> {
try {
//Look for realtime events on new notifactions from activity
Expand Down Expand Up @@ -127,7 +143,7 @@ function LeftSidebar({user} : any)
console.log("Error" , error)
}
}

load();

}, [])
Expand All @@ -136,6 +152,9 @@ function LeftSidebar({user} : any)
getNoti();
}, [noti]);

useEffect(()=> {
getAcivityAtStartUp();
}, [readActivity, setReadActivity])

useEffect(()=> {
try {
Expand Down
11 changes: 10 additions & 1 deletion lib/AppContext.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,9 @@ type AppContextProps = {

newLike: any;
setNewLike: React.Dispatch<React.SetStateAction<any>>;

readActivity: any;
setReadActivity: React.Dispatch<React.SetStateAction<any>>;
};

// Create the AppContext with an initial value of undefined
Expand All @@ -48,11 +51,16 @@ export const AppProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
//For when there is a new like activate all listening components
const [newLike, setNewLike] = useState(false);

//For when an acitivty notifcation has been read
const [readActivity, setReadActivity] = useState(false)


//Client Pusher Instance Logic
const pusher = pusherClient;
const [pusherChannel, setPusherChannel] = useState(pusher.subscribe('sparks'));

//If User Is inActvie for more than 15 mins, close the connection to Pusher

// Set the timeout duration in milliseconds (e.g., 15 minutes)
const timeoutDuration = 15 * 60 * 1000; // 15 minutes

Expand Down Expand Up @@ -84,7 +92,8 @@ export const AppProvider: React.FC<{ children: ReactNode }> = ({ children }) =>
setPusherChannel,
newComment,
setNewComment,
newLike, setNewLike
newLike, setNewLike,
setReadActivity, readActivity
};

// Set up event listeners for user activity (adjust as needed based on your application)
Expand Down
11 changes: 5 additions & 6 deletions lib/actions/chat.actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@ export const getPusher = async()=> {
}



export const sendMessage = async (text: string, sender: string, timestamp: string, receiver: string, messages: any[], pathname: string) => {
try {

// Use a parameterized query to select a chat by sender and receiver IDs
const connection = connectDb('spark');
// Use a parameterized query to select a chat by sender and receiver IDs
const queryAsync = util.promisify(connection.query).bind(connection);

const query = 'SELECT * FROM chat WHERE sender_id = ? AND receiver_id = ?';
Expand Down Expand Up @@ -75,9 +75,9 @@ export const getPusher = async()=> {

export const updateChatForOther = async ( sender: string, receiver: string, messages: any[], pathname: string) => {
try{
const connection = connectDb('spark');
console.log("OTHER USER PROCESSING")
// Use a parameterized query to select a chat by sender and receiver IDs
const connection = connectDb('spark');
const queryAsync = util.promisify(connection.query).bind(connection);

const query = 'SELECT * FROM chat WHERE sender_id = ? AND receiver_id = ?';
Expand Down Expand Up @@ -117,8 +117,8 @@ export const getPusher = async()=> {
//Get Chats that belong to the User who is the Sender
export const getChatsWithUsersByUserId = async (userId: string) => {
try {
// Use a parameterized query to select chats with user information
const connection = connectDb('spark');
// Use a parameterized query to select chats with user information
const queryAsync = util.promisify(connection.query).bind(connection);

const query = `
Expand Down Expand Up @@ -151,8 +151,8 @@ export const getPusher = async()=> {
//Get Chat that fills the reciever UI chat
export const getChatBySenderAndReceiver = async (senderId: string, receiverId: string) => {
try {
// Use a parameterized query to select a chat by both sender and receiver IDs
const connection = connectDb('spark');
// Use a parameterized query to select a chat by both sender and receiver IDs
const queryAsync = util.promisify(connection.query).bind(connection);

const query = `
Expand Down Expand Up @@ -187,7 +187,6 @@ export const getPusher = async()=> {
export const markChatAsRead = async (sender: string, receiver: string, messages: any[], pathname: string) => {
try {
console.log('Updating Chat with Read...');

const connection = connectDb('spark');
const queryAsync = util.promisify(connection.query).bind(connection);

Expand Down
25 changes: 25 additions & 0 deletions lib/actions/post.actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,31 @@ export const deletePost = async (postId: string, path: string, parent_id: string
}
};

export const updatePostReadStatus = async (postId: string): Promise<boolean> => {
try {
const connection = connectDb('spark'); // Replace 'spark' with your database name
const queryAsync = util.promisify(connection.query).bind(connection);

// Update post's read_status to 1
const updateQuery = 'UPDATE post SET read_status = null WHERE idpost = ?';

//@ts-ignore
const updateResult: any[] = await queryAsync(updateQuery, [postId]);

console.log("Read_status Update: ", updateResult)

// Close the database connection
connection.end();

return true
} catch (error) {
console.log('Error:', error);
throw new Error('Unable to update post read status');
}
};






Expand Down
2 changes: 1 addition & 1 deletion lib/s3.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export const getImageData = async (key: string) => {
const getResponseData = await getResponse.json();
const match = key.match(/[^.]+$/);
const result = match ? match[0] : 'jpg';
console.log("RESULT IMAGE TYPE:", result)

let base64 = `data:image/${result};base64,` + getResponseData;
return base64;

Expand Down

0 comments on commit 45f7b93

Please sign in to comment.