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
11router = APIRouter(
12 prefix="/inbounds", dependencies=[Depends(sudo_admin)], tags=["Inbounds"]
13)
14
15
16@router.get("", response_model=Page[Inbound])
17def get_inbounds(db: DBDep, tag: str = Query(None)):
18 """
19 Get all inbounds
20 """
21 query = db.query(DBInbound)
22 if tag:
23 query = query.filter(DBInbound.tag.ilike(f"%{tag}%"))
24
25 return paginate(db, query)
26
27
28@router.get("/hosts", response_model=Page[InboundHostResponse])
29def get_hosts(db: DBDep):
30 return paginate(db.query(DBInboundHost))
31
32
33@router.put("/hosts/{id}", response_model=InboundHostResponse)
34def update_host(id: int, host: InboundHost, db: DBDep):
35 """
36 Modify a host
37 """
38
39 db_host = crud.get_host(db, id)
40 if not db_host:
41 raise HTTPException(status_code=404, detail="Host not found")
42
43 return crud.update_host(db, db_host, host)
44
45
46@router.delete("/hosts/{id}")
47def delete_host(id: int, db: DBDep):
48 """
49 Remove a host
50 """
51 db_host = crud.get_host(db, id)
52 if not db_host:
53 raise HTTPException(status_code=404, detail="Host not found")
54
55 db.delete(db_host)
56 db.commit()
57 return {}
58
59
60@router.get("/{id}", response_model=Inbound)
61def get_inbound(id: int, db: DBDep):
62 """
63 Get a specific inbound
64 """
65 inbound = crud.get_inbound(db, id)
66 if not inbound:
67 raise HTTPException(status_code=404, detail="Inbound not found")
68
69 return inbound
70
71
72@router.get("/{id}/hosts", response_model=Page[InboundHostResponse])
73def get_inbound_hosts(id: int | None, db: DBDep):
74 """
75 Get hosts of a specific inbound
76 """
77 inbound = crud.get_inbound(db, id)
78 if not inbound:
79 raise HTTPException(status_code=404, detail="Inbound not found")
80
81 return paginate(db, db.query(DBInboundHost).filter(DBInboundHost.inbound_id == id))
82
83
84@router.post("/{id}/hosts", response_model=InboundHostResponse)
85def create_host(id: int, host: InboundHost, db: DBDep):
86 """
87 Add a host to the inbound
88 """
89 inbound = crud.get_inbound(db, id)
90 if not inbound:
91 raise HTTPException(status_code=404, detail="Inbound not found")
92
93 return crud.add_host(db, inbound, host)