@@ -955,42 +928,43 @@ def index():
@@ -1727,6 +1664,7 @@ def index():
'''
return Response(html_content, mimetype='text/html')
+
@app.route('/api/user_data', methods=['POST'])
def get_user_data():
data = request.get_json()
@@ -1736,20 +1674,37 @@ def get_user_data():
db = read_db()
user_info = db['users'].get(address)
username = user_info.get('username') if user_info else None
- return jsonify({'username': username})
+ # Always return the address and the found username (or null)
+ return jsonify({'address': address, 'username': username})
@app.route('/api/users', methods=['GET'])
def get_users():
db = read_db()
users_list = []
- for address, user_data in db['users'].items():
- users_list.append({
- 'address': address,
- 'username': user_data.get('username')
+ for address, user_info in db['users'].items():
+ users_list.append({
+ 'address': address,
+ 'username': user_info.get('username') # Include username if exists
+ })
+ # Include users who might have sent messages but don't have a username set explicitly
+ # This ensures all participants in chats are listed, even if just by address
+ all_addresses = set(db['users'].keys())
+ for room_messages in db['messages'].values():
+ for msg in room_messages:
+ all_addresses.add(msg['sender_address'])
+
+ final_users_list = []
+ for address in all_addresses:
+ user_info = db['users'].get(address, {})
+ final_users_list.append({
+ 'address': address,
+ 'username': user_info.get('username')
})
- # Optionally sort users
- users_list.sort(key=lambda x: x['username'] if x['username'] else x['address'])
- return jsonify({'users': users_list})
+
+ # Sort by username or address
+ final_users_list.sort(key=lambda x: x['username'] or x['address'])
+
+ return jsonify({'users': final_users_list})
@app.route('/api/set_username', methods=['POST'])
@@ -1761,13 +1716,8 @@ def set_username():
return jsonify({'error': 'Address and username are required'}), 400
if len(username) < 3 or len(username) > 20:
return jsonify({'error': 'Username must be between 3 and 20 characters'}), 400
-
- # Check for username uniqueness (optional but good practice)
- db = read_db()
- for existing_address, user_data in db['users'].items():
- if existing_address != address and user_data.get('username') == username:
- return jsonify({'error': 'Username already taken'}), 409 # Conflict
+ db = read_db()
if address not in db['users']:
db['users'][address] = {}
db['users'][address]['username'] = username
@@ -1794,16 +1744,15 @@ def create_chatroom():
creator_address = data.get('creator_address')
if not name or not creator_address:
return jsonify({'error': 'Name and creator address are required'}), 400
- if len(name) < 3 or len(name) > 50:
- return jsonify({'error': 'Chatroom name must be between 3 and 50 characters'}), 400
db = read_db()
room_id = str(uuid.uuid4())
db['chatrooms'][room_id] = {
+ 'id': room_id, # Store id in object too for easier reference if needed
'name': name,
'creator': creator_address,
'is_private': bool(password),
- 'password_hash': generate_password_hash(password) if password else None
+ 'password_hash': generate_password_hash(password).decode('utf-8') if password else None # Ensure hash is string
}
db['messages'][room_id] = []
write_db(db)
@@ -1819,7 +1768,7 @@ def join_chatroom():
if not chatroom:
return jsonify({'error': 'Chatroom not found'}), 404
if chatroom['is_private']:
- if not password or not chatroom['password_hash'] or not check_password_hash(chatroom['password_hash'], password):
+ if not password or not check_password_hash(chatroom['password_hash'], password):
return jsonify({'error': 'Invalid password'}), 403
return jsonify({'success': True})
@@ -1832,11 +1781,17 @@ def get_messages(chatroom_id):
messages_with_names = []
room_messages = db['messages'].get(chatroom_id, [])
+ # Pre-fetch usernames to avoid repeated lookups in the loop
+ user_names = {}
+ for address, user_info in db['users'].items():
+ user_names[address] = user_info.get('username')
+
for msg in room_messages:
sender_address = msg['sender_address']
- user_info = db['users'].get(sender_address)
- display_name = (user_info.get('username') if user_info and user_info.get('username')
- else f"{sender_address[:4]}...{sender_address[-4:]}")
+ # Get display name, prioritize username, fall back to truncated address
+ display_name = user_names.get(sender_address)
+ if not display_name:
+ display_name = f"{sender_address[:4]}...{sender_address[-4:]}"
msg_copy = msg.copy()
msg_copy['display_name'] = display_name
@@ -1853,10 +1808,6 @@ def send_message():
if not all([chatroom_id, sender_address, text]):
return jsonify({'error': 'Missing data'}), 400
- if not text.strip():
- return jsonify({'error': 'Message cannot be empty'}), 400
- if len(text) > 1000: # Simple message length limit
- return jsonify({'error': 'Message is too long'}), 400
db = read_db()
if chatroom_id not in db['messages']:
@@ -1865,11 +1816,11 @@ def send_message():
message = {
'id': str(uuid.uuid4()),
'sender_address': sender_address,
- 'text': text.strip(),
+ 'text': text,
'timestamp': datetime.utcnow().isoformat() + "Z"
}
- # Keep only the last 100 messages per chatroom
+ # Keep only the last 100 messages per room
if len(db['messages'][chatroom_id]) >= 100:
db['messages'][chatroom_id].pop(0)
@@ -1880,4 +1831,5 @@ def send_message():
if __name__ == '__main__':
init_db()
+ # Use host='0.0.0.0' for accessibility in development environments like Hugging Face Spaces
app.run(host='0.0.0.0', port=7860)
\ No newline at end of file