99import secrets
1010from typing import Annotated
1111import astroidapi .attachment_processor
12+ import astroidapi .emoji_handler
1213import astroidapi .endpoint_update_handler
1314import astroidapi .errors
1415import astroidapi .get_channel_information
@@ -173,28 +174,11 @@ async def get_cdn_asset(assetId: str):
173174 return fastapi .responses .JSONResponse (status_code = 404 , content = {"message" : "This asset does not exist." })
174175 except Exception as e :
175176 return fastapi .responses .JSONResponse (status_code = 500 , content = {"message" : f"An error occurred: { e } " })
176-
177- @api .get ("/docs/props" , description = "Get the properties of the API." )
178- def props ():
179- return json .load (open (f"{ pathlib .Path (__file__ ).parent .resolve ()} /props.json" , "r" ))
180-
181- @api .get ("/docs/parameters" , description = "Get the parameters of the API." )
182- def parameters ():
183- return json .load (open (f"{ pathlib .Path (__file__ ).parent .resolve ()} /parameters.json" , "r" ))
184-
185- @api .get ("/docs/responses" , description = "Get the responses of the API." )
186- def responses ():
187- return json .load (open (f"{ pathlib .Path (__file__ ).parent .resolve ()} /responses.json" , "r" ))
177+
188178
189179@api .get ("/getserverstructure" , description = "Get a server structure." )
190180def get_server_structure (id : int , token : Annotated [str , fastapi .Query (max_length = 85 , min_length = 71 )] = None ):
191- global data_token
192- try :
193- data_token = json .load (open (f"{ pathlib .Path (__file__ ).parent .resolve ()} /tokens.json" , "r" ))[f"{ id } " ]
194- except :
195- logging .exception (traceback .print_exc ())
196- data_token = None
197- pass
181+ data_token = await astroidapi .surrealdb_handler .TokenHandler .get_token (id )
198182 if token is not None :
199183 if token == data_token or token == Bot .config .MASTER_TOKEN :
200184 headers = {
@@ -323,7 +307,7 @@ async def new_token(endpoint: int,
323307 return fastapi .responses .JSONResponse (status_code = 403 , content = {"message" : "This endpoint is suspended." })
324308
325309 if master_token == Bot .config .MASTER_TOKEN :
326- token = secrets .token_urlsafe (53 )
310+ token = secrets .token_urlsafe (71 )
327311 exists = await astroidapi .surrealdb_handler .TokenHandler .get_token (endpoint )
328312 if exists :
329313 await astroidapi .surrealdb_handler .TokenHandler .update_token (endpoint , token )
@@ -344,10 +328,11 @@ async def daily_endpoint_check(master_token: Annotated[str, fastapi.Query(max_le
344328 for line in summary :
345329 txt_file .write (line + "\n " )
346330 txt_file .close ()
347- requests .post ("https://discord.com/api/webhooks/1279497897016299553/3GrZI75dDYwIkwYBac4o2ApJgzlVVCPIZnon_iE5RtaRIyiYUwcdaXxA327oNZyWZXs4" , json = {"content" : f"[Astroid API - Daily Endpoint Check] { len (summary )} endpoints checked. Summary: https://api.astroid.cc/healtcheck_summaries/{ random_token } " })
331+ requests .post (Bot . config . API_INFO_WEBHOOK_URL , json = {"content" : f"[Astroid API - Daily Endpoint Check] { len (summary )} endpoints checked. Summary: https://api.astroid.cc/healtcheck_summaries/{ random_token } " })
348332 return fastapi .responses .JSONResponse (status_code = 200 , content = {"message" : "Success." })
349333 except Exception as e :
350334 logging .exception (traceback .print_exc ())
335+ requests .post (Bot .config .API_INFO_WEBHOOK_URL , json = {"content" : f"[Astroid API - Daily Endpoint Check] An error occurred while checking the endpoints:\n \n `{ e } `" })
351336 return fastapi .responses .JSONResponse (status_code = 500 , content = {"message" : f"An error occurred: { e } " })
352337 else :
353338 return fastapi .responses .JSONResponse (status_code = 401 , content = {"message" : "The provided token is invalid." })
@@ -367,11 +352,11 @@ async def clear_temporary_attachments(master_token: Annotated[str, fastapi.Query
367352 try :
368353 total_files = len (os .listdir (f"{ pathlib .Path (__file__ ).parent .resolve ()} /astroidapi/TMP_attachments" )) - 1
369354 await astroidapi .attachment_processor .force_clear_temporary_attachments ()
370- requests .post ("https://discord.com/api/webhooks/1279497897016299553/3GrZI75dDYwIkwYBac4o2ApJgzlVVCPIZnon_iE5RtaRIyiYUwcdaXxA327oNZyWZXs4" , json = {"content" : f"[Astroid API - TMP Attachments] Deleted { total_files } temporary attachments." })
355+ requests .post (Bot . config . API_INFO_WEBHOOK_URL , json = {"content" : f"[Astroid API - TMP Attachments] Deleted { total_files } temporary attachments." })
371356 return fastapi .responses .JSONResponse (status_code = 200 , content = {"message" : "Success." })
372357 except Exception as e :
373358 logging .exception (traceback .print_exc ())
374- requests .post ("https://discord.com/api/webhooks/1279497897016299553/3GrZI75dDYwIkwYBac4o2ApJgzlVVCPIZnon_iE5RtaRIyiYUwcdaXxA327oNZyWZXs4" , json = {"content" : f"[Astroid API - TMP Attachments] An error occurred while deleting temporary attachments:\n \n `{ e } `" })
359+ requests .post (Bot . config . API_INFO_WEBHOOK_URL , json = {"content" : f"[Astroid API - TMP Attachments] An error occurred while deleting temporary attachments:\n \n `{ e } `" })
375360 return fastapi .responses .JSONResponse (status_code = 500 , content = {"message" : f"An error occurred: { e } " })
376361 else :
377362 return fastapi .responses .JSONResponse (status_code = 401 , content = {"message" : "The provided token is invalid." })
@@ -519,23 +504,23 @@ async def endpoint_healthcheck(endpoint: int, token: str):
519504 try :
520505 healty = await astroidapi .health_check .HealthCheck .EndpointCheck .check (endpoint )
521506 if healty :
522- return fastapi .responses .JSONResponse (status_code = 200 , content = {"message" : "This endpoint is healthy. " , "details" : None })
507+ return fastapi .responses .JSONResponse (status_code = 200 , content = {"message" : "This endpoint is healthy" , "details" : None , "isHealthy" : True })
523508 except astroidapi .errors .HealtCheckError .EndpointCheckError .EndpointConfigError as e :
524509 return fastapi .responses .JSONResponse (status_code = 200 , content = {"message" : f"There seems to be an error in the endpoint configuration: { e } " ,
525- "details" : "configerror" })
510+ "details" : "configerror" , "isHealthy" : False })
526511 except astroidapi .errors .HealtCheckError .EndpointCheckError .EndpointMetaDataError as e :
527512 return fastapi .responses .JSONResponse (status_code = 200 , content = {"message" : f"There seems to be an error in the endpoint meta data: { e } " ,
528- "details" : "metadataerror" })
513+ "details" : "metadataerror" , "isHealhy" : False })
529514 except astroidapi .errors .HealtCheckError .EndpointCheckError as e :
530515 return fastapi .responses .JSONResponse (status_code = 200 , content = {"message" : f"An error occurred: { e } " ,
531- "details" : "unexpectederror" })
516+ "details" : "unexpectederror" , "isHealthy" : False })
532517 except astroidapi .errors .SurrealDBHandler .EndpointNotFoundError :
533- return fastapi .responses .JSONResponse (status_code = 404 , content = {"message" : "This endpoint does not exist. " ,
534- "details" : "notfound" })
518+ return fastapi .responses .JSONResponse (status_code = 404 , content = {"message" : "This endpoint does not exist" ,
519+ "details" : "notfound" , "isHealthy" : False })
535520 except astroidapi .errors .SurrealDBHandler .GetEndpointError as e :
536521 traceback .print_exc ()
537522 return fastapi .responses .JSONResponse (status_code = 404 , content = {"message" : f"An error occurred: { e } " ,
538- "details" : "getendpointerror" })
523+ "details" : "getendpointerror" , "isHealthy" : False })
539524
540525
541526@api .post ("/healthcheck/{endpoint}/repair" , description = "Repair the endpoint." )
@@ -565,58 +550,7 @@ async def create_endpoint(endpoint: int):
565550 except :
566551 pass
567552 try :
568- data = {
569- "config" : {
570- "self-user" : False ,
571- "webhooks" : {
572- "discord" : [],
573- "guilded" : [],
574- "revolt" : [],
575- "nerimity" : []
576- },
577- "channels" : {
578- "discord" : [],
579- "guilded" : [],
580- "revolt" : [],
581- "nerimity" : []
582- },
583- "logs" : {
584- "discord" : None ,
585- "guilded" : None ,
586- "revolt" : None ,
587- "nerimity" : None
588- },
589- "blacklist" : [],
590- "allowed-ids" : [],
591- "isbeta" : False
592- },
593- "meta" : {
594- "sender-channel" : None ,
595- "trigger" : False ,
596- "sender" : None ,
597- "read" : {
598- "discord" : False ,
599- "guilded" : False ,
600- "revolt" : False ,
601- "nerimity" : False
602- },
603- "message" : {
604- "isReply" : False ,
605- "reply" : {
606- "message" : None ,
607- "author" : None
608- },
609- "author" : {
610- "name" : None ,
611- "avatar" : None ,
612- "id" : None
613- },
614-
615- "content" : None ,
616- "attachments" : []
617- }
618- }
619- }
553+ data = astroidapi .health_check .HealthCheck .EndpointCheck .healthy_endpoint_data
620554 await astroidapi .surrealdb_handler .create (endpoint , data )
621555 return fastapi .responses .JSONResponse (status_code = 201 , content = {"message" : "Created." })
622556 except FileExistsError :
@@ -860,7 +794,46 @@ async def add_contributor(id: int, username: str = None, avatar: str = None, tok
860794 return await astroidapi .surrealdb_handler .Contributions .Contributors .create_contributor (id , username , avatar )
861795 else :
862796 return fastapi .responses .JSONResponse (status_code = 401 , content = {"message" : "The provided token is invalid." })
797+
798+ @api .patch ("/emojis/{endpoint}/sync" , description = "Sync the emojis of a given platform. (From Discord to Nerimity sync only)" )
799+ async def sync_emojis (endpoint : int , platform : str , token : Annotated [str , fastapi .Query (max_length = 85 , min_length = 71 )] = None ):
800+ suspend_status = await astroidapi .suspension_handler .Endpoint .is_suspended (endpoint )
801+ if suspend_status :
802+ return fastapi .responses .JSONResponse (status_code = 403 , content = {"message" : "This endpoint is suspended." })
803+
804+ data_token = await astroidapi .surrealdb_handler .TokenHandler .get_token (endpoint )
805+ if platform != "discord" :
806+ return fastapi .responses .JSONResponse (status_code = 400 , content = {"message" : "This platform is not supported. Only from-discord sync is supported." })
863807
808+ if token == Bot .config .MASTER_TOKEN or token == data_token :
809+ return await astroidapi .emoji_handler .sync_discord_emojis (endpoint , platform )
810+ else :
811+ return fastapi .responses .JSONResponse (status_code = 401 , content = {"message" : "The provided token is invalid." })
812+
813+
814+ @api .post ("/optout/{userid}" , description = "Opt out of the Astroid API." )
815+ async def optout (userid : int , token : Annotated [str , fastapi .Query (max_length = 85 , min_length = 71 )] = None ):
816+ if token == Bot .config .MASTER_TOKEN :
817+ return await astroidapi .surrealdb_handler .OptOut .optout (userid )
818+ else :
819+ return fastapi .responses .JSONResponse (status_code = 401 , content = {"message" : "The provided token is invalid." })
820+
821+
822+ @api .post ("/optin/{userid}" , description = "Opt in to the Astroid API." )
823+ async def optin (userid : int , token : Annotated [str , fastapi .Query (max_length = 85 , min_length = 71 )] = None ):
824+ if token == Bot .config .MASTER_TOKEN :
825+ return await astroidapi .surrealdb_handler .OptOut .optin (userid )
826+ else :
827+ return fastapi .responses .JSONResponse (status_code = 401 , content = {"message" : "The provided token is invalid." })
828+
829+
830+ @api .get ("/optout/{userid}" , description = "Check if a user is opted out." )
831+ async def check_optout (userid : int , token : Annotated [str , fastapi .Query (max_length = 85 , min_length = 71 )] = None ):
832+ if token == Bot .config .MASTER_TOKEN :
833+ return {"optedOut" : await astroidapi .surrealdb_handler .OptOut .get_optout_status (userid )}
834+ else :
835+ return fastapi .responses .JSONResponse (status_code = 401 , content = {"message" : "The provided token is invalid." })
836+
864837
865838logging .info ("[CORE] API started." )
866839
0 commit comments