Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update Main Branch #32

Merged
merged 27 commits into from
Nov 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
c23aa85
Create documentazione
brucobruce Oct 29, 2023
e46212d
Merge branch 'marconicivitavecchia:dev' into dev
DavidePiccione Oct 29, 2023
4c20da0
Added graph of the backend logic
Splyxxx Oct 30, 2023
a0c4757
Merge branch 'marconicivitavecchia:dev' into dev
DavidePiccione Nov 11, 2023
a836343
Update index.js
Prinxino Nov 11, 2023
c4a8cfe
Updated some codes.
Prinxino Nov 11, 2023
83afdd4
Delete data.json
Prinxino Nov 11, 2023
d6720ea
Updated comments
Prinxino Nov 11, 2023
24b15dd
Adds a temporary proxy request test file
FThinker Nov 14, 2023
9aa4045
Update proxy.js
FThinker Nov 14, 2023
5e737d2
Updated comments
Prinxino Nov 15, 2023
476c2fe
Update proxy.js
Prinxino Nov 15, 2023
b7980ea
Update proxy.js
Rpinnkss Nov 15, 2023
2cf355b
Update proxy.js
Prinxino Nov 15, 2023
c05834e
Merge branch 'dev' of https://github.com/marconicivitavecchia/IFC-Bac…
Prinxino Nov 15, 2023
e45241b
Update proxy.js
Rpinnkss Nov 15, 2023
e929232
Added a loop to execute the request every second.
Kylessh Nov 15, 2023
2fc787e
Add rotating proxy in index.js
FThinker Nov 16, 2023
df9fd0c
Delete proxy.js
FThinker Nov 16, 2023
5aa29e2
Merge branch 'marconicivitavecchia:dev' into dev
FThinker Nov 17, 2023
5f129c1
Remove frontend testing changes from backend PR
DavidePiccione Nov 17, 2023
d950aba
Update mqtt.js
FThinker Nov 17, 2023
da4b168
Update README.rst
brucobruce Nov 19, 2023
677e8a9
Delete documentazione
FThinker Nov 19, 2023
b5e9836
Update README.rst
brucobruce Nov 25, 2023
e95ec71
Update README.rst
brucobruce Nov 28, 2023
e8e6943
Merge branch 'dev' into dev
DavidePiccione Nov 28, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 58 additions & 1 deletion Backend/README.rst
Original file line number Diff line number Diff line change
@@ -1 +1,58 @@
This code uses an Instagram API to acquire the number of followers from a specified user, then sends the data to an MQTT broker which passes it to an ESP-32 chip.
Documentazione del File Documentazione del File =======================
Questo file contiene il codice per un'applicazione Node.js basata su Express, che periodicamente recupera il numero di follower da un profilo Instagram specificato, pubblica il conteggio attraverso MQTT e fornisce l'informazione al frontend tramite un'API REST.
Struttura del File ------------------
Il file è diviso in due parti principali: la parte che gestisce le richieste Instagram e l'altra che gestisce le operazioni MQTT.
### Gestione Richieste Instagram #### Dipendenze -
`express`: framework per gestire le richieste HTTP -
`cors`: middleware per abilitare la condivisione di risorse tra origini diverse -
`path`: modulo per gestire i percorsi dei file -
`https`: modulo per effettuare richieste HTTPS -
`mqttClient`: modulo personalizzato per la gestione del protocollo MQTT -
`HttpsProxyAgent`: agente per gestire le richieste attraverso un proxy #### Variabili di Configurazione -
`proxyOptions`: URL del proxy (da configurare) #### Configurazione Express -
Inizializzazione dell'app Express e definizione della porta -
Abilitazione CORS per tutte le route - Servizio dei file statici dalla directory 'Frontend' ####
Configurazione Richiesta Instagram -
Definizione del nome utente Instagram da cui recuperare il conteggio dei follower -
Opzioni di richiesta per ottenere le informazioni del profilo Instagram
- Variabili per il conteggio dei follower e il conteggio precedente -
Funzione `fetchFollowerCount` per ottenere e pubblicare il conteggio dei follower tramite MQTT
- Chiamata periodica della funzione ogni 2 secondi tramite `setInterval` #
### Route Express - Una route `/getFollowerCount` per fornire il conteggio dei follower al frontend #### Avvio del Server Express - Avvio del server Express sulla porta specificata ### Gestione MQTT #### Dipendenze -
`mqtt`: modulo per la comunicazione MQTT #### Configurazione Connessione MQTT -
Parametri di connessione, come protocollo, host, porta, ID cliente, ecc.
- Creazione di un'istanza client MQTT e connessione al broker #### Eventi MQTT
- Gestione degli eventi `connect` e `message` per la connessione al broker e la ricezione di messaggi
#### Funzione di Pubblicazione MQTT - Funzione `publishMessage` per pubblicare un messaggio sul broker MQTT #### Esportazione della Funzione MQTT - Esportazione della funzione `publishMessage` per l'utilizzo esterno Utilizzo -------- 1. Configurare l'URL del proxy nella variabile `proxyOptions`. 2. Assicurarsi che le dipendenze siano installate eseguendo `npm install`. 3. Avviare l'applicazione eseguendo `node `. L'applicazione periodicamente recupera il conteggio dei follower da Instagram, lo pubblica tramite MQTT e fornisce l'informazione al frontend attraverso l'API REST.
La risposta JSON viene analizzata, e se il conteggio è cambiato rispetto al vecchio valore, viene pubblicato tramite MQTT.

