ABAO77 commited on
Commit
8c4ead2
·
verified ·
1 Parent(s): bc58832

Upload 157 files

Browse files
src/apis/controllers/__pycache__/comment_controller.cpython-311.pyc CHANGED
Binary files a/src/apis/controllers/__pycache__/comment_controller.cpython-311.pyc and b/src/apis/controllers/__pycache__/comment_controller.cpython-311.pyc differ
 
src/apis/controllers/__pycache__/post_controller.cpython-311.pyc CHANGED
Binary files a/src/apis/controllers/__pycache__/post_controller.cpython-311.pyc and b/src/apis/controllers/__pycache__/post_controller.cpython-311.pyc differ
 
src/apis/controllers/__pycache__/reaction_controller.cpython-311.pyc CHANGED
Binary files a/src/apis/controllers/__pycache__/reaction_controller.cpython-311.pyc and b/src/apis/controllers/__pycache__/reaction_controller.cpython-311.pyc differ
 
src/apis/controllers/comment_controller.py CHANGED
@@ -1,12 +1,11 @@
1
  from typing import Dict
2
  from datetime import datetime
3
- from src.utils.mongo import CommentCRUD
4
  from src.utils.logger import logger
5
  from datetime import datetime
6
  from bson import ObjectId
7
  from datetime import datetime
8
  from bson import ObjectId
9
- from src.utils.mongo import UserCRUD
10
  from asyncio import gather
11
 
12
 
@@ -26,6 +25,9 @@ async def create_a_comment_controller(content: str, user_id: str, post_id: str)
26
  "post_id": post_id,
27
  }
28
  await CommentCRUD.create(comment)
 
 
 
29
  return {"status": "success", "message": "Comment created successfully"}
30
  except Exception as e:
31
  return {"status": "error", "message": str(e)}
@@ -107,6 +109,9 @@ async def delete_a_comment_controller(user_id: str, comment_id: str) -> Dict:
107
  }
108
 
109
  await CommentCRUD.delete({"_id": ObjectId(comment_id)})
 
 
 
110
  return {"status": "success", "message": "Comment deleted successfully"}
111
  except Exception as e:
112
  logger.error(f"Error deleting post: {str(e)}")
 
1
  from typing import Dict
2
  from datetime import datetime
3
+ from src.utils.mongo import CommentCRUD, UserCRUD, PostCRUD
4
  from src.utils.logger import logger
5
  from datetime import datetime
6
  from bson import ObjectId
7
  from datetime import datetime
8
  from bson import ObjectId
 
9
  from asyncio import gather
10
 
11
 
 
25
  "post_id": post_id,
26
  }
27
  await CommentCRUD.create(comment)
28
+ await PostCRUD.update(
29
+ {"_id": ObjectId(post_id)}, {"$inc": {"comment_count": 1}}
30
+ )
31
  return {"status": "success", "message": "Comment created successfully"}
32
  except Exception as e:
33
  return {"status": "error", "message": str(e)}
 
109
  }
110
 
111
  await CommentCRUD.delete({"_id": ObjectId(comment_id)})
112
+ await PostCRUD.update(
113
+ {"_id": ObjectId(exist_data["post_id"])}, {"$inc": {"comment_count": -1}}
114
+ )
115
  return {"status": "success", "message": "Comment deleted successfully"}
116
  except Exception as e:
117
  logger.error(f"Error deleting post: {str(e)}")
src/apis/controllers/post_controller.py CHANGED
@@ -1,7 +1,7 @@
1
  from typing import Dict
2
  from src.utils.mongo import PostCRUD
3
  from src.utils.logger import logger
4
- from src.utils.mongo import UserCRUD
5
  from asyncio import gather
6
  from src.utils.helper import call_external_api, serialize_datetime
7
 
@@ -16,12 +16,12 @@ async def create_a_post_controller(
16
  url="https://abao77-image-retrieval.hf.space/upload_image",
17
  json={"base64_image": images},
18
  )
19
- print("image url", image_url)
20
  post = {
21
  "content": content,
22
  "user_id": user_id,
23
  "destination_id": destination_id,
24
- "comment_ids": [],
 
25
  "picture": image_url["public_url"] if image_url.get("public_url") else None,
26
  "like": [],
27
  }
@@ -42,8 +42,8 @@ async def get_a_post_controller(post_id: str) -> Dict:
42
  "content": post.get("content"),
43
  "user_id": post.get("user_id"),
44
  "destination_id": post.get("destination_id"),
45
- "comment_ids": post.get("comment_ids", []),
46
- "like": post.get("like", []),
47
  "created_at": serialize_datetime(post.get("created_at")),
