1from fastapi import APIRouter, Depends, Query
2from fastapi import HTTPException
3from fastapi_pagination.ext.sqlalchemy import paginate
4from fastapi_pagination.links import Page
5
6from app.db import crud
7from app.db.models import InboundHost as DBInboundHost, Inbound as DBInbound
8from app.dependencies import DBDep, sudo_admin
9from app.models.proxy import Inbound, InboundHost, InboundHostResponse
10
11HOST_NOT_FOUND_ERROR_MSG = "Host not found"
12
13router = APIRouter(
14 prefix="/inbounds", dependencies=[Depends(sudo_admin)], tags=["Inbounds"]
15)
16
17
18@router.get("", response_model=Page[Inbound])
19def get_inbounds(db: DBDep, tag: str = Query(None)):
20 """
21 Get all inbounds
22 """
23 query = db.query(DBInbound)
24 if tag:
25 query = query.filter(DBInbound.tag.ilike(f"%{tag}%"))
26
27 return paginate(db, query)
28
29
30@router.get("/hosts", response_model=Page[InboundHostResponse])
31def get_hosts(db: DBDep):
32 return paginate(db.query(DBInboundHost))
33
34
35@router.get("/hosts/{id}", response_model=InboundHostResponse)
36def get_host(id: int, db: DBDep):
37 """
38 Get a host
39 """
40 host = crud.get_host(db, id)
41 if not host:
42 raise HTTPException(status_code=404, detail=HOST_NOT_FOUND_ERROR_MSG)
43
44 return host
45
46
47@router.put("/hosts/{id}", response_model=InboundHostResponse)
48def update_host(id: int, host: InboundHost, db: DBDep):
49 """
50 Modify a host
51 """
52
53 db_host = crud.get_host(db, id)
54 if not db_host:
55 raise HTTPException(status_code=404, detail=HOST_NOT_FOUND_ERROR_MSG)
56
57 return crud.update_host(db, db_host, host)
58
59
60@router.delete("/hosts/{id}")
61def delete_host(id: int, db: DBDep):
62 """
63 Remove a host
64 """
65 db_host = crud.get_host(db, id)
66 if not db_host:
67 raise HTTPException(status_code=404, detail=HOST_NOT_FOUND_ERROR_MSG)
68
69 db.delete(db_host)
70 db.commit()
71 return {}
72
73
74@router.get("/{id}", response_model=Inbound)
75def get_inbound(id: int, db: DBDep):
76 """
77 Get a specific inbound
78 """
79 inbound = crud.get_inbound(db, id)
80 if not inbound:
81 raise HTTPException(status_code=404, detail="Inbound not found")
82
83 return inbound
84
85
86@router.get("/{id}/hosts", response_model=Page[InboundHostResponse])
87def get_inbound_hosts(id: int, db: DBDep):
88 """
89 Get hosts of a specific inbound
90 """
91 inbound = crud.get_inbound(db, id)
92 if not inbound:
93 raise HTTPException(status_code=404, detail="Inbound not found")
94
95 return paginate(
96 db, db.query(DBInboundHost).filter(DBInboundHost.inbound_id == id)
97 )
98
99
100@router.post("/{id}/hosts", response_model=InboundHostResponse)
101def create_host(id: int, host: InboundHost, db: DBDep):
102 """
103 Add a host to the inbound
104 """
105 inbound = crud.get_inbound(db, id)
106 if not inbound:
107 raise HTTPException(status_code=404, detail="Inbound not found")
108
109 return crud.add_host(db, inbound, host)