Intervallo di richiesta dei follower: La funzione per ottenere il conteggio dei follower viene chiamata ogni 10 secondi.

Route per ottenere il conteggio dei follower: Viene definita una route che restituisce il conteggio dei follower .

Avvio del server: Il server Express viene avviato sulla porta specificata
Gestione MQTT

Dipendenze
- `mqtt`: modulo per la comunicazione MQTT

Configurazione Connessione MQTT
- Parametri di connessione, come protocollo, host, porta, ID cliente, ecc.
- Creazione di un'istanza client MQTT e connessione al broker

Eventi MQTT
- Gestione degli eventi `connect` e `message` per la connessione al broker e la ricezione di messaggi

Funzione di Pubblicazione MQTT
- Funzione `publishMessage` per pubblicare un messaggio sul broker MQTT

Esportazione della Funzione MQTT
- Esportazione della funzione `publishMessage` per l'utilizzo esterno

Utilizzo

1. Configurare l'URL del proxy nella variabile `proxyOptions`.
2. Assicurarsi che le dipendenze siano installate eseguendo `npm install`.
3. Avviare l'applicazione eseguendo `node <nome_file>`.

L'applicazione periodicamente recupera il conteggio dei follower da Instagram, lo pubblica tramite MQTT e fornisce l'informazione al frontend attraverso l'API REST.
Binary file added Backend/Schema Backend.PNG
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
38 changes: 26 additions & 12 deletions Backend/index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,32 @@
// Import required modules
const express = require('express');
const path = require('path');
const https = require('https');
const mqttClient = require('./mqtt');
const express = require('express'); // Express framework for handling HTTP requests
const cors = require('cors'); // CORS middleware for enabling cross-origin resource sharing
const path = require('path'); // Path module for handling file paths
const https = require('https'); // HTTPS module for making secure requests
const mqttClient = require('./mqtt'); // Custom MQTT client module
const { HttpsProxyAgent } = require('https-proxy-agent');

const proxyOptions = ''; // Your Proxy URL goes here

// Create an Express application
const app = express();
const port = process.env.PORT || 3000;
const port = process.env.PORT || 5500; // Use the port defined by the environment variable, defaulting to 5500

// Enable CORS for all routes
app.use(cors());

// Serve static files (CSS, images, etc.) from a public directory
app.use(express.static(path.join(__dirname, 'public')));
// Serve static files (CSS, images, etc.) from a frontend directory
app.use(express.static(path.join(__dirname, 'Frontend')));

// Define the Instagram username to fetch follower count for
const username = "iismarconicivitavecchia";

// Define the request options
// Define the request options for fetching Instagram profile information
const options = {
hostname: 'i.instagram.com',
path: `/api/v1/users/web_profile_info/?username=${username}`,
method: 'GET',
agent: new HttpsProxyAgent(proxyOptions),
headers: {
'User-Agent': 'Instagram 76.0.0.15.395 Android (24/7.0; 640dpi; 1440x2560; samsung; SM-G930F; herolte; samsungexynos8890; en_US; 138226743)'
}
Expand All @@ -28,18 +36,22 @@ const options = {
let oldFollowerCount = 0;
let output;

// Function to fetch the follower count
// Function to fetch the follower count from Instagram
function fetchFollowerCount() {
const req = https.get(options, (res) => {
let data = '';

// Accumulate data as it is received
res.on('data', (chunk) => {
data += chunk;
});

// Process the complete response
res.on('end', () => {
try {
// Parse the JSON response from Instagram
const jsonData = JSON.parse(data);

if (jsonData.data.user) {
// Extract the follower count from the JSON response
const followerCount = jsonData.data.user.edge_followed_by.count;
Expand All @@ -63,22 +75,24 @@ function fetchFollowerCount() {
});
});

// Handle errors in the HTTPS request
req.on('error', (error) => {
console.error(error);
});

// Complete the request
req.end();
}

// Call fetchFollowerCount every 10 seconds
setInterval(fetchFollowerCount, 10000);
// Call fetchFollowerCount every 2 seconds using setInterval
setInterval(fetchFollowerCount, 2000);

// Define a route to send the follower count to the front end
app.get('/getFollowerCount', (req, res) => {
res.json({ followerCount: output || 'Loading...' });
});

// Start the Express server
// Start the Express server and listen on the specified port
app.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
14 changes: 7 additions & 7 deletions Backend/mqtt.js
DavidePiccione marked this conversation as resolved.
Show resolved Hide resolved
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@marconicivitavecchia/backend dovreste risolvere anche questa issue prima di fare il merge:
marconicivitavecchia#4 (comment)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ const connectUrl = `${protocol}://${host}:${port}`;

// Create an MQTT client instance and connect to the broker
const client = mqtt.connect(connectUrl, {
clientId,
clean: true,
connectTimeout: 4000,
username: 'emqx',
password: 'public',
reconnectPeriod: 1000,
clientId, // Unique client ID for the MQTT connection
clean: true, // Clean session flag, ensuring no previous session data is used
connectTimeout: 4000, // Timeout for the connection attempt
username: 'emqx', // MQTT broker username
password: 'public', // MQTT broker password
reconnectPeriod: 1000, // Period to attempt reconnection if the connection is lost
});

// Define the topic to subscribe to
const topic = 'IFC-Backend/1';
const topic = '';

// Event handler when the client is successfully connected to the broker
client.on('connect', () => {
Expand Down
Loading