48
  "updated_at": serialize_datetime(post.get("updated_at")),
49
  }
@@ -54,27 +54,53 @@ async def get_a_post_controller(post_id: str) -> Dict:
54
  return {"status": "error", "message": str(e)}
55
 
56
 
57
- async def list_all_posts_controller():
58
  try:
59
  posts = await PostCRUD.find_all()
60
  user_ids = [post.get("user_id") for post in posts]
61
  user_infos = await gather(
62
  *[UserCRUD.find_by_id(user_id) for user_id in user_ids]
63
  )
 
64
  user_info_map = {
65
  user_info.get("_id"): user_info for user_info in user_infos if user_info
66
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
 
68
  serialized_posts = []
69
- for post in posts:
70
  user_id = post.get("user_id")
71
  user_info = user_info_map.get(user_id)
72
  serialized_post = {
73
  "id": serialize_datetime(post.get("_id")),
74
  "content": post.get("content"),
75
  "destination_id": post.get("destination_id"),
76
- "comment_ids": post.get("comment_ids", []),
77
- "like": post.get("like", []),
 
 
 
 
 
78
  "picture": post.get("picture", []),
79
  "created_at": serialize_datetime(post.get("created_at")),
80
  "updated_at": serialize_datetime(post.get("updated_at")),
 
1
  from typing import Dict
2
  from src.utils.mongo import PostCRUD
3
  from src.utils.logger import logger
4
+ from src.utils.mongo import UserCRUD, ReactionCRUD
5
  from asyncio import gather
6
  from src.utils.helper import call_external_api, serialize_datetime
7
 
 
16
  url="https://abao77-image-retrieval.hf.space/upload_image",
17
  json={"base64_image": images},
18
  )
 
19
  post = {
20
  "content": content,
21
  "user_id": user_id,
22
  "destination_id": destination_id,
23
+ "comment_count": 0,
24
+ "reaction_count": 0,
25
  "picture": image_url["public_url"] if image_url.get("public_url") else None,
26
  "like": [],
27
  }
 
42
  "content": post.get("content"),
43
  "user_id": post.get("user_id"),
44
  "destination_id": post.get("destination_id"),
45
+ "comment_count": post.get("comment_count", 0),
46
+ "reaction_count": post.get("reaction_count", 0),
47
  "created_at": serialize_datetime(post.get("created_at")),
48
  "updated_at": serialize_datetime(post.get("updated_at")),
49
  }
 
54
  return {"status": "error", "message": str(e)}
55
 
56
 
57
+ async def list_all_posts_controller(user_id: str):
58
  try:
59
  posts = await PostCRUD.find_all()
60
  user_ids = [post.get("user_id") for post in posts]
61
  user_infos = await gather(
62
  *[UserCRUD.find_by_id(user_id) for user_id in user_ids]
63
  )
64
+
65
  user_info_map = {
66
  user_info.get("_id"): user_info for user_info in user_infos if user_info
67
  }
68
+ all_post_ids = {serialize_datetime(post.get("_id")) for post in posts}
69
+
70
+ formatted_user_reactions = []
71
+ if user_id:
72
+ reactions = await gather(
73
+ *[
74
+ ReactionCRUD.read_one({"user_id": user_id, "post_id": post_id})
75
+ for post_id in all_post_ids
76
+ ]
77
+ )
78
+ formatted_user_reactions = [
79
+ {
80
+ "id": serialize_datetime(reaction.get("_id", None)),
81
+ "post_id": reaction.get("post_id", None),
82
+ "user_id": reaction.get("user_id", None),
83
+ "reaction_type": reaction.get("type", None),
84
+ }
85
+ for reaction in reactions
86
+ if reaction is not None # Ensure only non-None reactions are processed
87
+ ]
88
 
89
  serialized_posts = []
90
+ for index, post in enumerate(posts):
91
  user_id = post.get("user_id")
92
  user_info = user_info_map.get(user_id)
93
  serialized_post = {
94
  "id": serialize_datetime(post.get("_id")),
95
  "content": post.get("content"),
96
  "destination_id": post.get("destination_id"),
97
+ "comment_count": post.get("comment_count", []),
98
+ "reaction_count": post.get("reaction_count", []),
99
+ "current_user_reaction": (
100
+ formatted_user_reactions[index]
101
+ if formatted_user_reactions
102
+ else None
103
+ ),
104
  "picture": post.get("picture", []),
105
  "created_at": serialize_datetime(post.get("created_at")),
106
  "updated_at": serialize_datetime(post.get("updated_at")),
src/apis/controllers/reaction_controller.py CHANGED
@@ -1,6 +1,6 @@
1
  from typing import Dict
2
  from datetime import datetime
3
- from src.utils.mongo import ReactionCRUD
4
  from src.utils.logger import logger
5
  from datetime import datetime
6
  from bson import ObjectId
@@ -26,6 +26,9 @@ async def create_a_reaction_controller(user_id: str, post_id: str, type: int) ->
26
  "type": type,
27
  }
