File size: 12,165 Bytes
3533fb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0eeeed2
3533fb9
 
 
 
 
 
 
 
0eeeed2
 
3533fb9
 
0eeeed2
3533fb9
0eeeed2
3533fb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
from fastapi import APIRouter, Depends, HTTPException, status, UploadFile, File
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import List
import os
import uuid
from app.core import config

from app.db.session import get_db
from app.schemas import schemas
from app.core.dependencies import get_current_user
from app.models.models import User, Conversation, ChatMessage, UserDevicePrekeyBundle, UserOneTimePrekey

router = APIRouter()

@router.post("/keys", response_model=schemas.User)
def upload_public_key(
    key_in: schemas.KeyUpload,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    current_user.public_key = key_in.public_key
    db.commit()
    db.refresh(current_user)
    return current_user

@router.get("/keys/{username}")
def get_user_public_key(
    username: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    user = db.query(User).filter(User.username == username).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return {"public_key": user.public_key}

from sqlalchemy.exc import IntegrityError

@router.post("/keys/prekey-bundle", response_model=schemas.PrekeyBundleOut)
def upload_prekey_bundle(
    bundle_in: schemas.PrekeyBundleUpload,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # Check if bundle already exists for this user and device
    bundle = db.query(UserDevicePrekeyBundle).filter(
        UserDevicePrekeyBundle.user_id == current_user.id,
        UserDevicePrekeyBundle.device_id == bundle_in.device_id
    ).first()
    
    if not bundle:
        bundle = UserDevicePrekeyBundle(
            user_id=current_user.id,
            device_id=bundle_in.device_id,
            identity_key=bundle_in.identity_key,
            signed_prekey=bundle_in.signed_prekey,
            signed_prekey_signature=bundle_in.signature
        )
        db.add(bundle)
    else:
        bundle.identity_key = bundle_in.identity_key
        bundle.signed_prekey = bundle_in.signed_prekey
        bundle.signed_prekey_signature = bundle_in.signature
        
    try:
        db.commit()
    except IntegrityError:
        db.rollback()
        bundle = db.query(UserDevicePrekeyBundle).filter(
            UserDevicePrekeyBundle.user_id == current_user.id,
            UserDevicePrekeyBundle.device_id == bundle_in.device_id
        ).first()
        if bundle:
            bundle.identity_key = bundle_in.identity_key
            bundle.signed_prekey = bundle_in.signed_prekey
            bundle.signed_prekey_signature = bundle_in.signature
            db.commit()
        else:
            raise HTTPException(status_code=500, detail="Database integrity error during bundle upload")
            
    db.refresh(bundle)
    
    # Store new one-time prekeys
    for otkey in bundle_in.one_time_prekeys:
        exists = db.query(UserOneTimePrekey).filter(
            UserOneTimePrekey.user_id == current_user.id,
            UserOneTimePrekey.device_id == bundle_in.device_id,
            UserOneTimePrekey.key_value == otkey
        ).first()
        if not exists:
            new_otk = UserOneTimePrekey(
                user_id=current_user.id,
                device_id=bundle_in.device_id,
                key_value=otkey,
                used=False
            )
            db.add(new_otk)
        
    try:
        db.commit()
    except IntegrityError:
        db.rollback()
        
    return schemas.PrekeyBundleOut(
        user_id=bundle.user_id,
        device_id=bundle.device_id,
        identity_key=bundle.identity_key,
        signed_prekey=bundle.signed_prekey,
        signature=bundle.signed_prekey_signature,
        one_time_prekey=None
    )

@router.get("/keys/prekey-bundle/{username}", response_model=List[schemas.PrekeyBundleOut])
def get_recipient_prekey_bundles(
    username: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    recipient = db.query(User).filter(User.username == username).first()
    if not recipient:
        raise HTTPException(status_code=404, detail="User not found")
        
    bundles = db.query(UserDevicePrekeyBundle).filter(UserDevicePrekeyBundle.user_id == recipient.id).all()
    
    response_bundles = []
    for b in bundles:
        # Get one unused one-time prekey
        otk = db.query(UserOneTimePrekey).filter(
            UserOneTimePrekey.user_id == recipient.id,
            UserOneTimePrekey.device_id == b.device_id,
            UserOneTimePrekey.used == False
        ).first()
        
        otk_value = None
        if otk:
            otk_value = otk.key_value
            otk.used = True
            db.add(otk)
            
        response_bundles.append(
            schemas.PrekeyBundleOut(
                user_id=b.user_id,
                device_id=b.device_id,
                identity_key=b.identity_key,
                signed_prekey=b.signed_prekey,
                signature=b.signed_prekey_signature,
                one_time_prekey=otk_value
            )
        )
        
    db.commit()
    return response_bundles

@router.post("/keys/one-time-prekeys")
def upload_one_time_prekeys(
    keys_in: schemas.OneTimePrekeysUpload,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    for key in keys_in.keys:
        otk = UserOneTimePrekey(
            user_id=current_user.id,
            device_id=keys_in.device_id,
            key_value=key,
            used=False
        )
        db.add(otk)
        
    db.commit()
    return {"status": "ok", "added": len(keys_in.keys)}

@router.get("/keys/devices")
def list_user_devices(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """List all registered devices for the current user."""
    bundles = db.query(UserDevicePrekeyBundle).filter(
        UserDevicePrekeyBundle.user_id == current_user.id
    ).all()
    return [
        {
            "device_id": b.device_id,
            "created_at": b.created_at.isoformat() if b.created_at else None
        }
        for b in bundles
    ]

@router.delete("/keys/devices/{device_id}")
def revoke_device(
    device_id: str,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    """Revoke a device by deleting its prekey bundle and associated one-time prekeys."""
    bundle = db.query(UserDevicePrekeyBundle).filter(
        UserDevicePrekeyBundle.user_id == current_user.id,
        UserDevicePrekeyBundle.device_id == device_id
    ).first()
    if not bundle:
        raise HTTPException(status_code=404, detail="Device not found")

    # Delete associated one-time prekeys
    db.query(UserOneTimePrekey).filter(
        UserOneTimePrekey.user_id == current_user.id,
        UserOneTimePrekey.device_id == device_id
    ).delete()

    db.delete(bundle)
    db.commit()
    return {"status": "ok", "device_id": device_id}

@router.post("/messages", response_model=schemas.ChatMessage)
def send_message(
    message_in: schemas.ChatMessageCreate,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # Find recipient
    recipient = db.query(User).filter(User.username == message_in.recipient_username).first()
    if not recipient:
        raise HTTPException(status_code=404, detail="Recipient not found")
    
    from sqlalchemy import and_
    # Find or create conversation
    conv = db.query(Conversation).filter(
        or_(
            and_(Conversation.user1_id == current_user.id, Conversation.user2_id == recipient.id),
            and_(Conversation.user1_id == recipient.id, Conversation.user2_id == current_user.id)
        )
    ).first()
    
    if not conv:
        conv = Conversation(user1_id=current_user.id, user2_id=recipient.id)
        db.add(conv)
        db.commit()
        db.refresh(conv)
    
    # Create message
    message = ChatMessage(
        conversation_id=conv.id,
        sender_id=current_user.id,
        encrypted_content=message_in.encrypted_content,
        iv=message_in.iv,
        recipient_key=message_in.recipient_key,
        sender_key=message_in.sender_key,
        message_type=message_in.message_type,
        attachment_url=message_in.attachment_url,
        file_metadata=message_in.file_metadata
    )
    db.add(message)
    db.commit()
    db.refresh(message)

    # Real-time WebSocket push to both parties
    import asyncio
    from app.core.ws_manager import manager as ws_manager
    ws_payload = {
        "type": "new_message",
        "message": {
            "id": message.id,
            "conversation_id": message.conversation_id,
            "sender_id": message.sender_id,
            "encrypted_content": message.encrypted_content,
            "iv": message.iv,
            "recipient_key": message.recipient_key,
            "sender_key": message.sender_key,
            "message_type": message.message_type,
            "attachment_url": message.attachment_url,
            "file_metadata": message.file_metadata,
            "created_at": message.created_at.isoformat()
        }
    }
    try:
        loop = asyncio.get_event_loop()
        loop.create_task(ws_manager.broadcast_to_conversation(
            [current_user.id, recipient.id], ws_payload
        ))
    except Exception:
        pass  # WebSocket push is best-effort

    return message

@router.get("/conversations", response_model=List[schemas.Conversation])
def get_conversations(
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    conversations = db.query(Conversation).filter(
        or_(Conversation.user1_id == current_user.id, Conversation.user2_id == current_user.id)
    ).all()
    return conversations

@router.get("/messages/{conversation_id}", response_model=List[schemas.ChatMessage])
def get_messages(
    conversation_id: int,
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    # Check if user is part of the conversation
    conv = db.query(Conversation).filter(Conversation.id == conversation_id).first()
    if not conv:
        raise HTTPException(status_code=404, detail="Conversation not found")
    
    if conv.user1_id != current_user.id and conv.user2_id != current_user.id:
        raise HTTPException(status_code=403, detail="Not authorized to view these messages")
    
    messages = db.query(ChatMessage).filter(ChatMessage.conversation_id == conversation_id).order_by(ChatMessage.created_at.asc()).all()
    return messages

@router.post("/messages/ack")
def acknowledge_messages(
    message_ids: List[int],
    db: Session = Depends(get_db),
    current_user: User = Depends(get_current_user)
):
    if not message_ids:
        return {"status": "ok", "acknowledged": 0, "deleted": 0}

    # Find conversations the user belongs to
    user_conv_ids = [
        r[0] for r in db.query(Conversation.id).filter(
            (Conversation.user1_id == current_user.id) | (Conversation.user2_id == current_user.id)
        ).all()
    ]

    # Count matching messages for the current user's conversations without deleting them from the database
    ack_count = db.query(ChatMessage).filter(
        ChatMessage.id.in_(message_ids),
        ChatMessage.conversation_id.in_(user_conv_ids)
    ).count()

    return {"status": "ok", "acknowledged": ack_count, "deleted": 0}

@router.post("/upload", response_model=schemas.AttachmentResponse)
def upload_attachment(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user)
):
    # Ensure directory exists
    attachments_dir = os.path.join(config.STATIC_DIR, "chat_attachments")
    os.makedirs(attachments_dir, exist_ok=True)
    
    # Save file
    file_id = str(uuid.uuid4())
    filename = f"{file_id}_{file.filename}"
    file_path = os.path.join(attachments_dir, filename)
    
    with open(file_path, "wb") as f:
        f.write(file.file.read())
        
    url = f"{config.BASE_URL}/static/chat_attachments/{filename}"
    return {"url": url, "filename": file.filename}