Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
SuperMitic committed Dec 11, 2024
1 parent da1f474 commit 00fcaa5
Show file tree
Hide file tree
Showing 8 changed files with 35 additions and 173 deletions.
7 changes: 1 addition & 6 deletions client/app/(app)/settings/page.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
"use server";
import Content from "@/components/settings/content";
import {
getNotificationStatus,
} from "@/actions/auth.action";
import { getNotificationStatus } from "@/actions/auth.action";
import { getUser, isAdmin } from "@/actions/user";
import { getEvents, getResource } from "@/actions/events";

Expand All @@ -19,9 +17,6 @@ const Page = async () => {
if (user instanceof Error) {
throw user.message;
}
// console.log("miao", user);
// console.log("events page", events);
// console.log("risorse", resource);

return (
<Content
Expand Down
46 changes: 10 additions & 36 deletions client/components/auth/NotificationSettings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,9 @@ export default function NotificationSettings() {

useEffect(() => {
if ("serviceWorker" in navigator && "PushManager" in window) {
navigator.serviceWorker
.register("/service-worker.js")
.then((registration) => {
console.log(
"Service Worker registered with scope:",
registration.scope,
);
})
.catch((error) => {
console.error("Service Worker registration failed:", error);
});
navigator.serviceWorker.register("/service-worker.js").catch((error) => {
console.error("Service Worker registration failed:", error);
});
}
}, []);

Expand Down Expand Up @@ -125,7 +117,7 @@ export default function NotificationSettings() {
setSubscriptionStatus("Unsubscribed successfully!");
setSelectedDevice(null);
const updatedDevices = allDevices.filter(
(device) => device !== selectedDevice,
(device) => device !== selectedDevice
);
setAllDevices(updatedDevices);
} else {
Expand Down Expand Up @@ -154,29 +146,6 @@ export default function NotificationSettings() {
}
};

const sendClientSideNotification = () => {
if (!("Notification" in window)) {
alert("This browser does not support desktop notification");
return;
}

if (Notification.permission === "granted") {
new Notification("Test Notification", {
body: "This is a test notification from the client side!",
icon: "/path/to/icon.png", // Sostituisci con il percorso della tua icona
});
} else if (Notification.permission !== "denied") {
Notification.requestPermission().then((permission) => {
if (permission === "granted") {
new Notification("Test Notification", {
body: "This is a test notification from the client side!",
icon: "/path/to/icon.png", // Sostituisci con il percorso della tua icona
});
}
});
}
};

return (
<div>
<h2 className="text-md mb-3">Aggiungi dispositivo Push</h2>
Expand Down Expand Up @@ -238,7 +207,12 @@ export default function NotificationSettings() {
</div>

<p
className={`mt-3 ${subscriptionStatus.includes("successfully") || subscriptionStatus.includes("Updated") ? "text-success" : "text-danger"}`}
className={`mt-3 ${
subscriptionStatus.includes("successfully") ||
subscriptionStatus.includes("Updated")
? "text-success"
: "text-danger"
}`}
>
{subscriptionStatus}
</p>
Expand Down
26 changes: 14 additions & 12 deletions client/components/maps/MapComponent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,9 @@ import {
Popup,
useMap,
useMapEvents,
CircleMarker,
} from "react-leaflet";
import "leaflet/dist/leaflet.css";
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css"; // Re-uses images from ~leaflet package
import "leaflet-defaulticon-compatibility/dist/leaflet-defaulticon-compatibility.webpack.css";
import * as L from "leaflet";
import "leaflet-defaulticon-compatibility";

Expand Down Expand Up @@ -45,16 +44,20 @@ const LocateControl = ({
toast(
<div className="bg-white dark:bg-gray-900 border border-gray-200 dark:border-gray-700 rounded-lg shadow-lg">
<div className="p-4">
<h4 className="font-semibold text-gray-900 dark:text-white">{"📍 No permission"}</h4>
<p className="text-sm text-red-400 dark:text-red-600">{"You have to allow GPS permission in your browser"}</p>
<h4 className="font-semibold text-gray-900 dark:text-white">
{"📍 No permission"}
</h4>
<p className="text-sm text-red-400 dark:text-red-600">
{"You have to allow GPS permission in your browser"}
</p>
</div>
</div>,
{
duration: 5000 ,
position: 'top-right',
duration: 5000,
position: "top-right",
}
);
}
},
});
return (
<div className="leaflet-top leaflet-right">
Expand All @@ -64,7 +67,7 @@ const LocateControl = ({
title="Centra sulla mia posizione"
onClick={(e) => {
e.preventDefault();

map.locate();
}}
className="inline-flex items-center justify-center w-10 h-10 bg-white text-black"
Expand Down Expand Up @@ -153,7 +156,9 @@ const MapComponent: React.FC<MapComponentProps> = ({
active:scale-95"
onClick={() => {
navigator.clipboard.writeText(
`${userLocation[0].toFixed(6)}, ${userLocation[1].toFixed(6)}`,
`${userLocation[0].toFixed(6)}, ${userLocation[1].toFixed(
6
)}`
);
}}
>
Expand Down Expand Up @@ -243,9 +248,6 @@ const MapComponent: React.FC<MapComponentProps> = ({
<h3 className="font-bold text-lg text-blue-900 dark:text-blue-100">
{friend.name}
</h3>
<div className="text-sm text-gray-600 dark:text-gray-300 mt-1">
Ultimo aggiornamento: {/* ADD last GPS update in db */}
</div>
<button
className="mt-3 px-4 py-1.5 bg-blue-600 hover:bg-blue-800
text-white rounded-full text-sm font-medium
Expand Down
27 changes: 9 additions & 18 deletions client/components/navbar/notifications-dropdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ export const NotificationsDropdown = () => {
setNotifications(data);
} catch (err) {
setError(
err instanceof Error ? err.message : "Error fetching notifications",
err instanceof Error ? err.message : "Error fetching notifications"
);
} finally {
setIsLoading(false);
Expand All @@ -52,17 +52,8 @@ export const NotificationsDropdown = () => {

const fetchID = async () => {
try {
/*const response = await fetch("/api/users/id", {
method: "GET",
credentials: "include",
});
if (!response.ok) {
throw new Error("Failed to fetch user ID");
}*/

const user = await getUser();
return user; // Ritorna l'utente
return user;
} catch (err) {
setError(err instanceof Error ? err.message : "Error fetching user ID");
throw err; // Rilancia l'errore per gestirlo in initializeSocket
Expand Down Expand Up @@ -113,9 +104,9 @@ export const NotificationsDropdown = () => {
{
duration: 5000,
position: "top-right",
},
}
);
},
}
);

// Gestione errori di connessione
Expand All @@ -126,15 +117,14 @@ export const NotificationsDropdown = () => {
} catch (error) {
console.error("Error initializing socket:", error);
setError(
error instanceof Error ? error.message : "Error initializing socket",
error instanceof Error ? error.message : "Error initializing socket"
);
} finally {
setIsLoading(false);
}
};

// Fetch le notifiche iniziali
// Avvia l'inizializzazione
initializeSocket();

// Cleanup
Expand Down Expand Up @@ -162,7 +152,7 @@ export const NotificationsDropdown = () => {
setNotifications([]); // Aggiorna lo stato locale dopo la cancellazione
} catch (err) {
setError(
err instanceof Error ? err.message : "Error clearing notifications",
err instanceof Error ? err.message : "Error clearing notifications"
);
}
};
Expand All @@ -179,11 +169,11 @@ export const NotificationsDropdown = () => {
}

setNotifications((prev) =>
prev.filter((n) => n._id !== notification._id),
prev.filter((n) => n._id !== notification._id)
);
} catch (err) {
setError(
err instanceof Error ? err.message : "Error deleting notification",
err instanceof Error ? err.message : "Error deleting notification"
);
}
};
Expand Down Expand Up @@ -258,6 +248,7 @@ export const NotificationsDropdown = () => {
<DropdownItem
key={index}
className="px-2 py-2"
textValue={notification.title}
onClick={(e) => {
e.preventDefault();
window.location.href = notification.link;
Expand Down
2 changes: 0 additions & 2 deletions client/public/service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ self.addEventListener("push", function (event) {

const notificationPromise = self.registration.showNotification(data.title, {
body: data.body,
//icon: "/icon.png",
//badge: "/badge.png",
data: { url: data.data.url },
actions: [
{
Expand Down
76 changes: 0 additions & 76 deletions server/src/notifications.js

This file was deleted.

14 changes: 0 additions & 14 deletions server/src/routes/time.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,6 @@ function createTimeRouter(db) {
const router = express.Router();

router.post("/time", cookieJwtAuth, function (req, res, next) {
// TODO: Remove this
/*if (req.user.role !== "admin") {
return res
.status(403)
.json({ message: "You are not authorized to change the time" });
}*/

if (!req.body.date) {
return res.status(400).json({ message: "Time required" });
}
Expand All @@ -28,13 +21,6 @@ function createTimeRouter(db) {
});

router.delete("/time", cookieJwtAuth, function (req, res, next) {
// TODO: Remove this
/*if (req.user.role !== "admin") {
return res
.status(403)
.json({ message: "You are not authorized to change the time" });
}*/

try {
db.changeDateTime(null, true);
console.log("Time has been reset to real time");
Expand Down
10 changes: 1 addition & 9 deletions server/src/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,13 +52,6 @@ export function createWebSocket(io, database, sendNotification) {
// Salva il socket ID dell'utente
notificationSockets.set(userId, socket.id);

// Invia una notifica di benvenuto
/*socket.emit("new_notification", {
title: "🔔 Notifiche attive",
body: "Riceverai qui le tue notifiche",
timestamp: new Date(),
});*/

console.log(`User ${userId} joined notification system< successfully`);
} catch (error) {
console.error("Error in notification join handler:", error);
Expand Down Expand Up @@ -256,8 +249,7 @@ export async function emitNotification(userId, notification) {
}

try {
//console.log("Trying to emit notification to user", userId, notification);
// Invia la notifica alla room personale dell'utente
// Invia la notifica all'utente
ioInstance.to(userId).emit("new_notification", notification);
console.log(`Notification emitted to user ${userId}`);
return true;
Expand Down

0 comments on commit 00fcaa5

Please sign in to comment.