Added messaging functions
This commit is contained in:
@@ -13,6 +13,7 @@ def init_app(app: Flask):
|
||||
from .auth import init_routes as init_auth_routes
|
||||
from .contacts import contacts_bp as contacts_routes
|
||||
from .rooms import rooms_bp as rooms_routes
|
||||
from .conversations import conversations_bp as conversations_routes
|
||||
|
||||
# Initialize routes
|
||||
init_main_routes(main_bp)
|
||||
@@ -29,6 +30,7 @@ def init_app(app: Flask):
|
||||
app.register_blueprint(auth_bp)
|
||||
app.register_blueprint(rooms_routes)
|
||||
app.register_blueprint(contacts_routes)
|
||||
app.register_blueprint(conversations_routes)
|
||||
|
||||
@app.route('/rooms/<int:room_id>/trash')
|
||||
@login_required
|
||||
|
||||
Binary file not shown.
BIN
routes/__pycache__/conversations.cpython-313.pyc
Normal file
BIN
routes/__pycache__/conversations.cpython-313.pyc
Normal file
Binary file not shown.
Binary file not shown.
390
routes/conversations.py
Normal file
390
routes/conversations.py
Normal file
@@ -0,0 +1,390 @@
|
||||
from flask import Blueprint, render_template, redirect, url_for, flash, request, jsonify, send_file
|
||||
from flask_login import login_required, current_user
|
||||
from flask_socketio import emit, join_room, leave_room
|
||||
from models import db, Conversation, User, Message, MessageAttachment
|
||||
from forms import ConversationForm
|
||||
import os
|
||||
from werkzeug.utils import secure_filename
|
||||
from datetime import datetime
|
||||
from extensions import socketio
|
||||
|
||||
conversations_bp = Blueprint('conversations', __name__, url_prefix='/conversations')
|
||||
|
||||
# Configure upload settings
|
||||
UPLOAD_FOLDER = os.environ.get('UPLOAD_FOLDER', 'uploads')
|
||||
ALLOWED_EXTENSIONS = {
|
||||
# Documents
|
||||
'pdf', 'docx', 'doc', 'txt', 'rtf', 'odt', 'md', 'csv',
|
||||
# Spreadsheets
|
||||
'xlsx', 'xls', 'ods', 'xlsm',
|
||||
# Presentations
|
||||
'pptx', 'ppt', 'odp',
|
||||
# Images
|
||||
'jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg', 'webp', 'tiff',
|
||||
# Archives
|
||||
'zip', 'rar', '7z', 'tar', 'gz',
|
||||
# Code/Text
|
||||
'py', 'js', 'html', 'css', 'json', 'xml', 'sql', 'sh', 'bat',
|
||||
# Audio
|
||||
'mp3', 'wav', 'ogg', 'm4a', 'flac',
|
||||
# Video
|
||||
'mp4', 'avi', 'mov', 'wmv', 'flv', 'mkv', 'webm',
|
||||
# CAD/Design
|
||||
'dwg', 'dxf', 'ai', 'psd', 'eps', 'indd',
|
||||
# Other
|
||||
'eml', 'msg', 'vcf', 'ics'
|
||||
}
|
||||
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB
|
||||
|
||||
def allowed_file(filename):
|
||||
return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
|
||||
|
||||
def get_file_extension(filename):
|
||||
return filename.rsplit('.', 1)[1].lower() if '.' in filename else ''
|
||||
|
||||
@conversations_bp.route('/')
|
||||
@login_required
|
||||
def conversations():
|
||||
search = request.args.get('search', '').strip()
|
||||
if current_user.is_admin:
|
||||
query = Conversation.query
|
||||
else:
|
||||
query = Conversation.query.filter(Conversation.members.any(id=current_user.id))
|
||||
if search:
|
||||
query = query.filter(Conversation.name.ilike(f'%{search}%'))
|
||||
conversations = query.order_by(Conversation.created_at.desc()).all()
|
||||
return render_template('conversations/conversations.html', conversations=conversations, search=search)
|
||||
|
||||
@conversations_bp.route('/create', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def create_conversation():
|
||||
if not current_user.is_admin:
|
||||
flash('Only administrators can create conversations.', 'error')
|
||||
return redirect(url_for('conversations.conversations'))
|
||||
|
||||
form = ConversationForm()
|
||||
if form.validate_on_submit():
|
||||
conversation = Conversation(
|
||||
name=form.name.data,
|
||||
description=form.description.data,
|
||||
created_by=current_user.id
|
||||
)
|
||||
|
||||
# Add creator as a member
|
||||
conversation.members.append(current_user)
|
||||
creator_id = current_user.id
|
||||
# Add selected members, skipping the creator if present
|
||||
for user_id in form.members.data:
|
||||
if int(user_id) != creator_id:
|
||||
user = User.query.get(user_id)
|
||||
if user and user not in conversation.members:
|
||||
conversation.members.append(user)
|
||||
|
||||
db.session.add(conversation)
|
||||
db.session.commit()
|
||||
|
||||
flash('Conversation created successfully!', 'success')
|
||||
return redirect(url_for('conversations.conversations'))
|
||||
return render_template('conversations/create_conversation.html', form=form)
|
||||
|
||||
@conversations_bp.route('/<int:conversation_id>')
|
||||
@login_required
|
||||
def conversation(conversation_id):
|
||||
conversation = Conversation.query.get_or_404(conversation_id)
|
||||
# Check if user is a member
|
||||
if not current_user.is_admin and current_user not in conversation.members:
|
||||
flash('You do not have access to this conversation.', 'error')
|
||||
return redirect(url_for('conversations.conversations'))
|
||||
|
||||
# Query messages directly using the Message model
|
||||
messages = Message.query.filter_by(conversation_id=conversation_id).order_by(Message.created_at.asc()).all()
|
||||
|
||||
# Get all users for member selection (only needed for admin)
|
||||
all_users = User.query.all() if current_user.is_admin else None
|
||||
|
||||
return render_template('conversations/conversation.html',
|
||||
conversation=conversation,
|
||||
messages=messages,
|
||||
all_users=all_users)
|
||||
|
||||
@conversations_bp.route('/<int:conversation_id>/members')
|
||||
@login_required
|
||||
def conversation_members(conversation_id):
|
||||
conversation = Conversation.query.get_or_404(conversation_id)
|
||||
if not current_user.is_admin and current_user not in conversation.members:
|
||||
flash('You do not have access to this conversation.', 'error')
|
||||
return redirect(url_for('conversations.conversations'))
|
||||
|
||||
if not current_user.is_admin:
|
||||
flash('Only administrators can manage conversation members.', 'error')
|
||||
return redirect(url_for('conversations.conversation', conversation_id=conversation_id))
|
||||
|
||||
available_users = User.query.filter(~User.id.in_([m.id for m in conversation.members])).all()
|
||||
return render_template('conversations/conversation_members.html',
|
||||
conversation=conversation,
|
||||
available_users=available_users)
|
||||
|
||||
@conversations_bp.route('/<int:conversation_id>/members/add', methods=['POST'])
|
||||
@login_required
|
||||
def add_member(conversation_id):
|
||||
conversation = Conversation.query.get_or_404(conversation_id)
|
||||
if not current_user.is_admin:
|
||||
flash('Only administrators can manage conversation members.', 'error')
|
||||
return redirect(url_for('conversations.conversation', conversation_id=conversation_id))
|
||||
|
||||
user_id = request.form.get('user_id')
|
||||
if not user_id:
|
||||
flash('Please select a user to add.', 'error')
|
||||
return redirect(url_for('conversations.conversation_members', conversation_id=conversation_id))
|
||||
|
||||
user = User.query.get_or_404(user_id)
|
||||
if user in conversation.members:
|
||||
flash('User is already a member of this conversation.', 'error')
|
||||
else:
|
||||
conversation.members.append(user)
|
||||
db.session.commit()
|
||||
flash(f'{user.username} has been added to the conversation.', 'success')
|
||||
|
||||
return redirect(url_for('conversations.conversation_members', conversation_id=conversation_id))
|
||||
|
||||
@conversations_bp.route('/<int:conversation_id>/members/<int:user_id>/remove', methods=['POST'])
|
||||
@login_required
|
||||
def remove_member(conversation_id, user_id):
|
||||
conversation = Conversation.query.get_or_404(conversation_id)
|
||||
if not current_user.is_admin:
|
||||
flash('Only administrators can manage conversation members.', 'error')
|
||||
return redirect(url_for('conversations.conversation', conversation_id=conversation_id))
|
||||
|
||||
if user_id == conversation.created_by:
|
||||
flash('Cannot remove the conversation creator.', 'error')
|
||||
else:
|
||||
user = User.query.get_or_404(user_id)
|
||||
if user not in conversation.members:
|
||||
flash('User is not a member of this conversation.', 'error')
|
||||
else:
|
||||
conversation.members.remove(user)
|
||||
db.session.commit()
|
||||
flash('User has been removed from the conversation.', 'success')
|
||||
|
||||
return redirect(url_for('conversations.conversation_members', conversation_id=conversation_id))
|
||||
|
||||
@conversations_bp.route('/<int:conversation_id>/edit', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
def edit_conversation(conversation_id):
|
||||
if not current_user.is_admin:
|
||||
flash('Only administrators can edit conversations.', 'error')
|
||||
return redirect(url_for('conversations.conversations'))
|
||||
conversation = Conversation.query.get_or_404(conversation_id)
|
||||
form = ConversationForm(obj=conversation)
|
||||
|
||||
if request.method == 'POST':
|
||||
# Get members from the form data
|
||||
member_ids = request.form.getlist('members')
|
||||
|
||||
# Update members
|
||||
current_member_ids = {str(user.id) for user in conversation.members}
|
||||
new_member_ids = set(member_ids)
|
||||
|
||||
# Remove members that are no longer in the list
|
||||
for member_id in current_member_ids - new_member_ids:
|
||||
if int(member_id) != conversation.created_by: # Don't remove the creator
|
||||
user = User.query.get(member_id)
|
||||
if user:
|
||||
conversation.members.remove(user)
|
||||
|
||||
# Add new members
|
||||
for member_id in new_member_ids - current_member_ids:
|
||||
user = User.query.get(member_id)
|
||||
if user and user not in conversation.members:
|
||||
conversation.members.append(user)
|
||||
|
||||
db.session.commit()
|
||||
flash('Conversation members updated successfully!', 'success')
|
||||
|
||||
# Check if redirect parameter is provided
|
||||
redirect_url = request.args.get('redirect')
|
||||
if redirect_url:
|
||||
return redirect(redirect_url)
|
||||
return redirect(url_for('conversations.conversations'))
|
||||
|
||||
# Prepopulate form members with current members
|
||||
form.members.data = [str(user.id) for user in conversation.members]
|
||||
return render_template('conversations/create_conversation.html', form=form, edit_mode=True, conversation=conversation)
|
||||
|
||||
@conversations_bp.route('/<int:conversation_id>/delete', methods=['POST'])
|
||||
@login_required
|
||||
def delete_conversation(conversation_id):
|
||||
if not current_user.is_admin:
|
||||
flash('Only administrators can delete conversations.', 'error')
|
||||
return redirect(url_for('conversations.conversations'))
|
||||
|
||||
conversation = Conversation.query.get_or_404(conversation_id)
|
||||
|
||||
# Delete all messages in the conversation
|
||||
Message.query.filter_by(conversation_id=conversation_id).delete()
|
||||
|
||||
# Delete the conversation
|
||||
db.session.delete(conversation)
|
||||
db.session.commit()
|
||||
|
||||
flash('Conversation has been deleted successfully.', 'success')
|
||||
return redirect(url_for('conversations.conversations'))
|
||||
|
||||
@socketio.on('join_conversation')
|
||||
@login_required
|
||||
def on_join(data):
|
||||
conversation_id = data.get('conversation_id')
|
||||
conversation = Conversation.query.get_or_404(conversation_id)
|
||||
|
||||
# Check if user is a member
|
||||
if not current_user.is_admin and current_user not in conversation.members:
|
||||
return
|
||||
|
||||
# Join the room
|
||||
join_room(f'conversation_{conversation_id}')
|
||||
|
||||
@socketio.on('leave_conversation')
|
||||
@login_required
|
||||
def on_leave(data):
|
||||
conversation_id = data.get('conversation_id')
|
||||
leave_room(f'conversation_{conversation_id}')
|
||||
|
||||
@conversations_bp.route('/<int:conversation_id>/send_message', methods=['POST'])
|
||||
@login_required
|
||||
def send_message(conversation_id):
|
||||
conversation = Conversation.query.get_or_404(conversation_id)
|
||||
|
||||
# Check if user is a member
|
||||
if not current_user.is_admin and current_user not in conversation.members:
|
||||
return jsonify({'success': False, 'error': 'You do not have access to this conversation.'}), 403
|
||||
|
||||
message_content = request.form.get('message', '').strip()
|
||||
file_count = int(request.form.get('file_count', 0))
|
||||
|
||||
if not message_content and file_count == 0:
|
||||
return jsonify({'success': False, 'error': 'Message or file is required.'}), 400
|
||||
|
||||
# Create new message
|
||||
message = Message(
|
||||
content=message_content,
|
||||
conversation_id=conversation_id,
|
||||
user_id=current_user.id
|
||||
)
|
||||
|
||||
# Create conversation-specific directory
|
||||
conversation_dir = os.path.join(UPLOAD_FOLDER, str(conversation_id))
|
||||
os.makedirs(conversation_dir, exist_ok=True)
|
||||
|
||||
# Handle file attachments
|
||||
attachments = []
|
||||
for i in range(file_count):
|
||||
file = request.files.get(f'file_{i}')
|
||||
if file and file.filename:
|
||||
if not allowed_file(file.filename):
|
||||
return jsonify({'success': False, 'error': f'File type not allowed: {file.filename}'}), 400
|
||||
|
||||
if file.content_length and file.content_length > MAX_FILE_SIZE:
|
||||
return jsonify({'success': False, 'error': f'File size exceeds limit: {file.filename}'}), 400
|
||||
|
||||
# Generate unique filename
|
||||
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
||||
filename = secure_filename(file.filename)
|
||||
unique_filename = f"{timestamp}_{filename}"
|
||||
file_path = os.path.join(conversation_dir, unique_filename)
|
||||
|
||||
# Save file
|
||||
file.save(file_path)
|
||||
|
||||
# Create attachment record
|
||||
attachment = MessageAttachment(
|
||||
name=filename,
|
||||
path=file_path,
|
||||
type=get_file_extension(filename),
|
||||
size=os.path.getsize(file_path)
|
||||
)
|
||||
message.attachments.append(attachment)
|
||||
attachments.append(attachment)
|
||||
|
||||
db.session.add(message)
|
||||
db.session.commit()
|
||||
|
||||
# Prepare message data for WebSocket
|
||||
message_data = {
|
||||
'id': message.id,
|
||||
'content': message.content,
|
||||
'created_at': message.created_at.strftime('%b %d, %Y %H:%M'),
|
||||
'sender_id': str(current_user.id),
|
||||
'sender_name': f"{current_user.username} {current_user.last_name}",
|
||||
'sender_avatar': url_for('profile_pic', filename=current_user.profile_picture) if current_user.profile_picture else url_for('static', filename='default-avatar.png'),
|
||||
'attachments': [{
|
||||
'name': attachment.name,
|
||||
'size': attachment.size,
|
||||
'url': url_for('conversations.download_attachment', message_id=message.id, attachment_index=index)
|
||||
} for index, attachment in enumerate(attachments)]
|
||||
}
|
||||
|
||||
# Emit the message to all users in the conversation room
|
||||
socketio.emit('new_message', message_data, room=f'conversation_{conversation_id}')
|
||||
|
||||
# Return minimal response since the message will be received through WebSocket
|
||||
return jsonify({'success': True})
|
||||
|
||||
@conversations_bp.route('/messages/<int:message_id>/attachment/<int:attachment_index>')
|
||||
@login_required
|
||||
def download_attachment(message_id, attachment_index):
|
||||
message = Message.query.get_or_404(message_id)
|
||||
conversation = message.conversation
|
||||
|
||||
# Check if user is a member
|
||||
if not current_user.is_admin and current_user not in conversation.members:
|
||||
flash('You do not have access to this file.', 'error')
|
||||
return redirect(url_for('conversations.conversation', conversation_id=conversation.id))
|
||||
|
||||
try:
|
||||
attachment = message.attachments[attachment_index]
|
||||
return send_file(
|
||||
attachment.path,
|
||||
as_attachment=True,
|
||||
download_name=attachment.name
|
||||
)
|
||||
except (IndexError, Exception) as e:
|
||||
flash('File not found.', 'error')
|
||||
return redirect(url_for('conversations.conversation', conversation_id=conversation.id))
|
||||
|
||||
@conversations_bp.route('/<int:conversation_id>/messages')
|
||||
@login_required
|
||||
def get_messages(conversation_id):
|
||||
conversation = Conversation.query.get_or_404(conversation_id)
|
||||
|
||||
# Check if user is a member
|
||||
if not current_user.is_admin and current_user not in conversation.members:
|
||||
return jsonify({'success': False, 'error': 'You do not have access to this conversation.'}), 403
|
||||
|
||||
# Get the last message ID from the request
|
||||
last_message_id = request.args.get('last_message_id', type=int)
|
||||
|
||||
# Query for new messages
|
||||
query = Message.query.filter_by(conversation_id=conversation_id)
|
||||
if last_message_id:
|
||||
query = query.filter(Message.id > last_message_id)
|
||||
|
||||
messages = query.order_by(Message.created_at.asc()).all()
|
||||
|
||||
# Format messages for response
|
||||
formatted_messages = []
|
||||
for message in messages:
|
||||
formatted_messages.append({
|
||||
'id': message.id,
|
||||
'content': message.content,
|
||||
'created_at': message.created_at.strftime('%b %d, %Y %H:%M'),
|
||||
'sender_id': str(message.user.id),
|
||||
'sender_name': f"{message.user.username} {message.user.last_name}",
|
||||
'sender_avatar': url_for('profile_pic', filename=message.user.profile_picture) if message.user.profile_picture else url_for('static', filename='default-avatar.png'),
|
||||
'attachments': [{
|
||||
'name': attachment.name,
|
||||
'size': attachment.size,
|
||||
'url': url_for('conversations.download_attachment', message_id=message.id, attachment_index=index)
|
||||
} for index, attachment in enumerate(message.attachments)]
|
||||
})
|
||||
|
||||
return jsonify({'success': True, 'messages': formatted_messages})
|
||||
@@ -324,6 +324,11 @@ def init_routes(main_bp):
|
||||
def starred():
|
||||
return render_template('starred/starred.html')
|
||||
|
||||
@main_bp.route('/conversations')
|
||||
@login_required
|
||||
def conversations():
|
||||
return redirect(url_for('conversations.conversations'))
|
||||
|
||||
@main_bp.route('/trash')
|
||||
@login_required
|
||||
def trash():
|
||||
|
||||
Reference in New Issue
Block a user