implemented our own quotes DB via a json object

This commit is contained in:
Sura Hanna 2024-10-16 17:45:47 -04:00
parent 16b2379df0
commit 319f83afaf
6 changed files with 306 additions and 67 deletions

View File

@ -127,28 +127,38 @@ function updateFontSize(elementId) {
// Function to fetch and display a quote // Function to fetch and display a quote
async function fetchAndDisplayQuote() { async function fetchAndDisplayQuote() {
try { try {
const response = await fetch('http://localhost:8080/api/quotes'); // Update the endpoint if you created a new one
const response = await fetch('http://localhost:8080/api/quotes'); // or '/api/quotes/random'
if (response.ok) { if (response.ok) {
const data = await response.json(); const randomQuote = await response.json();
const quotes = data.results;
const randomIndex = Math.floor(Math.random() * quotes.length);
const randomQuote = quotes[randomIndex];
document.getElementById('quote').innerHTML = `<i>${randomQuote.content}</i>`;
updateFontSize('quote');
document.getElementById('author').innerHTML = `${randomQuote.author}`;
// Validate the received quote
if (randomQuote && randomQuote.quote && randomQuote.author) {
document.getElementById('quote').innerHTML = `<i>${randomQuote.quote}</i>`;
updateFontSize('quote');
document.getElementById('author').innerHTML = `${randomQuote.author}`;
} else {
throw new Error('Invalid quote data received');
}
} else { } else {
document.getElementById('quote').innerHTML = `<i>Wishing you an utmost wonderful day!</i>`; console.error('Server responded with status:', response.status);
updateFontSize('quote'); displayDefaultQuote();
document.getElementById('author').innerHTML = `Next-Generation Cities Institute`;
} }
} catch (error) { } catch (error) {
console.error('An error occurred:', error); console.error('An error occurred:', error);
displayDefaultQuote();
} }
} }
// Helper function to display a default quote
function displayDefaultQuote() {
document.getElementById('quote').innerHTML = `<i>Wishing you an utmost wonderful day!</i>`;
updateFontSize('quote');
document.getElementById('author').innerHTML = `Next-Generation Cities Institute`;
}
// Fetch Current Weather // Fetch Current Weather
async function fetchWeather() { async function fetchWeather() {
const response = await fetch('http://localhost:8080/api/weather'); const response = await fetch('http://localhost:8080/api/weather');
@ -258,7 +268,7 @@ setInterval(function() {
}, 600000); }, 600000);
fetchAndDisplayQuote(); fetchAndDisplayQuote();
setInterval(fetchAndDisplayQuote, 60 * 60 * 1000); setInterval(fetchAndDisplayQuote, 60 * 60 * 1000 * 24);
fetchWeather(); fetchWeather();
setInterval(fetchWeather, 5 * 60 * 1000); setInterval(fetchWeather, 5 * 60 * 1000);

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -6,7 +6,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>NGCI Daily Schedule</title> <title>NGCI Daily Schedule</title>
<script type="module" crossorigin src="/assets/index-CWJf9nUx.js"></script> <script type="module" crossorigin src="/assets/index-HtVCQZEd.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Bq7sOAzP.css"> <link rel="stylesheet" crossorigin href="/assets/index-Bq7sOAzP.css">
</head> </head>

210
quotes.json Normal file
View File

@ -0,0 +1,210 @@
[
{
"quote": "Architecture is the very mirror of life. You only have to cast your eyes on buildings to feel the presence of the past, the spirit of a place.",
"author": "I.M. Pei"
},
{
"quote": "We dont need a handful of people doing zero waste perfectly. We need millions of people doing it imperfectly.",
"author": "Anne Marie Bonneau"
},
{
"quote": "By being sweet to the pedestrian and the cyclist you hit five birds with one stone you get a lively, attractive, safe, sustainable city thats good for health.",
"author": "Jan Gehl"
},
{
"quote": "The ultimate test of mans conscience may be his willingness to sacrifice something today for future generations whose words of thanks will not be heard.",
"author": "Gaylord Nelson"
},
{
"quote": "When we destroy something created by man, we call it vandalism. When we destroy something created by nature, we call it progress.",
"author": "Ed Begley Jr."
},
{
"quote": "You cannot get through a single day without having an impact on the world around you. What you do makes a difference and you have to decide what kind of a difference you want to make.",
"author": "Jane Goodall"
},
{
"quote": "As an architect, you design for the present, with an awareness of the past, for a future which is essentially unknown.",
"author": "Norman Foster"
},
{
"quote": "Every day I wake up in Copenhagen I know the city will be a little bit better than yesterday.",
"author": "Jan Gehl"
},
{
"quote": "The architects role is to fight for a better world, where he can produce an architecture that serves everyone and not just a group of privileged people.",
"author": "Oscar Niemeyer"
},
{
"quote": "Going back to a simpler life based on living by sufficiency rather than excess is not a step backwards.",
"author": "Yvon Chouinard"
},
{
"quote": "Consume less; share better.",
"author": "Hervé Kempf"
},
{
"quote": "We never know the worth of water till the well is dry.",
"author": "Thomas Fuller"
},
{
"quote": "First life, then spaces, then buildings the other way around never works.",
"author": "Jan Gehl"
},
{
"quote": "It seems to me that the natural world is the greatest source of excitement; the greatest source of visual beauty.",
"author": "David Attenborough"
},
{
"quote": "Space and light and order. Those are the things that men need just as much as they need bread or a place to sleep.",
"author": "Le Corbusier"
},
{
"quote": "The Sun never knew how great it was until it hit the side of a building.",
"author": "Louis Kahn"
},
{
"quote": "Simplicity is the ultimate sophistication.",
"author": "Leonardo da Vinci"
},
{
"quote": "Our planets alarm is going off, and it is time to wake up and take action!",
"author": "Leonardo DiCaprio"
},
{
"quote": "An endless number of green buildings dont make a sustainable city.",
"author": "Jan Gehl"
},
{
"quote": "We are all crew on spaceship Earth.",
"author": "Marshall McLuhan"
},
{
"quote": "The best way to predict the future is to design it.",
"author": "Buckminster Fuller"
},
{
"quote": "A city is more than a place in space, it is a drama in time.",
"author": "Patrick Geddes"
},
{
"quote": "A great building must begin with the unmeasurable, must go through measurable means when it is being designed and in the end must be unmeasurable.",
"author": "Louis Kahn"
},
{
"quote": "The mother art is architecture. Without an architecture of our own we have no soul of our own civilization.",
"author": "Frank Lloyd Wright"
},
{
"quote": "Sustainability is no longer about doing less harm. Its about doing more good.",
"author": "Jochen Zeitz"
},
{
"quote": "Sustainable development is the pathway to the future we want for all.",
"author": "Ban Ki-moon"
},
{
"quote": "The greatest threat to our planet is the belief that someone else will save it.",
"author": "Robert Swan"
},
{
"quote": "The future depends on what you do today.",
"author": "Mahatma Gandhi"
},
{
"quote": "Buildings should serve people, not the other way around.",
"author": "John Portman"
},
{
"quote": "Urbanization is not an evil, but it becomes a problem when it is unplanned.",
"author": "Sheikh Hasina"
},
{
"quote": "Architecture should speak of its time and place, but yearn for timelessness.",
"author": "Frank Gehry"
},
{
"quote": "We shape our buildings; thereafter, they shape us.",
"author": "Winston Churchill"
},
{
"quote": "We cannot solve our problems with the same thinking we used when we created them.",
"author": "Albert Einstein"
},
{
"quote": "Less is more.",
"author": "Ludwig Mies van der Rohe"
},
{
"quote": "Nature is not a place to visit. It is home.",
"author": "Gary Snyder"
},
{
"quote": "The environment is where we all meet; where we all have a mutual interest; it is the one thing all of us share.",
"author": "Lady Bird Johnson"
},
{
"quote": "The first rule of sustainability is to align with natural forces.",
"author": "Paul Hawken"
},
{
"quote": "We do not inherit the earth from our ancestors, we borrow it from our children.",
"author": "Native American Proverb"
},
{
"quote": "When we build, let us think that we build forever.",
"author": "John Ruskin"
},
{
"quote": "A society grows great when old men plant trees whose shade they know they shall never sit in.",
"author": "Greek Proverb"
},
{
"quote": "In the end, our society will be defined not only by what we create, but by what we refuse to destroy.",
"author": "John Sawhill"
},
{
"quote": "What is the use of a house if you haven't got a tolerable planet to put it on?",
"author": "Henry David Thoreau"
},
{
"quote": "Sustainability is about ecology, economy, and equity.",
"author": "Ralph Bicknese"
},
{
"quote": "The Earth is what we all have in common.",
"author": "Wendell Berry"
},
{
"quote": "Adopt the pace of nature: her secret is patience.",
"author": "Ralph Waldo Emerson"
},
{
"quote": "Cities have the capability of providing something for everybody, only because they are created by everybody.",
"author": "Jane Jacobs"
},
{
"quote": "Good buildings come from good people, and all problems are solved by good design.",
"author": "Stephen Gardiner"
},
{
"quote": "Environmental pollution is an incurable disease. It can only be prevented.",
"author": "Barry Commoner"
},
{
"quote": "Our future is at stake, and we have no option but to act decisively on climate change.",
"author": "Angela Merkel"
},
{
"quote": "The future will either be green or not at all.",
"author": "Bob Brown"
},
{
"quote": "The future belongs to those who believe in the beauty of their dreams.",
"author": "Eleanor Roosevelt"
},
{
"quote": "To waste, to destroy our natural resources will result in undermining in the days of our children.",
"author": "Theodore Roosevelt"
}
]

123
server.js
View File

@ -1,3 +1,4 @@
// Import necessary modules
const express = require('express'); const express = require('express');
const http = require('http'); const http = require('http');
const fs = require('fs'); const fs = require('fs');
@ -6,72 +7,85 @@ const path = require('path');
const cors = require('cors'); const cors = require('cors');
require('dotenv').config(); require('dotenv').config();
// Import custom modules
const msGraphHelper = require('./msGraphHelper'); const msGraphHelper = require('./msGraphHelper');
const settings = require('./settings'); const settings = require('./settings');
// Set the port
const HTTP_PORT = process.env.HTTP_PORT || 8080; const HTTP_PORT = process.env.HTTP_PORT || 8080;
// Initialize Express app
const app = express(); const app = express();
const slideshowDir = './slideshow'; const slideshowDir = path.join(__dirname, 'slideshow');
app.use(express.static(path.join(__dirname, 'public')));
// Middleware configurations
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors({ app.use(cors({
origin: 'http://localhost:5173' origin: 'http://localhost:5173',
})); }));
app.use(express.json()); app.use(express.json());
app.use(express.static('public'));
// GRAPH API SECTION - USER AUTH // Initialize Microsoft Graph API for App Only Auth
//
// msGraphHelper.initializeGraphForUserAuth(settings, async (deviceCodeResponse) => {
// if (!deviceCodeResponse) {
// throw new Error("Device code response is undefined.");
// }
// console.log(deviceCodeResponse.message);
// });
//
// GRAPH API SECTION - APP ONLY AUTH
//
msGraphHelper.initializeGraphForAppOnlyAuth(settings); msGraphHelper.initializeGraphForAppOnlyAuth(settings);
// Read resource UPNs once at startup
const data = fs.readFileSync('./resourceUPNs.json', 'utf8'); const data = fs.readFileSync('./resourceUPNs.json', 'utf8');
const resourceUPNs = JSON.parse(data); const resourceUPNs = JSON.parse(data);
app.get('/api/events', async (req, res) => { // Cache quotes to avoid reading the file on every request
let quotesCache = [];
const quotesFilePath = path.join(__dirname, 'quotes.json');
fs.readFile(quotesFilePath, 'utf8', (err, data) => {
if (err) {
console.error('Error reading quotes:', err.message);
} else {
try {
const parsedData = JSON.parse(data);
if (Array.isArray(parsedData) && parsedData.length > 0) {
quotesCache = parsedData;
console.log('Quotes loaded into cache.');
} else {
console.error('Quotes file is empty or malformed.');
}
} catch (parseError) {
console.error('Error parsing quotes:', parseError.message);
}
}
});
// API endpoint to get events
app.get('/api/events', async (req, res) => {
try { try {
let now = new Date(); const now = new Date();
let startDateTime = new Date(now); const startDateTime = new Date(now);
// startDateTime.setHours(8, 0, 0, 0); const endDateTime = new Date(now);
let endDateTime = new Date(now);
endDateTime.setHours(20, 0, 0, 0); endDateTime.setHours(20, 0, 0, 0);
if (startDateTime > endDateTime) { if (startDateTime > endDateTime) {
// Exit early since there are no relevant events to display // No relevant events to display
return res.json({}); return res.json({});
} }
let events = {}; const events = {};
for (const resource of resourceUPNs) { for (const resource of resourceUPNs) {
try { try {
const data = const data = await msGraphHelper.getCalendarView(
await msGraphHelper.getCalendarView(resource, startDateTime.toISOString(), endDateTime.toISOString()); resource,
// fs.readFileSync(`./events/${resource}.json`, 'utf8'); startDateTime.toISOString(),
const resourceEvents = data; endDateTime.toISOString()
events[resource] = resourceEvents; );
// console.log(`${new Date()}: Grabbed events for ${resource}`); events[resource] = data;
} catch (error) { } catch (error) {
console.error(error); console.error(`Error fetching events for ${resource}:`, error);
} }
} }
res.json(events); res.json(events);
} catch (err) { } catch (err) {
res.status(500).json({ message: err.message }); res.status(500).json({ message: err.message });
} }
}); });
// API endpoint to get weather information
app.get('/api/weather', async (req, res) => { app.get('/api/weather', async (req, res) => {
try { try {
const lat = 45.49; const lat = 45.49;
@ -85,47 +99,52 @@ app.get('/api/weather', async (req, res) => {
const json = await response.json(); const json = await response.json();
res.json(json); res.json(json);
} else { } else {
res.status(500).json({ message: 'Error in /weather' }); res.status(500).json({ message: 'Error fetching weather data' });
} }
} catch (err) { } catch (err) {
res.status(500).json({ message: err.message }); res.status(500).json({ message: err.message });
} }
}); });
app.get('/api/quotes', async (req, res) => { // API endpoint to get a random quote
app.get('/api/quotes', (req, res) => {
try { try {
const url = `https://api.quotable.io/quotes?limit=150&tags=urban|city|technology|future` if (quotesCache.length === 0) {
const response = await fetch(url); return res.status(500).json({ message: 'No quotes available' });
if (response.ok) {
const json = await response.json();
res.json(json);
} else {
res.status(500).json({ message: 'Error in /quotes' });
} }
const randomIndex = Math.floor(Math.random() * quotesCache.length);
const randomQuote = quotesCache[randomIndex];
res.json(randomQuote); // Send only one quote
} catch (err) { } catch (err) {
res.status(500).json({ message: err.message }); res.status(500).json({ message: 'Error retrieving quote' });
} }
}); });
// Serve slideshow images
app.use('/slideshow', express.static(slideshowDir)); app.use('/slideshow', express.static(slideshowDir));
// API endpoint to get slideshow images
app.get('/api/slideshow', (req, res) => { app.get('/api/slideshow', (req, res) => {
fs.readdir(slideshowDir, (err, files) => { fs.readdir(slideshowDir, (err, files) => {
if (err) { if (err) {
console.error('Failed to list slideshow images: ', err.message); console.error('Failed to list slideshow images:', err.message);
res.status(500).json({ message: err.message }); res.status(500).json({ message: err.message });
return; return;
} else {
const imagePaths = files
.filter(file => /\.(jpg|jpeg|png|gif)$/i.test(file))
.map(file => `/slideshow/${file}`);
res.json(imagePaths);
} }
const imagePaths = files
.filter(file => /\.(jpg|jpeg|png|gif)$/i.test(file))
.map(file => `/slideshow/${file}`);
res.json(imagePaths);
}); });
}); });
// Create and start the HTTP server
const httpServer = http.createServer(app); const httpServer = http.createServer(app);
httpServer.listen(HTTP_PORT, () => console.log(`HTTP Server listening on http://localhost:${HTTP_PORT}`)); httpServer.listen(HTTP_PORT, () => {
console.log(`HTTP Server listening on http://localhost:${HTTP_PORT}`);
});