Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions ctfeed.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
from src.database import database
from src.backend.config import update_config_cache
from src.utils import ctf_api
from src.utils import commit_id
from src import crud
from src import schema
from src import bot
Expand All @@ -23,6 +24,9 @@
@asynccontextmanager
async def lifespan(app:FastAPI):
# startup
## get commit id
settings.COMMIT_ID = await commit_id.get_commit_id()

## initialize database
try:
await database.init_db()
Expand Down Expand Up @@ -100,3 +104,11 @@ async def index() -> schema.General:
success=True,
message="Shirakami Fubuki is the cutest fox in the world!"
)


@app.get("/version", tags=["Metadata"])
async def version() -> schema.General:
return schema.General(
success=True,
message=settings.COMMIT_ID
)
35 changes: 30 additions & 5 deletions src/cog/ctfmenu.py
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,7 @@ async def build_embed_and_view(self) -> discord.Embed:
lines = []
for idx, e in enumerate(current, start=display_start + 1):
channel_created = "[⭐️ Channel created]" if e.channel_id is not None else ""
users_count = len(e.users)

if self.type == "ctftime":
time_now = int(datetime.now(timezone.utc).timestamp())
Expand All @@ -173,11 +174,13 @@ async def build_embed_and_view(self) -> discord.Embed:
lines.append(f"{channel_created}{now_running}")
lines.append(f"Start: <t:{e.start}:F> (<t:{e.start}:R>)")
lines.append(f"End: <t:{e.finish}:F> (<t:{e.finish}:R>)")
lines.append(f"Participants: {users_count}")
lines.append(f"")
else:
lines.append(f"**[ID: {e.id}] {e.title}**")
if len(channel_created) != 0:
lines.append(f"{channel_created}")
lines.append(f"Participants: {users_count}")
lines.append("")
description = "\n".join(lines)

Expand Down Expand Up @@ -287,6 +290,20 @@ async def _check_permission(self, interaction: discord.Interaction, force_pm:boo
return member


async def _check_administrator_permission(self, interaction: discord.Interaction) -> Optional[discord.Member]:
if await security.discord_check_administrator(interaction) is False:
return None

member = interaction.user
if isinstance(member, discord.Member) is False:
return None

if member.id != self.owner_id:
await interaction.response.send_message("You are not the owner of this view", ephemeral=True)
return None
return member


async def _read_event(self) -> Optional[model.Event]:
try:
async with database.with_get_db() as session:
Expand Down Expand Up @@ -331,21 +348,29 @@ async def build_embed_and_view(self) -> discord.Embed:

# build view
pm_member = None
admin_member = None
try:
pm_member = await security.check_user(self.owner_id, True)
except Exception:
pass
try:
admin_member = await security.check_administrator(self.owner_id)
except Exception:
pass
if pm_member:
if self.relink_channel not in self.children:
self.add_item(self.relink_channel)
if self.archive_event not in self.children:
self.add_item(self.archive_event)
else:
if self.relink_channel in self.children:
self.remove_item(self.relink_channel)
if self.archive_event in self.children:
self.remove_item(self.archive_event)

if admin_member:
if self.relink_channel not in self.children:
self.add_item(self.relink_channel)
else:
if self.relink_channel in self.children:
self.remove_item(self.relink_channel)

return embed


Expand Down Expand Up @@ -403,7 +428,7 @@ async def archive_event(self, button: discord.ui.Button, interaction: discord.In
)
async def relink_channel(self, select: discord.ui.Select, interaction: discord.Interaction):
# check permission
if await self._check_permission(interaction, True) is None:
if await self._check_administrator_permission(interaction) is None:
return

# argument check
Expand Down
1 change: 1 addition & 0 deletions src/cog/help.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ async def build_embed_and_view(self) -> discord.Embed:
value="\n".join(commands_info),
inline=False
)
embed.set_footer(text=f"Commit: {settings.COMMIT_ID}")

return embed

Expand Down
3 changes: 3 additions & 0 deletions src/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ class Settings(BaseSettings):

# Database configuration
DATABASE_URL:str

# Metadata
COMMIT_ID:str="unknown"

model_config = SettingsConfigDict(env_file=".env")

Expand Down
2 changes: 1 addition & 1 deletion src/router/ctf.py
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,7 @@ async def archive_event(
async def relink_event(
event_db_id:int,
data:schema.RelinkEvent,
member:discord.Member=Depends(security.fastapi_check_pm_user)
member:discord.Member=Depends(security.fastapi_check_administrator)
) -> schema.General:
try:
await channel_op.link_event_to_channel(event_db_id, data.channel_id)
Expand Down
30 changes: 30 additions & 0 deletions src/utils/commit_id.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import asyncio
import logging

# logging
logger = logging.getLogger("uvicorn")


# functions
async def get_commit_id(timeout_sec: float = 3.0) -> str:
try:
process = await asyncio.create_subprocess_exec(
"git",
"rev-parse",
"--short",
"HEAD",
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE,
)
stdout, stderr = await asyncio.wait_for(process.communicate(), timeout=timeout_sec)
if process.returncode != 0:
logger.error(f"fail to read commit id: {stderr.decode(errors='replace').strip()}")
return "unknown"

commit_id = stdout.decode(errors="replace").strip()
if len(commit_id) == 0:
return "unknown"
return commit_id
except Exception as e:
logger.error(f"fail to read commit id: {str(e)}")
return "unknown"
Loading