Skip to content

Commit

Permalink
Merge pull request #98 from Sanat-Jha/json-backup
Browse files Browse the repository at this point in the history
created server backup file import export feature #41
  • Loading branch information
Smitbafna authored Jan 16, 2025
2 parents 08c77e1 + 9d7880b commit 6e8255c
Show file tree
Hide file tree
Showing 2 changed files with 107 additions and 1 deletion.
22 changes: 22 additions & 0 deletions bin/prompt_chat.dart
Original file line number Diff line number Diff line change
Expand Up @@ -422,6 +422,28 @@ void runApp(ChatAPI api) async {
}
break;
}
case "export-server-backup":
{
var serverName = getFlagValue("--server", currentCommand);
await api.exportServerData(serverName, currUsername);
logger.info(
"Exported server data for $serverName", currUsername as String);
print("Server data exported successfully!");
break;
}

case "import-server-from-backup":
{
if (currUsername == null) {
print("Please login first to import server data.");
break;
}
var filePath = getFlagValue("--file", currentCommand);
await api.importServerData(filePath, currUsername);
logger.info("Imported server data from $filePath", currUsername);
print("Server data imported successfully!");
break;
}
case "block":
{
if (currUsername == null) {
Expand Down
86 changes: 85 additions & 1 deletion lib/prompt_chat.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import 'package:prompt_chat/db/database_crud.dart';
import 'package:prompt_chat/enum/channel_type.dart';
import 'package:prompt_chat/enum/permissions.dart';
import 'package:prompt_chat/enum/server_type.dart';
import 'dart:convert';

class ChatAPI {
List<User> users = [];
Expand Down Expand Up @@ -633,6 +634,7 @@ class ChatAPI {
// Only show messages if sender is not blocked
if (dm.receiver.username == user.username &&
!user.blockedUsers.contains(dm.sender.username)) {

messages.add("${dm.sender.username} : ${dm.message}");
}
}
Expand All @@ -651,7 +653,89 @@ class ChatAPI {
return messages;
}

Future<void> blockUser(String? blockerUsername, String? userToBlock) async {
Future<void> exportServerData(String? serverName, String? username) async {
if (serverName == null || username == null) {
throw Exception("Please provide valid server name and username");
}

var reqServer = getServer(serverName);
reqServer.checkAccessLevel(username, 2); // Ensure only owner can export

// Convert server to JSON
final serverJson = reqServer.toMap();

// Create timestamp for unique filename
final timestamp =
DateTime.now().toIso8601String().replaceAll(RegExp(r'[:.]'), '-');
final fileName =
'server_${serverName.replaceAll(' ', '_')}_$timestamp.json';

try {
// Create a backup directory if it doesn't exist
var backupDir = Directory('backups');
if (!await backupDir.exists()) {
await backupDir.create();
}

// Write JSON to file in backups directory
final file = File('${backupDir.path}${Platform.pathSeparator}$fileName');
await file.writeAsString(jsonEncode(serverJson), flush: true);
print('Server data exported successfully to ${file.path}');
} catch (e) {
throw Exception('Failed to export server data: $e');
}
}

Future<void> importServerData(String? filePath, String? username) async {
if (filePath == null || username == null) {
throw Exception("Please provide valid file path and username");
}

try {
final file = File(filePath);
if (!await file.exists()) {
throw Exception('File not found: $filePath');
}

// Read and parse JSON file
final jsonString = await file.readAsString();
final serverData = jsonDecode(jsonString);

// Basic validation of JSON structure
if (!serverData.containsKey('serverName') ||
!serverData.containsKey('members') ||
!serverData.containsKey('roles')) {
throw Exception('Invalid server data format');
}

// Check if server name already exists
final serverName = serverData['serverName'];
if (servers.any((server) => server.serverName == serverName)) {
throw Exception('A server with this name already exists');
}

// Create new server instance
var newServer = Server.fromMap(serverData);

// Validate that the importing user exists and will be the owner
var importingUser = getUser(username);
if (!newServer.isAccessAllowed(username, 2)) {
// Ensure the importing user becomes the owner
await newServer.swapOwner(
newServer.getRole('owner').holders[0].username, username);
}

// Add server to the list and database
servers.add(newServer);
await DatabaseIO.addToDB(newServer, 'servers');

print('Server data imported successfully');
} catch (e) {
throw Exception('Failed to import server data: $e');
}
}
Future<void> blockUser(String? blockerUsername, String? userToBlock) async {

if (blockerUsername == null || userToBlock == null) {
throw Exception("Please enter valid usernames");
}
Expand Down

0 comments on commit 6e8255c

Please sign in to comment.