Skip to content

Commit

Permalink
New Post Notfication
Browse files Browse the repository at this point in the history
  • Loading branch information
max.tyson committed Jun 17, 2024
1 parent b81f1ed commit abb029f
Show file tree
Hide file tree
Showing 5 changed files with 130 additions and 32 deletions.
9 changes: 8 additions & 1 deletion website/src/pages/api/user/follow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -96,13 +96,20 @@ export default async function handler(
query = `SELECT * FROM follows WHERE ${tables.follower_id} = ${userId} AND ${tables.following_id} = ${id}`
break;

case "list":
case "listFollowing":

if(!await checkApiPermissions(request, response, session, client, makeQuery, "api:user:follow:list")) return response.status(401).json({error: "Not Authorized"})

query = `SELECT ${tables.following_id} FROM follows WHERE ${tables.follower_id} = ${userId}`
break;

case "listFollowers":

if(!await checkApiPermissions(request, response, session, client, makeQuery, "api:user:follow:list")) return response.status(401).json({error: "Not Authorized"})

query = `SELECT ${tables.follower_id} FROM follows WHERE ${tables.following_id} = ${userId}`
break;

default:
return response.status(400).json({error: 'Invalid operation'});

Expand Down
96 changes: 79 additions & 17 deletions website/src/pages/api/user/notifications.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,32 +22,92 @@ export default async function handler(
const tables = getTables();

// Get the variables
let {
operation,
user_ids,
message_ids,
title,
body,
image,
status,
} = request.query;


// Check if the user is permitted to access the API
// const session = await getServerSession(request, response, authOptions)
// const permission = await checkApiPermissions(request, response, session, client, makeQuery, "api:user:new:access")
// if(!permission) return response.status(401).json({error: "Not Authorized"})

try {
let axiosConfig;

try {

const axiosConfig = {
method: 'post',
url: 'https://api.knock.app/v1/workflows/test/trigger',
data: {
recipients: ["10"],
data: {
title: "Test Notification",
body: "This is a test notification",
image: "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg"
}
},
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.KNOCK_API_KEY_SECRET}`
}
};
switch (operation) {
case "send_notification":

if(!user_ids || !title || !body )
return response.status(400).json({ error: 'Missing variables, must have user_ids, title and body', user_ids, title, body });



// Make user_ids an array if it is not
if(!Array.isArray(user_ids))
user_ids = [user_ids];

axiosConfig = {
method: 'post',
url: 'https://api.knock.app/v1/workflows/test/trigger',
data: {
recipients: user_ids,
data: {
title: title,
body: body,
image: image ? image : "https://rongoa.maxtyson.net/media/images/logo.svg"
}
},
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.KNOCK_API_KEY_SECRET}`
}
};

break;

case "update_status":
if(!user_ids || !message_ids)
return response.status(400).json({ error: 'Missing variables, must have user_ids and message_ids', user_ids, message_ids });

// Make user_ids an array if it is not
if(!Array.isArray(user_ids))
user_ids = [user_ids];

// Make message_ids an array if it is not
if(!Array.isArray(message_ids))
message_ids = [message_ids];

axiosConfig = {
method: 'post',
url: 'https://api.knock.app/v1/workflows/test/trigger',
data: {
recipients: user_ids,
data: {
title: title,
body: body,
image: image ? image : "https://rongoa.maxtyson.net/media/images/logo.svg"
}
},
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.KNOCK_API_KEY_SECRET}`
}
};

break;


default:
return response.status(400).json({ error: 'Invalid operation', operation });
}

const d = await axios.request(axiosConfig);
console.log(d.data);
Expand All @@ -56,6 +116,8 @@ export default async function handler(





} catch (error) {

// If there is an error, return the error
Expand Down
2 changes: 1 addition & 1 deletion website/src/pages/media/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ export default function Home(){
const fetchData = async () => {

// Fetch who the user is following
const following = await makeRequestWithToken("get", "/api/user/follow?operation=list")
const following = await makeRequestWithToken("get", "/api/user/follow?operation=listFollowing")

// No stories
if(following.data.data.length === 0) {
Expand Down
29 changes: 27 additions & 2 deletions website/src/pages/media/new.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import {getNamesInPreference, macronCodeToChar, numberDictionary} from "@/lib/pl
import {Loading} from "@/components/loading";
import {useSession} from "next-auth/react";
import {RongoaUser} from "@/lib/users";
import {cleanInput} from "@/lib/data";
import {cleanInput, getFilePath} from "@/lib/data";


export default function Post(){
Expand All @@ -23,6 +23,7 @@ export default function Post(){

const [plantNames, setPlantNames] = useState<string[]>(["Loading..."]);
const [plantIDs, setPlantIDs] = useState<string[]>([""]);
const [userIDs, setUserIDs] = useState<string[]>([]);

const [image, setImage] = useState<File | null>(null);
const [imageURL, setImageURL] = useState<string>("");
Expand All @@ -46,9 +47,29 @@ export default function Post(){

useEffect(() => {
if(session?.user == null) return;
setUserID((session.user as RongoaUser).database.id);

const id = (session.user as RongoaUser).database.id;

setUserID(id);
followersFetch(id);




}, [session]);

const followersFetch = async (id: number) => {

const followers = await makeRequestWithToken('get', '/api/user/follow?operation=listFollowers&id=' + id);
const ids = followers.data.data

let previousIDs = []
for (let i = 0; i < ids.length; i++) {
previousIDs.push(ids[i].follower_id)
}
setUserIDs(previousIDs)
}

const fetchData = async () => {

// Get the plants
Expand Down Expand Up @@ -143,6 +164,10 @@ export default function Post(){
}


// Send the notification to the followers
setLoading("Sending Notifications...")
const response2 = await makeRequestWithToken('post', '/api/user/notifications?operation=send_notification&user_ids=' + userIDs + '&title=New Post&body=' + (session?.user as RongoaUser).name + ' has made a new post&image=' + getFilePath(userID, newId, plant_image));

setLoading("")

// Redirect to the post
Expand Down
26 changes: 15 additions & 11 deletions website/src/pages/media/notifications.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ export default function Page(){

const fetchNotifications = async (knockClient: Knock) => {
const messages = await knockClient.users.getMessages("10");
console.log(messages)
return messages
}

Expand Down Expand Up @@ -84,17 +85,20 @@ export default function Page(){
<div className={styles.notifications}>
{notifications.length === 0 && <h1>No notifications</h1>}
{notifications.map((notification, index) => {
return(
<Notification
key={index}
title={notification.data.title}
body={notification.data.body}
image={notification.data.image}
clear={() => {
setNotifications(notifications.filter((_, i) => i !== index))
}}
/>
)
{
return(
<Notification
key={index}
title={notification.data.title}
body={notification.data.body}
image={notification.data.image}
clear={() => {
setNotifications(notifications.filter((_, i) => i !== index))
}}
/>
)
}

})}
</div>

Expand Down

0 comments on commit abb029f

Please sign in to comment.