Code Sketch
yoio chat
Category: Programming
import java.awt.BorderLayout
import java.awt.Color
import java.awt.Dimension
import java.awt.Font
import java.awt.GridLayout
import java.awt.Image
import java.awt.Toolkit
import java.awt.datatransfer.DataFlavor
import java.awt.image.BufferedImage
import java.awt.event.ActionEvent
import java.awt.event.ActionListener
import java.awt.event.MouseAdapter
import java.awt.event.MouseEvent
import java.io.BufferedReader
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.io.IOException
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.PrintWriter
import java.net.Inet4Address
import java.net.InetSocketAddress
import java.net.NetworkInterface
import java.net.ServerSocket
import java.net.Socket
import java.nio.charset.StandardCharsets
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
import java.security.MessageDigest
import java.security.SecureRandom
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import java.util.Base64
import java.util.Properties
import java.util.UUID
import javax.imageio.ImageIO
import javax.swing.BorderFactory
import javax.swing.DefaultListModel
import javax.swing.JDialog
import javax.swing.JFileChooser
import javax.swing.JFrame
import javax.swing.JLabel
import javax.swing.JList
import javax.swing.JOptionPane
import javax.swing.JPanel
import javax.swing.JPasswordField
import javax.swing.JScrollPane
import javax.swing.JTextArea
import javax.swing.JTextField
import javax.swing.JButton
import javax.swing.ListSelectionModel
import javax.swing.SwingConstants
import javax.swing.SwingUtilities
import javax.swing.UIManager
import javax.swing.WindowConstants
import scala.collection.mutable
object LiveChatApp {
// ==========================================================
// SETTINGS
// ==========================================================
private val APP_NAME =
"YADNESH LIVE CHAT"
private val DEFAULT_PORT =
5050
// ==========================================================
// UTILITY
// ==========================================================
object Util {
private val random =
new SecureRandom()
private val encoder =
Base64.getUrlEncoder.withoutPadding()
private val decoder =
Base64.getUrlDecoder
def encode(
value: String
): String = {
val text =
if (value == null) "" else value
encoder.encodeToString(
text.getBytes(
StandardCharsets.UTF_8
)
)
}
def decode(
value: String
): String = {
if (
value == null ||
value.isEmpty
) {
""
} else {
try {
new String(
decoder.decode(value),
StandardCharsets.UTF_8
)
} catch {
case _: Throwable =>
""
}
}
}
def sha256(
value: String
): String = {
val md =
MessageDigest.getInstance(
"SHA-256"
)
md.digest(
value.getBytes(
StandardCharsets.UTF_8
)
).map(
"%02x".format(_)
).mkString
}
def randomHex(
size: Int
): String = {
val bytes =
new Array[Byte](size)
random.nextBytes(
bytes
)
bytes.map(
"%02x".format(_)
).mkString
}
def secureEquals(
a: String,
b: String
): Boolean = {
if (
a == null ||
b == null
) {
false
} else {
MessageDigest.isEqual(
a.getBytes(
StandardCharsets.UTF_8
),
b.getBytes(
StandardCharsets.UTF_8
)
)
}
}
def clean(
value: String,
maximum: Int
): String = {
val text =
if (value == null) "" else value.trim
if (
text.length <= maximum
) {
text
} else {
text.substring(
0,
maximum
)
}
}
def validUsername(
name: String
): Boolean = {
name != null &&
name.matches(
"[A-Za-z0-9_]{3,20}"
)
}
def now(): String = {
LocalDateTime.now().format(
DateTimeFormatter.ofPattern(
"HH:mm:ss"
)
)
}
// --------------------------------------------------------
// IMAGE -> BASE64
// --------------------------------------------------------
def imageToBase64(
original: Image
): String = {
if (original == null) {
return ""
}
try {
val width =
math.max(
1,
original.getWidth(null)
)
val height =
math.max(
1,
original.getHeight(null)
)
val image =
new BufferedImage(
width,
height,
BufferedImage.TYPE_INT_ARGB
)
val graphics =
image.createGraphics()
try {
graphics.drawImage(
original,
0,
0,
null
)
} finally {
graphics.dispose()
}
val out =
new ByteArrayOutputStream()
ImageIO.write(
image,
"png",
out
)
out.close()
val data =
out.toByteArray
if (
data.length >
350 * 1024
) {
""
} else {
encoder.encodeToString(
data
)
}
} catch {
case _: Throwable =>
""
}
}
// --------------------------------------------------------
// FILE -> BASE64
// --------------------------------------------------------
def fileToBase64(
path: String
): String = {
try {
val image =
ImageIO.read(
new java.io.File(
path
)
)
imageToBase64(
image
)
} catch {
case _: Throwable =>
""
}
}
// --------------------------------------------------------
// BASE64 -> IMAGE
// --------------------------------------------------------
def base64ToImage(
value: String
): BufferedImage = {
if (
value == null ||
value.isEmpty
) {
null
} else {
try {
val bytes =
decoder.decode(
value
)
ImageIO.read(
new ByteArrayInputStream(
bytes
)
)
} catch {
case _: Throwable =>
null
}
}
}
// --------------------------------------------------------
// PASTE IMAGE FROM CLIPBOARD
// --------------------------------------------------------
def clipboardImageBase64():
String = {
try {
val clipboard =
Toolkit
.getDefaultToolkit
.getSystemClipboard
if (
clipboard.isDataFlavorAvailable(
DataFlavor.imageFlavor
)
) {
val image =
clipboard.getData(
DataFlavor.imageFlavor
).asInstanceOf[Image]
imageToBase64(
image
)
} else {
""
}
} catch {
case _: Throwable =>
""
}
}
// --------------------------------------------------------
// LAN IPv4
// --------------------------------------------------------
def localIPs():
Seq[String] = {
val values =
mutable.ListBuffer[String]()
try {
val interfaces =
NetworkInterface.getNetworkInterfaces()
while (
interfaces != null &&
interfaces.hasMoreElements
) {
val network =
interfaces.nextElement()
if (
network.isUp &&
!network.isLoopback &&
!network.isVirtual
) {
val addresses =
network.getInetAddresses()
while (
addresses.hasMoreElements
) {
val address =
addresses.nextElement()
if (
address
.isInstanceOf[Inet4Address] &&
!address.isLoopbackAddress
) {
val ip =
address.getHostAddress()
if (
!values.contains(
ip
)
) {
values +=
ip
}
}
}
}
}
} catch {
case _: Throwable =>
}
if (
values.isEmpty
) {
Seq(
"127.0.0.1"
)
} else {
values.toSeq
}
}
def setupFont(): Unit = {
val font =
new Font(
"Segoe UI",
Font.PLAIN,
14
)
UIManager.put(
"Label.font",
font
)
UIManager.put(
"Button.font",
font
)
UIManager.put(
"TextField.font",
font
)
UIManager.put(
"PasswordField.font",
font
)
UIManager.put(
"TextArea.font",
font
)
UIManager.put(
"List.font",
font
)
}
}
// ==========================================================
// DATA
// ==========================================================
case class UserRecord(
username: String,
passwordSalt: String,
passwordVerifier: String,
bio: String,
avatar: String
)
case class ChatMessage(
sender: String,
text: String,
time: String
)
case class PersonItem(
username: String,
bio: String,
online: Boolean
) {
override def toString: String = {
if (online) {
username +
" ? ONLINE"
} else {
username +
" ? OFFLINE"
}
}
}
case class ChatItem(
id: String,
title: String,
group: Boolean
) {
override def toString: String =
title
}
// ==========================================================
// SERVER
// ==========================================================
object Server {
private val lock =
new Object
private val users =
mutable.Map[
String,
UserRecord
]()
private val sessions =
mutable.Map[
String,
ClientConnection
]()
private val chatMembers =
mutable.Map[
String,
mutable.Set[String]
]()
private val chatNames =
mutable.Map[
String,
String
]()
private val chatGroups =
mutable.Map[
String,
Boolean
]()
private val chatHistory =
mutable.Map[
String,
mutable.ListBuffer[
ChatMessage
]
]()
private val loginChallenges =
mutable.Map[
Socket,
(String, String)
]()
private val registerChallenges =
mutable.Map[
Socket,
(String, String)
]()
private val recoveryChallenges =
mutable.Map[
Socket,
(String, String)
]()
// --------------------------------------------------------
// RECOVERY SECRET HASH
// --------------------------------------------------------
//
// This is the SHA-256 verifier of the private recovery
// secret. The secret itself is not shown in the UI/code.
//
// --------------------------------------------------------
private val recoveryVerifier =
"7f3f667469f4945d7b63b6831e26f1bd84bd02d57b455542b6144fe2b2a6a92d"
private val dataFolder =
Paths.get(
"YadneshLiveChatData"
)
private val profilesFolder =
dataFolder.resolve(
"profiles"
)
private var serverSocket:
ServerSocket = null
private var running =
false
// ========================================================
// CONNECTION
// ========================================================
class ClientConnection(
val socket: Socket,
val reader: BufferedReader,
val writer: PrintWriter
) {
var username =
""
def send(
line: String
): Unit = {
lock.synchronized {
try {
if (
!socket.isClosed
) {
writer.println(
line
)
writer.flush()
}
} catch {
case _: Throwable =>
}
}
}
def close(): Unit = {
try {
socket.close()
} catch {
case _: Throwable =>
}
}
}
// ========================================================
// START SERVER
// ========================================================
def start(
port: Int
): Boolean = {
lock.synchronized {
if (running) {
true
} else {
try {
Files.createDirectories(
profilesFolder
)
loadProfiles()
serverSocket =
new ServerSocket()
serverSocket.setReuseAddress(
true
)
// Important:
// listen on ALL network interfaces.
serverSocket.bind(
new InetSocketAddress(
"0.0.0.0",
port
)
)
running =
true
val thread =
new Thread(
new Runnable {
override def run(): Unit = {
acceptLoop()
}
}
)
thread.setDaemon(
true
)
thread.start()
true
} catch {
case _: Throwable =>
running =
false
false
}
}
}
}
// ========================================================
// ACCEPT LOOP
// ========================================================
private def acceptLoop():
Unit = {
while (
running
) {
try {
val sock =
serverSocket.accept()
sock.setKeepAlive(
true
)
sock.setTcpNoDelay(
true
)
val reader =
new BufferedReader(
new InputStreamReader(
sock.getInputStream,
StandardCharsets.UTF_8
)
)
val writer =
new PrintWriter(
new OutputStreamWriter(
sock.getOutputStream,
StandardCharsets.UTF_8
),
true
)
val client =
new ClientConnection(
sock,
reader,
writer
)
val thread =
new Thread(
new Runnable {
override def run(): Unit = {
clientLoop(
client
)
}
}
)
thread.setDaemon(
true
)
thread.start()
} catch {
case _: Throwable =>
}
}
}
// ========================================================
// PROFILE FILE
// ========================================================
private def profileFile(
username: String
): Path = {
profilesFolder.resolve(
username +
".profile"
)
}
private def saveProfile(
user: UserRecord
): Unit = {
val props =
new Properties()
props.setProperty(
"username",
user.username
)
props.setProperty(
"passwordSalt",
user.passwordSalt
)
props.setProperty(
"passwordVerifier",
user.passwordVerifier
)
props.setProperty(
"bio",
user.bio
)
props.setProperty(
"avatar",
user.avatar
)
val out =
Files.newOutputStream(
profileFile(
user.username
)
)
try {
props.store(
out,
"Yadnesh Live Chat Account"
)
} finally {
out.close()
}
}
// ========================================================
// LOAD ALL ACCOUNTS
// ========================================================
private def loadProfiles():
Unit = {
users.clear()
if (
!Files.exists(
profilesFolder
)
) {
return
}
val stream =
Files.list(
profilesFolder
)
try {
val iterator =
stream.iterator()
while (
iterator.hasNext
) {
val path =
iterator.next()
if (
path.toString
.endsWith(
".profile"
)
) {
try {
val props =
new Properties()
val input =
Files.newInputStream(
path
)
try {
props.load(
input
)
} finally {
input.close()
}
val username =
props.getProperty(
"username",
""
)
if (
Util.validUsername(
username
)
) {
val user =
UserRecord(
username,
props.getProperty(
"passwordSalt",
""
),
props.getProperty(
"passwordVerifier",
""
),
props.getProperty(
"bio",
""
),
props.getProperty(
"avatar",
""
)
)
users.put(
username.toLowerCase,
user
)
}
} catch {
case _: Throwable =>
}
}
}
} finally {
stream.close()
}
}
// ========================================================
// DIRECT CHAT ID
// ========================================================
private def directChatId(
a: String,
b: String
): String = {
val pair =
Seq(
a.toLowerCase,
b.toLowerCase
).sorted
"DM:" +
pair.head +
":" +
pair(1)
}
// ========================================================
// ADD MEMBER
// ========================================================
private def addMember(
chatId: String,
username: String
): Unit = {
val set =
chatMembers.getOrElseUpdate(
chatId,
mutable.Set[String]()
)
set +=
username
}
// ========================================================
// SEND TO USER
// ========================================================
private def sendToUser(
username: String,
line: String
): Unit = {
sessions
.get(
username.toLowerCase
)
.foreach {
client =>
client.send(
line
)
}
}
// ========================================================
// BROADCAST CHAT
// ========================================================
private def broadcastChat(
chatId: String,
line: String
): Unit = {
chatMembers
.get(chatId)
.foreach {
members =>
members.foreach {
username =>
sendToUser(
username,
line
)
}
}
}
// ========================================================
// SEND CHAT TO USER
// ========================================================
private def addChatToUser(
chatId: String,
username: String
): Unit = {
val group =
chatGroups.getOrElse(
chatId,
false
)
val title = {
if (group) {
"#" +
chatNames.getOrElse(
chatId,
"Group"
)
} else {
val members =
chatMembers.getOrElse(
chatId,
mutable.Set[String]()
)
val other =
members.find {
x =>
!x.equalsIgnoreCase(
username
)
}
other match {
case Some(value) =>
"@" + value
case None =>
"@Chat"
}
}
}
sendToUser(
username,
"CHAT|" +
Util.encode(
chatId
) +
"|" +
Util.encode(
title
) +
"|" +
(
if (group) "1"
else "0"
)
)
}
// ========================================================
// SEND ALL USER CHATS
// ========================================================
private def sendAllUserChats(
username: String
): Unit = {
chatMembers.keys.foreach {
chatId =>
chatMembers
.get(chatId)
.foreach {
members =>
if (
members.contains(
username
)
) {
addChatToUser(
chatId,
username
)
}
}
}
}
// ========================================================
// HISTORY
// ========================================================
private def sendHistory(
client: ClientConnection,
chatId: String
): Unit = {
val list =
chatHistory.getOrElse(
chatId,
mutable.ListBuffer[
ChatMessage
]()
)
val start =
math.max(
0,
list.length - 100
)
val recent =
list.slice(
start,
list.length
)
val out =
new StringBuilder()
out.append(
"HISTORY|"
)
out.append(
Util.encode(
chatId
)
)
out.append(
"|" +
recent.length
)
recent.foreach {
message =>
out.append(
"|" +
Util.encode(
message.sender
)
)
out.append(
"|" +
Util.encode(
message.time
)
)
out.append(
"|" +
Util.encode(
message.text
)
)
}
client.send(
out.toString
)
}
// ========================================================
// CLIENT LOOP
// ========================================================
private def clientLoop(
client: ClientConnection
): Unit = {
try {
while (
!client.socket.isClosed
) {
val line =
client.reader.readLine()
if (
line == null
) {
throw new IOException(
"Disconnected"
)
}
processCommand(
client,
line
)
}
} catch {
case _: Throwable =>
}
lock.synchronized {
val name =
client.username
if (
name != null &&
name.nonEmpty
) {
sessions.get(
name.toLowerCase
) match {
case Some(current)
if current eq client =>
sessions.remove(
name.toLowerCase
)
broadcastPresence(
name
)
case _ =>
}
}
loginChallenges.remove(
client.socket
)
registerChallenges.remove(
client.socket
)
recoveryChallenges.remove(
client.socket
)
}
client.close()
}
// ========================================================
// COMMAND PROCESSOR
// ========================================================
private def processCommand(
client: ClientConnection,
line: String
): Unit = {
val p =
line.split(
"\\|",
-1
)
if (
p.length == 0
) {
return
}
val command =
p(0)
// ======================================================
// REGISTER START
// ======================================================
if (
command ==
"REGISTER_START"
) {
if (
p.length < 2
) {
return
}
val username =
Util.decode(
p(1)
).trim
if (
!Util.validUsername(
username
)
) {
client.send(
"ERROR|" +
Util.encode(
"Username must be 3-20 characters."
)
)
return
}
lock.synchronized {
if (
users.contains(
username.toLowerCase
)
) {
client.send(
"ERROR|" +
Util.encode(
"This account already exists. Login instead."
)
)
} else {
val salt =
Util.randomHex(
16
)
registerChallenges.put(
client.socket,
(
username,
salt
)
)
client.send(
"REGISTER_CHALLENGE|" +
Util.encode(
salt
)
)
}
}
return
}
// ======================================================
// REGISTER FINISH
// ======================================================
if (
command ==
"REGISTER_FINISH"
) {
if (
p.length < 6
) {
return
}
lock.synchronized {
registerChallenges
.get(
client.socket
) match {
case None =>
client.send(
"ERROR|" +
Util.encode(
"Registration expired."
)
)
case Some(
(
username,
salt
)
) =>
if (
users.contains(
username.toLowerCase
)
) {
client.send(
"ERROR|" +
Util.encode(
"Account already exists."
)
)
registerChallenges.remove(
client.socket
)
} else {
val passwordVerifier =
Util.decode(
p(2)
)
val bio =
Util.clean(
Util.decode(
p(3)
),
500
)
val avatar =
Util.decode(
p(4)
)
val validAvatar =
if (
avatar.length <=
480000
) {
avatar
} else {
""
}
val user =
UserRecord(
username,
salt,
passwordVerifier,
bio,
validAvatar
)
users.put(
username.toLowerCase,
user
)
saveProfile(
user
)
registerChallenges.remove(
client.socket
)
client.username =
username
sessions.put(
username.toLowerCase,
client
)
client.send(
"LOGIN_OK|" +
Util.encode(
username
)
)
sendAllUserChats(
username
)
broadcastPresence(
username
)
}
}
}
return
}
// ======================================================
// LOGIN START
// ======================================================
if (
command ==
"LOGIN_START"
) {
if (
p.length < 2
) {
return
}
val username =
Util.decode(
p(1)
).trim
lock.synchronized {
users.get(
username.toLowerCase
) match {
case None =>
client.send(
"ERROR|" +
Util.encode(
"Account not found. Create a new account."
)
)
case Some(user) =>
val nonce =
Util.randomHex(
32
)
loginChallenges.put(
client.socket,
(
user.username,
nonce
)
)
client.send(
"LOGIN_CHALLENGE|" +
Util.encode(
user.passwordSalt
) +
"|" +
Util.encode(
nonce
)
)
}
}
return
}
// ======================================================
// LOGIN FINISH
// ======================================================
if (
command ==
"LOGIN_FINISH"
) {
if (
p.length < 3
) {
return
}
lock.synchronized {
loginChallenges
.get(
client.socket
) match {
case None =>
client.send(
"ERROR|" +
Util.encode(
"Login expired."
)
)
case Some(
(
username,
nonce
)
) =>
users.get(
username.toLowerCase
) match {
case None =>
client.send(
"ERROR|" +
Util.encode(
"Account not found."
)
)
case Some(user) =>
val proof =
Util.decode(
p(2)
)
val expected =
Util.sha256(
user.passwordVerifier +
nonce
)
if (
Util.secureEquals(
proof,
expected
)
) {
sessions
.get(
username.toLowerCase
)
.foreach {
old =>
old.close()
}
client.username =
username
sessions.put(
username.toLowerCase,
client
)
loginChallenges.remove(
client.socket
)
client.send(
"LOGIN_OK|" +
Util.encode(
username
)
)
sendAllUserChats(
username
)
broadcastPresence(
username
)
} else {
loginChallenges.remove(
client.socket
)
client.send(
"ERROR|" +
Util.encode(
"Wrong password."
)
)
}
}
}
}
return
}
// ======================================================
// FORGOT PASSWORD START
// ======================================================
if (
command ==
"RECOVERY_START"
) {
if (
p.length < 2
) {
return
}
val username =
Util.decode(
p(1)
).trim
lock.synchronized {
users.get(
username.toLowerCase
) match {
case None =>
client.send(
"ERROR|" +
Util.encode(
"Recovery failed."
)
)
case Some(user) =>
val nonce =
Util.randomHex(
32
)
recoveryChallenges.put(
client.socket,
(
user.username,
nonce
)
)
client.send(
"RECOVERY_CHALLENGE|" +
Util.encode(
nonce
)
)
}
}
return
}
// ======================================================
// FORGOT PASSWORD FINISH
// ======================================================
if (
command ==
"RECOVERY_FINISH"
) {
if (
p.length < 5
) {
return
}
lock.synchronized {
recoveryChallenges
.get(
client.socket
) match {
case None =>
client.send(
"ERROR|" +
Util.encode(
"Recovery expired."
)
)
case Some(
(
username,
nonce
)
) =>
val proof =
Util.decode(
p(2)
)
val newSalt =
Util.decode(
p(3)
)
val newVerifier =
Util.decode(
p(4)
)
val expected =
Util.sha256(
recoveryVerifier +
nonce
)
if (
Util.secureEquals(
proof,
expected
)
) {
users.get(
username.toLowerCase
) match {
case Some(oldUser) =>
val updated =
oldUser.copy(
passwordSalt =
newSalt,
passwordVerifier =
newVerifier
)
users.put(
username.toLowerCase,
updated
)
saveProfile(
updated
)
client.send(
"RECOVERY_OK"
)
case None =>
client.send(
"ERROR|" +
Util.encode(
"Recovery failed."
)
)
}
} else {
client.send(
"ERROR|" +
Util.encode(
"Recovery failed."
)
)
}
recoveryChallenges.remove(
client.socket
)
}
}
return
}
// ======================================================
// REQUIRE LOGIN
// ======================================================
val currentUser =
client.username
if (
currentUser == null ||
currentUser.isEmpty
) {
client.send(
"ERROR|" +
Util.encode(
"Please login first."
)
)
return
}
// ======================================================
// SEARCH PEOPLE
// ======================================================
if (
command ==
"SEARCH"
) {
val query =
if (
p.length >= 2
) {
Util.decode(
p(1)
).trim.toLowerCase
} else {
""
}
val found =
users.values
.filter {
user =>
user.username
.toLowerCase
.contains(
query
) &&
!user.username
.equalsIgnoreCase(
currentUser
)
}
.toSeq
.sortBy(
_.username.toLowerCase
)
.take(100)
val result =
new StringBuilder()
result.append(
"SEARCH_RESULT|" +
found.length
)
found.foreach {
user =>
result.append(
"|" +
Util.encode(
user.username
)
)
result.append(
"|" +
Util.encode(
user.bio
)
)
result.append(
"|" +
(
if (
sessions.contains(
user.username.toLowerCase
)
) {
"1"
} else {
"0"
}
)
)
}
client.send(
result.toString
)
return
}
// ======================================================
// GET PROFILE
// ======================================================
if (
command ==
"PROFILE"
) {
if (
p.length < 2
) {
return
}
val target =
Util.decode(
p(1)
).trim
users.get(
target.toLowerCase
) match {
case None =>
client.send(
"ERROR|" +
Util.encode(
"Profile not found."
)
)
case Some(user) =>
client.send(
"PROFILE_DATA|" +
Util.encode(
user.username
) +
"|" +
Util.encode(
user.bio
) +
"|" +
Util.encode(
user.avatar
) +
"|" +
(
if (
sessions.contains(
user.username.toLowerCase
)
) {
"1"
} else {
"0"
}
)
)
}
return
}
// ======================================================
// UPDATE PROFILE
// ======================================================
if (
command ==
"UPDATE_PROFILE"
) {
if (
p.length < 3
) {
return
}
lock.synchronized {
users.get(
currentUser.toLowerCase
) match {
case None =>
client.send(
"ERROR|" +
Util.encode(
"Profile not found."
)
)
case Some(oldUser) =>
val bio =
Util.clean(
Util.decode(
p(1)
),
500
)
val avatar =
Util.decode(
p(2)
)
val finalAvatar =
if (
avatar.length <=
480000
) {
avatar
} else {
oldUser.avatar
}
val updated =
oldUser.copy(
bio =
bio,
avatar =
finalAvatar
)
users.put(
currentUser.toLowerCase,
updated
)
saveProfile(
updated
)
client.send(
"PROFILE_SAVED"
)
onlineUsersNotify(
currentUser
)
}
}
return
}
// ======================================================
// OPEN DIRECT CHAT
// ======================================================
if (
command ==
"OPEN_DM"
) {
if (
p.length < 2
) {
return
}
val target =
Util.decode(
p(1)
).trim
if (
!users.contains(
target.toLowerCase
)
) {
client.send(
"ERROR|" +
Util.encode(
"User does not exist."
)
)
} else if (
target.equalsIgnoreCase(
currentUser
)
) {
client.send(
"ERROR|" +
Util.encode(
"You cannot chat with yourself."
)
)
} else {
lock.synchronized {
val chatId =
directChatId(
currentUser,
target
)
addMember(
chatId,
currentUser
)
addMember(
chatId,
target
)
chatGroups.put(
chatId,
false
)
chatNames.put(
chatId,
""
)
chatHistory.getOrElseUpdate(
chatId,
mutable.ListBuffer[
ChatMessage
]()
)
addChatToUser(
chatId,
currentUser
)
addChatToUser(
chatId,
target
)
sendHistory(
client,
chatId
)
}
}
return
}
// ======================================================
// CREATE GROUP
// ======================================================
if (
command ==
"CREATE_GROUP"
) {
if (
p.length < 3
) {
return
}
val groupName =
Util.clean(
Util.decode(
p(1)
),
40
)
val count =
try {
p(2).toInt
} catch {
case _: Throwable =>
0
}
if (
groupName.isEmpty ||
count < 1 ||
count > 20 ||
p.length <
3 + count
) {
client.send(
"ERROR|" +
Util.encode(
"Invalid group."
)
)
return
}
lock.synchronized {
val members =
mutable.Set[String]()
members +=
currentUser
var i =
0
while (
i < count
) {
val name =
Util.decode(
p(
3 + i
)
).trim
if (
users.contains(
name.toLowerCase
) &&
!name.equalsIgnoreCase(
currentUser
)
) {
members +=
users(
name.toLowerCase
).username
}
i +=
1
}
if (
members.size < 2
) {
client.send(
"ERROR|" +
Util.encode(
"At least one other person is required."
)
)
} else {
val chatId =
"GROUP:" +
UUID.randomUUID()
.toString
chatMembers.put(
chatId,
members
)
chatGroups.put(
chatId,
true
)
chatNames.put(
chatId,
groupName
)
chatHistory.put(
chatId,
mutable.ListBuffer[
ChatMessage
]()
)
members.foreach {
member =>
addChatToUser(
chatId,
member
)
}
client.send(
"GROUP_CREATED|" +
Util.encode(
groupName
)
)
}
}
return
}
// ======================================================
// OPEN CHAT
// ======================================================
if (
command ==
"OPEN_CHAT"
) {
if (
p.length < 2
) {
return
}
val chatId =
Util.decode(
p(1)
)
val allowed =
chatMembers
.get(chatId)
.exists {
members =>
members.contains(
currentUser
)
}
if (
allowed
) {
sendHistory(
client,
chatId
)
} else {
client.send(
"ERROR|" +
Util.encode(
"You are not a member of this chat."
)
)
}
return
}
// ======================================================
// SEND MESSAGE
// ======================================================
if (
command ==
"SEND_MESSAGE"
) {
if (
p.length < 3
) {
return
}
val chatId =
Util.decode(
p(1)
)
val message =
Util.clean(
Util.decode(
p(2)
),
2000
)
val allowed =
chatMembers
.get(chatId)
.exists {
members =>
members.contains(
currentUser
)
}
if (
allowed &&
message.nonEmpty
) {
val item =
ChatMessage(
currentUser,
message,
Util.now()
)
val list =
chatHistory.getOrElseUpdate(
chatId,
mutable.ListBuffer[
ChatMessage
]()
)
list +=
item
while (
list.length > 300
) {
list.remove(0)
}
broadcastChat(
chatId,
"MESSAGE|" +
Util.encode(
chatId
) +
"|" +
Util.encode(
item.sender
) +
"|" +
Util.encode(
item.time
) +
"|" +
Util.encode(
item.text
)
)
}
return
}
// ======================================================
// PING
// ======================================================
if (
command ==
"PING"
) {
client.send(
"PONG"
)
return
}
}
// ========================================================
// PRESENCE
// ========================================================
private def broadcastPresence(
username: String
): Unit = {
val state =
if (
sessions.contains(
username.toLowerCase
)
) {
"1"
} else {
"0"
}
val line =
"PRESENCE|" +
Util.encode(
username
) +
"|" +
state
sessions.values.foreach {
client =>
client.send(
line
)
}
}
// ========================================================
// PROFILE NOTIFICATION
// ========================================================
private def onlineUsersNotify(
username: String
): Unit = {
sessions.values.foreach {
client =>
client.send(
"PROFILE_CHANGED|" +
Util.encode(
username
)
)
}
}
}
// ==========================================================
// CLIENT
// ==========================================================
class ChatClient {
var socket:
Socket = null
var reader:
BufferedReader = null
var writer:
PrintWriter = null
var connected =
false
var username =
""
var password =
""
var registerUsername =
""
var registerPassword =
""
var registerBio =
""
var registerAvatar =
""
var recoveryUsername =
""
var recoverySecret =
""
var recoveryNewPassword =
""
var ownBio =
""
var ownAvatar =
""
var callback:
String => Unit =
(_: String) => {}
// ========================================================
// CONNECT
// ========================================================
def connect(
host: String,
port: Int
): Boolean = {
if (
connected
) {
return true
}
try {
socket =
new Socket()
socket.setKeepAlive(
true
)
socket.setTcpNoDelay(
true
)
socket.connect(
new InetSocketAddress(
host,
port
),
7000
)
reader =
new BufferedReader(
new InputStreamReader(
socket.getInputStream,
StandardCharsets.UTF_8
)
)
writer =
new PrintWriter(
new OutputStreamWriter(
socket.getOutputStream,
StandardCharsets.UTF_8
),
true
)
connected =
true
val thread =
new Thread(
new Runnable {
override def run(): Unit = {
readLoop()
}
}
)
thread.setDaemon(
true
)
thread.start()
true
} catch {
case _: Throwable =>
connected =
false
false
}
}
// ========================================================
// SEND
// ========================================================
def send(
line: String
): Unit = {
if (
connected &&
writer != null
) {
try {
writer.println(
line
)
writer.flush()
} catch {
case _: Throwable =>
}
}
}
// ========================================================
// CLOSE
// ========================================================
def close(): Unit = {
connected =
false
try {
if (
socket != null
) {
socket.close()
}
} catch {
case _: Throwable =>
}
}
// ========================================================
// READ LOOP
// ========================================================
private def readLoop():
Unit = {
try {
while (
connected
) {
val line =
reader.readLine()
if (
line == null
) {
throw new IOException(
"Disconnected"
)
}
val message =
line
SwingUtilities.invokeLater(
new Runnable {
override def run(): Unit = {
processEvent(
message
)
}
}
)
}
} catch {
case _: Throwable =>
connected =
false
}
}
// ========================================================
// EVENTS
// ========================================================
private def processEvent(
line: String
): Unit = {
val p =
line.split(
"\\|",
-1
)
if (
p.length == 0
) {
return
}
p(0) match {
// ----------------------------------------------------
// LOGIN CHALLENGE
// ----------------------------------------------------
case "LOGIN_CHALLENGE" =>
if (
p.length >= 3
) {
val salt =
Util.decode(
p(1)
)
val nonce =
Util.decode(
p(2)
)
val verifier =
Util.sha256(
salt +
password
)
val proof =
Util.sha256(
verifier +
nonce
)
send(
"LOGIN_FINISH|" +
Util.encode(
username
) +
"|" +
Util.encode(
proof
)
)
}
// ----------------------------------------------------
// REGISTER CHALLENGE
// ----------------------------------------------------
case "REGISTER_CHALLENGE" =>
if (
p.length >= 2
) {
val salt =
Util.decode(
p(1)
)
val verifier =
Util.sha256(
salt +
registerPassword
)
// Empty field kept for protocol compatibility.
send(
"REGISTER_FINISH|" +
Util.encode(
registerUsername
) +
"|" +
Util.encode(
verifier
) +
"|" +
Util.encode(
registerBio
) +
"|" +
Util.encode(
registerAvatar
) +
"|" +
Util.encode(
"END"
)
)
}
// ----------------------------------------------------
// RECOVERY CHALLENGE
// ----------------------------------------------------
case "RECOVERY_CHALLENGE" =>
if (
p.length >= 2
) {
val nonce =
Util.decode(
p(1)
)
val recoveryHash =
Util.sha256(
recoverySecret
)
val proof =
Util.sha256(
recoveryHash +
nonce
)
val newSalt =
Util.randomHex(
16
)
val newVerifier =
Util.sha256(
newSalt +
recoveryNewPassword
)
send(
"RECOVERY_FINISH|" +
Util.encode(
recoveryUsername
) +
"|" +
Util.encode(
proof
) +
"|" +
Util.encode(
newSalt
) +
"|" +
Util.encode(
newVerifier
)
)
recoverySecret =
""
recoveryNewPassword =
""
}
// ----------------------------------------------------
// LOGIN OK
// ----------------------------------------------------
case "LOGIN_OK" =>
if (
p.length >= 2
) {
username =
Util.decode(
p(1)
)
password =
""
callback(
line
)
}
case "RECOVERY_OK" =>
callback(line)
case "SEARCH_RESULT" =>
callback(line)
case "PROFILE_DATA" =>
callback(line)
case "PROFILE_SAVED" =>
callback(line)
case "PROFILE_CHANGED" =>
callback(line)
case "CHAT" =>
callback(line)
case "HISTORY" =>
callback(line)
case "MESSAGE" =>
callback(line)
case "PRESENCE" =>
callback(line)
case "GROUP_CREATED" =>
callback(line)
case "ERROR" =>
val text =
if (
p.length >= 2
) {
Util.decode(
p(1)
)
} else {
"Unknown error."
}
JOptionPane.showMessageDialog(
null,
text,
APP_NAME,
JOptionPane.ERROR_MESSAGE
)
case _ =>
}
}
}
// ==========================================================
// LOGIN FRAME
// ==========================================================
class LoginFrame {
private val frame =
new JFrame(
APP_NAME
)
private val client =
new ChatClient
private val hostField =
new JTextField(
"127.0.0.1"
)
private val portField =
new JTextField(
DEFAULT_PORT.toString
)
private val usernameField =
new JTextField()
private val passwordField =
new JPasswordField()
// ========================================================
// SHOW
// ========================================================
def show(): Unit = {
Util.setupFont()
frame.setTitle(
APP_NAME +
" - Login"
)
frame.setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE
)
frame.setSize(
760,
560
)
frame.setLocationRelativeTo(
null
)
val root =
new JPanel(
new BorderLayout(
15,
15
)
)
root.setBorder(
BorderFactory.createEmptyBorder(
20,
20,
20,
20
)
)
// ------------------------------------------------------
// TITLE
// ------------------------------------------------------
val title =
new JLabel(
"<html>" +
"<font size='6'><b>YADNESH LIVE CHAT</b></font><br>" +
"<font size='3'>Permanent Accounts ? Wi-Fi PC ? PC</font>" +
"</html>"
)
root.add(
title,
BorderLayout.NORTH
)
// ------------------------------------------------------
// FORM
// ------------------------------------------------------
val form =
new JPanel(
new GridLayout(
4,
2,
8,
8
)
)
form.add(
new JLabel(
"Server IP / Host:"
)
)
form.add(
hostField
)
form.add(
new JLabel(
"Port:"
)
)
form.add(
portField
)
form.add(
new JLabel(
"Username / ID:"
)
)
form.add(
usernameField
)
form.add(
new JLabel(
"Password:"
)
)
form.add(
passwordField
)
root.add(
form,
BorderLayout.CENTER
)
// ------------------------------------------------------
// BUTTONS
// ------------------------------------------------------
val loginButton =
new JButton(
"LOGIN"
)
val registerButton =
new JButton(
"CREATE NEW ACCOUNT"
)
val forgotButton =
new JButton(
"FORGOT PASSWORD"
)
val hostButton =
new JButton(
"HOST SERVER"
)
val buttons =
new JPanel(
new GridLayout(
2,
2,
8,
8
)
)
buttons.add(
loginButton
)
buttons.add(
registerButton
)
buttons.add(
forgotButton
)
buttons.add(
hostButton
)
root.add(
buttons,
BorderLayout.SOUTH
)
// ======================================================
// LOGIN
// ======================================================
loginButton.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
doLogin()
}
}
)
// ======================================================
// REGISTER
// ======================================================
registerButton.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
doRegister()
}
}
)
// ======================================================
// FORGOT
// ======================================================
forgotButton.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
forgotPassword()
}
}
)
// ======================================================
// HOST
// ======================================================
hostButton.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
hostServer()
}
}
)
frame.setContentPane(
root
)
frame.setVisible(
true
)
}
// ========================================================
// PORT
// ========================================================
private def portNumber(): Int = {
try {
val port =
portField
.getText
.trim
.toInt
if (
port >= 1024 &&
port <= 65535
) {
port
} else {
-1
}
} catch {
case _: Throwable =>
-1
}
}
// ========================================================
// CONNECT
// ========================================================
private def connect(): Boolean = {
val host =
hostField
.getText
.trim
val port =
portNumber()
if (
host.isEmpty ||
port <= 0
) {
JOptionPane.showMessageDialog(
frame,
"Enter correct server IP and port.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
false
} else {
val ok =
client.connect(
host,
port
)
if (!ok) {
JOptionPane.showMessageDialog(
frame,
"Cannot connect.\n\n" +
"Host: " +
host +
"\nPort: " +
port +
"\n\n" +
"Check the Host PC, Wi-Fi and Windows Firewall.",
APP_NAME,
JOptionPane.ERROR_MESSAGE
)
}
ok
}
}
// ========================================================
// LOGIN
// ========================================================
private def doLogin(): Unit = {
val name =
usernameField
.getText
.trim
val pass =
new String(
passwordField
.getPassword
)
if (
!Util.validUsername(
name
)
) {
JOptionPane.showMessageDialog(
frame,
"Username must be 3-20 characters.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
if (
pass.isEmpty
) {
JOptionPane.showMessageDialog(
frame,
"Enter password.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
if (
connect()
) {
client.username =
name
client.password =
pass
client.callback =
loginEvent
client.send(
"LOGIN_START|" +
Util.encode(
name
)
)
}
}
// ========================================================
// LOGIN EVENT
// ========================================================
private def loginEvent(
line: String
): Unit = {
if (
line.startsWith(
"LOGIN_OK|"
)
) {
openMain()
}
}
// ========================================================
// REGISTER
// ========================================================
private def doRegister(): Unit = {
val dialog =
new JDialog(
frame,
"CREATE NEW ACCOUNT",
true
)
dialog.setSize(
680,
560
)
dialog.setLocationRelativeTo(
frame
)
val username =
new JTextField()
val password =
new JPasswordField()
val confirm =
new JPasswordField()
val bio =
new JTextField(
"Hello! I use Yadnesh Live Chat."
)
val choose =
new JButton(
"CHOOSE IMAGE"
)
val paste =
new JButton(
"PASTE IMAGE"
)
val imageLabel =
new JLabel(
"No image selected"
)
var avatar =
""
// ------------------------------------------------------
// FORM
// ------------------------------------------------------
val form =
new JPanel(
new GridLayout(
6,
2,
8,
8
)
)
form.setBorder(
BorderFactory.createEmptyBorder(
15,
15,
15,
15
)
)
form.add(
new JLabel(
"Username / ID:"
)
)
form.add(
username
)
form.add(
new JLabel(
"Password:"
)
)
form.add(
password
)
form.add(
new JLabel(
"Confirm Password:"
)
)
form.add(
confirm
)
form.add(
new JLabel(
"Public Bio:"
)
)
form.add(
bio
)
form.add(
new JLabel(
"Profile Image:"
)
)
val imagePanel =
new JPanel(
new BorderLayout(
5,
5
)
)
val imageButtons =
new JPanel(
new GridLayout(
1,
2,
5,
5
)
)
imageButtons.add(
choose
)
imageButtons.add(
paste
)
imagePanel.add(
imageButtons,
BorderLayout.WEST
)
imagePanel.add(
imageLabel,
BorderLayout.CENTER
)
form.add(
imagePanel
)
val create =
new JButton(
"CREATE ACCOUNT"
)
form.add(
new JLabel(
""
)
)
form.add(
create
)
// ------------------------------------------------------
// CHOOSE IMAGE
// ------------------------------------------------------
choose.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
val chooser =
new JFileChooser()
if (
chooser.showOpenDialog(
dialog
) ==
JFileChooser.APPROVE_OPTION
) {
val encoded =
Util.fileToBase64(
chooser
.getSelectedFile
.getAbsolutePath
)
if (
encoded.nonEmpty
) {
avatar =
encoded
imageLabel.setText(
"Image selected ?"
)
} else {
JOptionPane.showMessageDialog(
dialog,
"Image invalid or larger than about 350 KB.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
}
}
}
}
)
// ------------------------------------------------------
// PASTE IMAGE
// ------------------------------------------------------
paste.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
val encoded =
Util.clipboardImageBase64()
if (
encoded.nonEmpty
) {
avatar =
encoded
imageLabel.setText(
"Pasted image saved ?"
)
} else {
JOptionPane.showMessageDialog(
dialog,
"Clipboard does not contain an image.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
}
}
}
)
// ------------------------------------------------------
// CREATE
// ------------------------------------------------------
create.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
val name =
username
.getText
.trim
val pass =
new String(
password
.getPassword
)
val confirmPass =
new String(
confirm
.getPassword
)
if (
!Util.validUsername(
name
)
) {
JOptionPane.showMessageDialog(
dialog,
"Username must be 3-20 characters.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
if (
pass.length < 4
) {
JOptionPane.showMessageDialog(
dialog,
"Password needs at least 4 characters.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
if (
pass != confirmPass
) {
JOptionPane.showMessageDialog(
dialog,
"Passwords do not match.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
if (
!connect()
) {
return
}
client.registerUsername =
name
client.registerPassword =
pass
client.registerBio =
bio.getText.trim
client.registerAvatar =
avatar
client.callback =
registerEvent
client.send(
"REGISTER_START|" +
Util.encode(
name
)
)
dialog.dispose()
}
}
)
dialog.setContentPane(
form
)
dialog.setVisible(
true
)
}
// ========================================================
// REGISTER EVENT
// ========================================================
private def registerEvent(
line: String
): Unit = {
if (
line.startsWith(
"LOGIN_OK|"
)
) {
openMain()
}
}
// ========================================================
// FORGOT PASSWORD
// ========================================================
private def forgotPassword(): Unit = {
val dialog =
new JDialog(
frame,
"FORGOT PASSWORD",
true
)
dialog.setSize(
570,
420
)
dialog.setLocationRelativeTo(
frame
)
val username =
new JTextField()
val recovery =
new JPasswordField()
val newPassword =
new JPasswordField()
val confirm =
new JPasswordField()
val reset =
new JButton(
"RESET PASSWORD"
)
val note =
new JLabel(
"<html>" +
"Enter your Username / ID, private recovery secret,<br>" +
"and choose a new password." +
"</html>"
)
val form =
new JPanel(
new GridLayout(
5,
2,
8,
8
)
)
form.setBorder(
BorderFactory.createEmptyBorder(
15,
15,
15,
15
)
)
form.add(
new JLabel(
"Info:"
)
)
form.add(
note
)
form.add(
new JLabel(
"Username / ID:"
)
)
form.add(
username
)
form.add(
new JLabel(
"Recovery Secret:"
)
)
form.add(
recovery
)
form.add(
new JLabel(
"New Password:"
)
)
form.add(
newPassword
)
form.add(
new JLabel(
"Confirm:"
)
)
form.add(
confirm
)
val panel =
new JPanel(
new BorderLayout(
8,
8
)
)
panel.add(
form,
BorderLayout.CENTER
)
panel.add(
reset,
BorderLayout.SOUTH
)
reset.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
val name =
username
.getText
.trim
val secret =
new String(
recovery
.getPassword
)
val newPass =
new String(
newPassword
.getPassword
)
val confirmPass =
new String(
confirm
.getPassword
)
if (
!Util.validUsername(
name
)
) {
JOptionPane.showMessageDialog(
dialog,
"Enter valid username.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
if (
secret.isEmpty
) {
JOptionPane.showMessageDialog(
dialog,
"Enter recovery secret.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
if (
newPass.length < 4
) {
JOptionPane.showMessageDialog(
dialog,
"New password needs at least 4 characters.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
if (
newPass != confirmPass
) {
JOptionPane.showMessageDialog(
dialog,
"New passwords do not match.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
if (
!connect()
) {
return
}
client.recoveryUsername =
name
client.recoverySecret =
secret
client.recoveryNewPassword =
newPass
client.callback =
recoveryEvent
client.send(
"RECOVERY_START|" +
Util.encode(
name
)
)
dialog.dispose()
}
}
)
dialog.setContentPane(
panel
)
dialog.setVisible(
true
)
}
// ========================================================
// RECOVERY EVENT
// ========================================================
private def recoveryEvent(
line: String
): Unit = {
if (
line ==
"RECOVERY_OK"
) {
JOptionPane.showMessageDialog(
frame,
"Password reset successfully.\nYou can now login.",
APP_NAME,
JOptionPane.INFORMATION_MESSAGE
)
client.callback =
loginEvent
}
}
// ========================================================
// HOST SERVER
// ========================================================
private def hostServer(): Unit = {
val port =
portNumber()
if (
port <= 0
) {
JOptionPane.showMessageDialog(
frame,
"Port must be between 1024 and 65535.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
val started =
Server.start(
port
)
if (!started) {
JOptionPane.showMessageDialog(
frame,
"Could not start server.\nThe port may already be in use.",
APP_NAME,
JOptionPane.ERROR_MESSAGE
)
return
}
val ips =
Util.localIPs()
val text =
new StringBuilder()
text.append(
"SERVER STARTED\n\n"
)
text.append(
"Port: " +
port +
"\n\n"
)
text.append(
"OTHER PC SHOULD USE:\n\n"
)
var i =
0
while (
i < ips.length
) {
text.append(
ips(i) +
":" +
port +
"\n"
)
i +=
1
}
text.append(
"\nBoth PCs must normally be on the same Wi-Fi/router."
)
JOptionPane.showMessageDialog(
frame,
text.toString,
APP_NAME,
JOptionPane.INFORMATION_MESSAGE
)
hostField.setText(
"127.0.0.1"
)
portField.setText(
port.toString
)
}
// ========================================================
// OPEN MAIN
// ========================================================
private def openMain(): Unit = {
frame.dispose()
val main =
new MainFrame(
client
)
client.callback =
main.handleServerEvent
main.show()
client.send(
"PROFILE|" +
Util.encode(
client.username
)
)
client.send(
"SEARCH|" +
Util.encode(
""
)
)
}
}
// ==========================================================
// MAIN CHAT WINDOW
// ==========================================================
class MainFrame(
client: ChatClient
) {
private val frame =
new JFrame(
APP_NAME +
" - " +
client.username
)
private val peopleModel =
new DefaultListModel[
PersonItem
]()
private val chatModel =
new DefaultListModel[
ChatItem
]()
private val peopleList =
new JList[
PersonItem
](
peopleModel
)
private val chatList =
new JList[
ChatItem
](
chatModel
)
private val searchField =
new JTextField()
private val chatArea =
new JTextArea()
private val messageField =
new JTextField()
private val sendButton =
new JButton(
"SEND"
)
private val chatTitle =
new JLabel(
"Select a chat"
)
private val profileName =
new JLabel(
"No person selected"
)
private val profileStatus =
new JLabel(
""
)
private val profileBio =
new JTextArea()
private val profileImage =
new JLabel(
"No Photo",
SwingConstants.CENTER
)
private val openChatButton =
new JButton(
"OPEN DIRECT CHAT"
)
private val groupButton =
new JButton(
"CREATE GROUP"
)
private val editButton =
new JButton(
"EDIT MY PROFILE"
)
private var selectedPerson =
""
private var currentChat =
""
private val chatMap =
mutable.Map[
String,
ChatItem
]()
// ========================================================
// SHOW
// ========================================================
def show(): Unit = {
Util.setupFont()
frame.setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE
)
frame.setSize(
1250,
760
)
frame.setMinimumSize(
new Dimension(
1000,
650
)
)
frame.setLocationRelativeTo(
null
)
val root =
new JPanel(
new BorderLayout(
7,
7
)
)
// ======================================================
// TOP BAR
// ======================================================
val top =
new JPanel(
new BorderLayout()
)
top.setBackground(
new Color(
33,
38,
46
)
)
val title =
new JLabel(
" YADNESH LIVE CHAT"
)
title.setForeground(
Color.WHITE
)
title.setFont(
new Font(
"Segoe UI",
Font.BOLD,
22
)
)
val userText =
new JLabel(
"Logged in: " +
client.username +
" "
)
userText.setForeground(
Color.WHITE
)
top.add(
title,
BorderLayout.WEST
)
top.add(
userText,
BorderLayout.EAST
)
root.add(
top,
BorderLayout.NORTH
)
// ======================================================
// LEFT
// ======================================================
val left =
new JPanel(
new BorderLayout(
5,
5
)
)
left.setPreferredSize(
new Dimension(
300,
100
)
)
val searchPanel =
new JPanel(
new BorderLayout(
5,
5
)
)
val searchButton =
new JButton(
"SEARCH"
)
searchPanel.add(
searchField,
BorderLayout.CENTER
)
searchPanel.add(
searchButton,
BorderLayout.EAST
)
left.add(
searchPanel,
BorderLayout.NORTH
)
// ------------------------------------------------------
// PEOPLE
// ------------------------------------------------------
peopleList.setSelectionMode(
ListSelectionModel.MULTIPLE_INTERVAL_SELECTION
)
val peoplePanel =
new JPanel(
new BorderLayout(
3,
3
)
)
peoplePanel.add(
new JLabel(
" PEOPLE"
),
BorderLayout.NORTH
)
peoplePanel.add(
new JScrollPane(
peopleList
),
BorderLayout.CENTER
)
// ------------------------------------------------------
// CHATS
// ------------------------------------------------------
val chatPanel =
new JPanel(
new BorderLayout(
3,
3
)
)
chatPanel.add(
new JLabel(
" MY CHATS"
),
BorderLayout.NORTH
)
chatPanel.add(
new JScrollPane(
chatList
),
BorderLayout.CENTER
)
val leftCenter =
new JPanel(
new GridLayout(
2,
1,
5,
5
)
)
leftCenter.add(
peoplePanel
)
leftCenter.add(
chatPanel
)
left.add(
leftCenter,
BorderLayout.CENTER
)
left.add(
groupButton,
BorderLayout.SOUTH
)
root.add(
left,
BorderLayout.WEST
)
// ======================================================
// CENTER
// ======================================================
val center =
new JPanel(
new BorderLayout(
5,
5
)
)
chatTitle.setFont(
new Font(
"Segoe UI",
Font.BOLD,
18
)
)
center.add(
chatTitle,
BorderLayout.NORTH
)
chatArea.setEditable(
false
)
chatArea.setLineWrap(
true
)
chatArea.setWrapStyleWord(
true
)
chatArea.setFont(
new Font(
"Segoe UI",
Font.PLAIN,
14
)
)
val messageScroll =
new JScrollPane(
chatArea
)
center.add(
messageScroll,
BorderLayout.CENTER
)
val sendPanel =
new JPanel(
new BorderLayout(
5,
5
)
)
sendPanel.add(
messageField,
BorderLayout.CENTER
)
sendPanel.add(
sendButton,
BorderLayout.EAST
)
center.add(
sendPanel,
BorderLayout.SOUTH
)
root.add(
center,
BorderLayout.CENTER
)
// ======================================================
// RIGHT PROFILE
// ======================================================
val right =
new JPanel(
new BorderLayout(
5,
5
)
)
right.setPreferredSize(
new Dimension(
285,
100
)
)
right.add(
new JLabel(
" PROFILE"
),
BorderLayout.NORTH
)
profileImage.setPreferredSize(
new Dimension(
235,
180
)
)
profileImage.setBorder(
BorderFactory.createLineBorder(
new Color(
180,
180,
180
)
)
)
val profileText =
new JPanel(
new BorderLayout(
5,
5
)
)
val names =
new JPanel(
new GridLayout(
2,
1,
3,
3
)
)
names.add(
profileName
)
names.add(
profileStatus
)
profileText.add(
names,
BorderLayout.NORTH
)
profileBio.setEditable(
false
)
profileBio.setLineWrap(
true
)
profileBio.setWrapStyleWord(
true
)
profileText.add(
new JScrollPane(
profileBio
),
BorderLayout.CENTER
)
val profileCenter =
new JPanel(
new BorderLayout(
5,
5
)
)
profileCenter.add(
profileImage,
BorderLayout.NORTH
)
profileCenter.add(
profileText,
BorderLayout.CENTER
)
right.add(
profileCenter,
BorderLayout.CENTER
)
val profileButtons =
new JPanel(
new GridLayout(
3,
1,
5,
5
)
)
profileButtons.add(
openChatButton
)
profileButtons.add(
editButton
)
profileButtons.add(
groupButton
)
// group button exists already in left.
// Keep right panel only for profile actions.
profileButtons.remove(
groupButton
)
right.add(
profileButtons,
BorderLayout.SOUTH
)
root.add(
right,
BorderLayout.EAST
)
// ======================================================
// SEARCH
// ======================================================
searchButton.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
searchPeople()
}
}
)
searchField.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
searchPeople()
}
}
)
// ======================================================
// PERSON SELECT
// ======================================================
peopleList.addListSelectionListener(
_ => {
val person =
peopleList
.getSelectedValue
if (
person != null
) {
selectedPerson =
person.username
profileName.setText(
person.username
)
profileStatus.setText(
if (person.online) {
"? ONLINE"
} else {
"? OFFLINE"
}
)
profileBio.setText(
if (
person.bio.isEmpty
) {
"No public bio."
} else {
person.bio
}
)
client.send(
"PROFILE|" +
Util.encode(
person.username
)
)
}
}
)
// ======================================================
// DOUBLE CLICK
// ======================================================
peopleList.addMouseListener(
new MouseAdapter {
override def mouseClicked(
e: MouseEvent
): Unit = {
if (
e.getClickCount == 2
) {
val person =
peopleList
.getSelectedValue
if (
person != null
) {
openDirectChat(
person.username
)
}
}
}
}
)
// ======================================================
// OPEN DIRECT CHAT
// ======================================================
openChatButton.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
if (
selectedPerson != null &&
selectedPerson.nonEmpty
) {
openDirectChat(
selectedPerson
)
}
}
}
)
// ======================================================
// CHAT LIST
// ======================================================
chatList.addListSelectionListener(
_ => {
val chat =
chatList
.getSelectedValue
if (
chat != null
) {
currentChat =
chat.id
chatTitle.setText(
chat.title
)
chatArea.setText(
"Loading messages..."
)
client.send(
"OPEN_CHAT|" +
Util.encode(
chat.id
)
)
}
}
)
// ======================================================
// SEND
// ======================================================
sendButton.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
sendMessage()
}
}
)
messageField.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
sendMessage()
}
}
)
// ======================================================
// EDIT
// ======================================================
editButton.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
editProfile()
}
}
)
frame.setContentPane(
root
)
frame.setVisible(
true
)
}
// ========================================================
// SEARCH
// ========================================================
private def searchPeople(): Unit = {
client.send(
"SEARCH|" +
Util.encode(
searchField
.getText
.trim
)
)
}
// ========================================================
// DIRECT CHAT
// ========================================================
private def openDirectChat(
username: String
): Unit = {
client.send(
"OPEN_DM|" +
Util.encode(
username
)
)
}
// ========================================================
// SEND MESSAGE
// ========================================================
private def sendMessage(): Unit = {
if (
currentChat == null ||
currentChat.isEmpty
) {
JOptionPane.showMessageDialog(
frame,
"First select a chat.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
val message =
messageField
.getText
.trim
if (
message.isEmpty
) {
return
}
client.send(
"SEND_MESSAGE|" +
Util.encode(
currentChat
) +
"|" +
Util.encode(
message
)
)
messageField.setText(
""
)
}
// ========================================================
// CREATE GROUP
// ========================================================
private def createGroup(): Unit = {
val selected =
peopleList
.getSelectedValuesList()
if (
selected == null ||
selected.size() < 1
) {
JOptionPane.showMessageDialog(
frame,
"Select at least one person.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
return
}
val name =
JOptionPane.showInputDialog(
frame,
"Group name:",
"CREATE GROUP",
JOptionPane.QUESTION_MESSAGE
)
if (
name == null ||
name.trim.isEmpty
) {
return
}
val request =
new StringBuilder()
request.append(
"CREATE_GROUP|"
)
request.append(
Util.encode(
name.trim
)
)
request.append(
"|" +
selected.size()
)
var i =
0
while (
i < selected.size()
) {
val person =
selected.get(
i
)
request.append(
"|" +
Util.encode(
person.username
)
)
i +=
1
}
client.send(
request.toString
)
}
// ========================================================
// EDIT PROFILE
// ========================================================
private def editProfile(): Unit = {
val dialog =
new JDialog(
frame,
"EDIT MY PROFILE",
true
)
dialog.setSize(
700,
540
)
dialog.setLocationRelativeTo(
frame
)
val bio =
new JTextField(
client.ownBio
)
val choose =
new JButton(
"CHOOSE IMAGE"
)
val paste =
new JButton(
"PASTE IMAGE"
)
val imageLabel =
new JLabel(
if (
client.ownAvatar.nonEmpty
) {
"Current image saved ?"
} else {
"No image"
}
)
var avatar =
client.ownAvatar
val save =
new JButton(
"SAVE PROFILE"
)
val form =
new JPanel(
new GridLayout(
4,
2,
8,
8
)
)
form.setBorder(
BorderFactory.createEmptyBorder(
15,
15,
15,
15
)
)
form.add(
new JLabel(
"Username:"
)
)
form.add(
new JLabel(
client.username
)
)
form.add(
new JLabel(
"Public Bio:"
)
)
form.add(
bio
)
form.add(
new JLabel(
"Profile Image:"
)
)
val imagePanel =
new JPanel(
new BorderLayout(
5,
5
)
)
val imageButtons =
new JPanel(
new GridLayout(
1,
2,
5,
5
)
)
imageButtons.add(
choose
)
imageButtons.add(
paste
)
imagePanel.add(
imageButtons,
BorderLayout.WEST
)
imagePanel.add(
imageLabel,
BorderLayout.CENTER
)
form.add(
imagePanel
)
form.add(
new JLabel(
"Save:"
)
)
form.add(
save
)
choose.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
val chooser =
new JFileChooser()
if (
chooser.showOpenDialog(
dialog
) ==
JFileChooser.APPROVE_OPTION
) {
val encoded =
Util.fileToBase64(
chooser
.getSelectedFile
.getAbsolutePath
)
if (
encoded.nonEmpty
) {
avatar =
encoded
imageLabel.setText(
"New image selected ?"
)
} else {
JOptionPane.showMessageDialog(
dialog,
"Image invalid or too large.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
}
}
}
}
)
paste.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
val encoded =
Util.clipboardImageBase64()
if (
encoded.nonEmpty
) {
avatar =
encoded
imageLabel.setText(
"Pasted image saved ?"
)
} else {
JOptionPane.showMessageDialog(
dialog,
"Clipboard does not contain an image.",
APP_NAME,
JOptionPane.WARNING_MESSAGE
)
}
}
}
)
save.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
client.ownBio =
bio.getText.trim
client.ownAvatar =
avatar
client.send(
"UPDATE_PROFILE|" +
Util.encode(
client.ownBio
) +
"|" +
Util.encode(
client.ownAvatar
)
)
dialog.dispose()
}
}
)
dialog.setContentPane(
form
)
dialog.setVisible(
true
)
}
// ========================================================
// SERVER EVENTS
// ========================================================
def handleServerEvent(
line: String
): Unit = {
val p =
line.split(
"\\|",
-1
)
if (
p.length == 0
) {
return
}
p(0) match {
// ----------------------------------------------------
// SEARCH RESULTS
// ----------------------------------------------------
case "SEARCH_RESULT" =>
peopleModel.clear()
if (
p.length >= 2
) {
val count =
try {
p(1).toInt
} catch {
case _: Throwable =>
0
}
var index =
2
var i =
0
while (
i < count &&
index + 2 <
p.length
) {
val name =
Util.decode(
p(index)
)
val bio =
Util.decode(
p(index + 1)
)
val online =
p(index + 2) ==
"1"
peopleModel.addElement(
PersonItem(
name,
bio,
online
)
)
index +=
3
i +=
1
}
}
// ----------------------------------------------------
// PROFILE
// ----------------------------------------------------
case "PROFILE_DATA" =>
if (
p.length >= 5
) {
val name =
Util.decode(
p(1)
)
val bio =
Util.decode(
p(2)
)
val avatar =
Util.decode(
p(3)
)
val online =
p(4) ==
"1"
if (
name.equalsIgnoreCase(
client.username
)
) {
client.ownBio =
bio
client.ownAvatar =
avatar
}
if (
name.equalsIgnoreCase(
selectedPerson
)
) {
profileName.setText(
name
)
profileStatus.setText(
if (online) {
"? ONLINE"
} else {
"? OFFLINE"
}
)
profileBio.setText(
if (bio.isEmpty) {
"No public bio."
} else {
bio
}
)
displayAvatar(
avatar
)
}
}
// ----------------------------------------------------
// PROFILE SAVED
// ----------------------------------------------------
case "PROFILE_SAVED" =>
JOptionPane.showMessageDialog(
frame,
"Profile saved permanently on the host server.",
APP_NAME,
JOptionPane.INFORMATION_MESSAGE
)
client.send(
"PROFILE|" +
Util.encode(
client.username
)
)
searchPeople()
// ----------------------------------------------------
// PROFILE CHANGED
// ----------------------------------------------------
case "PROFILE_CHANGED" =>
if (
p.length >= 2
) {
val name =
Util.decode(
p(1)
)
if (
name.equalsIgnoreCase(
selectedPerson
)
) {
client.send(
"PROFILE|" +
Util.encode(
selectedPerson
)
)
}
searchPeople()
}
// ----------------------------------------------------
// CHAT
// ----------------------------------------------------
case "CHAT" =>
if (
p.length >= 4
) {
val id =
Util.decode(
p(1)
)
val title =
Util.decode(
p(2)
)
val group =
p(3) ==
"1"
if (
!chatMap.contains(
id
)
) {
val entry =
ChatItem(
id,
title,
group
)
chatMap.put(
id,
entry
)
chatModel.addElement(
entry
)
}
}
// ----------------------------------------------------
// HISTORY
// ----------------------------------------------------
case "HISTORY" =>
if (
p.length >= 3
) {
val id =
Util.decode(
p(1)
)
val count =
try {
p(2).toInt
} catch {
case _: Throwable =>
0
}
if (
id ==
currentChat
) {
val out =
new StringBuilder()
var index =
3
var i =
0
while (
i < count &&
index + 2 <
p.length
) {
val sender =
Util.decode(
p(index)
)
val time =
Util.decode(
p(index + 1)
)
val message =
Util.decode(
p(index + 2)
)
out.append(
"[" +
time +
"] " +
sender +
": " +
message +
"\n"
)
index +=
3
i +=
1
}
chatArea.setText(
out.toString
)
chatArea.setCaretPosition(
chatArea.getDocument
.getLength
)
}
}
// ----------------------------------------------------
// LIVE MESSAGE
// ----------------------------------------------------
case "MESSAGE" =>
if (
p.length >= 5
) {
val id =
Util.decode(
p(1)
)
val sender =
Util.decode(
p(2)
)
val time =
Util.decode(
p(3)
)
val message =
Util.decode(
p(4)
)
if (
id ==
currentChat
) {
chatArea.append(
"[" +
time +
"] " +
sender +
": " +
message +
"\n"
)
chatArea.setCaretPosition(
chatArea.getDocument
.getLength
)
}
}
// ----------------------------------------------------
// PRESENCE
// ----------------------------------------------------
case "PRESENCE" =>
if (
p.length >= 3
) {
val name =
Util.decode(
p(1)
)
val online =
p(2) ==
"1"
var i =
0
while (
i < peopleModel.size()
) {
val old =
peopleModel
.getElementAt(
i
)
if (
old.username
.equalsIgnoreCase(
name
)
) {
peopleModel.setElementAt(
old.copy(
online =
online
),
i
)
}
i +=
1
}
if (
selectedPerson
.equalsIgnoreCase(
name
)
) {
profileStatus.setText(
if (online) {
"? ONLINE"
} else {
"? OFFLINE"
}
)
}
}
// ----------------------------------------------------
// GROUP
// ----------------------------------------------------
case "GROUP_CREATED" =>
if (
p.length >= 2
) {
JOptionPane.showMessageDialog(
frame,
"Group created:\n" +
Util.decode(
p(1)
),
APP_NAME,
JOptionPane.INFORMATION_MESSAGE
)
}
case _ =>
}
}
// ========================================================
// DISPLAY AVATAR
// ========================================================
private def displayAvatar(
base64: String
): Unit = {
if (
base64 == null ||
base64.isEmpty
) {
profileImage.setIcon(
null
)
profileImage.setText(
"No Photo"
)
} else {
val image =
Util.base64ToImage(
base64
)
if (
image == null
) {
profileImage.setIcon(
null
)
profileImage.setText(
"No Photo"
)
} else {
val scaled =
image.getScaledInstance(
225,
165,
Image.SCALE_SMOOTH
)
profileImage.setText(
""
)
profileImage.setIcon(
new javax.swing.ImageIcon(
scaled
)
)
}
}
}
}
// ==========================================================
// START SCREEN
// ==========================================================
object StartScreen {
def show(): Unit = {
Util.setupFont()
val frame =
new JFrame(
APP_NAME
)
frame.setDefaultCloseOperation(
WindowConstants.EXIT_ON_CLOSE
)
frame.setSize(
720,
520
)
frame.setLocationRelativeTo(
null
)
val root =
new JPanel(
new BorderLayout(
15,
15
)
)
root.setBorder(
BorderFactory.createEmptyBorder(
30,
30,
30,
30
)
)
val title =
new JLabel(
"<html>" +
"<center>" +
"<font size='7'><b>YADNESH LIVE CHAT</b></font><br>" +
"<font size='4'>PERMANENT ACCOUNT ? WIFI LIVE CHAT</font>" +
"</center>" +
"</html>",
SwingConstants.CENTER
)
root.add(
title,
BorderLayout.NORTH
)
val info =
new JTextArea(
"FEATURES\n\n" +
"? Permanent user accounts\n" +
"? Same account after restarting app\n" +
"? Same account available from another PC through the same server\n" +
"? PC to PC live Wi-Fi chat\n" +
"? 2-person direct chat\n" +
"? Multiple-person group chat\n" +
"? Username search\n" +
"? Online / offline status\n" +
"? Profile photo\n" +
"? CHOOSE IMAGE\n" +
"? PASTE IMAGE FROM CLIPBOARD\n" +
"? Public profile bio\n" +
"? Forgot Password recovery\n\n" +
"Account files are stored on the HOST SERVER PC."
)
info.setEditable(
false
)
info.setLineWrap(
true
)
info.setWrapStyleWord(
true
)
root.add(
new JScrollPane(
info
),
BorderLayout.CENTER
)
val start =
new JButton(
"START YADNESH LIVE CHAT"
)
start.setPreferredSize(
new Dimension(
330,
55
)
)
root.add(
start,
BorderLayout.SOUTH
)
start.addActionListener(
new ActionListener {
override def actionPerformed(
e: ActionEvent
): Unit = {
frame.dispose()
val login =
new LoginFrame()
login.show()
}
}
)
frame.setContentPane(
root
)
frame.setVisible(
true
)
}
}
// ==========================================================
// LAUNCHER
// ==========================================================
def startApp(): Unit = {
SwingUtilities.invokeLater(
new Runnable {
override def run(): Unit = {
try {
UIManager.setLookAndFeel(
UIManager
.getSystemLookAndFeelClassName
)
} catch {
case _: Throwable =>
}
StartScreen.show()
}
}
)
}
}
// ============================================================
// KOJO DIRECT RUN
// ============================================================
LiveChatApp.startApp()