28
  await ReactionCRUD.create(reaction)
 
 
 
29
  return {"status": "success", "message": "Reaction created successfully"}
30
  except Exception as e:
31
  return {"status": "error", "message": str(e)}
@@ -70,7 +73,9 @@ async def list_all_reaction_controller(post_id: str) -> Dict:
70
  return {"status": "error", "message": str(e)}
71
 
72
 
73
- async def update_a_reaction_controller(user_id: str, reaction_id: str, type: int) -> Dict:
 
 
74
  try:
75
  exist_data = await ReactionCRUD.find_by_id(reaction_id)
76
  if exist_data["user_id"] != user_id:
@@ -103,6 +108,9 @@ async def delete_a_reaction_controller(user_id: str, reaction_id: str) -> Dict:
103
  if exist_data is None:
104
  return {"status": "error", "message": "Reaction not found"}
105
  await ReactionCRUD.delete({"_id": ObjectId(reaction_id)})
 
 
 
106
  return {"status": "success", "message": "Reaction deleted successfully"}
107
  except Exception as e:
108
  logger.error(f"Error deleting reaction: {str(e)}")
 
1
  from typing import Dict
2
  from datetime import datetime
3
+ from src.utils.mongo import ReactionCRUD, PostCRUD
4
  from src.utils.logger import logger
5
  from datetime import datetime
6
  from bson import ObjectId
 
26
  "type": type,
27
  }
28
  await ReactionCRUD.create(reaction)
29
+ await PostCRUD.update(
30
+ {"_id": ObjectId(post_id)}, {"$inc": {"reaction_count": 1}}
31
+ )
32
  return {"status": "success", "message": "Reaction created successfully"}
33
  except Exception as e:
34
  return {"status": "error", "message": str(e)}
 
73
  return {"status": "error", "message": str(e)}
74
 
75
 
76
+ async def update_a_reaction_controller(
77
+ user_id: str, reaction_id: str, type: int
78
+ ) -> Dict:
79
  try:
80
  exist_data = await ReactionCRUD.find_by_id(reaction_id)
81
  if exist_data["user_id"] != user_id:
 
108
  if exist_data is None:
109
  return {"status": "error", "message": "Reaction not found"}
110
  await ReactionCRUD.delete({"_id": ObjectId(reaction_id)})
111
+ await PostCRUD.update(
112
+ {"_id": ObjectId(exist_data["post_id"])}, {"$inc": {"reaction_count": -1}}
113
+ )
114
  return {"status": "success", "message": "Reaction deleted successfully"}
115
  except Exception as e:
116
  logger.error(f"Error deleting reaction: {str(e)}")
src/apis/models/__pycache__/post_models.cpython-311.pyc CHANGED
Binary files a/src/apis/models/__pycache__/post_models.cpython-311.pyc and b/src/apis/models/__pycache__/post_models.cpython-311.pyc differ
 
src/apis/models/post_models.py CHANGED
@@ -18,10 +18,11 @@ class Comment(BaseDocument):
18
  }
19
  }
20
 
 
21
  class Reaction(BaseDocument):
22
  user_id: str = Field("", description="User's id")
23
  post_id: str = Field("", description="Post's id")
24
- type: int = Field(0, description="Type of like", gt=0, lt=5)
25
 
26
  model_config = {
27
  "json_schema_extra": {
@@ -38,8 +39,8 @@ class Post(BaseDocument):
38
  content: str = Field("", description="Post's content")
39
  user_id: str = Field("", description="User's id")
40
  destination_id: str = Field("", description="Destination's id")
41
- comment_ids: list[str] = Field([], description="Comment's id")
42
- like: list[str] = Field([], description="User's id who like this post")
43
  picture: Optional[list[str]] = Field([], description="Picture's url")
44
  model_config = {
45
  "json_schema_extra": {
@@ -47,8 +48,8 @@ class Post(BaseDocument):
47
  "content": "John Doe",
48
  "user_id": "1234567890",
49
  "destination_id": "1234567890",
50
- "comment_ids": ["1234567890"],
51
- "like": ["1234567890"],
52
  "picture": ["https://example.com/picture.jpg"],
53
  }
54
  }
 
18
  }
19
  }
