RealTime and openChat

This commit is contained in:
2025-06-30 22:22:08 +03:30
parent 5afe3662d4
commit ee037532a1
20 changed files with 2222 additions and 275 deletions
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,20 @@
package org.to.telegramfinalproject.Client;
public class EventProcessorThread extends Thread {
private final ActionHandler handler;
public EventProcessorThread(ActionHandler handler) {
this.handler = handler;
setDaemon(true);
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(2000);
handler.processIncomingEvents();
} catch (InterruptedException ignored) {}
}
}
}
@@ -15,72 +15,107 @@ public class IncomingMessageListener implements Runnable {
@Override
public void run() {
try {
System.out.println("👂 Real-Time Listener started.");
String line;
while ((line = in.readLine()) != null) {
JSONObject response = new JSONObject(line);
System.out.println("📥 Received raw line: " + line);
if (!response.has("action")) continue;
String action = response.getString("action");
switch (action) {
case "new_message" -> {
JSONObject msg = response.getJSONObject("data");
System.out.println("\n🔔 New Message:");
System.out.println("From: " + msg.getString("sender"));
System.out.println("Time: " + msg.getString("time"));
System.out.println("Content: " + msg.getString("content"));
System.out.print(">> ");
if (response.has("action")) {
String action = response.getString("action");
if (isRealTimeEvent(action)) {
handleRealTimeEvent(response);
} else {
TelegramClient.responseQueue.put(response);
}
case "message_edited" -> {
JSONObject msg = response.getJSONObject("data");
System.out.println("\n✏️ Message Edited:");
System.out.println("ID: " + msg.getString("message_id"));
System.out.println("New Content: " + msg.getString("new_content"));
System.out.println("Edit Time: " + msg.getString("edit_time"));
System.out.print(">> ");
}
case "message_deleted" -> {
JSONObject msg = response.getJSONObject("data");
System.out.println("\n🗑️ Message Deleted:");
System.out.println("Message ID: " + msg.getString("message_id"));
System.out.print(">> ");
}
case "status_change" -> {
JSONObject msg = response.getJSONObject("data");
System.out.println("\n🔄 User Status Changed:");
System.out.println("User: " + msg.getString("user_id"));
System.out.println("Status: " + msg.getString("status"));
System.out.print(">> ");
}
case "system_notification" -> {
JSONObject msg = response.getJSONObject("data");
System.out.println("\n⚠️ System Notification:");
System.out.println(msg.getString("content"));
System.out.print(">> ");
}
case "contact_added" ->{
System.out.println("\n🔔 You were added by a new contact: " + response.getString("user_id"));
System.out.print(">> ");
}
default -> {
if (!action.equals("search")) { // ignore action: search
System.out.println("\n❓ Unknown action received: " + action);
System.out.print(">> ");
}
}
} else if (response.has("status") && response.has("message")) {
TelegramClient.responseQueue.put(response);
} else {
TelegramClient.responseQueue.put(response);
}
}
} catch (Exception e) {
System.out.println("🔴 Listener stopped: " + e.getMessage());
}
}
private boolean isRealTimeEvent(String action) {
return switch (action) {
case "new_message", "message_edited", "message_deleted",
"user_status_changed", "added_to_group", "added_to_channel",
"update_group_or_channel", "chat_deleted",
"blocked_by_user", "unblocked_by_user", "message_seen" -> true;
default -> false;
};
}
private void handleRealTimeEvent(JSONObject response) {
String action = response.getString("action");
JSONObject msg = response.getJSONObject("data");
switch (action) {
case "new_message" -> {
System.out.println("\n🔔 New Message:");
System.out.println("From: " + msg.getString("sender"));
System.out.println("Time: " + msg.getString("time"));
System.out.println("Content: " + msg.getString("content"));
}
case "message_edited" -> {
System.out.println("\n✏️ Message Edited:");
System.out.println("ID: " + msg.getString("message_id"));
System.out.println("New Content: " + msg.getString("new_content"));
System.out.println("Edit Time: " + msg.getString("edited_at"));
}
case "message_deleted" -> {
System.out.println("\n🗑️ Message Deleted:");
System.out.println("Message ID: " + msg.getString("message_id"));
}
case "user_status_changed" -> {
System.out.println("\n🔄 User Status Changed:");
System.out.println("User: " + msg.getString("user_id"));
System.out.println("Status: " + msg.getString("status"));
}
case "added_to_group" -> {
System.out.println("\n👥 You were added to a group: " + msg.getString("chat_name"));
}
case "added_to_channel" -> {
System.out.println("\n📢 You were added to a channel: " + msg.getString("chat_name"));
}
case "update_group_or_channel" -> {
System.out.println("\n🔄 Group/Channel updated: " + msg.getString("new_name"));
}
case "chat_deleted" -> {
System.out.println("\n🗑️ Chat deleted: " + msg.getString("chat_id"));
}
case "blocked_by_user" -> {
System.out.println("\n⛔ You were blocked by user: " + msg.getString("blocker_id"));
}
case "unblocked_by_user" -> {
System.out.println("\n✅ You were unblocked by user: " + msg.getString("unblocker_id"));
}
case "message_seen" -> {
System.out.println("\n👁️ Your message was seen:");
System.out.println("Message ID: " + msg.getString("message_id"));
System.out.println("Seen at: " + msg.getString("seen_at"));
}
default -> {
System.out.println("\n❓ Unknown real-time action: " + action);
}
}
System.out.print(">> ");
}
}
@@ -0,0 +1,12 @@
package org.to.telegramfinalproject.Client;
import org.json.JSONObject;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class RealTimeBuffer {
public static final BlockingQueue<JSONObject> incomingEvents = new LinkedBlockingQueue<>();
}
@@ -9,6 +9,8 @@ import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
public class TelegramClient {
private static final String SERVER_HOST = "localhost";
@@ -18,6 +20,7 @@ public class TelegramClient {
private PrintWriter out;
private final Scanner scanner;
ActionHandler handler = null;
public static BlockingQueue<JSONObject> responseQueue = new LinkedBlockingQueue<>();
public TelegramClient() {
this.scanner = new Scanner(System.in);
@@ -28,76 +31,52 @@ public class TelegramClient {
this.socket = new Socket(SERVER_HOST, SERVER_PORT);
this.in = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.out = new PrintWriter(this.socket.getOutputStream(), true);
System.out.println(" Connected to Telegram Server");
System.out.println(" Connected to Telegram Server");
this.handler = new ActionHandler(this.out, this.in, this.scanner);
this.showMainMenu();
} catch (IOException e) {
System.err.println("Error connecting to server: " + e.getMessage());
}
// 👂 فقط این ترد مجاز به خواندن از in است
Thread listenerThread = new Thread(new IncomingMessageListener(in));
listenerThread.setDaemon(true);
listenerThread.start();
showMainMenu();
} catch (IOException e) {
System.err.println("❌ Error connecting to server: " + e.getMessage());
}
}
private void showMainMenu() {
while(true) {
while (true) {
System.out.println("Main Menu:");
System.out.println("1. Register");
System.out.println("2. Login");
System.out.println("3. Exit");
System.out.print("Choose an option: ");
switch (this.scanner.nextLine()) {
case "1":
this.handler.register();
break;
case "2":
this.handler.loginHandler();
String choice = scanner.nextLine();
switch (choice) {
case "1" -> handler.register();
case "2" -> {
handler.loginHandler();
if (Session.currentUser != null) {
System.out.println("Login successful.");
UUID internalId = UUID.fromString(Session.currentUser.getString("internalUUID"));
//Thread listenerThread = new Thread(new IncomingMessageListener(in));
//listenerThread.setDaemon(true);
//listenerThread.start();
this.handler.userMenu(internalId);
System.out.println("Login successful.");
UUID internalId = UUID.fromString(Session.currentUser.getString("internal_uuid"));
handler.userMenu(internalId);
} else {
System.out.println("Login failed.");
System.out.println("Login failed.");
}
break;
case "3":
System.out.println("Disconnecting...");
if (Session.currentUser != null && Session.currentUser.has("internalUUID")) {
try {
JSONObject logoutRequest = new JSONObject();
logoutRequest.put("action", "logout");
logoutRequest.put("user_id", Session.currentUser.getString("internalUUID"));
out.println(logoutRequest.toString());
in.readLine();
} catch (Exception e) {
System.err.println("Failed to notify server on logout: " + e.getMessage());
}
}
try {
if (socket != null) socket.close();
if (in != null) in.close();
if (out != null) out.close();
System.out.println("Disconnected.");
} catch (IOException e) {
System.err.println("Error closing connection: " + e.getMessage());
}
}
case "3" -> {
System.out.println("Exiting...");
return;
default:
System.out.println("Invalid choice. Please try again.");
}
default -> System.out.println("Invalid choice.");
}
}
}
public static void main(String[] args) {
TelegramClient client = new TelegramClient();
client.start();
new TelegramClient().start();
}
}