File size: 10,932 Bytes
3533fb9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b4d24b5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, Depends, HTTPException, status, File, UploadFile, Form, BackgroundTasks
from sqlalchemy.orm import Session
from typing import List, Optional
from uuid import uuid4

from app.db.session import get_db, SessionLocal
from app.core.dependencies import get_current_user, get_current_user_optional
from app.schemas import schemas
from app.core import config
from app.models.models import Post, Follow, Like, Comment, User
from app.crud import video as crud_video
from sqlalchemy import case, func

router = APIRouter()

@router.get("/", response_model=List[schemas.Post])
def get_posts(
    skip: int = 0, 
    limit: int = 20, 
    db: Session = Depends(get_db),
    current_user: Optional[dict] = Depends(get_current_user_optional)
):
    limit = min(limit, 3)
    query = db.query(Post)
    
    if current_user:
        # Get IDs of people user follows
        following_ids = db.query(Follow.following_id).filter(Follow.follower_id == current_user.id).all()
        following_ids = [f[0] for f in following_ids]
        
        if following_ids:
            is_followed = case(
                (Post.owner_id.in_(following_ids), 1),
                else_=0
            ).label('is_followed')
            query = query.order_by(is_followed.desc(), Post.id.desc())
        else:
            query = query.order_by(Post.id.desc())
    else:
        query = query.order_by(Post.id.desc())
        
    posts = query.offset(skip).limit(limit).all()

    # Advanced Viral Expansion & Discovery
    if len(posts) < limit:
        remaining = limit - len(posts)
        seen_ids = [p.id for p in posts]
        
        # Pull high engagement posts as fallback
        exp_query = db.query(Post).filter(Post.id.notin_(seen_ids), Post.views_count > 5)
        remaining_posts = exp_query.order_by(Post.views_count.desc()).limit(remaining).all()
        posts.extend(remaining_posts)

    # Populate metadata & handle engagement attribution
    for post in posts:
        # Determine the target for engagement attribution
        target = post
        if post.original_post_id and post.original_post:
            target = post.original_post
            
        # Metadata counts always reflect the ORIGINAL post
        target.likes_count = db.query(func.count(Like.id)).filter(Like.post_id == target.id).scalar() or 0
        target.comments_count = db.query(func.count(Comment.id)).filter(Comment.post_id == target.id).scalar() or 0
        
        if current_user:
            target.liked_by_user = db.query(Like).filter(Like.post_id == target.id, Like.user_id == current_user.id).first() is not None
        else:
            target.liked_by_user = False
        
        # Increment View on Original
        crud_video.increment_view(db, user_id=current_user.id if current_user else None, post_id=target.id)
        
    db.commit()
    return posts

