Encrypted-Chat-Client/components/dbconnector.jsx

219 lines
6.8 KiB
React
Raw Permalink Normal View History

2024-12-15 14:40:35 +00:00
import { Platform } from 'react-native';
import initSqlJs from 'sql.js'; // Load sql.js for Web
// For React Native, use react-native-sqlite-storage
let SQLite;
if (Platform.OS !== 'web') {
SQLite = require('react-native-sqlite-storage'); // Load for React Native
SQLite.enablePromise(true); // Enable promise support for React Native SQLite
}
let db;
// Initialize the SQLite database
export const initializeDatabase = async () => {
try {
if (Platform.OS !== 'web') {
// React Native version using react-native-sqlite-storage
db = await SQLite.openDatabase({ name: 'app.db', location: 'default' });
// Create tables for React Native
await db.executeSql(`
CREATE TABLE IF NOT EXISTS Clients (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
public_key TEXT NOT NULL,
private_key TEXT NOT NULL
)
`);
await db.executeSql(`
CREATE TABLE IF NOT EXISTS FriendList (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
public_key TEXT NOT NULL
)
`);
await db.executeSql(`
CREATE TABLE IF NOT EXISTS Messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sender_username TEXT NOT NULL,
receiver_username TEXT NOT NULL,
message TEXT NOT NULL,
nonce TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
} else {
// Web version using sql.js
const SQL = await initSqlJs({
locateFile: (file) => {
// Correct the path to sql-wasm.wasm based on where it's served in the public folder
if (file === "sql-wasm.wasm") {
return "/assets/wasm/sql-wasm.wasm"; // This assumes it's in the public folder and served correctly
}
return file;
}
});
// Create an in-memory database for the web
db = new SQL.Database();
// Create tables for Web
db.run(`
CREATE TABLE IF NOT EXISTS Clients (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
public_key TEXT NOT NULL,
private_key TEXT NOT NULL
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS FriendList (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
public_key TEXT NOT NULL
)
`);
db.run(`
CREATE TABLE IF NOT EXISTS Messages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
sender_username TEXT NOT NULL,
receiver_username TEXT NOT NULL,
message TEXT NOT NULL,
nonce TEXT NOT NULL,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
)
`);
}
console.log('Database initialized and tables created');
} catch (err) {
console.error('Error initializing database:', err);
throw err;
}
};
// CRUD Operations for React Native and Web
export const addClient = async (username, publicKey, privateKey) => {
try {
if (Platform.OS !== 'web') {
// React Native version using react-native-sqlite-storage
await db.executeSql(
`INSERT INTO Clients (username, public_key, private_key) VALUES (?, ?, ?)`,
[username, publicKey, privateKey]
);
} else {
// Web version using sql.js
db.run(
`INSERT INTO Clients (username, public_key, private_key) VALUES (?, ?, ?)`,
[username, publicKey, privateKey]
);
}
console.log('Client added successfully');
} catch (err) {
console.error('Error adding client:', err);
}
};
export const getAllFriends = async () => {
try {
let results;
if (Platform.OS !== 'web') {
// React Native version using react-native-sqlite-storage
results = await db.executeSql(`SELECT * FROM FriendList`);
return results[0].rows.raw(); // Return friends for React Native
} else {
// Web version using sql.js
results = db.exec(`SELECT * FROM FriendList`);
return results[0].values; // Return friends for Web
}
} catch (err) {
console.error('Error retrieving friends:', err);
}
};
export const getMessages = async (username) => {
try {
let results;
if (Platform.OS !== 'web') {
// React Native version using react-native-sqlite-storage
results = await db.executeSql(
`SELECT * FROM Messages WHERE sender_username = ? OR receiver_username = ? ORDER BY timestamp ASC`,
[username, username]
);
return results[0].rows.raw(); // Return messages for React Native
} else {
// Web version using sql.js
results = db.exec(
`SELECT * FROM Messages WHERE sender_username = ? OR receiver_username = ? ORDER BY timestamp ASC`,
[username, username]
);
return results[0].values; // Return messages for Web
}
} catch (err) {
console.error('Error retrieving messages:', err);
}
};
// Close the database
export const closeDatabase = () => {
try {
if (Platform.OS !== 'web') {
// React Native version using react-native-sqlite-storage
db.close();
} else {
// Web version using sql.js (no explicit close method, just stop using the db)
console.log('Database is in-memory on the web, no close method.');
}
console.log('Database closed');
} catch (err) {
console.error('Error closing database:', err);
}
};
export const getClient = async (username) => {
try {
let results;
if (Platform.OS !== 'web') {
// React Native version using react-native-sqlite-storage
results = await db.executeSql(
`SELECT * FROM Clients WHERE username = ?`,
[username]
);
if (results[0].rows.length > 0) {
const client = results[0].rows.item(0); // Get the first matching row
return {
username: client.username,
public_key: client.public_key,
private_key: client.private_key,
};
} else {
console.warn('Client not found for username:', username);
return null;
}
} else {
// Web version using sql.js
results = db.exec(`SELECT * FROM Clients WHERE username = ?`, [username]);
if (results.length > 0 && results[0].values.length > 0) {
const client = results[0].values[0]; // Get the first matching row
return {
username: client[1], // The second column is the username
public_key: client[2], // The third column is the public_key
private_key: client[3], // The fourth column is the private_key
};
} else {
console.warn('Client not found for username:', username);
return null;
}
}
} catch (err) {
console.error('Error retrieving client:', err);
}
};