Skip to content

Commit

Permalink
Merge pull request #3715 from KBVE/dev
Browse files Browse the repository at this point in the history
Preparing Alpha Branch
  • Loading branch information
Fudster authored Jan 11, 2025
2 parents f5686c9 + 59e738f commit 0ff09d5
Show file tree
Hide file tree
Showing 5 changed files with 129 additions and 12 deletions.
2 changes: 1 addition & 1 deletion apps/pydiscordsh/README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# PyDiscordSh

This is a `/v1/` of the Discord.sh API.
We will use a different setup for `/v0/` and `/v2/`.
We will use a different setup for `/v0/` and `/v2/`.
8 changes: 4 additions & 4 deletions apps/pydiscordsh/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -74,15 +74,15 @@
"metadata": {
"images": ["kbve/pydiscordsh"],
"load": true,
"tags": ["1.43", "1.43.0"]
"tags": ["1.44", "1.44.0"]
},
"configurations": {
"local": {
"tags": ["1.43", "1.43.0"],
"tags": ["1.44", "1.44.0"],
"push": false
},
"production": {
"tags": ["1.43", "1.43.0"],
"tags": ["1.44", "1.44.0"],
"push": true,
"customBuildOptions": "--push",
"cache-from": [
Expand All @@ -104,7 +104,7 @@
"forwardAllArgs": false
},
{
"command": "docker run --env-file .env -p 3000:3000 kbve/pydiscordsh:1.43",
"command": "docker run --env-file .env -p 3000:3000 kbve/pydiscordsh:1.44",
"forwardAllArgs": false
}
],
Expand Down
105 changes: 100 additions & 5 deletions apps/pydiscordsh/pydiscordsh/api/schema.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Optional, List
from typing import Optional, List, Tuple
import os, re, html
from sqlmodel import Field, Session, SQLModel, create_engine, select, JSON, Column
from pydantic import field_validator, model_validator
Expand Down Expand Up @@ -108,9 +108,18 @@ def validate_invite(cls, value):

@field_validator("categories")
def validate_categories(cls, value):
if value and len(value) > 2:
raise ValueError("Categories list cannot have more than 2 items.")
return value
if not isinstance(value, list):
raise ValueError("Categories must be a list.")
try:
value = [int(item) for item in value]
except ValueError:
raise ValueError("Categories must be a list of integers or strings representing integers.")
if not (1 <= len(value) <= 2):
raise ValueError("Categories list must have 1 or 2 items.")
for category_index in value:
if not DiscordCategories.is_valid_category(category_index):
raise ValueError(f"Invalid category index: {category_index}.")
return value

@field_validator("video")
def validate_video(cls, value):
Expand All @@ -123,6 +132,92 @@ def validate_video(cls, value):
return value
raise ValueError("Invalid YouTube video ID or URL.")

class DiscordCategories:
# In-memory categories with their "active" status, each category will now have an index
CATEGORIES = {
0: {"category": "Anime", "active": True},
1: {"category": "Art", "active": True},
2: {"category": "Community", "active": True},
3: {"category": "Cooking", "active": True},
4: {"category": "Design", "active": True},
5: {"category": "Education", "active": True},
6: {"category": "Entertainment", "active": True},
7: {"category": "eSports", "active": True},
8: {"category": "Fitness", "active": True},
9: {"category": "Gaming", "active": True},
10: {"category": "Health", "active": True},
11: {"category": "Hobbies", "active": True},
12: {"category": "Memes", "active": True},
13: {"category": "Music", "active": True},
14: {"category": "PC", "active": True},
15: {"category": "Photography", "active": True},
16: {"category": "Programming", "active": True},
17: {"category": "RolePlaying", "active": True},
18: {"category": "Social", "active": True},
19: {"category": "Sports", "active": True}
}

@classmethod
def is_valid_category(cls, index: int) -> bool:
"""
Check if the category with the given index is valid and active.
Args:
index (int): The index of the category to check.
Returns:
bool: True if the category exists and is active, False otherwise.
Example:
>>> DiscordCategories.is_valid_category(9)
True
>>> DiscordCategories.is_valid_category(100)
False
"""
category = cls.CATEGORIES.get(index)
return category is not None and category["active"]

@classmethod
def set_category_active(cls, index: int, active: bool):
"""
Set the 'active' status for a specific category by its index.
Args:
index (int): The index of the category to modify.
active (bool): The active status to set (True or False).
Example:
>>> DiscordCategories.set_category_active(9, False)
>>> DiscordCategories.is_valid_category(9)
False
"""
category = cls.CATEGORIES.get(index)
if category:
category["active"] = active
else:
raise ValueError(f"Category with index {index} does not exist.")

@classmethod
def get_all_active_categories(cls) -> List[str]:
"""
Get a list of all active categories by index.
Returns:
List[str]: A list of category names that are marked as active.
Example:
>>> DiscordCategories.get_all_active_categories()
['Anime', 'Art', 'Community', 'Cooking', 'Design', 'Education', 'Entertainment', 'eSports', 'Fitness', 'Gaming', 'Health', 'Hobbies', 'Memes', 'Music', 'PC', 'Photography', 'Programming', 'RolePlaying', 'Social', 'Sports']
"""
return [cls.CATEGORIES[index]["category"] for index, category in cls.CATEGORIES.items() if category["active"]]

@classmethod
def get_all_categories(cls) -> List[Tuple[int, str]]:
"""
Get a list of all categories by index, active or not.
Returns:
List[Tuple[int, str]]: A list of tuples containing index and category names, regardless of active status.
Example:
>>> DiscordCategories.get_all_categories()
[(0, 'Anime'), (1, 'Art'), (2, 'Community'), ...]
"""
return [(index, cls.CATEGORIES[index]["category"]) for index in cls.CATEGORIES]



# class BumpVote(SanitizedBaseModel, table=False)

class SchemaEngine:
Expand All @@ -138,7 +233,7 @@ def __init__(self):
db_url = f"sqlite+{self.TURSO_DATABASE_URL}/?authToken={self.TURSO_AUTH_TOKEN}&secure=true"

# Create the engine
self.engine = create_engine(db_url, connect_args={'check_same_thread': False}, echo=True)
self.engine = create_engine(db_url, connect_args={'check_same_thread': False}, pool_pre_ping=True, echo=True)

def get_session(self) -> Session:
"""Provide the database session."""
Expand Down
24 changes: 23 additions & 1 deletion apps/pydiscordsh/pydiscordsh/apps/kilobase.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,4 +97,26 @@ def extract_user_id(self, token: str) -> str:
except InvalidTokenError:
raise ValueError("Invalid token.")
except Exception as e:
raise ValueError(f"Token verification error: {e}")
raise ValueError(f"Token verification error: {e}")


def health_status(self) -> dict:
"""
Check the health status of the Supabase connection.
Returns:
dict: A dictionary containing the status and a message.
"""
try:
# Attempt a simple query to check the connection health
response = self.client.table("users").select("id").limit(1).execute()

# Check if the response is valid
if response.data is not None:
return {"status": "healthy", "message": "Supabase connection is active."}
else:
return {"status": "unhealthy", "message": "Failed to fetch data from Supabase."}

except Exception as e:
# Return an error status if the connection test fails
return {"status": "unhealthy", "message": f"Error: {str(e)}"}
2 changes: 1 addition & 1 deletion migrations/kube/charts/discordsh/discord/values.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ pydiscordsh:
replicaCount: 1
image:
repository: kbve/pydiscordsh
tag: 1.42.0
tag: 1.43.0
digest: 'sha256:sha256:cc49e2b2fede31eb242b9b7fe981c4a594e9cec797144816267f9b02e9630630'
service:
name: pydiscordsh
Expand Down

0 comments on commit 0ff09d5

Please sign in to comment.