11from __future__ import annotations
22
3+ import json
4+ import time
5+ import ssl
36from abc import ABC , abstractmethod
47from typing import Optional
58from collections import defaultdict
69from threading import Thread , Event
710from collections .abc import Callable
811import traceback
12+
913from scratchattach .utils .requests import requests
1014from scratchattach .utils import exceptions
1115
@@ -41,7 +45,7 @@ def start(self, *, thread=True, ignore_exceptions=True):
4145 else :
4246 self ._thread = None
4347 self ._updater ()
44-
48+
4549 def call_event (self , event_name , args : list = []):
4650 try :
4751 # print(f"Calling for {event_name}...")
@@ -69,7 +73,7 @@ def call_event(self, event_name, args : list = []):
6973 @abstractmethod
7074 def _updater (self ):
7175 pass
72-
76+
7377 def __del__ (self ):
7478 self .stop ()
7579
@@ -120,4 +124,169 @@ def inner(function):
120124 return inner
121125 else :
122126 # => the decorator doesn't provide arguments
123- inner (function )
127+ inner (function )
128+
129+ class BaseCloudServer (BaseEventHandler ):
130+ def __init__ (self ,
131+ hostname : str ,
132+ * ,
133+ certfile : str | None = None ,
134+ keyfile : str | None = None ,
135+ ssl_version : int = ssl .PROTOCOL_TLSv1_2 ,
136+ ssl_context : ssl .SSLContext | None = None ,
137+ port : int ,
138+ websocketclass : WebSocket ,
139+ length_limit : int | None = None ,
140+ allow_non_numeric : bool = True ,
141+ whitelisted_projects : list [Any ]| None = None ,
142+ allow_nonscratch_names : bool = True ,
143+ blocked_ips : list [str ]| None = None ,
144+ sync_players : bool = True ,
145+ log_var_sets : bool = True ):
146+
147+ BaseEventHandler .__init__ (self )
148+
149+ self .running = False
150+ self ._events = {} # saves event functions called on cloud updates
151+
152+ self .tw_clients = {} # saves connected clients
153+ self .tw_variables = {} # holds cloud variable states
154+
155+ self .hostname = hostname
156+ self .port = port
157+
158+ # server config
159+ self .allow_non_numeric = allow_non_numeric
160+ self .whitelisted_projects = whitelisted_projects
161+ self .length_limit = length_limit
162+ self .allow_nonscratch_names = allow_nonscratch_names
163+ self .blocked_ips = blocked_ips
164+ self .sync_players = sync_players
165+ self .log_var_sets = log_var_sets
166+
167+ def check_for_ip_ban (self , client ):
168+ if (
169+ client .address [0 ] in self .blocked_ips
170+ or client .address [0 ] + ":" + str (client .address [1 ]) in self .blocked_ips
171+ or client .address in self .blocked_ips
172+ ):
173+ client .sendMessage ("You have been banned from this server" )
174+ client .close (4002 )
175+ print (client .address [0 ] + ":" + str (client .address [1 ]), "(IP-banned) was disconnected" )
176+ return True
177+ return False
178+
179+ def active_projects (self ):
180+ only_active = {}
181+ for project_id in self .tw_variables :
182+ if self .active_user_ips (project_id ) != []:
183+ only_active [project_id ] = self .tw_variables [project_id ]
184+ return only_active
185+
186+ def active_user_names (self , project_id ):
187+ return [self .tw_clients [user ]["username" ] for user in self .active_user_ips (project_id )]
188+
189+ def active_user_ips (self , project_id ):
190+ return list (filter (lambda user : str (self .tw_clients [user ]["project_id" ]) == str (project_id ), self .tw_clients ))
191+
192+ def get_global_vars (self ):
193+ return self .tw_variables
194+
195+ def get_project_vars (self , project_id ):
196+ project_id = str (project_id )
197+ if project_id in self .tw_variables :
198+ return self .tw_variables [project_id ]
199+ else :
200+ return {}
201+
202+ def get_var (self , project_id , var_name ):
203+ project_id = str (project_id )
204+ var_name = var_name .replace ("☁ " , "" )
205+ if project_id in self .tw_variables :
206+ if var_name in self .tw_variables [project_id ]:
207+ return self .tw_variables [project_id ][var_name ]
208+ else :
209+ return None
210+ else :
211+ return None
212+
213+ def set_global_vars (self , data ):
214+ for project_id in data :
215+ self .set_project_vars (project_id , data [project_id ])
216+
217+ def set_project_vars (self , project_id , data , * , user = "@server" ):
218+ project_id = str (project_id )
219+ self .tw_variables [project_id ] = data
220+ for client in [self .tw_clients [ip ]["client" ] for ip in self .active_user_ips (project_id )]:
221+ client .sendMessage (
222+ "\n " .join (
223+ [
224+ json .dumps (
225+ {
226+ "method" : "set" ,
227+ "project_id" : project_id ,
228+ "name" : "☁ " + varname ,
229+ "value" : data [varname ],
230+ "server" : "scratchattach/2.0.0" ,
231+ "timestamp" : time .time () * 1000 ,
232+ "user" : user ,
233+ }
234+ )
235+ for varname in data
236+ ]
237+ )
238+ )
239+
240+ def set_var (self , project_id , var_name , value , * , user = "@server" , skip_forward = None ):
241+ var_name = var_name .replace ("☁ " , "" )
242+ project_id = str (project_id )
243+ if project_id not in self .tw_variables :
244+ self .tw_variables [project_id ] = {}
245+ self .tw_variables [project_id ][var_name ] = value
246+
247+ if self .sync_players is True :
248+ for client in [self .tw_clients [ip ]["client" ] for ip in self .active_user_ips (project_id )]:
249+ if client == skip_forward :
250+ continue
251+ client .sendMessage (
252+ json .dumps (
253+ {
254+ "method" : "set" ,
255+ "project_id" : project_id ,
256+ "name" : "☁ " + var_name ,
257+ "value" : value ,
258+ "timestamp" : time .time () * 1000 ,
259+ "user" : user ,
260+ }
261+ )
262+ )
263+
264+ def _check_value (self , value ):
265+ # Checks if a received cloud value satisfies the server's constraints
266+ if self .length_limit is not None :
267+ if len (str (value )) > self .length_limit :
268+ return False
269+ if self .allow_non_numeric is False :
270+ x = value .replace ("." , "" )
271+ x = x .replace ("-" , "" )
272+ if not (x .isnumeric () or x == "" ):
273+ return False
274+ return True
275+
276+ def _updater (self ):
277+ try :
278+ # Function called when .start() is executed (.start is inherited from BaseEventHandler)
279+ print (f"Serving websocket server: ws://{ self .hostname } :{ self .port } " )
280+ self .serveforever ()
281+ except Exception as e :
282+ raise exceptions .WebsocketServerError (str (e ))
283+
284+ def pause (self ):
285+ self .running = False
286+
287+ def resume (self ):
288+ self .running = True
289+
290+ def stop (self , wait_call_threads : bool = True ):
291+ BaseEventHandler .stop (self , wait_call_threads )
292+ self .close ()
0 commit comments