20
 
21
+
22
  class Reaction(BaseDocument):
23
  user_id: str = Field("", description="User's id")
24
  post_id: str = Field("", description="Post's id")
25
+ type: int = Field(0, description="Type of like", ge=0, lt=5)
26
 
27
  model_config = {
28
  "json_schema_extra": {
 
39
  content: str = Field("", description="Post's content")
40
  user_id: str = Field("", description="User's id")
41
  destination_id: str = Field("", description="Destination's id")
42
+ comment_count: int = Field(0, description="Comment's id")
43
+ reaction_count: int = Field(0, description="User's id who like this post")
44
  picture: Optional[list[str]] = Field([], description="Picture's url")
45
  model_config = {
46
  "json_schema_extra": {
 
48
  "content": "John Doe",
49
  "user_id": "1234567890",
50
  "destination_id": "1234567890",
51
+ "comment_count": 1,
52
+ "reaction_count": 1,
53
  "picture": ["https://example.com/picture.jpg"],
54
  }
55
  }
src/apis/routes/__pycache__/post_router.cpython-311.pyc CHANGED
Binary files a/src/apis/routes/__pycache__/post_router.cpython-311.pyc and b/src/apis/routes/__pycache__/post_router.cpython-311.pyc differ
 
src/apis/routes/post_router.py CHANGED
@@ -67,13 +67,13 @@ async def get_post(post_id: str):
67
 
68
 
69
  @router.get("/list", status_code=status.HTTP_200_OK)
70
- async def list_all_posts(background_tasks: BackgroundTasks):
71
- result = await get_key_redis("all_posts")
72
  result = None
73
- result = eval(result) if result else None
74
  if not result:
75
- result = await list_all_posts_controller()
76
- background_tasks.add_task(set_key_redis, "all_posts", str(result), 20)
77
  if result["status"] == "error":
78
  return JSONResponse(content=result, status_code=404)
79
  else:
 
67
 
68
 
69
  @router.get("/list", status_code=status.HTTP_200_OK)
70
+ async def list_all_posts(user_id: Optional[str] = None):
71
+ # result = await get_key_redis("all_posts")
72
  result = None
73
+ # result = eval(result) if result else None
74
  if not result:
75
+ result = await list_all_posts_controller(user_id)
76
+ # background_tasks.add_task(set_key_redis, "all_posts", str(result), 20)
77
  if result["status"] == "error":
78
  return JSONResponse(content=result, status_code=404)
79
  else:
src/utils/__pycache__/mongo.cpython-311.pyc CHANGED
Binary files a/src/utils/__pycache__/mongo.cpython-311.pyc and b/src/utils/__pycache__/mongo.cpython-311.pyc differ
 
src/utils/mongo.py CHANGED
@@ -93,12 +93,18 @@ class MongoCRUD:
93
  async def update(self, query: Dict, data: Dict) -> int:
94
  """Update documents in the collection based on a query asynchronously."""
95
  await self._ensure_ttl_index()
96
- data["updated_at"] = get_date_time().replace(tzinfo=None)
97
- if self.ttl_seconds is not None:
98
- data["expire_at"] = data["updated_at"] + timedelta(seconds=self.ttl_seconds)
99
- update_data = self.model(**data).model_dump(exclude_unset=True)
100
- ordered_update = self._order_fields(update_data)
101
- result = await self.collection.update_many(query, {"$set": ordered_update})
 
 
 
 
 
 
102
  return result.modified_count
103
 
104
  async def delete(self, query: Dict) -> int:
 
93
  async def update(self, query: Dict, data: Dict) -> int:
94
  """Update documents in the collection based on a query asynchronously."""
95
  await self._ensure_ttl_index()
96
+
97
+ # Check if update operators like $inc, $set, etc., are used
98
+ if any(key.startswith('$') for key in data.keys()):
99
+ update_data = data
100
+ else:
101
+ # If no MongoDB operators are used, treat it as a normal update
102
+ data["updated_at"] = get_date_time().replace(tzinfo=None)
103
+ if self.ttl_seconds is not None:
104
+ data["expire_at"] = data["updated_at"] + timedelta(seconds=self.ttl_seconds)
105
+ update_data = {"$set": self._order_fields(self.model(**data).model_dump(exclude_unset=True))}
106
+
107
+ result = await self.collection.update_many(query, update_data)
108
  return result.modified_count
109
 
110
  async def delete(self, query: Dict) -> int: