File size: 4,479 Bytes
45645ab
 
 
19a6cbe
 
 
45645ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a6cbe
 
 
 
 
 
 
45645ab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
19a6cbe
45645ab
 
19a6cbe
45645ab
 
 
 
19a6cbe
 
45645ab
19a6cbe
 
45645ab
 
19a6cbe
45645ab
19a6cbe
45645ab
19a6cbe
45645ab
 
19a6cbe
45645ab
19a6cbe
 
45645ab
 
19a6cbe
45645ab
19a6cbe
45645ab
19a6cbe
45645ab
19a6cbe
45645ab
19a6cbe
 
45645ab
 
19a6cbe
 
 
 
 
45645ab
 
 
 
 
19a6cbe
45645ab
19a6cbe
45645ab
19a6cbe
 
45645ab
 
19a6cbe
45645ab
 
 
19a6cbe
 
45645ab
19a6cbe
 
45645ab
 
 
19a6cbe
45645ab
 
 
 
 
19a6cbe
45645ab
 
19a6cbe
45645ab
 
 
19a6cbe
 
45645ab
 
 
19a6cbe
45645ab
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import FastAPI, HTTPException, Request, Depends
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import pymongo
from bson.objectid import ObjectId

# Khởi tạo FastAPI app và cho phép CORS
app = FastAPI()

origins = [
    "*"  # Cho phép tất cả origin, bạn nên thay đổi trong môi trường production
]

app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# MongoDB connection   

mongo_url = "mongodb+srv://ip6ofme:[email protected]/"
client = pymongo.MongoClient(mongo_url)
db = client["test"]
pdf_collection = db["PdfDetails"]
voter_collection = db["Voters"]

# Pydantic models để validate dữ liệu
class PDF(BaseModel):
    title: str
    group: str
    url: str

class Vote(BaseModel):
    id: str

class Voter(BaseModel):
    name: str
    group: str

class VoteByVoter(BaseModel):
    voter_id: str
    file_id: str

# API để upload file và lưu thông tin vào MongoDB
@app.post("/upload-files")
async def upload_file(pdf: PDF):
    new_pdf = {
        "title": pdf.title,
        "group": pdf.group,
        "url": pdf.url,
        "votes": 0
    }
    result = pdf_collection.insert_one(new_pdf)
    return {"status": "ok", "id": str(result.inserted_id)}

# API để tăng số lượng vote của file dựa trên ID
@app.post("/vote")
async def vote(vote: Vote):
    try:
        file = pdf_collection.find_one({"_id": ObjectId(vote.id)})
        if not file:
            raise HTTPException(status_code=404, detail="File not found")

        pdf_collection.update_one({"_id": ObjectId(vote.id)}, {"$inc": {"votes": 1}})
        return {"status": "ok"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# API để lấy số lượng votes của file theo ID
@app.get("/get-votes")
async def get_votes(id: str):
    try:
        file = pdf_collection.find_one({"_id": ObjectId(id)})
        if not file:
            raise HTTPException(status_code=404, detail="File not found")

        return {"status": "ok", "votes": file.get("votes", 0)}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# API để lấy danh sách tất cả các file
@app.get("/get-files")
async def get_files():
    try:
        files = pdf_collection.find({})
        file_list = []
        for file in files:
            file_list.append({
                "id": str(file["_id"]),
                "title": file["title"],
                "group": file["group"],
                "url": file["url"],
                "votes": file.get("votes", 0)
            })
        return {"status": "ok", "data": file_list}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

# API mới để đăng ký người bình chọn
@app.post("/register-voter")
async def register_voter(voter: Voter):
    new_voter = {
        "name": voter.name,
        "group": voter.group,
        "number_of_votes": 0
    }
    result = voter_collection.insert_one(new_voter)
    return {"status": "ok", "id": str(result.inserted_id)}

# API mới để bình chọn
@app.post("/vote-by-voter")
async def vote_by_voter(vote: VoteByVoter):
    voter = voter_collection.find_one({"_id": ObjectId(vote.voter_id)})
    if not voter:
        raise HTTPException(status_code=404, detail="Voter not found")

    if voter["number_of_votes"] >= 5:
        raise HTTPException(status_code=400, detail="Maximum votes reached")

    # Tăng số lượt bình chọn của người dùng
    voter_collection.update_one({"_id": ObjectId(vote.voter_id)}, {"$inc": {"number_of_votes": 1}})

    # Tăng số lượt bình chọn cho file
    pdf_collection.update_one({"_id": ObjectId(vote.file_id)}, {"$inc": {"votes": 1}})

    return {"status": "ok", "message": "Vote recorded successfully"}

# API để lấy thông tin người bình chọn
@app.get("/get-voter")
async def get_voter(id: str):
    voter = voter_collection.find_one({"_id": ObjectId(id)})
    if not voter:
        raise HTTPException(status_code=404, detail="Voter not found")
    return {
        "status": "ok",
        "name": voter["name"],
        "group": voter["group"],
        "number_of_votes": voter["number_of_votes"]
    }

# Khởi chạy server
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)