added `twutr` example app - a twitter clone

Commit cd5462e · patx · 01/22/2025 at 5:33AM

Changeset
cd5462e677b8457bf8f1f42c2d5d77f13fb97a5b
Parents
af56ee7591251edaa994ad7e5e973a578f951e97

View source at this commit

Comments

No comments yet.

Log in to comment

Diff

diff --git a/docs/index.html b/docs/index.html
index 1d544fa..a113f46 100644
--- a/docs/index.html
+++ b/docs/index.html
@@ -4,14 +4,11 @@
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
     <link rel="shortcut icon" href="https://cherrypy.dev/images/favicon.gif" type="image/x-icon">
-    <link href="https://fonts.googleapis.com/css2?family=Playwrite+VN:[email protected]&display=swap" rel="stylesheet">
     <title>MicroPie - An actual micro web framework</title>
     <style>
         .logo {
             width: 800px;
             margin: 40px auto;
-            font-family: "Playwrite VN", "Helvetica", sans-serif;
-            font-size: 100px
         }
         .body {
             font-family: "Helvetica", sans-serif;
@@ -43,7 +40,7 @@
 </head>
 <body>
     <div class="logo">
-        <img src="logo.png" alt="MicroPie logo" width=150px height=150px> MicroPie
+        <img src="logo2.png" alt="MicroPie logo">
     </div>
     <div class="body">
         <h1>Welcome</h1>
diff --git a/docs/logo.png b/docs/logo.png
deleted file mode 100644
index 7ea83ac..0000000
Binary files a/docs/logo.png and /dev/null differ
diff --git a/examples/pastebin-app/app.py b/examples/pastebin/app.py
similarity index 100%
rename from examples/pastebin-app/app.py
rename to examples/pastebin/app.py
diff --git a/examples/pastebin-app/templates/index.html b/examples/pastebin/templates/index.html
similarity index 100%
rename from examples/pastebin-app/templates/index.html
rename to examples/pastebin/templates/index.html
diff --git a/examples/pastebin-app/templates/paste.html b/examples/pastebin/templates/paste.html
similarity index 100%
rename from examples/pastebin-app/templates/paste.html
rename to examples/pastebin/templates/paste.html
diff --git a/examples/todo-app/app.py b/examples/todolist/app.py
similarity index 100%
rename from examples/todo-app/app.py
rename to examples/todolist/app.py
diff --git a/examples/todo-app/templates/index.html b/examples/todolist/templates/index.html
similarity index 100%
rename from examples/todo-app/templates/index.html
rename to examples/todolist/templates/index.html
diff --git a/examples/todo-app/templates/login.html b/examples/todolist/templates/login.html
similarity index 100%
rename from examples/todo-app/templates/login.html
rename to examples/todolist/templates/login.html
diff --git a/examples/todo-app/templates/tag.html b/examples/todolist/templates/tag.html
similarity index 100%
rename from examples/todo-app/templates/tag.html
rename to examples/todolist/templates/tag.html
diff --git a/examples/twutr/templates/layout.html b/examples/twutr/templates/layout.html
new file mode 100644
index 0000000..e8e0351
--- /dev/null
+++ b/examples/twutr/templates/layout.html
@@ -0,0 +1,162 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+    <meta charset="UTF-8">
+    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+    <title>{% block title %}MiniTwit{% endblock %}</title>
+    {% block extra_css %}{% endblock %}
+
+    <style>
+        /* Global Styles */
+        * {
+            margin: 0;
+            padding: 0;
+            box-sizing: border-box;
+            font-family: Arial, sans-serif;
+        }
+
+        body {
+            background-color: #f9f9f9;
+            color: #333;
+            font-size: 16px;
+            line-height: 1.6;
+            display: flex;
+            justify-content: center;
+            align-items: flex-start;
+            padding: 40px;
+        }
+
+        /* Container to hold main content and navigation */
+        .container {
+            display: flex;
+            align-items: flex-start;
+            gap: 40px; /* Space between content and nav */
+            max-width: 1000px; /* Limiting total width */
+            width: 100%;
+        }
+
+        /* Navigation styles */
+        .nav-container {
+            width: 200px; /* Fixed width for nav */
+            padding: 20px;
+            background: #fff;
+            border-radius: 8px;
+            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
+        }
+
+        nav {
+            display: flex;
+            flex-direction: column;
+            gap: 15px;
+        }
+
+        nav a {
+            color: #333;
+            text-decoration: none;
+            font-weight: 500;
+            font-size: 18px;
+            transition: color 0.3s ease;
+        }
+
+        nav a:hover {
+            color: #000;
+        }
+
+        /* Main content styles */
+        main {
+            flex: 3; /* Takes three times more space than nav */
+            background: #fff;
+            padding: 30px;
+            border-radius: 8px;
+            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
+        }
+
+        h2 {
+            font-size: 24px;
+            font-weight: 600;
+            margin-bottom: 20px;
+            text-align: left;
+        }
+
+        h1 {
+            text-align: right;
+        }
+
+        ul {
+            list-style: none;
+        }
+
+        ul li {
+            border-bottom: 1px solid #eee;
+            padding: 15px 0;
+        }
+
+        ul li:last-child {
+            border-bottom: none;
+        }
+
+        ul li h3 {
+            font-size: 18px;
+            font-weight: 500;
+            margin-bottom: 5px;
+        }
+
+        ul li small {
+            color: #888;
+            font-size: 14px;
+        }
+
+        a.button {
+            display: inline-block;
+            padding: 10px 20px;
+            border: 1px solid #333;
+            color: #333;
+            border-radius: 5px;
+            text-decoration: none;
+            font-size: 16px;
+            transition: background 0.3s ease, color 0.3s ease;
+            text-align: center;
+        }
+
+        a.button:hover {
+            background: #333;
+            color: #fff;
+        }
+
+        .center {
+            text-align: center;
+        }
+
+        footer {
+            margin-top: 40px;
+            font-size: 14px;
+            color: #aaa;
+            text-align: center;
+        }
+
+    </style>
+</head>
+<body>
+    <div class="container">
+        <main>
+        <h1>twutr</h1>
+            {% block content %}{% endblock %}
+        </main>
+
+        <div class="nav-container">
+<nav>
+    {% if session['logged_in'] %}
+        <a href="/">Home</a>
+        <a href="/user/{{ session['user_id'] }}">My Profile</a>
+        <a href="/public">Public Timeline</a>
+        <a href="/logout">Logout</a>
+    {% else %}
+        <a href="/public">Public Timeline</a>
+        <a href="/login">Login</a>
+        <a href="/register">Register</a>
+    {% endif %}
+</nav>
+        </div>
+    </div>
+</body>
+</html>
diff --git a/examples/twutr/templates/list_followers.html b/examples/twutr/templates/list_followers.html
new file mode 100644
index 0000000..aec67b1
--- /dev/null
+++ b/examples/twutr/templates/list_followers.html
@@ -0,0 +1,13 @@
+{% extends 'layout.html' %}
+{% block title %}{{ username }}'s Followers{% endblock %}
+{% block content %}
+<h2>{{ username }}'s Followers</h2>
+
+<ul>
+    {% for follower in followers %}
+        <li><a href="/user/{{ follower }}">{{ follower }}</a></li>
+    {% endfor %}
+</ul>
+
+<p><a href="/user/{{ username }}">Back to profile</a></p>
+{% endblock %}
diff --git a/examples/twutr/templates/list_following.html b/examples/twutr/templates/list_following.html
new file mode 100644
index 0000000..744fa4b
--- /dev/null
+++ b/examples/twutr/templates/list_following.html
@@ -0,0 +1,13 @@
+{% extends 'layout.html' %}
+{% block title %}{{ username }} is Following{% endblock %}
+{% block content %}
+<h2>{{ username }} is Following</h2>
+
+<ul>
+    {% for follow in following %}
+        <li><a href="/user/{{ follow }}">{{ follow }}</a></li>
+    {% endfor %}
+</ul>
+
+<p><a href="/user/{{ username }}">Back to profile</a></p>
+{% endblock %}
diff --git a/examples/twutr/templates/login.html b/examples/twutr/templates/login.html
new file mode 100644
index 0000000..cd8696b
--- /dev/null
+++ b/examples/twutr/templates/login.html
@@ -0,0 +1,80 @@
+{% extends 'layout.html' %}
+{% block title %}Login{% endblock %}
+{% block content %}
+<h2>Login</h2>
+
+<div class="form-container">
+    <form action="/login" method="post">
+        <input id="username" type="text" name="username" placeholder="Username" required>
+        <input id="password" type="password" name="password" placeholder="Password" required>
+        <button id="submit-btn" type="submit">Login</button>
+    </form>
+</div>
+
+{% endblock %}
+
+{% block extra_css %}
+<style>
+    .form-container {
+        display: flex;
+        flex-direction: column;
+        gap: 15px;
+        width: 100%;
+        max-width: 400px;
+        margin: 0 auto;
+    }
+
+    input[type="text"],
+    input[type="password"] {
+        width: 100%;
+        padding: 15px;
+        font-size: 18px;
+        border: 1px solid #ccc;
+        border-radius: 8px;
+        outline: none;
+        transition: border-color 0.3s ease;
+    }
+
+    input:focus {
+        border-color: #007bff;
+    }
+
+    #submit-btn {
+        padding: 15px;
+        font-size: 18px;
+        border: none;
+        border-radius: 8px;
+        background-color: #007bff;
+        color: #fff;
+        cursor: pointer;
+        transition: background 0.3s ease;
+        width: 100%;
+    }
+
+    #submit-btn:hover {
+        background-color: #0056b3;
+    }
+
+    /* Responsive Design for Mobile */
+    @media (max-width: 600px) {
+        h2 {
+            font-size: 22px;
+            text-align: center;
+        }
+
+        .form-container {
+            width: 90%;
+            max-width: 100%;
+            padding: 0 10px;
+        }
+
+        input[type="text"],
+        input[type="password"],
+        #submit-btn {
+            font-size: 16px;
+            padding: 12px;
+        }
+    }
+</style>
+{% endblock %}
+
diff --git a/examples/twutr/templates/public.html b/examples/twutr/templates/public.html
new file mode 100644
index 0000000..e583dd3
--- /dev/null
+++ b/examples/twutr/templates/public.html
@@ -0,0 +1,10 @@
+{% extends 'layout.html' %}
+{% block title %}Public Timeline{% endblock %}
+{% block content %}
+<h2>Public Timeline</h2>
+<ul>
+    {% for message in messages %}
+        <li><h3>{{ message[1] }}</h3> <a href="/user/{{ message[0] }}">{{ message[0] }}</a> <small>@ {{ message[2] }}</small></li>
+    {% endfor %}
+</ul>
+{% endblock %}
diff --git a/examples/twutr/templates/register.html b/examples/twutr/templates/register.html
new file mode 100644
index 0000000..4204817
--- /dev/null
+++ b/examples/twutr/templates/register.html
@@ -0,0 +1,80 @@
+{% extends 'layout.html' %}
+{% block title %}Register{% endblock %}
+{% block content %}
+<h2>Register</h2>
+
+<div class="form-container">
+    <form action="/register" method="post">
+        <input id="username" type="text" name="username" placeholder="Username" required>
+        <input id="password" type="password" name="password" placeholder="Password" required>
+        <button id="submit-btn" type="submit">Register</button>
+    </form>
+</div>
+
+{% endblock %}
+
+{% block extra_css %}
+<style>
+    .form-container {
+        display: flex;
+        flex-direction: column;
+        gap: 15px;
+        width: 100%;
+        max-width: 400px;
+        margin: 0 auto;
+    }
+
+    input[type="text"],
+    input[type="password"] {
+        width: 100%;
+        padding: 15px;
+        font-size: 18px;
+        border: 1px solid #ccc;
+        border-radius: 8px;
+        outline: none;
+        transition: border-color 0.3s ease;
+    }
+
+    input:focus {
+        border-color: #007bff;
+    }
+
+    #submit-btn {
+        padding: 15px;
+        font-size: 18px;
+        border: none;
+        border-radius: 8px;
+        background-color: #007bff;
+        color: #fff;
+        cursor: pointer;
+        transition: background 0.3s ease;
+        width: 100%;
+    }
+
+    #submit-btn:hover {
+        background-color: #0056b3;
+    }
+
+    /* Responsive Design for Mobile */
+    @media (max-width: 600px) {
+        h2 {
+            font-size: 22px;
+            text-align: center;
+        }
+
+        .form-container {
+            width: 90%;
+            max-width: 100%;
+            padding: 0 10px;
+        }
+
+        input[type="text"],
+        input[type="password"],
+        #submit-btn {
+            font-size: 16px;
+            padding: 12px;
+        }
+    }
+</style>
+{% endblock %}
+
diff --git a/examples/twutr/templates/timeline.html b/examples/twutr/templates/timeline.html
new file mode 100644
index 0000000..81f8481
--- /dev/null
+++ b/examples/twutr/templates/timeline.html
@@ -0,0 +1,121 @@
+{% extends 'layout.html' %}
+{% block title %}Your Timeline{% endblock %}
+{% block content %}
+<h2>Your Timeline</h2>
+
+<div class="form-container">
+    <form action="/add_message" method="post">
+        <textarea id="message-input" name="message" placeholder="What's happening?" required maxlength="140"></textarea>
+        <div id="char-count">140 characters remaining</div>
+        <button id="submit-btn" type="submit">Post</button>
+    </form>
+</div>
+<script>
+    const messageInput = document.getElementById('message-input');
+    const charCount = document.getElementById('char-count');
+
+    messageInput.addEventListener('input', function () {
+        const remaining = 140 - messageInput.value.length;
+        charCount.textContent = remaining + " characters remaining";
+
+        if (remaining < 0) {
+            charCount.style.color = 'red';
+        } else {
+            charCount.style.color = '#333';
+        }
+    });
+</script>
+<br><br>
+<ul class="messages">
+    {% for message in messages %}
+        <li>
+            <h3>{{ message[1] }}</h3>
+            <a href="/user/{{ message[0] }}">{{ message[0] }}</a> <small>@ {{ message[2] }}</small>
+        </li>
+    {% endfor %}
+</ul>
+{% endblock %}
+
+{% block extra_css %}
+<style>
+    h2 {
+        text-align: center;
+        font-size: 28px;
+        font-weight: 600;
+        margin-bottom: 20px;
+    }
+
+    .form-container {
+        display: flex;
+        flex-direction: column;
+        gap: 15px;
+        width: 100%;
+        max-width: 600px;
+        margin: 0 auto;
+    }
+
+    #message-input {
+        width: 100%;
+        height: 100px;
+        padding: 15px;
+        font-size: 18px;
+        border: 1px solid #ccc;
+        border-radius: 8px;
+        outline: none;
+        transition: border-color 0.3s ease;
+        resize: none;
+    }
+
+    #message-input:focus {
+        border-color: #007bff;
+    }
+
+    #char-count {
+        font-size: 14px;
+        color: #777;
+        text-align: right;
+    }
+
+    #submit-btn {
+        padding: 15px;
+        font-size: 18px;
+        border: none;
+        border-radius: 8px;
+        background-color: #007bff;
+        color: #fff;
+        cursor: pointer;
+        transition: background 0.3s ease;
+        width: 25%;
+    }
+
+    #submit-btn:hover {
+        background-color: #0056b3;
+    }
+
+    /* Responsive Design for Mobile */
+    @media (max-width: 600px) {
+        h2 {
+            font-size: 22px;
+            text-align: center;
+        }
+
+        .form-container {
+            width: 90%;
+            max-width: 100%;
+            padding: 0 10px;
+        }
+
+        #message-input {
+            font-size: 16px;
+            padding: 12px;
+            height: 100px;
+        }
+
+        #submit-btn {
+            font-size: 16px;
+            padding: 12px;
+        }
+    }
+</style>
+{% endblock %}
+
diff --git a/examples/twutr/templates/user.html b/examples/twutr/templates/user.html
new file mode 100644
index 0000000..da7eef8
--- /dev/null
+++ b/examples/twutr/templates/user.html
@@ -0,0 +1,23 @@
+{% extends 'layout.html' %}
+{% block title %}User Timeline{% endblock %}
+{% block content %}
+<h2>{{ username }}</h2>
+
+<p>
+    <a href="/list_followers/{{ username }}">{{ followers|length }} Followers</a> |
+    <a href="/list_following/{{ username }}">{{ following_count }} Following</a>
+{% if session['logged_in'] and following is not none %}
+    {% if following %}
+        | <a href="/unfollow/{{ username }}">Unfollow</a>
+    {% else %}
+        | <a href="/follow/{{ username }}">Follow</a>
+    {% endif %}
+{% endif %}
+</p>
+
+<ul>
+    {% for message in messages %}
+        <li><h3>{{ message[0] }}</h3> <small>{{ message[1] }}</small></li>
+    {% endfor %}
+</ul>
+{% endblock %}
diff --git a/examples/twutr/twutr.py b/examples/twutr/twutr.py
new file mode 100644
index 0000000..a6f7d0a
--- /dev/null
+++ b/examples/twutr/twutr.py
@@ -0,0 +1,330 @@
+"""
+    twutr, a really basic Twitter clone. "Instead of tweets, just utr."
+    Built with MicroPie and pickleDB.
+    Written by Harrison Erd as an example application using MicroPie.
+    https://patx.github.io/
+"""
+from datetime import datetime
+import re
+
+from MicroPie import Server
+from pickledb import PickleDB
+from markupsafe import escape
+
+
+# Set up database, we are using pickleDB switch to mongoDB for production
+db = PickleDB('minitwit.db')
+
+
+# ----------------
+#  HELPER METHODS
+# ----------------
+
+def get_user_data(username):
+    """Retrieve user data from the database by username."""
+    return db.get(username)
+
+def save_user_data(username, data):
+    """Save updated user data back to the database."""
+    db.set(username, data)
+    db.save()
+
+def sort_messages_by_timestamp(messages, timestamp_index):
+    """
+    Sort a list of messages (tuples) by a timestamp field located
+    at the specified index in each tuple. The timestamp format
+    is '%m/%d/%Y %I:%M %p'.
+    """
+    return sorted(
+        messages,
+        key=lambda x: datetime.strptime(x[timestamp_index], '%m/%d/%Y %I:%M %p'),
+        reverse=True
+    )
+
+def get_all_messages_for_user_and_following(user_id):
+    """
+    Retrieve all messages from the specified user and from
+    any users they are following. Returns a list of tuples:
+    (username, message, timestamp).
+    """
+    all_messages = []
+    user_data = get_user_data(user_id)
+
+    if user_data:
+        # User's own messages
+        for message in user_data.get('messages', []):
+            all_messages.append((user_id, message[0], message[1]))
+
+        # Followed users' messages
+        for following in user_data.get('following', []):
+            followed_user_data = get_user_data(following)
+            if followed_user_data:
+                for message in followed_user_data.get('messages', []):
+                    all_messages.append((following, message[0], message[1]))
+    return all_messages
+
+def get_all_messages_from_all_users():
+    """
+    Retrieve messages from every user in the database.
+    Returns a list of tuples: (username, message, timestamp).
+    """
+    all_messages = []
+    for user_key in db.all():
+        user_data = get_user_data(user_key)
+        if user_data and 'messages' in user_data:
+            for message in user_data['messages']:
+                all_messages.append((user_key, message[0], message[1]))
+    return all_messages
+
+def update_follow_relationship(current_user, username, follow=True):
+    """
+    Handle following or unfollowing logic between current_user and username.
+    If follow=True, current_user follows username; if follow=False, unfollows.
+    """
+    current_user_data = get_user_data(current_user)
+    target_user_data = get_user_data(username)
+
+    if current_user_data and target_user_data:
+        if follow:
+            # Add username to following if not present
+            if username not in current_user_data['following']:
+                current_user_data['following'].append(username)
+            # Add current_user to the target's followers if not present
+            if current_user not in target_user_data['followers']:
+                target_user_data['followers'].append(current_user)
+        else:
+            # Remove username from following if present
+            if username in current_user_data['following']:
+                current_user_data['following'].remove(username)
+            # Remove current_user from the target's followers if present
+            if current_user in target_user_data['followers']:
+                target_user_data['followers'].remove(current_user)
+
+        save_user_data(current_user, current_user_data)
+        save_user_data(username, target_user_data)
+
+def convert_custom_syntax(text):
+    """
+    Convert @link.com, @https://link.com/page to clickable links,
+    and @/user/name to internal site links.
+    """
+    # Regex patterns
+    link_pattern = r'@((?:https?:\/\/)?[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(?:\/\S*)?)'  # External links
+    internal_pattern = r'@(/[\w\-/]+)'  # Internal site links (e.g., @/user/name)
+
+    # Escape the entire input first to avoid XSS
+    escaped_text = escape(text)
+
+    # Convert @link.com, @https://link.com/page to clickable links
+    def replace_link(match):
+        url = match.group(1)
+        if not url.startswith('http'):
+            url = f'http://{url}'
+        return f'<a href="{url}" target="_blank">@{match.group(1)}</a>'
+
+    # Convert @/user/name to internal links
+    def replace_internal(match):
+        path = match.group(1)
+        return f'<a href="{path}">@{path}</a>'
+
+    # Apply replacements
+    escaped_text = re.sub(link_pattern, replace_link, escaped_text)
+    escaped_text = re.sub(internal_pattern, replace_internal, escaped_text)
+
+    return escaped_text
+
+
+
+
+#-----------------
+# MAIN APPLICATION
+# ----------------
+
+
+class Twutr(Server):
+    """
+    Main application class for handling routes.
+    The helper functions above are outside the class,
+    so MicroPie does not treat them as routes.
+    """
+
+    def index(self):
+        """Shows the user's timeline (the messages of people they follow, including their own)."""
+        if not self.session.get('logged_in'):
+            return self.redirect('/public')
+
+        user_id = self.session.get('user_id')
+        all_messages = get_all_messages_for_user_and_following(user_id)
+        all_messages = sort_messages_by_timestamp(all_messages, timestamp_index=2)
+
+        return self.render_template('timeline.html', messages=all_messages, session=self.session)
+
+    def public(self):
+        """Displays the latest messages of all users with usernames."""
+        all_messages = get_all_messages_from_all_users()
+        all_messages = sort_messages_by_timestamp(all_messages, timestamp_index=2)
+
+        return self.render_template('public.html', messages=all_messages, session=self.session)
+
+    def user(self, username):
+        """Displays a specific user's messages."""
+        logged_in = self.session.get('logged_in')
+        current_user = self.session.get('user_id')
+
+        # Determine if current_user is following, is the same user, or is not logged in
+        if not logged_in or not current_user:
+            following = False
+        elif current_user == username:
+            following = None  # Viewing own profile
+        else:
+            current_user_data = get_user_data(current_user)
+            following = username in current_user_data.get('following', [])
+
+        user_data = get_user_data(username)
+        if user_data:
+            messages = user_data.get('messages', [])
+            messages = sort_messages_by_timestamp(messages, timestamp_index=1)
+
+            followers = user_data.get('followers', [])
+            following_count = len(user_data.get('following', []))
+
+            return self.render_template(
+                'user.html',
+                messages=messages,
+                username=username,
+                session=self.session,
+                following=following,
+                followers=followers,
+                following_count=following_count
+            )
+
+        return "User not found", 404
+
+    def follow(self, username):
+        """Follow another user."""
+        if not self.session.get('logged_in'):
+            return self.redirect('/login')
+
+        current_user = self.session.get('user_id')
+        if username == current_user:
+            return "You cannot follow yourself"
+
+        update_follow_relationship(current_user, username, follow=True)
+        return self.redirect(f'/user/{username}')
+
+    def unfollow(self, username):
+        """Unfollow another user."""
+        if not self.session.get('logged_in'):
+            return self.redirect('/login')
+
+        current_user = self.session.get('user_id')
+        update_follow_relationship(current_user, username, follow=False)
+
+        return self.redirect(f'/user/{username}')
+
+    def list_followers(self, username):
+        """Displays the list of followers for a given user."""
+        user_data = get_user_data(username)
+        if not user_data:
+            return "User not found", 404
+
+        followers = user_data.get('followers', [])
+        return self.render_template(
+            'list_followers.html',
+            username=username,
+            followers=followers,
+            session=self.session
+        )
+
+    def list_following(self, username):
+        """Displays the list of users that a given user is following."""
+        user_data = get_user_data(username)
+        if not user_data:
+            return "User not found", 404
+
+        following = user_data.get('following', [])
+        return self.render_template(
+            'list_following.html',
+            username=username,
+            following=following,
+            session=self.session
+        )
+
+    def add_message(self):
+        """Registers a new message for the logged-in user with custom link and mention handling."""
+        if not self.session.get('logged_in'):
+            return self.redirect('/login')
+
+        if self.request == 'POST':
+            message = self.body_params.get('message', [''])[0]
+
+            # Convert @link syntax and escape everything else
+            sanitized_message = convert_custom_syntax(message)
+
+            # Prevent empty message submissions
+            if not sanitized_message.strip():
+                return self.render_template('timeline.html', error="Message cannot be empty", session=self.session)
+
+            time_stamp = str(datetime.utcnow().strftime('%m/%d/%Y %I:%M %p'))
+            message_tuple = (sanitized_message, time_stamp)
+
+            user_data = get_user_data(self.session.get('user_id'))
+            user_data['messages'].append(message_tuple)
+            save_user_data(self.session.get('user_id'), user_data)
+
+        return self.redirect('/')
+
+    def login(self):
+        """Logs the user in."""
+        if self.session.get('logged_in'):
+            return self.redirect('/')
+
+        if self.request == 'POST':
+            username = self.body_params.get('username', [''])[0].strip()
+            password = self.body_params.get('password', [''])[0].strip()
+
+            if not username or not password:
+                return self.render_template('login.html', error="Fields cannot be empty", session=self.session)
+
+            user = get_user_data(username)
+            if not user or user['password'] != password:
+                return self.render_template('login.html', error="Invalid credentials", session=self.session)
+
+            self.session['user_id'] = username
+            self.session['logged_in'] = True
+            return self.redirect('/')
+
+        return self.render_template('login.html', session=self.session)
+
+    def register(self):
+        """Registers a new user."""
+        if self.session.get('logged_in'):
+            return self.redirect('/')
+
+        if self.request == 'POST':
+            username = self.body_params.get('username', [''])[0].strip()
+            password = self.body_params.get('password', [''])[0].strip()
+
+            if username and password:
+                db.set(username, {
+                    'username': username,
+                    'password': password,
+                    'messages': [],
+                    'followers': [],
+                    'following': []
+                })
+                db.save()
+                return self.redirect('/login')
+
+        return self.render_template('register.html', session=self.session)
+
+    def logout(self):
+        """Logs the user out."""
+        if self.session.get('logged_in'):
+            self.session.clear()
+        return self.redirect('/public')
+
+
+if __name__ == "__main__":
+    Twutr().run()
+