Skip to content

Commit

Permalink
Merge pull request #32 from marconicivitavecchia/dev
Browse files Browse the repository at this point in the history
Add backend code
  • Loading branch information
DavidePiccione authored Nov 28, 2023
2 parents 4af150e + e8e6943 commit d762fa6
Show file tree
Hide file tree
Showing 6 changed files with 596 additions and 20 deletions.
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
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

0 comments on commit d762fa6

Please sign in to comment.