Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
name: CI

on:
push:
branches: [main]
pull_request:
workflow_dispatch:

permissions:
contents: read

concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: true

jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
- run: uv sync --locked
- run: uv run ruff check .
- run: uv run ruff format --check .

test:
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
python: ["3.12", "3.13", "3.14"]
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: astral-sh/setup-uv@c18668ad3cf93ea998bef934396af7bb5c839dc7 # v10.2.0
with:
python-version: ${{ matrix.python }}
- run: uv sync --locked
- run: uv run pytest -v
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
chatroom.db
__pycache__/
.venv/
1 change: 1 addition & 0 deletions .python-version
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
3.14
60 changes: 34 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,41 +1,49 @@
# Socket Chat

A socket-based chatroom application built with Python. It allows users to sign up, log in, send messages, and manage friend requests in real-time. The chatroom supports multiple clients and enables seamless communication between users using a combination of **Tkinter** for the graphical user interface and **SQLite** for database management.
[![CI](https://github.com/ABuljko/Socket-Chat/actions/workflows/ci.yml/badge.svg)](https://github.com/ABuljko/Socket-Chat/actions/workflows/ci.yml)

## Features
A simple chat app written in Python. Users sign up, add friends and send each other messages.

- **User Authentication:**
- Sign up and login functionality.
- User credentials stored securely in an SQLite database.
## Requirements

- **Real-Time Messaging:**
- Users can send and receive messages in real-time using sockets.
- Multiple users can be connected simultaneously.
- Python 3.12 or newer

- **Friend Request Management:**
- Send, accept, or reject friend requests.
- View friends list.
## How to run

- **Graphical User Interface (GUI):**
- Built with **Tkinter** for an intuitive and responsive chat interface.
Start the server:

---
```
python server.py
```

## Technologies Used
Start the app (once for each user):

- **Python** - Main programming language.
- **SQLite** - Database management system for storing user data, messages, and friend requests.
- **Tkinter** - GUI library for building the user interface.
- **Sockets** - For real-time communication between clients and server.
```
python main.py
```

---
## How to use

## Requirements
1. **File > Sign up** to create an account.
2. **Friends > Find User** to send a friend request.
3. Your friend accepts it in **Friends > Pending Requests**.
4. Click your friend's name on the left and start chatting.

## Good to know

- To start over with an empty database, run `python initialize_db.py`.
- Messages are not encrypted. Use it only on a network you trust.

## For developers

Install [uv](https://docs.astral.sh/uv/), then run the checks:

```
uv sync
uv run ruff check .
uv run pytest
```

- Python 3.x or above
- Required Python libraries:
- `socket`
- `sqlite3`
- `tkinter` (usually comes with Python)
## Contributors

Amin Niaziardekani, Swapnaneel Sarkhel, Ajdin Buljko
21 changes: 0 additions & 21 deletions add_initial_users.py

This file was deleted.

Binary file removed chatroom.db
Binary file not shown.
225 changes: 155 additions & 70 deletions chatroom_db.py
Original file line number Diff line number Diff line change
@@ -1,81 +1,166 @@
import hashlib
import hmac
import os
import sqlite3
import threading
from contextlib import closing
from datetime import UTC, datetime
from pathlib import Path

def get_chat_history(user1, user2):
conn = sqlite3.connect('chatroom.db')
c = conn.cursor()
c.execute('''
SELECT sender, receiver, message, timestamp
FROM messages
WHERE (sender = ? AND receiver = ?) OR (sender = ? AND receiver = ?)
ORDER BY timestamp
''', (user1, user2, user2, user1))
chat_history = c.fetchall()
conn.close()
return chat_history
DB_PATH = os.environ.get("CHATROOM_DB", str(Path(__file__).with_name("chatroom.db")))

def check_user(username, password):
conn = sqlite3.connect('chatroom.db')
c = conn.cursor()
c.execute('SELECT 1 FROM users WHERE username = ? AND password = ?', (username, password))
return c.fetchone() is not None
SCHEMA = """
CREATE TABLE IF NOT EXISTS users (
username TEXT PRIMARY KEY,
password TEXT
);
CREATE TABLE IF NOT EXISTS messages (
sender TEXT,
receiver TEXT,
message TEXT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS requests (
sender TEXT,
receiver TEXT,
status TEXT
);
CREATE INDEX IF NOT EXISTS messages_pair ON messages (sender, receiver);
CREATE INDEX IF NOT EXISTS requests_pair ON requests (sender, receiver);
"""

def add_user(username, password):
conn = sqlite3.connect('chatroom.db')
c = conn.cursor()
try:
c.execute('INSERT INTO users (username, password) VALUES (?, ?)', (username, password))
conn.commit()
return True
except sqlite3.IntegrityError:
SCRYPT_N, SCRYPT_R, SCRYPT_P = 2**14, 8, 1

# Request updates read, then write, so run them one at a time.
_request_lock = threading.Lock()


def connect():
return closing(sqlite3.connect(DB_PATH, timeout=10))


def init_db():
with connect() as conn:
conn.executescript(SCHEMA)


def reset_db():
with connect() as conn:
conn.executescript("""
DROP TABLE IF EXISTS users;
DROP TABLE IF EXISTS messages;
DROP TABLE IF EXISTS requests;
""")
conn.executescript(SCHEMA)


def hash_password(password):
salt = os.urandom(16)
digest = hashlib.scrypt(password.encode(), salt=salt, n=SCRYPT_N, r=SCRYPT_R, p=SCRYPT_P)
return f"scrypt${SCRYPT_N}${SCRYPT_R}${SCRYPT_P}${salt.hex()}${digest.hex()}"


def verify_password(password, stored):
if not stored or not stored.startswith("scrypt$"):
return False
_, n, r, p, salt, digest = stored.split("$")
candidate = hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=int(n), r=int(r), p=int(p))
return hmac.compare_digest(candidate, bytes.fromhex(digest))

def get_messages(username):
conn = sqlite3.connect('chatroom.db')
c = conn.cursor()
c.execute(
'SELECT sender, receiver, message, timestamp FROM messages WHERE sender = ? OR receiver = ? ORDER BY timestamp',
(username, username)
)
return c.fetchall()

def add_message(sender, receiver, message):
conn = sqlite3.connect('chatroom.db')
c = conn.cursor()
c.execute('INSERT INTO messages (sender, receiver, message) VALUES (?, ?, ?)', (sender, receiver, message))
conn.commit()
conn.close()
def add_user(username, password):
with connect() as conn, conn:
try:
conn.execute("INSERT INTO users (username, password) VALUES (?, ?)", (username, hash_password(password)))
except sqlite3.IntegrityError:
return False
return True


def check_user(username, password):
with connect() as conn:
row = conn.execute("SELECT password FROM users WHERE username = ?", (username,)).fetchone()
return row is not None and verify_password(password, row[0])


def user_exists(username):
with connect() as conn:
return conn.execute("SELECT 1 FROM users WHERE username = ?", (username,)).fetchone() is not None


def add_request(sender, receiver):
conn = sqlite3.connect('chatroom.db')
c = conn.cursor()
c.execute('INSERT INTO requests (sender, receiver, status) VALUES (?, ?, "pending")', (sender, receiver))
conn.commit()
"""Return 'sent', 'pending', 'friends', or 'accepted' if receiver had already asked sender."""
with _request_lock, connect() as conn, conn:
rows = conn.execute(
"SELECT sender, status FROM requests WHERE (sender = ? AND receiver = ?) OR (sender = ? AND receiver = ?)",
(sender, receiver, receiver, sender),
).fetchall()
if any(status == "accepted" for _, status in rows):
return "friends"
if (sender, "pending") in rows:
return "pending"
if (receiver, "pending") in rows:
conn.execute(
"UPDATE requests SET status = 'accepted' WHERE sender = ? AND receiver = ? AND status = 'pending'",
(receiver, sender),
)
return "accepted"
conn.execute("DELETE FROM requests WHERE sender = ? AND receiver = ?", (sender, receiver))
conn.execute("INSERT INTO requests (sender, receiver, status) VALUES (?, ?, 'pending')", (sender, receiver))
return "sent"


def respond_to_request(sender, receiver, accept):
"""Return False if there was no pending request."""
status = "accepted" if accept else "rejected"
with _request_lock, connect() as conn, conn:
cursor = conn.execute(
"UPDATE requests SET status = ? WHERE sender = ? AND receiver = ? AND status = 'pending'",
(status, sender, receiver),
)
return cursor.rowcount > 0


def get_requests(username):
try:
conn = sqlite3.connect('chatroom.db')
c = conn.cursor()
c.execute('SELECT sender FROM requests WHERE receiver = ? AND status = "pending"', (username,))
requests = c.fetchall()
conn.close()
return [req[0] for req in requests]
except Exception as e:
print(f"Error retrieving requests for {username}: {e}")
return []

def get_accepted_requests(username):
conn = sqlite3.connect('chatroom.db')
c = conn.cursor()
c.execute('''
SELECT sender, receiver FROM requests
WHERE (sender = ? OR receiver = ?) AND status = "accepted"
''', (username, username))
requests = c.fetchall()
conn.close()
accepted_users = set()
for sender, receiver in requests:
if sender != username:
accepted_users.add(sender)
if receiver != username:
accepted_users.add(receiver)
return list(accepted_users)
with connect() as conn:
rows = conn.execute(
"SELECT DISTINCT sender FROM requests WHERE receiver = ? AND status = 'pending' ORDER BY sender",
(username,),
).fetchall()
return [row[0] for row in rows]


def get_friends(username):
with connect() as conn:
rows = conn.execute(
"SELECT sender, receiver FROM requests WHERE (sender = ? OR receiver = ?) AND status = 'accepted'",
(username, username),
).fetchall()
return sorted({receiver if sender == username else sender for sender, receiver in rows})


def are_friends(user1, user2):
return user2 in get_friends(user1)


def add_message(sender, receiver, message):
timestamp = datetime.now(UTC).strftime("%Y-%m-%d %H:%M:%S")
with connect() as conn, conn:
conn.execute(
"INSERT INTO messages (sender, receiver, message, timestamp) VALUES (?, ?, ?, ?)",
(sender, receiver, message, timestamp),
)
return timestamp


def get_chat_history(user1, user2):
with connect() as conn:
return conn.execute(
"""
SELECT sender, receiver, message, timestamp
FROM messages
WHERE (sender = ? AND receiver = ?) OR (sender = ? AND receiver = ?)
ORDER BY timestamp, rowid
""",
(user1, user2, user2, user1),
).fetchall()
Loading
Loading