diff --git a/redlight_alert_bot.py b/redlight_alert_bot.py index f5710e2..24db6a3 100644 --- a/redlight_alert_bot.py +++ b/redlight_alert_bot.py @@ -12,6 +12,7 @@ class RedlightAlertBot: "Authorization": f"Bearer {self.access_token}", "Content-Type": "application/json" } + self.logger = configure_logger() def send_alert_message(self, room_id, message): endpoint = f"{self.homeserver}/_matrix/client/r0/rooms/{room_id}/send/m.room.message" diff --git a/redlight_client_module.py b/redlight_client_module.py index 2f01f6e..2debc20 100755 --- a/redlight_client_module.py +++ b/redlight_client_module.py @@ -8,8 +8,6 @@ from synapse.api.errors import AuthError from redlight_alert_bot import RedlightAlertBot from logging_module import configure_logger -logger = configure_logger() - class RedlightClientModule: def __init__(self, config: dict, api: ModuleApi): self._api = api @@ -24,16 +22,18 @@ class RedlightClientModule: # Redlight API token self._redlight_api_token = config.get("redlight_api_token", "") + self.logger = configure_logger() + # Use the SimpleHttpClient from ModuleApi self.http_client = api.http_client # Create an instance of the RedlightAlertBot self.bot = RedlightAlertBot(self._homeserver_url, self._redlight_alert_bot_token) # Adjust the homeserver and token as required - logger.info("RedLightClientModule initialized.") - logger.info(f"Redlight bot user token: {self._redlight_alert_bot_token}") - logger.info(f"Redlight alert room: {self._redlight_alert_room}") - logger.info(f"Redlight server endpoint set to: {self._redlight_endpoint}") + self.logger.info("RedLightClientModule initialized.") + self.logger.info(f"Redlight bot user token: {self._redlight_alert_bot_token}") + self.logger.info(f"Redlight alert room: {self._redlight_alert_room}") + self.logger.info(f"Redlight server endpoint set to: {self._redlight_endpoint}") # Register the user_may_join_room function to be called by Synapse before a user joins a room. api.register_spam_checker_callbacks( @@ -50,7 +50,7 @@ class RedlightClientModule: self, user: str, room: str, is_invited: bool ) -> Union["synapse.module_api.NOT_SPAM", "synapse.module_api.errors.Codes"]: - logger.info(f"User {user} is attempting to join room {room}. Invitation status: {is_invited}.") + self.logger.info(f"User {user} is attempting to join room {room}. Invitation status: {is_invited}.") # Double-hash the room and user IDs. hashed_room_id = self.hash_blake2(room) @@ -72,7 +72,7 @@ class RedlightClientModule: response_body = await response.content() # Fetch the content of the response # Log the response content - logger.info(f"Received response with code {response.code}. Content: {response_body}. Response: {response}") + self.logger.info(f"Received response with code {response.code}. Content: {response_body}. Response: {response}") # If HTTP response code is not 'No Content' if response.code != 204: @@ -80,11 +80,11 @@ class RedlightClientModule: # Try to parse the response body as a JSON response_json = json.loads(response_body) except json.JSONDecodeError: - logger.error(f"Failed to decode response body: {response_body}") + self.logger.error(f"Failed to decode response body: {response_body}") # Handle the response based on its HTTP status code if response.code == 200: - logger.warn(f"User {user} not allowed to join restricted room. report_id: {response_json['report_id']} room_id: {room}.") + self.logger.warn(f"User {user} not allowed to join restricted room. report_id: {response_json['report_id']} room_id: {room}.") # Create the alert message alert_message = f"WARNING: Incident detected! User {user} was attempting to access a restricted room. report_id: {response_json['report_id']}, For the room id please check your redlight logs." # Start the synchronous send_alert_message method in a thread but don't await it @@ -93,22 +93,22 @@ class RedlightClientModule: # Throw a 403 error that the user will see raise AuthError(403, "PERMISSION DENIED - This room violates server policy.") elif response.code == 204: - logger.info(f"User {user} allowed to join room {room}.") + self.logger.info(f"User {user} allowed to join room {room}.") return NOT_SPAM # Allow the user to join else: alert_message = f"Unexpected response code {response.code} with body {response_body}. Defaulting to allowing user {user} to join due to unexpected response code." # Handle unexpected responses by alerting and logging them, and allowing the user to join as a fallback - logger.error(alert_message) + self.logger.error(alert_message) loop = asyncio.get_event_loop() loop.run_in_executor(None, self.bot.send_alert_message, self._redlight_alert_room, alert_message) return NOT_SPAM except AuthError as ae: # This will catch the AuthError specifically and log it as an expected error - logger.info(f"User action denied with reason: {ae}") + self.logger.info(f"User action denied with reason: {ae}") raise # Re-raise the error after logging except Exception as e: # Handle any exceptions that arise from making the HTTP request - logger.error(f"HTTP request failed: {e}") + self.logger.error(f"HTTP request failed: {e}") #return NOT_SPAM # Allow the user to join as a fallback raise AuthError(403, "DEBUG: REQUEST FAILED") diff --git a/redlight_server_module.py b/redlight_server_module.py index 399ddb5..a7c1809 100755 --- a/redlight_server_module.py +++ b/redlight_server_module.py @@ -11,8 +11,6 @@ from twisted.web.server import NOT_DONE_YET from twisted.web.http import OK, NO_CONTENT from logging_module import configure_logger -logger = configure_logger() - class SourceDataManager: def __init__(self, module, config): self._module = module @@ -23,6 +21,7 @@ class SourceDataManager: self._source_dict = {} self._source_dict_last_update = None self.update_data() + self.logger = configure_logger() def fetch_file_from_gitea(self, repo_url, token, file_path): # Construct the API URL for the file. @@ -30,7 +29,7 @@ class SourceDataManager: api_url = f"{base_url}/contents/{file_path}?ref=main&access_token={token}" # Log attempt to fetch the file. - logger.info(f"Attempting to update source list, fetching file from: {api_url}") + self.logger.info(f"Attempting to update source list, fetching file from: {api_url}") response = requests.get(api_url) @@ -39,15 +38,15 @@ class SourceDataManager: if content_base64: decoded_content = base64.b64decode(content_base64).decode('utf-8') # Log success - logger.info(f"Successfully fetched content with length: {len(decoded_content)} characters.") + self.logger.info(f"Successfully fetched content with length: {len(decoded_content)} characters.") return decoded_content else: error_message = "Content not found in the response!" - logger.error(error_message) + self.logger.error(error_message) raise ValueError(error_message) else: error_message = f"Failed to fetch file. Response code: {response.status_code}. Content: {response.content.decode('utf-8')}" - logger.error(error_message) + self.logger.error(error_message) response.raise_for_status() def update_data(self): @@ -63,7 +62,7 @@ class SourceDataManager: } self._source_dict_last_update = now - logger.info(f"Source data updated. Number of reports matching the filtered tags: {len(self._source_dict)}") + self.logger.info(f"Source data updated. Number of reports matching the filtered tags: {len(self._source_dict)}") def get_data(self): self.update_data() @@ -79,7 +78,7 @@ class RedlightServerModule: RedlightServerResource(config, self) ) - logger.info("RedlightServerModule initialized.") + self.logger.info("RedlightServerModule initialized.") class RedlightServerResource: # This flag helps Twisted identify this as a final resource and not look for children. @@ -91,7 +90,7 @@ class RedlightServerResource: self._source_dict = self._data_manager.get_data() self._api_tokens = ["stong-access-token"] # Logging for debug purposes - logger.debug(f"Filtered room_id_hashes: {list(self._source_dict.keys())}") + self.logger.debug(f"Filtered room_id_hashes: {list(self._source_dict.keys())}") # Handle incoming HTTP requests to the registered endpoint. def render(self, request): @@ -107,7 +106,7 @@ class RedlightServerResource: request.finish() def _error(failure): - logger.error(f"Error processing abuse lookup request: {failure}") + self.logger.error(f"Error processing abuse lookup request: {failure}") request.setResponseCode(500) request.write(json.dumps({"error": "Internal Server Error"}).encode("utf-8")) request.finish() @@ -117,19 +116,19 @@ class RedlightServerResource: # Indicates asynchronous processing. return NOT_DONE_YET else: - logger.warning(f"Received a request with unsupported method: {method}") + self.logger.warning(f"Received a request with unsupported method: {method}") # If no handler is found for the method, return "Method Not Allowed". return self.method_not_allowed(request) # Handle PUT requests to the endpoint. @inlineCallbacks def on_PUT(self, request): - logger.info(f"Processing PUT request from {request.getClientIP()}.") + self.logger.info(f"Processing PUT request from {request.getClientIP()}.") try: # Read and decode the request body. body = yield request.content.read() content = body.decode("utf-8") - logger.info(f"Received abuse lookup request: {content}") + self.logger.info(f"Received abuse lookup request: {content}") # Extract specific data points from the request content. data = json.loads(content) @@ -139,7 +138,7 @@ class RedlightServerResource: # Check if the provided API token is valid. if api_token not in self._api_tokens: - logger.warning(f"Invalid API token provided by {request.getClientIP()}.") + self.logger.warning(f"Invalid API token provided by {request.getClientIP()}.") request.setResponseCode(401) defer.returnValue(json.dumps({"error": "Unauthorized"}).encode("utf-8")) return @@ -153,20 +152,20 @@ class RedlightServerResource: # Respond based on whether the request is identified as abusive or not. if is_abuse: report_id = source_dict[room_id_hash] - logger.warning(f"Abuse detected from {request.getClientIP()}, user_id_hash: {user_id_hash} report_id: {report_id}.") - logger.debug(f"room_id_hash: {room_id_hash}.") + self.logger.warning(f"Abuse detected from {request.getClientIP()}, user_id_hash: {user_id_hash} report_id: {report_id}.") + self.logger.debug(f"room_id_hash: {room_id_hash}.") request.setResponseCode(http.OK) defer.returnValue(json.dumps({ "error": None, "report_id": report_id, }).encode("utf-8")) else: - logger.info(f"No abuse detected for request from {request.getClientIP()}.") + self.logger.info(f"No abuse detected for request from {request.getClientIP()}.") request.setResponseCode(http.NO_CONTENT) defer.returnValue(b"") except Exception as e: - logger.error(f"Error processing abuse lookup PUT request from {request.getClientIP()}: {e}") + self.logger.error(f"Error processing abuse lookup PUT request from {request.getClientIP()}: {e}") request.setResponseCode(400) defer.returnValue(json.dumps({"error": "Bad Request"}).encode("utf-8")) @@ -180,7 +179,7 @@ class RedlightServerResource: # General method to respond with "Method Not Allowed" for disallowed or unrecognized HTTP methods. def method_not_allowed(self, request): - logger.warning(f"Method Not Allowed: {request.method.decode('ascii')} from {request.getClientIP()}.") + self.logger.warning(f"Method Not Allowed: {request.method.decode('ascii')} from {request.getClientIP()}.") request.setResponseCode(405) return json.dumps({"error": "Method Not Allowed"}).encode("utf-8")