Sure! Below is a Rust program that reads the patch3.txt file, parses the filenames (ignoring lines that start with //), downloads each file via FTP from ftp://fpatch.levelupgames.com.br/patch/, saves them to a local folder called update, and outputs progress information in JSON format. This progress information includes currentFile, totalFiles, fileName, downloadedBytes, and totalBytes, which you can consume in your React application to update the UI.
First, ensure that you have the following dependencies in your Cargo.toml:
[dependencies]
ftp = "7.0"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
Here's the Rust code:
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::Path;
use ftp::FtpStream;
use std::error::Error;
use serde::Serialize;
#[derive(Serialize)]
struct ProgressInfo {
currentFile: usize,
totalFiles: usize,
fileName: String,
downloadedBytes: u64,
totalBytes: u64,
}
fn main() -> Result<(), Box<dyn Error>> {
// Read and parse patch3.txt
let patch_file = "patch3.txt";
let content = fs::read_to_string(patch_file)?;
// Collect filenames
let mut filenames = Vec::new();
for line in content.lines() {
let line = line.trim();
if line.starts_with("//") || line.is_empty() {
continue;
}
// Extract the filename (everything after the first space)
let parts: Vec<&str> = line.splitn(2, ' ').collect();
if parts.len() == 2 {
let filename = parts[1];
filenames.push(filename.to_string());
} else {
eprintln!("Skipping invalid line: {}", line);
}
}
let total_files = filenames.len();
// Send initial total files info
let initial_info = ProgressInfo {
currentFile: 0,
totalFiles: total_files,
fileName: "".to_string(),
downloadedBytes: 0,
totalBytes: 0,
};
println!("{}", serde_json::to_string(&initial_info)?);
// Create update folder if it doesn't exist
let update_folder = "update";
if !Path::new(update_folder).exists() {
fs::create_dir(update_folder)?;
}
// Connect to FTP server
let server = "fpatch.levelupgames.com.br:21";
let mut ftp_stream = FtpStream::connect(server)?;
ftp_stream.login("anonymous", "anonymous")?;
ftp_stream.cwd("/patch")?;
// Download each file
for (index, filename) in filenames.iter().enumerate() {
let current_file = index + 1;
// Get the size of the file
let size = ftp_stream.size(filename)?;
let total_bytes = size;
let file_name = filename.clone();
// Open local file for writing
let local_path = format!("{}/{}", update_folder, filename);
// Create directories if necessary
if let Some(parent) = Path::new(&local_path).parent() {
fs::create_dir_all(parent)?;
}
let mut local_file = File::create(&local_path)?;
// Start retrieving the file
let mut data_stream = ftp_stream.retr_as_stream(filename)?;
let mut downloaded_bytes = 0u64;
let mut buffer = [0u8; 8192];
loop {
let bytes_read = data_stream.read(&mut buffer)?;
if bytes_read == 0 {
break;
}
local_file.write_all(&buffer[..bytes_read])?;
downloaded_bytes += bytes_read as u64;
// Report progress
let progress = ProgressInfo {
currentFile: current_file,
totalFiles: total_files,
fileName: file_name.clone(),
downloadedBytes,
totalBytes: total_bytes,
};
println!("{}", serde_json::to_string(&progress)?);
}
data_stream.finalize();
// Ensure we report completion of the current file
let progress = ProgressInfo {
currentFile: current_file,
totalFiles: total_files,
fileName: file_name.clone(),
downloadedBytes: total_bytes,
totalBytes: total_bytes,
};
println!("{}", serde_json::to_string(&progress)?);
}
ftp_stream.quit()?;
Ok(())
}
Explanation:
-
Reading and Parsing patch3.txt: The program reads the patch3.txt file, trims each line, ignores empty lines and lines starting with //, and extracts the filename from each valid line (assuming the filename is everything after the first space).
-
Setting Up FTP Connection: It connects to the FTP server ftp://fpatch.levelupgames.com.br/patch/ and logs in anonymously.
-
Downloading Files: For each filename:
- It retrieves the file size using
ftp_stream.size(filename).
- Opens a local file in the
update directory for writing.
- Initiates the file download using
retr_as_stream, reads data in chunks, writes to the local file, and updates the downloadedBytes.
- Outputs progress information in JSON format to stdout after each chunk is written.
-
Reporting Progress: The progress is reported by printing JSON-formatted ProgressInfo structs to stdout. You can capture and parse these JSON messages in your React application to update the UI accordingly.
Integrating with Your React Application:
To integrate the Rust program's output with your React application, you can run the Rust program as a child process from a Node.js script and listen to its stdout stream. Here's an example of how you might do this:
// download.js (Node.js script)
const { spawn } = require('child_process');
function startDownload() {
const rustProcess = spawn('./your_rust_program_executable'); // replace with the path to your compiled Rust executable
rustProcess.stdout.on('data', (data) => {
const lines = data.toString().split('\n').filter(line => line);
lines.forEach(line => {
try {
const progressInfo = JSON.parse(line);
// Send `progressInfo` to your React app, e.g., via WebSocket, IPC, or state management
// You can use Electron IPC or any inter-process communication method appropriate for your app
console.log('Progress:', progressInfo);
} catch (err) {
console.error('Failed to parse JSON:', err);
}
});
});
rustProcess.stderr.on('data', (data) => {
console.error(`Error: ${data}`);
});
rustProcess.on('close', (code) => {
console.log(`Rust process exited with code ${code}`);
});
}
startDownload();
In your React application, you can establish communication with this Node.js script using WebSockets, Electron IPC, or any other method suitable for your environment. When you receive the progressInfo object, you can update the state and pass it to your DownloadProgress component.
Assuming you're using Electron with React, you might set up IPC communication between the main and renderer processes. Here's a basic example:
// main.js (Electron Main Process)
const { app, BrowserWindow, ipcMain } = require('electron');
const { spawn } = require('child_process');
function createWindow () {
const win = new BrowserWindow({
webPreferences: {
nodeIntegration: true, // Make sure nodeIntegration is enabled
contextIsolation: false,
}
});
win.loadURL('http://localhost:3000'); // Assuming your React app runs on port 3000
const rustProcess = spawn('./your_rust_program_executable');
rustProcess.stdout.on('data', (data) => {
const lines = data.toString().split('\n').filter(line => line);
lines.forEach(line => {
try {
const progressInfo = JSON.parse(line);
// Send progressInfo to renderer process
win.webContents.send('download-progress', progressInfo);
} catch (err) {
console.error('Failed to parse JSON:', err);
}
});
});
rustProcess.stderr.on('data', (data) => {
console.error(`Error: ${data}`);
});
rustProcess.on('close', (code) => {
console.log(`Rust process exited with code ${code}`);
});
}
app.whenReady().then(createWindow);
// App.jsx (React Component)
import React, { useEffect, useState } from 'react';
import DownloadProgress from './DownloadProgress';
const { ipcRenderer } = window.require('electron');
function App() {
const [progress, setProgress] = useState({
currentFile: 0,
totalFiles: 0,
fileName: '',
downloadedBytes: 0,
totalBytes: 0,
});
useEffect(() => {
ipcRenderer.on('download-progress', (event, progressInfo) => {
setProgress(progressInfo);
});
return () => {
ipcRenderer.removeAllListeners('download-progress');
};
}, []);
return (
<div>
<DownloadProgress {...progress} />
</div>
);
}
export default App;
Note: Ensure that nodeIntegration is enabled in your Electron app's webPreferences. In production, consider using a safer method like context bridges to expose necessary APIs.
In your DownloadProgress component, you'll receive the progress updates through props and can display them accordingly, as you have set up in your original code.
Security Considerations:
-
Be cautious with nodeIntegration: true as it can introduce security risks. Consider using Electron's preload scripts and context bridges for a safer approach.
-
Validate and sanitize any data received from the Rust process before using it in your React app.
Additional Notes:
-
Error Handling: The Rust code includes basic error handling using Result and the ? operator. You might want to add more robust error handling depending on your requirements.
-
Creating Directories: The code ensures that all necessary directories are created before writing files, which is useful if the filenames include subdirectories.
-
FTP Connection Security: The FTP connection is using anonymous login and unencrypted data transfer. For security, consider using FTPS (FTP over SSL) if the server supports it.
-
Character Encoding: Be mindful of character encoding when dealing with FTP servers. The code assumes UTF-8 encoding.
Testing the Code:
-
Before running the code, ensure that the patch3.txt file is correctly formatted and placed in the same directory as the Rust program.
-
Compile the Rust program using cargo build --release.
-
Run the Rust executable and ensure it's outputting progress information as expected.
Final Thoughts:
By integrating the Rust program with your React application through IPC or another communication method, you can display real-time download progress to the user, providing a responsive and informative user experience.