@router.get("/{post_id}", response_model=schemas.Post)
def get_post(
    post_id: int,
    db: Session = Depends(get_db),
    current_user: Optional[dict] = Depends(get_current_user_optional)
):
    """Single post for SEO / deep links (used by Next.js /post/[id])."""
    post = db.query(Post).filter(Post.id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")

    target = post
    if post.original_post_id and post.original_post:
        target = post.original_post

    target.likes_count = db.query(func.count(Like.id)).filter(Like.post_id == target.id).scalar() or 0
    target.comments_count = db.query(func.count(Comment.id)).filter(Comment.post_id == target.id).scalar() or 0
    if current_user:
        target.liked_by_user = (
            db.query(Like)
            .filter(Like.post_id == target.id, Like.user_id == current_user.id)
            .first()
            is not None
        )
    else:
        target.liked_by_user = False

    # Attribute counts onto the returned row when it is a repost wrapper
    if post.original_post_id and post.original_post:
        post.likes_count = target.likes_count
        post.comments_count = target.comments_count
        post.liked_by_user = target.liked_by_user

    return post

@router.post("/create", response_model=schemas.Post)
async def create_post(
    content: str = Form(...),
    tags: Optional[str] = Form(None),
    image: Optional[UploadFile] = File(None),
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    image_url = None
    if image:
        from app.core.storage import storage
        import time
        
        file_ext = image.filename.split(".")[-1]
        timestamp = int(time.time())
        s3_key = f"posts/{current_user.id}_{timestamp}.{file_ext}"
        
        try:
            image_url = storage.upload_file_obj(image.file, s3_key)
        except Exception as e:
            print(f"Failed to upload post image to S3: {e}")
            raise HTTPException(status_code=500, detail="Failed to upload image to cloud storage")
    
    post_in = schemas.PostCreate(content=content, image_url=image_url, tags=tags)
    return crud_video.create_post(db, post=post_in, user_id=current_user.id)

@router.post("/{post_id}/repost", response_model=schemas.Post)
def repost_post(
    post_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    original_post = db.query(Post).filter(Post.id == post_id).first()
    if not original_post:
        raise HTTPException(status_code=404, detail="Post not found")
    
    # Check if already reposted by this user to avoid spam
    existing = db.query(Post).filter(Post.original_post_id == post_id, Post.owner_id == current_user.id).first()
    if existing:
        return existing

    new_repost = Post(
        owner_id=current_user.id,
        original_post_id=original_post.id,
        is_active=True
    )
    db.add(new_repost)
    db.commit()
    db.refresh(new_repost)
    return new_repost

def handle_post_like_background(user_id: int, post_id: int):
    """Background task to handle side effects of a post like."""
    db = SessionLocal()
    try:
        crud_video.handle_like_side_effects(db, user_id, post_id=post_id)
    finally:
        db.close()

@router.post("/{post_id}/like")
def like_post(
    post_id: int,
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    post = db.query(Post).filter(Post.id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    
    is_liked = crud_video.toggle_like(db, user_id=current_user.id, post_id=post_id)
    
    if is_liked:
        # Background side effects
        background_tasks.add_task(handle_post_like_background, current_user.id, post_id)
        
    likes_count = db.query(func.count(Like.id)).filter(Like.post_id == post_id).scalar() or 0
    
    return {"status": "success", "liked": is_liked, "likes_count": likes_count}

def handle_post_comment_background(user_id: int, post_id: int):
    """Background task for post comment side effects."""
    db = SessionLocal()
    try:
        crud_video.handle_comment_side_effects(db, user_id, post_id=post_id)
    finally:
        db.close()

@router.post("/{post_id}/comment", response_model=schemas.Comment)
def comment_post(
    post_id: int,
    comment: schemas.CommentCreate,
    background_tasks: BackgroundTasks,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    post = db.query(Post).filter(Post.id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    
    db_comment = crud_video.create_comment(db, comment=comment, user_id=current_user.id, post_id=post_id)
    
    # Background side effects
    background_tasks.add_task(handle_post_comment_background, current_user.id, post_id)
    
    return db_comment

@router.get("/{post_id}/comments", response_model=List[schemas.Comment])
def read_post_comments(post_id: int, db: Session = Depends(get_db), current_user: Optional[User] = Depends(get_current_user_optional)):
    return crud_video.get_comments(db, post_id=post_id, current_user_id=current_user.id if current_user else None)

@router.delete("/{post_id}")
def delete_post(
    post_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    post = db.query(Post).filter(Post.id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
    
    # Check ownership or admin
    if post.owner_id != current_user.id and current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not authorized to delete this post")
    
    # Delete local image if exists
    if post.image_url and post.image_url.startswith(config.BASE_URL):
        import os
        relative_path = post.image_url.replace(f"{config.BASE_URL}/static/", "")
        local_path = os.path.join(config.STATIC_DIR, relative_path.replace("/", os.sep))
        if os.path.exists(local_path):
            try:
                os.remove(local_path)
            except Exception as e:
                print(f"Failed to delete post image {local_path}: {e}")
                
    db.delete(post)
    db.commit()
    return {"status": "success", "message": "Post deleted successfully"}

@router.put("/{post_id}/comments/{comment_id}", response_model=schemas.Comment)
def update_comment(
    post_id: int,
    comment_id: int,
    comment_in: schemas.CommentBase,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    # Verify post exists
    post = db.query(Post).filter(Post.id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
        
    result = crud_video.update_comment(db, comment_id=comment_id, user_id=current_user.id, content=comment_in.content)
    if result is None:
        raise HTTPException(status_code=404, detail="Comment not found")
    if result is False:
        raise HTTPException(status_code=403, detail="Not authorized to edit this comment")
    return result

@router.delete("/{post_id}/comments/{comment_id}")
def delete_comment(
    post_id: int,
    comment_id: int,
    db: Session = Depends(get_db),
    current_user: dict = Depends(get_current_user)
):
    # Verify post exists
    post = db.query(Post).filter(Post.id == post_id).first()
    if not post:
        raise HTTPException(status_code=404, detail="Post not found")
        
    result = crud_video.delete_comment(db, comment_id=comment_id, user_id=current_user.id)
    if result is None:
        raise HTTPException(status_code=404, detail="Comment not found")
    if result is False:
        raise HTTPException(status_code=403, detail="Not authorized to delete this comment")
    return {"status": "success", "message": "Comment deleted successfully"}