Commit Graph

47 Commits

Author SHA1 Message Date
Stacy Olivas
ad77d7b00d fix: BUG-025/026/027/028/029 implementations and ruff/mypy refinements
BUG-025: send_channel_message retry logic on no_event_received
BUG-026: split_text_into_chunks and chunked dispatch in message_handler
BUG-027: test_weekly_on_wrong_day_does_not_run patch uses fake_now
BUG-028: byte_data = b"" initialised before try in decode_meshcore_packet
BUG-029: app.py db_path via self._config_base; realtime.html socket race
  fixed; base.html forceNew removed; ping_timeout 5 to 20s

Additional: ruff and mypy refinements across all modules; discord bridge,
telegram bridge, rate limiter, and service plugin updates
2026-03-17 18:07:19 -07:00
Stacy Olivas
ce884cee87 fix: auth, db migrations, retry, chunking, socket race, trace, timezone, repeater, and ruff/mypy cleanup
BUG-001: web viewer login/session auth (in web viewer commit)
BUG-002: db_manager ALTER TABLE for missing channel_operations and
  feed_message_queue columns on startup
BUG-015: scheduler thread blocked on future.result(); replaced all
  blocking waits with add_done_callback (fire-and-forget)
BUG-016: reboot_radio sends meshcore.commands.reboot() before disconnect
BUG-017: radio disconnect uses asyncio.wait_for(timeout=10)
BUG-022: custom asyncio loop exception handler suppresses IndexError
  from meshcore parser at DEBUG level
BUG-024: last_db_backup_run updated after each run; 2-min startup
  window; last-run seeded from DB on restart
BUG-025: send_channel_message retries up to 2 times (2s delay) on
  no_event_received via _is_no_event_received() helper
BUG-026: split_text_into_chunks() and get_max_message_length() added
  to CommandManager; keyword dispatch uses send_response_chunked()
BUG-028: byte_data = b"" initialised before try block in
  decode_meshcore_packet to prevent UnboundLocalError in except handler
TraceCommand: path nodes reversed and return path truncated; fixed
format_elapsed_display: UTC normalisation before elapsed computation (#75)
RepeaterManager: auto_manage_contacts guard before any purge logic (#50)
Command aliases: [Aliases] config section injects shorthands at startup
JSON logging: _JsonFormatter; json_logging = true in [Logging]
Structured JSON logging compatible with Loki, Elasticsearch, Splunk
Discord bridge, Telegram bridge, and all service plugins updated
MeshGraph edge promotion logic corrected
Shutdown: scheduler and meshcore disconnect joined cleanly; log spam fixed
All modules: ruff and mypy cleanup applied (type annotations, imports)
2026-03-17 18:07:18 -07:00
agessaman
7d76ed443b Update dependencies and enhance path handling for multi-byte support
- Updated `meshcore` dependency version to `2.2.14` in both `pyproject.toml` and `requirements.txt`.
- Added multi-byte path support in the `PathCommand`, allowing for 1-, 2-, and 3-byte-per-hop paths.
- Enhanced `MessageHandler` to utilize `routing_info` for accurate path extraction and validation.
- Improved path extraction methods in `MultitestCommand` and `TestCommand` to prefer `routing_info` for node IDs.
- Refactored path handling logic across various commands to ensure consistent multi-byte path processing.
2026-03-05 13:37:38 -08:00
agessaman
4982ba482d Enhance mesh graph handling for multi-resolution prefix support
- Updated `MeshGraph` to support multi-resolution storage of edges, allowing prefixes of 2, 4, or 6 hex chars without truncation.
- Implemented prefix matching logic to ensure distinct links are maintained and accurately retrieved based on prefix queries.
- Refactored methods in `MessageHandler` and `PathCommand` to accommodate variable prefix lengths during graph lookups.
- Enhanced tests to validate prefix match functionality and edge management in the mesh graph.
2026-03-01 20:42:06 -08:00
agessaman
6b624c567a Enhance path handling and database schema for multi-byte prefix support
- Introduced a new utility function `decode_path_len_byte` to decode RF packet path length bytes, supporting both legacy and multi-byte paths.
- Updated various modules to utilize the new decoding logic, ensuring compatibility with configured prefix lengths.
- Modified database schemas to include `bytes_per_hop` and `out_bytes_per_hop` columns for better path management.
- Enhanced path parsing and validation across commands and services to accommodate variable prefix lengths.
- Improved logging and error handling for path-related operations, ensuring robustness during transitions.
2026-02-28 13:03:48 -08:00
Adam Gessaman
af5961bf53 Merge branch 'dev' into prefixes 2026-02-28 10:19:50 -08:00
Ian Rifkin
36a8a67543 Add transitional support for 2-byte prefixes while keeping legacy 1-byte compatibility
- Update prefix command to accept BOTH legacy 2-char prefixes and
  configured prefix_hex_chars (e.g. 4-char) during firmware transition
- Replace strict length validation with dual-length validation (2 or N)
- Ensure prefix lookups work with either input length via LIKE matching
- Update related SQL prefix extraction to use configured prefix length
- Add fallback handling in path parsing for legacy 2-char route data

Notes:
- This is an interim compatibility change to support mixed networks
  where RF path data is still 1-byte while bot config may be 2-byte.
- Needs additional testing across real multi-hop scenarios and mixed
  bot configurations.
- Translation updates are incomplete: only English strings were updated;
  other translation files still need review.
- Behavior and UX may need refinement after real-world testing.
2026-02-27 23:48:27 -05:00
Ian Rifkin
7671c3a8de Add RandomLine matcher for file-based trigger responses with default momjokes and fun facts 2026-02-25 00:06:09 -05:00
agessaman
1c204dc389 Add trace command, configuration and documentation
- Introduced `[Trace_Command]` section in `config.ini.example` to enable link diagnostics with customizable parameters such as maximum hops, trace mode, and retry settings.
- Updated `command-reference.md` to include usage instructions and examples for the new `trace` and `tracer` commands, detailing their functionality for manual and round-trip tracing.
- Enhanced `mesh_graph.py` to support 2-byte trace confirmation for improved path weighting.
- Modified `message_handler.py` to update the mesh graph based on trace data, ensuring accurate edge representation in the graph.
- Added translations for the new trace commands in `en.json` to support user interaction in multiple languages.
2026-02-23 14:26:50 -08:00
agessaman
cb9d8255d7 Enhance web viewer integration with circuit breaker logic and improved error handling
- Introduced a circuit breaker mechanism to manage consecutive connection failures when sending updates to the web viewer, preventing log flooding during outages.
- Added methods to track send attempts and determine when to skip sending based on the circuit breaker state.
- Updated logging to provide feedback on circuit status and failures, improving troubleshooting capabilities.
- Refined message handling to ensure efficient communication with the web viewer, reducing unnecessary requests during downtime.
2026-02-20 15:51:23 -08:00
agessaman
5b7250cdd4 Enhance graph data handling and configuration options
- Updated `config.ini.example` to include new settings for edge loading and graph data capture, providing clearer guidance on usage.
- Modified `MeshGraph` class to respect the new `graph_capture_enabled` setting, controlling the collection of edge data from incoming packets.
- Adjusted message handling to ensure graph updates only occur when data capture is enabled, optimizing performance and resource usage.
- Added tests to validate the new configuration options, ensuring proper functionality in various scenarios.
2026-02-18 15:09:53 -08:00
Adam Gessaman
40e30def2c feat: Implement per-user rate limiting for bot responses
- Added per-user rate limiting functionality to control the minimum time between bot replies to the same user, identified by public key or sender name.
- Updated configuration files to include `per_user_rate_limit_seconds` and `per_user_rate_limit_enabled` options for enabling and configuring this feature.
- Enhanced the command manager and message handler to support per-user rate limiting, ensuring efficient message handling and reduced spam.
- Updated documentation to reflect the new rate limiting options and their usage.
2026-02-11 09:13:24 -08:00
agessaman
1559860dcb feat: Introduce prefix best location feature and enhance message handling
- Added configuration options for the "prefix best <location>" command in config.ini.example, allowing users to enable/disable the feature and customize its behavior.
- Implemented logic in the PrefixCommand class to find the best prefix for a given location, considering neighbor prefixes and user-defined criteria.
- Enhanced MessageHandler to skip processing old cached messages based on connection time, improving message handling efficiency.
- Updated core bot to track connection time, ensuring accurate message processing and cache management.
2026-01-26 17:15:25 -08:00
agessaman
df8dc8cafb feat: Enhance path selection and observation tracking
- Added new configuration options for path selection presets and proximity methods in config.ini.example, allowing users to customize routing behavior.
- Implemented a new database table for storing observed paths, enabling better tracking of paths from advertisements and messages.
- Updated MessageHandler to store complete paths in the observed_paths table, improving path validation and selection accuracy.
- Enhanced the PathCommand class to utilize new proximity and recency settings, optimizing repeater selection based on user-defined criteria.
- Improved web viewer functionality to display multiple paths for contacts, enhancing user experience and interaction with path data.
2026-01-25 10:12:46 -08:00
agessaman
bd2849655c feat: Enhance mesh graph functionality and path validation
- Added a new mesh graph feature for improved path validation, allowing for enhanced routing accuracy.
- Introduced configuration options for recency decay half-life and graph-based validation settings in config.ini.example.
- Updated the PathCommand class to utilize graph-based selection methods, combining graph and geographic scores for better repeater selection.
- Implemented new methods in MessageHandler to update the mesh graph with advertisement paths and trace packet data.
- Created a new database table for mesh connections to support graph-based path validation.
- Enhanced web viewer integration to display mesh graph updates in real-time, improving user interaction and monitoring capabilities.
2026-01-23 20:26:56 -08:00
agessaman
c53bfce4b7 feat: Enhance elapsed time handling in messages
- Updated the message handling logic to format elapsed time more accurately, displaying "Nms" when the device clock is valid or "Sync Device Clock" when invalid.
- Introduced a new utility function `format_elapsed_display` to centralize elapsed time formatting, improving code maintainability.
- Modified configuration examples to clarify the usage of the {elapsed} placeholder.
- Added translations for the "Sync Device Clock" message in multiple languages to support internationalization.
2026-01-19 09:55:31 -08:00
agessaman
abe8e57ae3 feat: Update banned user handling to support prefix matching
- Modified configuration examples to clarify that banned users are now identified by sender names using prefix matching.
- Implemented a new method in CommandManager to check if a user is banned based on prefix matching, enhancing the bot's ability to ignore messages from banned senders.
- Updated message handling logic to utilize the new prefix matching functionality for improved user management.
2026-01-18 20:04:50 -08:00
Adam Gessaman
8bef8ed485 refactor: Clarify repeater prefix extraction in message handling
- Updated comments in `message_handler.py` and `transmission_tracker.py` to specify that the repeater prefix is extracted from the last hop in the message path.
- Modified the `extract_repeater_prefixes_from_path` method to focus on the last node, improving clarity and functionality by returning only the prefix from the last hop instead of intermediate nodes.
2026-01-12 09:51:34 -08:00
agessaman
7984fa3af6 feat: Enhance command messaging with repeat tracking and transmission monitoring
- Updated `send_dm` and `send_channel_message` methods to include an optional `command_id` for tracking message repeats.
- Integrated transmission tracking to record and manage repeat messages, improving message handling and response accuracy.
- Enhanced `capture_command` method in `BotIntegration` to store repeat information for better analysis in the web viewer.
- Added favicon support and improved web viewer templates to display repeat information effectively.
- Implemented JavaScript updates in the web viewer to handle command updates and display repeat counts dynamically.
2026-01-11 20:30:02 -08:00
agessaman
ca80924e38 feat: Enhance web viewer functionality and configuration options
- Updated `config.ini.example` to include a new option for additional hashtag channels to decode in the packet stream.
- Modified `BotDataViewer` to retrieve and display additional decode-only channels from the configuration.
- Improved packet handling in `message_handler.py` to capture full packet data for web viewer integration.
- Enhanced the web viewer's JavaScript to support detailed packet analysis and display, including color-coded hex breakdowns and improved user interface elements.
- Added new styles and scripts to the web viewer templates for better visual representation of packet data and improved user experience.
2026-01-10 16:39:07 -08:00
agessaman
578fa2caa4 fix: Prevent potential segfaults by deep copying event payloads
- Added deep copy of event payloads in multiple modules to avoid segmentation faults when events are freed.
- Updated the handling of payloads in ChannelManager, MessageHandler, DiscordBridgeService, MapUploaderService, and PacketCaptureService to ensure safe access to event data.
- Enhanced logging for cases where payloads are missing, improving error handling and debugging capabilities.
2026-01-05 17:20:15 -08:00
agessaman
a32fe0dcfd docs: Add docstrings and type hints across modules for improved clarity and maintainability. 2026-01-01 20:12:49 -08:00
agessaman
5abf0a20dd Enhance location resolution in MessageHandler and RepeaterManager
- Implemented a mechanism in MessageHandler to resolve location names from the database using public keys, providing a more user-friendly display of locations.
- Added fallback logic to ensure coordinates are used if no resolved location is found.
- Updated comments in RepeaterManager to clarify the order of preference for city extraction and introduced county as a fallback for rural areas, improving location accuracy.
2026-01-01 18:52:32 -08:00
agessaman
4e890b4b7b Improve message content processing by stripping trailing whitespace and newlines
- Added a step to always strip trailing whitespace and newlines from message content in MessageHandler
2026-01-01 15:20:53 -08:00
agessaman
80b6bcceea Refactor database connection handling in web viewer and improve error logging; fix keyword reporting to web viewer
- Simplified database connection management by using context managers to ensure connections are properly closed.
- Enhanced error handling during MQTT client disconnection in packet capture service, logging specific exceptions.
- Updated message handling in MessageHandler to capture command data for web viewer integration, improving response tracking.
2026-01-01 12:16:22 -08:00
agessaman
cf43362ad5 Enhance error handling and cache management in core and message handler modules
- Improved exception handling in MeshCoreBot to catch specific errors related to database and service initialization.
- Added a new method in MessageHandler for cleaning up stale RF data cache entries, enforcing maximum size limits and periodic cleanup.
- Updated message processing to handle potential AttributeError in multitest listener, ensuring robustness during message handling.
2026-01-01 11:34:57 -08:00
lincomatic
2395c0765d add elapsed for test command 2025-12-24 16:10:26 -08:00
agessaman
f525d2e1d0 Enhance message handling and web viewer with path information support
- Updated MessageHandler to extract and store path information from packet_info and routing_info, improving data tracking.
- Added a new API endpoint in the web viewer for decoding path hex strings to repeater names.
- Enhanced the contacts template to display path information with tooltips, improving user experience.
- Implemented tooltip functionality for path data in the web viewer, allowing users to view detailed repeater information on hover.
2025-12-13 14:41:56 -08:00
agessaman
d62e63cdb9 Apply code quality improvements to PR16 security enhancements
Security Improvements:
- Add DNS timeout (2.0s default) to validate_external_url() to prevent DoS
  attacks from malicious URLs causing DNS resolution to hang
- Make path validation OS-aware: supports Windows, macOS (Darwin), and Linux
  with platform-specific dangerous path detection
- Add validation for negative max_length values in sanitize_input()

Code Quality Improvements:
- Extract bot_root property in MeshCoreBot class to eliminate code duplication
  (was calculated twice in __init__ and setup_logging)
- Use explicit bot_root directory instead of '.' for predictable path validation
  in both database and log file path validation
- Make sanitize_input() max_length parameter Optional to allow disabling length
  check for radio messages (firmware enforces 150-char limit at hardware level)
- Update message_handler.py to use max_length=None for radio messages while
  preserving control character stripping for security
- Replace inline regex with centralized validate_pubkey_format() function in
  base_command.py for consistency and maintainability
- Improve documentation: add comments about socket timeout behavior and
  firmware-enforced message length limits

All improvements have been tested and verified:
- Syntax checks pass
- All functions work correctly
- No circular dependencies
- Bot initializes successfully with all attributes present

Files modified:
- modules/security_utils.py: DNS timeout, OS-aware paths, Optional max_length
- modules/core.py: bot_root property, explicit base directory usage
- modules/message_handler.py: max_length=None for radio messages
- modules/commands/base_command.py: centralized validation function
2025-12-09 21:44:42 -08:00
eddieoz
8a35dc8270 feat: Add security utilities for path validation, SQL injection prevention, and input sanitization. 2025-12-09 21:26:42 -08:00
agessaman
c151fba7a5 Enhance configuration and database management for feed and channel operations. Add channel refresh interval setting to config.ini.example, implement feed manager functionality with new database tables for feed subscriptions and activity tracking, and improve greeter command logic with human greeting detection and Levenshtein distance matching for user greetings. Update web viewer to include feed management pages and integrate global template variables for better user experience. 2025-12-06 10:18:12 -08:00
agessaman
5c2af1a014 added generic per-command channel configuration, allows commands to be mapped to different channels or dms only 2025-11-25 21:19:48 -08:00
agessaman
82aa5ee160 Add greeter command configuration to config.ini.example and implement greeter functionality in message handling. Introduce favorite status management for repeaters, allowing users to toggle favorite status via API. Update path command and test command to incorporate favorite bias in scoring. Enhance database schema to support star status tracking for repeaters and roomservers. 2025-11-25 17:26:40 -08:00
agessaman
732b7551ba Enhance message handling and repeater management by adding packet_hash support for tracking advertisements. Implement geocoding cache to prevent duplicate API calls based on packet_hash, improving efficiency in location data retrieval. Update relevant methods to accept packet_hash and ensure proper handling in geocoding logic. 2025-11-23 11:45:31 -08:00
agessaman
6c660dc14c Enhance configuration and command files to support new distance metrics in message responses. Updated Keywords section to include {path_distance} and {firstlast_distance} placeholders. Refactored distance calculation methods into utils and improved path command logic for better accuracy in distance reporting. Added detailed logging for packet hash calculations and message handling in multitest command. 2025-11-20 21:41:10 -08:00
agessaman
0ec60e48c2 Add multitest functionality to message handler for path collection and implement packet hash calculation for message tracking. Updated translations to support multitest commands. 2025-11-18 20:11:11 -08:00
agessaman
7e2c478662 Implement localization support across various commands and configuration. Added language settings in config.ini.example, integrated translation functionality in command responses, and enhanced error handling with localized messages. Improved fallback mechanisms for missing translations and updated help text for better user guidance. 2025-11-16 20:17:58 -08:00
agessaman
7bb51f219b Web Viewer Integration
- Add Flask + Flask-SocketIO web viewer with dashboard (modules/web_viewer/app.py and related)
- Add web viewer templates: index, realtime, tracking (contacts), cache, purging, stats (modules/web_viewer/templates/)
- Add integration hooks and utility functions for web viewer (modules/web_viewer/integration.py, modules/utils.py)
- Add command to launch web viewer from bot CLI (modules/commands/webviewer_command.py)
- Update .gitignore: ignore db/log files, test scripts, and web viewer artifacts
- Add restart_viewer.sh helper script for standalone web viewer restart/troubleshooting
- Add guidance and documentation for modern viewer in WEB_VIEWER.md and docs/
- Various code structure and import improvements to core bot and command modules to support integration
- Add ACL support for sensitive commands
- Example config updates

Benefits:
- Decouples monitoring/UI from bot core process
- Enables real-time browser dashboard and unified contact/repeater tracking
- Easier integration, dev, and troubleshooting
2025-10-21 21:57:00 -07:00
agessaman
4adf9fe301 Updated database schema for complete contact tracking and optimized handling of repeater commands. Revised method for removing contacts from the device to use meshcore.py. 2025-10-18 17:16:50 -07:00
agessaman
52c7e5fa31 added channel overrides for sports command; updated channels command; added stats command; consolidated t_phrase as a shortcut to test; added scheduled adverts 2025-10-05 16:09:39 -07:00
agessaman
d7eab28395 improved repeater purge, implement sports command, and improve message path detection. 2025-09-16 16:36:02 -07:00
agessaman
7445e2ad10 first draft of a sports command using the ESPN endpoints 2025-09-13 13:35:35 -07:00
agessaman
ef02529a4b make @ command work in public channels 2025-09-07 10:45:43 -07:00
agessaman
b17016087b Add sender name to routing info logs 2025-09-06 18:38:38 -07:00
agessaman
2206265e10 Update modules with latest development changes
- Enhanced command processing with exclamation mark handling
- Improved message handling and RF data correlation
- Updated repeater management functionality
- Enhanced command implementations across all modules
- Updated database manager and core functionality
- All changes maintain backward compatibility
2025-09-06 11:22:58 -07:00
agessaman
04b3542411 Enhance configuration and command structure for MeshCore Bot. Added RF data correlation settings in config.ini, implemented a BotTxRateLimiter for transmission control, and refactored command handling to support plugins. Removed obsolete scripts and improved command metadata for better usability. 2025-09-04 18:48:59 -07:00
agessaman
9fa8b02be6 Initial commit: MeshCore Bot project 2025-09-04 15:33:51 -07:00