diff --git a/NewsAlerts.spec b/NewsAlerts.spec index 8d1b54a..6003f19 100644 --- a/NewsAlerts.spec +++ b/NewsAlerts.spec @@ -5,6 +5,10 @@ from PyInstaller.utils.hooks import collect_data_files, collect_submodules block_cipher = None +# Read application version dynamically from root VERSION (SSOT) +_ver_file = Path('VERSION') +app_version = _ver_file.read_text(encoding='utf-8').strip() if _ver_file.is_file() else '2.12.1' + # Collect tzdata for zoneinfo on Windows tzdata_datas = collect_data_files('tzdata') @@ -117,8 +121,8 @@ if sys.platform == 'darwin': 'CFBundleName': 'NewsAlerts', 'CFBundleDisplayName': 'NewsAlerts', 'CFBundleIdentifier': 'com.mlgitdev.newsalerts', - 'CFBundleVersion': '2.9.0', - 'CFBundleShortVersionString': '2.9.0', + 'CFBundleVersion': app_version, + 'CFBundleShortVersionString': app_version, 'NSHighResolutionCapable': True, 'LSMinimumSystemVersion': '12.0', }, diff --git a/VERSION b/VERSION index d8b6989..3cf561c 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -2.12.0 +2.12.1 diff --git a/app/api.py b/app/api.py index ab8045f..f62b5a1 100644 --- a/app/api.py +++ b/app/api.py @@ -2,9 +2,11 @@ import json import logging import threading +import urllib.parse import webbrowser from . import sessions as S +from .borrow import ALPACA_LIVE_API, ALPACA_PAPER_API, alpaca_trading_base from .news import NewsService from .sounds import list_sounds from .version import get_version, get_version_info @@ -52,6 +54,7 @@ class Api: # Attributes prefixed with "_" are not exposed to JS by pywebview. def __init__(self, app) -> None: self._app = app + self._focused = True # ----------------------------------------------------------------- state def get_state(self): @@ -107,6 +110,7 @@ def save_config(self, cfg: dict): paused=False ) a.sounds.muted = is_paused + a.sounds.suppressed = bool(self._focused) and bool(ac.get("quiet_when_focused", False)) if "volume" in ac: a.sounds.set_volume(int(ac["volume"])) a.screener.poke() @@ -136,7 +140,11 @@ def test_alpaca(self, key_id: str = "", secret_key: str = ""): try: import requests headers = {"APCA-API-KEY-ID": kid, "APCA-API-SECRET-KEY": sec} - r = requests.get("https://paper-api.alpaca.markets/v2/account", headers=headers, timeout=6) + base = alpaca_trading_base(kid) + r = requests.get(f"{base}/v2/account", headers=headers, timeout=6) + if r.status_code in (401, 403): + alt_base = ALPACA_LIVE_API if base == ALPACA_PAPER_API else ALPACA_PAPER_API + r = requests.get(f"{alt_base}/v2/account", headers=headers, timeout=6) if r.status_code == 200: acc = r.json() bp = acc.get("buying_power", "0") @@ -152,7 +160,8 @@ def test_alpaca(self, key_id: str = "", secret_key: str = ""): def set_focused(self, focused: bool): a = self._app - a.sounds.suppressed = bool(focused) and bool(a.cfg["alerts"]["quiet_when_focused"]) + self._focused = bool(focused) + a.sounds.suppressed = self._focused and bool(a.cfg["alerts"]["quiet_when_focused"]) return True # ------------------------------------------------------------------ news @@ -170,7 +179,15 @@ def get_story(self, story_id: str): return self._app.news.story(story_id) def get_bamsec(self, ticker: str, force: bool = False): - cfg = getattr(self._app, "config", {}).get("news", {}) + raw_cfg = None + if hasattr(self._app, "cfg") and hasattr(self._app.cfg, "get"): + cand = self._app.cfg.get() + if isinstance(cand, dict): + raw_cfg = cand + if raw_cfg is None: + cand = getattr(self._app, "config", None) + raw_cfg = cand if isinstance(cand, dict) else {} + cfg = raw_cfg.get("news", {}) if not cfg.get("bamsec_enabled", True): return {"ticker": ticker, "company": ticker, "bamsec_url": "", "categories": {}, "all_filings": [], "total": 0, "disabled": True} if hasattr(self._app, "bamsec"): @@ -223,12 +240,14 @@ def play_alert(self, kind: str): return False def open_url(self, url: str): - if url.startswith("http"): - webbrowser.open(url) + raw = str(url or "").strip() + if raw.lower().startswith(("http://", "https://")): + webbrowser.open(raw) return True def open_chart(self, ticker: str): - webbrowser.open(f"https://www.tradingview.com/chart/?symbol={ticker}") + safe_ticker = urllib.parse.quote(str(ticker or "").strip(), safe=":") + webbrowser.open(f"https://www.tradingview.com/chart/?symbol={safe_ticker}") return True def open_app_dir(self): diff --git a/app/bamsec.py b/app/bamsec.py index 593d7bb..471cf15 100644 --- a/app/bamsec.py +++ b/app/bamsec.py @@ -1,6 +1,7 @@ """BamSEC SEC filings provider, parser, and caching service.""" from __future__ import annotations +from collections import OrderedDict import html import logging import re @@ -44,10 +45,11 @@ def form_group(form: str) -> str: class BamSECService: """Fetches, parses, and caches SEC filings directly from BamSEC.""" - def __init__(self, ttl: float = 120.0, timeout: float = 7.0) -> None: + def __init__(self, ttl: float = 120.0, timeout: float = 7.0, max_cache: int = 200) -> None: self.ttl = ttl self.timeout = timeout - self._cache: dict[str, tuple[float, dict[str, Any]]] = {} + self._max_cache = max_cache + self._cache: OrderedDict[str, tuple[float, float, dict[str, Any]]] = OrderedDict() self._lock = threading.Lock() def get_filings(self, ticker: str, force: bool = False) -> dict[str, Any]: @@ -67,8 +69,9 @@ def get_filings(self, ticker: str, force: bool = False) -> dict[str, Any]: now = time.time() with self._lock: hit = self._cache.get(sym) - if hit and not force and (now - hit[0] < self.ttl): - return hit[1] + if hit and not force and (now - hit[0] < hit[1]): + self._cache.move_to_end(sym) + return hit[2] url = f"https://www.bamsec.com/search?q={sym}" headers = { @@ -89,13 +92,21 @@ def get_filings(self, ticker: str, force: bool = False) -> dict[str, Any]: "total": 0, "error": f"BamSEC returned HTTP {r.status_code}", } - with self._lock: - self._cache[sym] = (now, res) + # Do not cache transient 429 / 5xx errors; use short 15s negative TTL for 4xx not-found + if r.status_code not in (429,) and r.status_code < 500: + with self._lock: + self._cache[sym] = (now, min(15.0, self.ttl), res) + self._cache.move_to_end(sym) + while len(self._cache) > self._max_cache: + self._cache.popitem(last=False) return res parsed = self.parse_html(sym, r.text, r.url) with self._lock: - self._cache[sym] = (now, parsed) + self._cache[sym] = (now, self.ttl, parsed) + self._cache.move_to_end(sym) + while len(self._cache) > self._max_cache: + self._cache.popitem(last=False) return parsed except Exception as e: diff --git a/app/borrow.py b/app/borrow.py index a3dd80a..1add00f 100644 --- a/app/borrow.py +++ b/app/borrow.py @@ -43,6 +43,17 @@ STATUS_NA: "N/A", } +ALPACA_PAPER_API = "https://paper-api.alpaca.markets" +ALPACA_LIVE_API = "https://api.alpaca.markets" + + +def alpaca_trading_base(key_id: str) -> str: + """Select Paper vs Live Alpaca trading API endpoint based on key prefix (PK=paper, AK=live).""" + kid = (key_id or "").strip().upper() + if kid.startswith("PK"): + return ALPACA_PAPER_API + return ALPACA_LIVE_API + def load_alpaca_secrets() -> tuple[str, str]: p = find_secrets_file() @@ -86,11 +97,15 @@ def update_credentials(self, key_id: str, secret_key: str, mode: str = "auto") - secret_key = secret_key or s kid = (key_id or "").strip() sec = (secret_key or "").strip() - if kid == self.key_id and sec == self.secret_key and mode == self.mode and len(self._cache) > 0: + changed = (kid != self.key_id or sec != self.secret_key or mode != self.mode) + if not changed and len(self._cache) > 0: return self.key_id = kid self.secret_key = sec self.mode = mode + if changed: + self._cache.clear() + self._details.clear() if self.key_id and self.secret_key and self.mode in ("auto", "alpaca"): threading.Thread(target=self._sync_bulk_assets, daemon=True, name="alpaca-bulk-assets").start() @@ -131,15 +146,26 @@ def _classify_alpaca_asset(self, a: dict) -> tuple[str, dict]: def _sync_bulk_assets(self) -> None: """Fetch all active US equity assets from Alpaca to pre-populate locate data in memory.""" try: - url = "https://paper-api.alpaca.markets/v2/assets?status=active&asset_class=us_equity" + with self._lock: + kid = self.key_id + sec = self.secret_key + if not (kid and sec): + return + base = alpaca_trading_base(kid) + url = f"{base}/v2/assets?status=active&asset_class=us_equity" headers = { - "APCA-API-KEY-ID": self.key_id, - "APCA-API-SECRET-KEY": self.secret_key, + "APCA-API-KEY-ID": kid, + "APCA-API-SECRET-KEY": sec, } r = requests.get(url, headers=headers, timeout=15) + if r.status_code in (401, 403): + alt_base = ALPACA_LIVE_API if base == ALPACA_PAPER_API else ALPACA_PAPER_API + r = requests.get(f"{alt_base}/v2/assets?status=active&asset_class=us_equity", headers=headers, timeout=15) if r.status_code == 200: assets = r.json() with self._lock: + if self.mode not in ("auto", "alpaca"): + return for a in assets: sym = str(a.get("symbol", "")).upper() st, details = self._classify_alpaca_asset(a) @@ -225,15 +251,22 @@ def _estimate(self, sym: str, float_shares: float | None) -> dict: return {"status": STATUS_EASY, "label": LABEL_MAP[STATUS_EASY], "source": "heuristic"} def _query_alpaca(self, sym: str) -> dict | None: - if not (self.key_id and self.secret_key): + with self._lock: + kid = self.key_id + sec = self.secret_key + if not (kid and sec): return None - url = f"https://paper-api.alpaca.markets/v2/assets/{sym}" + base = alpaca_trading_base(kid) + url = f"{base}/v2/assets/{sym}" headers = { - "APCA-API-KEY-ID": self.key_id, - "APCA-API-SECRET-KEY": self.secret_key, + "APCA-API-KEY-ID": kid, + "APCA-API-SECRET-KEY": sec, } try: r = requests.get(url, headers=headers, timeout=5) + if r.status_code in (401, 403): + alt_base = ALPACA_LIVE_API if base == ALPACA_PAPER_API else ALPACA_PAPER_API + r = requests.get(f"{alt_base}/v2/assets/{sym}", headers=headers, timeout=5) if r.status_code == 200: d = r.json() st, details = self._classify_alpaca_asset(d) @@ -251,14 +284,21 @@ def _worker(self) -> None: while True: sym, float_shares, cb = self.q.get() try: + with self._lock: + mode = self.mode + has_keys = bool(self.key_id and self.secret_key) result = None - if self.key_id and self.secret_key and self.mode in ("auto", "alpaca"): + if has_keys and mode in ("auto", "alpaca"): result = self._query_alpaca(sym) if not result: - result = self._estimate(sym, float_shares) + if mode == "alpaca": + result = {"status": STATUS_NA, "label": LABEL_MAP[STATUS_NA], "source": "alpaca"} + else: + result = self._estimate(sym, float_shares) with self._lock: - self._cache[sym] = result + if self.mode == mode: + self._cache[sym] = result if cb: cb(sym, result) diff --git a/app/config.py b/app/config.py index a1a0f79..15d636c 100644 --- a/app/config.py +++ b/app/config.py @@ -6,7 +6,7 @@ import os import sys import threading -from pathlib import Path +from pathlib import Path, PurePosixPath def get_app_dir() -> Path: """Resolve and ensure the application data directory exists across all operating systems. @@ -73,6 +73,19 @@ def get_app_dir() -> Path: ) +def _default_sound_path(win_name: str, mac_name: str, linux_candidates: tuple[str, ...]) -> str: + """Resolve an OS-native default alert sound path without mixing path separators.""" + if sys.platform == "win32": + return str(Path(MEDIA) / win_name) + if sys.platform == "darwin": + return str(PurePosixPath(MEDIA) / mac_name) + for rel in linux_candidates: + candidate = Path(MEDIA) / rel + if candidate.is_file(): + return str(candidate) + return "" + + def find_secrets_file() -> Path | None: """Find keys.toml / secrets.toml in standard locations: 1. %APPDATA%\\NewsAlerts\\keys.toml or secrets.toml @@ -128,6 +141,7 @@ def find_secrets_file() -> Path | None: DEFAULT_HOTKEYS = { "mute": "m", + "toggle_telegram": "Ctrl+Shift+T", "popout_tape": "t", "pause_tape": "Space", "settings": "s", @@ -150,11 +164,23 @@ def find_secrets_file() -> Path | None: "mute": False, "volume": 80, "quiet_when_focused": False, - "sound_new_symbol": MEDIA + r"\Windows Notify System Generic.wav", + "sound_new_symbol": _default_sound_path( + "Windows Notify System Generic.wav", + "Glass.aiff", + ("freedesktop/stereo/message-new-instant.oga", "freedesktop/stereo/bell.oga", "alsa/Front_Center.wav"), + ), "news_sound_enabled": True, - "sound_news": MEDIA + r"\Windows Ding.wav", + "sound_news": _default_sound_path( + "Windows Ding.wav", + "Ping.aiff", + ("freedesktop/stereo/message.oga", "freedesktop/stereo/complete.oga", "alsa/Front_Center.wav"), + ), "tape_sound_enabled": False, - "sound_tape": MEDIA + r"\Windows Navigation Start.wav", + "sound_tape": _default_sound_path( + "Windows Navigation Start.wav", + "Pop.aiff", + ("freedesktop/stereo/audio-volume-change.oga", "freedesktop/stereo/bell.oga", "alsa/Front_Center.wav"), + ), "telegram_enabled": True, "telegram_tape_enabled": True, "telegram_tape_cooldown_sec": 60, @@ -215,7 +241,7 @@ def _merge(base: dict, override: dict) -> dict: if isinstance(v, dict) and isinstance(out.get(k), dict): out[k] = _merge(out[k], v) else: - out[k] = v + out[k] = copy.deepcopy(v) # Ensure any new default tape strategies are added to existing configs, respecting user deletions if "tape" in out and isinstance(out["tape"], dict) and "strategies" in out["tape"]: deleted = set(out["tape"].get("deleted_strategies", [])) diff --git a/app/news.py b/app/news.py index a7d24f8..5aca142 100644 --- a/app/news.py +++ b/app/news.py @@ -1,6 +1,7 @@ """News providers, caching and story rendering.""" from __future__ import annotations +from collections import OrderedDict from datetime import datetime import html import logging @@ -59,10 +60,11 @@ def story(self, story_id: str) -> dict: class AlpacaNews(NewsProvider): """Fetches real-time Benzinga headlines and stories via Alpaca News API.""" - def __init__(self, key_id: str = "", secret_key: str = "") -> None: + def __init__(self, key_id: str = "", secret_key: str = "", max_stories: int = 500) -> None: self.key_id = key_id.strip() self.secret_key = secret_key.strip() - self._stories: dict[str, dict] = {} + self._max_stories = max_stories + self._stories: OrderedDict[str, dict] = OrderedDict() self._lock = threading.Lock() def update_credentials(self, key_id: str, secret_key: str) -> None: @@ -111,6 +113,9 @@ def headlines(self, ticker: str) -> list[dict]: with self._lock: self._stories[sid] = {"html": body_html, "source_url": link} + self._stories.move_to_end(sid) + while len(self._stories) > self._max_stories: + self._stories.popitem(last=False) out.append({ "id": sid, @@ -187,8 +192,11 @@ def ast_to_html(node) -> str: if t == "root": return inner if t == "url": - url = html.escape(params.get("url", ""), quote=True) - text = html.escape(params.get("linkText") or params.get("url", "")) + raw_url = str(params.get("url", "")).strip() + text = html.escape(params.get("linkText") or raw_url) + if not raw_url.lower().startswith(("http://", "https://")): + return text + url = html.escape(raw_url, quote=True) return f'{text}' if t == "symbol": sym = html.escape(params.get("symbol", "")) @@ -204,21 +212,28 @@ def ast_to_html(node) -> str: class NewsService: """Caches headlines per ticker (TTL) and answers 'has fresh news?' queries.""" - def __init__(self, provider: NewsProvider, ttl: float = 45.0) -> None: + def __init__(self, provider: NewsProvider, ttl: float = 45.0, max_cache: int = 300, max_stories: int = 300) -> None: self.p = provider self.ttl = ttl - self._cache: dict[str, tuple[float, list[dict]]] = {} - self._stories: dict[str, dict] = {} + self._max_cache = max_cache + self._max_stories = max_stories + self._cache: OrderedDict[str, tuple[float, list[dict]]] = OrderedDict() + self._stories: OrderedDict[str, dict] = OrderedDict() self._lock = threading.Lock() def get(self, ticker: str, force: bool = False) -> list[dict]: with self._lock: hit = self._cache.get(ticker) + if hit is not None: + self._cache.move_to_end(ticker) if hit and not force and time.time() - hit[0] < self.ttl: return hit[1] items = self.p.headlines(ticker) with self._lock: self._cache[ticker] = (time.time(), items) + self._cache.move_to_end(ticker) + while len(self._cache) > self._max_cache: + self._cache.popitem(last=False) return items def cached(self, ticker: str) -> list[dict] | None: @@ -229,10 +244,15 @@ def cached(self, ticker: str) -> list[dict] | None: def story(self, story_id: str) -> dict: with self._lock: if story_id in self._stories: + self._stories.move_to_end(story_id) return self._stories[story_id] s = self.p.story(story_id) - with self._lock: - self._stories[story_id] = s + if s and (s.get("html") or s.get("source_url")): + with self._lock: + self._stories[story_id] = s + self._stories.move_to_end(story_id) + while len(self._stories) > self._max_stories: + self._stories.popitem(last=False) return s @staticmethod diff --git a/app/screener.py b/app/screener.py index 5667103..6a9b2f1 100644 --- a/app/screener.py +++ b/app/screener.py @@ -68,21 +68,32 @@ def __init__(self, sig: str) -> None: class NewsPrefetcher(threading.Thread): """Background fetch of headlines so rows can show a ๐Ÿ“ฐ flag.""" - def __init__(self, news: NewsService, ttl: float = 120.0) -> None: + def __init__(self, news: NewsService, ttl: float = 120.0, max_tracked: int = 1000) -> None: super().__init__(daemon=True, name="news-prefetch") self.news = news self.ttl = ttl - self.q: "queue.Queue[tuple[str, Callable | None]]" = queue.Queue() + self._max_tracked = max_tracked + self._lock = threading.Lock() + self._seq = 0 + self.q: "queue.PriorityQueue[tuple[int, int, str, Callable | None]]" = queue.PriorityQueue() self._fetched: dict[str, float] = {} def want(self, ticker: str, cb: Callable | None = None, priority: bool = False) -> None: - if priority or time.time() - self._fetched.get(ticker, 0) > self.ttl: - self._fetched[ticker] = time.time() - self.q.put((ticker, cb)) + now = time.time() + with self._lock: + if not priority and now - self._fetched.get(ticker, 0) <= self.ttl: + return + self._fetched[ticker] = now + if len(self._fetched) > self._max_tracked: + cutoff = now - self.ttl + self._fetched = {k: v for k, v in self._fetched.items() if v >= cutoff} + self._seq += 1 + prio = 0 if priority else 1 + self.q.put((prio, self._seq, ticker, cb)) def run(self) -> None: while True: - ticker, cb = self.q.get() + _prio, _seq, ticker, cb = self.q.get() try: items = self.news.get(ticker, force=True) if cb: diff --git a/app/server.py b/app/server.py index 53a7e35..b7db792 100644 --- a/app/server.py +++ b/app/server.py @@ -6,9 +6,10 @@ from pathlib import Path from socketserver import ThreadingMixIn import threading +from urllib.parse import urlparse from wsgiref.simple_server import WSGIServer, make_server -from bottle import Bottle, request, response, static_file +from bottle import Bottle, abort, request, response, static_file log = logging.getLogger(__name__) @@ -25,6 +26,24 @@ def json_resp(data): response.content_type = "application/json; charset=utf-8" return json.dumps(data) + def _is_local_origin(val: str) -> bool: + try: + host = (urlparse(val).hostname or "").lower() + return host in ("127.0.0.1", "localhost", "::1") + except Exception: + return False + + @app.hook("before_request") + def guard_local_csrf(): + if request.method == "POST" and request.path.startswith("/api/"): + origin = request.get_header("Origin") + if origin and not _is_local_origin(origin): + abort(403, "Forbidden: cross-origin API request blocked") + if not origin: + referer = request.get_header("Referer") + if referer and not _is_local_origin(referer): + abort(403, "Forbidden: cross-origin API request blocked") + @app.hook("after_request") def no_cache(): response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" @@ -338,6 +357,30 @@ def toggle_filter_banned(): log.exception("Error in /api/toggle_filter_banned: %s", e) return json_resp({"ok": False, "error": str(e)}) + @app.route("/api/open_app_dir", method=["POST"]) + def open_app_dir(): + try: + return json_resp(api.open_app_dir()) + except Exception as e: + log.exception("Error in /api/open_app_dir: %s", e) + return json_resp({"ok": False, "error": str(e)}) + + @app.route("/api/reset_config", method=["POST"]) + def reset_config(): + try: + return json_resp(api.reset_config()) + except Exception as e: + log.exception("Error in /api/reset_config: %s", e) + return json_resp({"ok": False, "error": str(e)}) + + @app.route("/api/version", method=["GET"]) + def get_version(): + try: + return json_resp(api.get_version()) + except Exception as e: + log.exception("Error in /api/version: %s", e) + return json_resp({"error": str(e)}) + return app diff --git a/app/sounds.py b/app/sounds.py index e459c23..9c83fb4 100644 --- a/app/sounds.py +++ b/app/sounds.py @@ -85,12 +85,20 @@ def play(self, path: str, force: bool = False) -> bool: elif sys.platform.startswith("linux"): player = shutil.which("paplay") or shutil.which("aplay") or shutil.which("canberra-gtk-play") if os.path.isfile(path) and player: - cmd = [player, path] if "canberra" not in player else [player, "-f", path] + if "paplay" in player: + pa_vol = int((self.volume / 100.0) * 65536) + cmd = [player, f"--volume={pa_vol}", path] + elif "canberra" in player: + cmd = [player, "-f", path] + else: + cmd = [player, path] subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) return True - # Fallback beep - sys.stdout.write("\a") - sys.stdout.flush() - return True + # Fallback beep (guard sys.stdout for frozen windowed builds where stdout is None) + if sys.stdout is not None: + sys.stdout.write("\a") + sys.stdout.flush() + return True + return False except Exception: return False diff --git a/app/tape.py b/app/tape.py index c882161..30d42b6 100644 --- a/app/tape.py +++ b/app/tape.py @@ -74,6 +74,9 @@ def __init__(self, cfg: Config, client: TVClient, sounds: SoundPlayer, self._save_lock = threading.RLock() self.events: list[dict] = self._load_history() self._session = None + self._seeded = False + self._last_save_ts = 0.0 + self._dirty = False def _load_history(self) -> list[dict]: try: @@ -84,8 +87,8 @@ def _load_history(self) -> list[dict]: if not isinstance(data, list): return [] c = self.cfg.get() - retention_days = float(c.get("tape", {}).get("retention_days", 4)) - retention_sec = max(retention_days, 4.0) * 86400 # at least 4 days + retention_days = max(float(c.get("tape", {}).get("retention_days", 4)), 1.0) + retention_sec = retention_days * 86400 now = time.time() cutoff = now - retention_sec valid = [e for e in data if isinstance(e, dict) and float(e.get("ts", 0)) >= cutoff] @@ -102,9 +105,9 @@ def _save_history(self) -> None: with self._save_lock: APP_DIR.mkdir(parents=True, exist_ok=True) c = self.cfg.get() - retention_days = float(c.get("tape", {}).get("retention_days", 4)) - retention_sec = max(retention_days, 4.0) * 86400 - max_events = max(int(c.get("tape", {}).get("max_events", 5000)), 5000) + retention_days = max(float(c.get("tape", {}).get("retention_days", 4)), 1.0) + retention_sec = retention_days * 86400 + max_events = max(int(c.get("tape", {}).get("max_events", 5000)), 100) now = time.time() cutoff = now - retention_sec @@ -113,6 +116,8 @@ def _save_history(self) -> None: with open(tmp, "w", encoding="utf-8") as f: json.dump(events_to_save, f, separators=(",", ":")) tmp.replace(self._history_file) + self._last_save_ts = now + self._dirty = False except Exception as e: log.warning("Failed to save tape history to %s: %s", self._history_file, e) @@ -146,10 +151,13 @@ def tick(self) -> None: tc = c["tape"] u = tc["universe"] session = S.current_session() - if session != self._session: # new session: reset HOD tracking + if session != self._session: # new session: reset HOD tracking & re-seed silently self.state.clear() self._session = session + self._seeded = False if S.market_state() == "closed": + if self._dirty and (time.time() - self._last_save_ts >= 10.0): + self._save_history() return f = lambda k: S.tv_field(k, session) # noqa: E731 p_min = u.get("price_min", 1) @@ -167,20 +175,27 @@ def tick(self) -> None: now = time.time() enabled = set(tc["enabled"]) cooldown = float(tc["cooldown_sec"]) + was_seeded = self._seeded new_events = [] for r in rows: ev = self._process(r, session, now, tc["strategies"], cooldown) - new_events.extend(ev) + if was_seeded: + new_events.extend(ev) + if not was_seeded: + self._seeded = True + return if new_events: with self._save_lock: - retention_days = float(tc.get("retention_days", 4)) - retention_sec = max(retention_days, 4.0) * 86400 - max_events = max(int(tc.get("max_events", 5000)), 5000) + retention_days = max(float(tc.get("retention_days", 4)), 1.0) + retention_sec = retention_days * 86400 + max_events = max(int(tc.get("max_events", 5000)), 100) cutoff = now - retention_sec combined = new_events + self.events self.events = [e for e in combined if float(e.get("ts", 0)) >= cutoff][:max_events] - self._save_history() + self._dirty = True + if (now - self._last_save_ts >= 10.0) or len(new_events) >= 20: + self._save_history() self.emit("tape", new_events) filter_banned = bool(c.get("filter_banned", False)) @@ -195,6 +210,8 @@ def tick(self) -> None: tg_on = c["alerts"].get("telegram_enabled", True) and c["alerts"].get("telegram_tape_enabled", True) if self.telegram and tg_on: tg_cd = float(c["alerts"].get("telegram_tape_cooldown_sec", 60)) + if len(self._tg_last_alert) > 2000: + self._tg_last_alert = {k: v for k, v in self._tg_last_alert.items() if now - v < max(tg_cd * 2, 600)} for ev in unbanned_events: if ev.get("strategy") in enabled: sym = str(ev.get("symbol") or ev.get("ticker", "")) @@ -202,6 +219,8 @@ def tick(self) -> None: if now - last_t >= tg_cd: self._tg_last_alert[sym] = now self.telegram.send_tape_alert(ev, session=session) + elif self._dirty and (now - self._last_save_ts >= 10.0): + self._save_history() def _process(self, r: dict, session: str, now: float, strategies: list, cooldown: float) -> list: lg = S.logical_row(r, session) diff --git a/app/telegram.py b/app/telegram.py index 735917b..b6a6bc0 100644 --- a/app/telegram.py +++ b/app/telegram.py @@ -12,6 +12,7 @@ import queue import threading import time +import urllib.parse import requests @@ -89,8 +90,9 @@ def is_configured(self) -> bool: return bool(self.bot_token and self.chat_id) def send_raw(self, text: str) -> None: - if not self.enabled or self.paused: - return + with self._lock: + if not self.enabled or self.paused: + return self._queue.put(text) def send_test_message(self, bot_token: str = "", chat_id: str = "") -> tuple[bool, str]: @@ -118,8 +120,9 @@ def send_test_message(self, bot_token: str = "", chat_id: str = "") -> tuple[boo return False, f"Request failed: {e}" def send_new_symbol_alert(self, screen_name: str, session: str, row: dict, latest_news: str = "") -> None: - if not self.enabled or self.paused: - return + with self._lock: + if not self.enabled or self.paused: + return sym = html.escape(str(row.get("symbol") or row.get("ticker", ""))) desc = html.escape(str(row.get("desc") or "")) @@ -148,10 +151,10 @@ def fmt_big(v): borrow = row.get("borrow") or {} bst = borrow.get("status", "na") - borrow_str = BORROW_EMOJI.get(bst, f"๐ŸŸ  {borrow.get('label', 'N/A')}") + borrow_str = BORROW_EMOJI.get(bst, f"๐ŸŸ  {html.escape(str(borrow.get('label', 'N/A')))}") sess_label = {"pre": "Pre-Market", "regular": "Regular Hours", "post": "Post-Market"}.get(session, session.upper()) - ticker = row.get("ticker", sym) + ticker = str(row.get("ticker") or row.get("symbol") or "") lines = [ f"๐Ÿšจ New Symbol Alert: {sym} ({sess_label})", @@ -169,17 +172,19 @@ def fmt_big(v): if latest_news: lines.append(f"\n๐Ÿ“ฐ News: {html.escape(latest_news)}") - chart_url = f"https://www.tradingview.com/chart/?symbol={ticker}" + safe_tkr = urllib.parse.quote(ticker, safe=":") + chart_url = html.escape(f"https://www.tradingview.com/chart/?symbol={safe_tkr}", quote=True) lines.append(f"\n๐Ÿ”— Open TradingView Chart") self.send_raw("\n".join(lines)) def send_tape_alert(self, event: dict, session: str = "") -> None: - if not self.enabled or self.paused: - return + with self._lock: + if not self.enabled or self.paused: + return sym = html.escape(str(event.get("symbol") or event.get("ticker", ""))) - ticker = event.get("ticker", sym) + ticker = str(event.get("ticker") or event.get("symbol") or "") strat = html.escape(str(event.get("strategy") or "Momentum Alert")) fam = str(event.get("family") or "low") price = event.get("price") @@ -190,7 +195,7 @@ def send_tape_alert(self, event: dict, session: str = "") -> None: relvol5 = event.get("relvol5") borrow = event.get("borrow") or {} bst = borrow.get("status", "na") - borrow_str = BORROW_EMOJI.get(bst, f"๐ŸŸ  {borrow.get('label', 'N/A')}") + borrow_str = BORROW_EMOJI.get(bst, f"๐ŸŸ  {html.escape(str(borrow.get('label', 'N/A')))}") pos52 = event.get("pos52") price_str = f"${price:.2f}" if price is not None else "โ€”" @@ -225,7 +230,8 @@ def fmt_big(v): if pos52 is not None: lines.append(f"๐Ÿ“ˆ 52w Range: {pos52:.1f}%") - chart_url = f"https://www.tradingview.com/chart/?symbol={ticker}" + safe_tkr = urllib.parse.quote(ticker, safe=":") + chart_url = html.escape(f"https://www.tradingview.com/chart/?symbol={safe_tkr}", quote=True) lines.append(f"\n๐Ÿ”— Open TradingView Chart") self.send_raw("\n".join(lines)) @@ -234,15 +240,34 @@ def _worker(self) -> None: while True: text = self._queue.get() with self._lock: + active = self.enabled and not self.paused token = self.bot_token cid = self.chat_id - if token and cid: - try: - requests.post( - f"https://api.telegram.org/bot{token}/sendMessage", - json={"chat_id": cid, "text": text, "parse_mode": "HTML", "disable_web_page_preview": True}, - timeout=8, - ) - except Exception as e: - log.warning("Telegram send failed: %s", e) + if not active or not (token and cid): + continue + try: + r = requests.post( + f"https://api.telegram.org/bot{token}/sendMessage", + json={"chat_id": cid, "text": text, "parse_mode": "HTML", "disable_web_page_preview": True}, + timeout=8, + ) + if r.status_code == 429: + retry_after = 5.0 + try: + retry_after = min(30.0, float(r.json().get("parameters", {}).get("retry_after", 5))) + except Exception: + pass + log.warning("Telegram rate limited (HTTP 429); backing off %.1fs", retry_after) + time.sleep(retry_after) + elif r.status_code != 200: + log.warning("Telegram send returned HTTP %s: %s", r.status_code, r.text[:200]) + else: + try: + data = r.json() + if not data.get("ok", True): + log.warning("Telegram API error: %s", data.get("description", r.text[:200])) + except Exception: + pass + except Exception as e: + log.warning("Telegram send failed: %s", e) time.sleep(0.3) diff --git a/app/tv_client.py b/app/tv_client.py index 362cfc7..dc01295 100644 --- a/app/tv_client.py +++ b/app/tv_client.py @@ -36,14 +36,9 @@ class TVClient: def __init__(self, sessionid: str = "", sessionid_sign: str = "", on_auth_change: Callable[[dict], None] | None = None) -> None: self._lock = threading.Lock() + self._local = threading.local() + self._cookie_ver = 0 self.on_auth_change = on_auth_change - self._s = requests.Session() - self._s.headers.update({ - "User-Agent": UA, - "Origin": "https://www.tradingview.com", - "Referer": "https://www.tradingview.com/", - "Accept": "application/json", - }) self._backoff_until = 0.0 self.sessionid = "" self.sessionid_sign = "" @@ -56,6 +51,36 @@ def __init__(self, sessionid: str = "", sessionid_sign: str = "", } self.set_cookies(sessionid, sessionid_sign) + def _session(self) -> requests.Session: + """Return a thread-local requests.Session synchronized with current cookies.""" + with self._lock: + ver = self._cookie_ver + sid = self.sessionid + ssign = self.sessionid_sign + sess = getattr(self._local, "session", None) + sess_ver = getattr(self._local, "cookie_ver", -1) + if sess is None: + sess = requests.Session() + sess.headers.update({ + "User-Agent": UA, + "Origin": "https://www.tradingview.com", + "Referer": "https://www.tradingview.com/", + "Accept": "application/json", + }) + self._local.session = sess + if sess_ver != ver: + sess.cookies.clear() + if sid: + sess.cookies.set("sessionid", sid, domain=".tradingview.com") + if ssign: + sess.cookies.set("sessionid_sign", ssign, domain=".tradingview.com") + self._local.cookie_ver = ver + return sess + + @property + def _s(self) -> requests.Session: + return self._session() + def set_cookies(self, sessionid: str, sessionid_sign: str = "") -> None: s_id = (sessionid or "").strip() s_sign = (sessionid_sign or "").strip() @@ -64,11 +89,9 @@ def set_cookies(self, sessionid: str, sessionid_sign: str = "") -> None: return self.sessionid = s_id self.sessionid_sign = s_sign - self._s.cookies.clear() - if self.sessionid: - self._s.cookies.set("sessionid", self.sessionid, domain=".tradingview.com") - if self.sessionid_sign: - self._s.cookies.set("sessionid_sign", self.sessionid_sign, domain=".tradingview.com") + self._cookie_ver += 1 + # Eagerly sync caller thread session + self._session() threading.Thread(target=self.check_auth, daemon=True, name="tv-auth-check").start() def _set_auth_info(self, info: dict) -> dict: diff --git a/app/version.py b/app/version.py index eebedc6..0557453 100644 --- a/app/version.py +++ b/app/version.py @@ -161,7 +161,7 @@ def _load_version() -> str: except Exception: pass # 3. Safe institutional fallback - return "2.4.5" + return "2.12.1" # Current application version (Single Source of Truth from root VERSION file) diff --git a/docs/RELEASES.md b/docs/RELEASES.md index 9645d0c..e328379 100644 --- a/docs/RELEASES.md +++ b/docs/RELEASES.md @@ -37,6 +37,7 @@ All official releases are produced deterministically through GitHub Actions: ## Release History +- [v2.12.1 Release Notes](releases/v2.12.1.md) โ€” Hardening patch resolving 15 live-verified issues across Settings/API wiring, BamSEC opt-out & search UX, pop-out tape quick-add, modifier hotkeys, thread-safe TradingView sessions, Alpaca live/paper routing, tape startup seeding, Telegram error handling, bounded LRU caches, cross-platform audio, macOS packaging, and local CSRF/XSS protections (Resolves #67โ€“#81). - [v2.12.0 Release Notes](releases/v2.12.0.md) โ€” Introduced Dual Independent Alert Controls Architecture with dedicated topbar Telegram alert toggle icon (Telegram paper airplane + bell) decoupled from in-app audio chimes for instant desk/mobile alert switching (Resolves #65). - [v2.11.2 Release Notes](releases/v2.11.2.md) โ€” Refactored documentation feature showcase tables in `README.md` and `docs/SPEC.md` to prominent 68/32 image-first HTML tables for instant visual clarity, and added dedicated cross-platform `make env`, `make env-win`, `make env-linux`, `make env-mac`, and `build.ps1 -Task env` targets (Resolves #63). - [v2.11.1 Release Notes](releases/v2.11.1.md) โ€” Added toggleable opt-out capability for BamSEC SEC filings in Settings (opt-in by default), with complete DOM element unmounting, background scraper and network call suppression, and instant reactive live update on save (Resolves #61). diff --git a/docs/SPEC.md b/docs/SPEC.md index f370e04..93dd1b7 100644 --- a/docs/SPEC.md +++ b/docs/SPEC.md @@ -252,7 +252,7 @@ Displays a color-coded status badge directly next to each symbol in both the Scr - **Hard to Borrow (HTB)**: ๐ŸŸก **Yellow** (`hard yellow`) โ€” Limited supply / locate fee required - **No Borrow Available**: ๐ŸŸข **Green** (`no borrow is green`) โ€” No shares available to short / highest squeeze potential - **N/A / Unknown**: ๐ŸŸ  **Orange** (`na data orange`) โ€” Data unavailable or symbol unlisted for locate -- **Data Source**: Integrated with Alpaca Broker API (free paper account keys in Settings / secrets) for real-time broker locates (`borrow_status: hard_to_borrow` -> HTB Yellow, `easy_to_borrow` -> ETB Red), with an intelligent float-based heuristic fallback (float < 500K = No Borrow, 500Kโ€“50M = HTB, > 50M = ETB). +- **Data Source**: Integrated with Alpaca Broker API (auto-selecting `paper-api.alpaca.markets` for `PK...` paper keys and `api.alpaca.markets` for live keys, with fallback) for real-time broker locates (`borrow_status: hard_to_borrow` -> HTB Yellow, `easy_to_borrow` -> ETB Red), with an intelligent float-based heuristic fallback when in `auto`/`heuristic` mode (float < 500K = No Borrow, 500Kโ€“50M = HTB, > 50M = ETB). Switching modes or credentials automatically invalidates cached borrow entries. ### 3.4 TradingView Cloud Watchlist Integration & 1-Click Quick-Add Seamless cloud watchlist synchronization with user TradingView accounts: @@ -450,7 +450,7 @@ The right-hand pane combines real-time catalyst PR headlines with deep SEC EDGAR - **Event** = a symbol matching โ‰ฅ1 enabled strategy AND one of: - makes a **new high of day** (session-aware high) vs the previous poll, or - triggers a squeeze condition (ยง8.2), with per-symbol/per-strategy cooldown (default 30 s). **Monotonic Window Progression**: During an active time window (e.g. 5 min / 10 min), subsequent triggers for the same symbol & strategy require strictly higher prices (`price > last_alert_price`). If the price falls or is flat vs the previous trigger, alerts are suppressed; once the time window resets (`now - last_alert_time >= window_min * 60`), a new squeeze cycle can begin. -- **Persistent Storage & Off-Hours Review**: Tape alerts are automatically saved to `%APPDATA%\NewsAlerts\tape_history.json` and retained for at least 4 days (configurable). When the app restarts, reloads, or opens during off-hours / weekends, all historical alerts are immediately loaded into the tape for retrospective review. +- **Persistent Storage & Off-Hours Review**: Tape alerts are automatically saved to `/tape_history.json` via debounced atomic writes and respect user-configured `retention_days` (default 4 days, minimum 1 day) and `max_events` (default 5,000, minimum 100). On startup or session transition, the first poll silently seeds initial universe state before emitting live alerts. When the app restarts, reloads, or opens during off-hours / weekends, all historical alerts are immediately loaded into the tape for retrospective review. - **Timestamp Formatting**: Displays `H:MM:SS am/pm` for alerts triggered today, and `MMM DD H:MM am/pm` for older alerts, with full ET date/time and relative age tooltips. - Newest events on top; up to 3,000 scrollable rows; โธ pause freezes scrolling and shows "New events โ†‘"; ๐Ÿ—‘๏ธ clear button removes history. @@ -525,7 +525,9 @@ Optional tape sound (default off โ€” the tape is noisy). ## 10. Settings & Integrations TradingView `sessionid`/`sessionid_sign` & real-time connection status ยท poll intervals ยท re-entry window ยท alert volume (0%โ€“100%) ยท unified pause alerts toggle ยท news recency & provider ยท sounds ยท tape universe & strategy thresholds ยท interactive Strategy Builder (`+ Add Strategy`, triggers, family, deletion) ยท Backup / Import & Export tab (Full config backup `.json`, Strategies `.json` export/import, factory reset) ยท Alpaca keys for short borrow locates ยท Telegram Bot Token, Chat ID, and independent toggles for Screener alerts and Tape momentum alerts (with per-symbol cooldown) ยท customizable keyboard shortcuts & hotkeys with interactive re-binding and institutional defaults ยท always-on-top ยท font size. -- **Storage Transparency & Direct Directory Access**: Settings โ†’ About and Settings โ†’ Backup & Sync display the active resolved OS directory (`APP_DIR`) on disk alongside a one-click `๐Ÿ“‚ Open App Data Folder` button (spawning Windows Explorer, macOS Finder, or Linux file manager). +- **Storage Transparency & Direct Directory Access**: Settings โ†’ About and Settings โ†’ Backup & Sync display the active resolved OS directory (`APP_DIR`) on disk alongside a one-click `๐Ÿ“‚ Open App Data Folder` button (`POST /api/open_app_dir`, spawning Windows Explorer, macOS Finder, or Linux file manager) and `โ†บ Restore Factory Defaults` (`POST /api/reset_config`). Full Backup `.json` exports sanitize credentials by default unless explicitly opted in. +- **Local HTTP API Security & Concurrency**: Mutating `POST /api/*` routes enforce localhost `Origin`/`Referer` verification (blocking cross-site CSRF with HTTP 403). `TVClient` uses thread-local `requests.Session` instances synced atomically to cookie updates, news/BamSEC caches use bounded LRU eviction, and `NewsPrefetcher` prioritizes newly alerted tickers via `PriorityQueue`. +- **Keyboard Shortcuts & Modifier Combos**: Hotkeys support both single keys (`m`, `t`, `Space`, `s`, `r`, `Escape`, `Enter`, `1`โ€“`5`) and modifier combinations (default `toggle_telegram: "Ctrl+Shift+T"`), honoring user remappings cleanly. - **Credential Storage Architecture**: Credentials entered in the GUI are stored in `/config.json` with password masking and atomic writes. Alternatively, a standalone `/keys.toml` file can be used for separated secret management (which takes priority when present). - **Broker Closing-Only & Banned Stock Filter**: - Interactive topbar toggle pill (`[๐Ÿšซ Banned: ON / OFF]`) dynamically filters banned/closing-only symbols from both the Screener table and Running Tape stream without reloads. diff --git a/docs/releases/v2.12.1.md b/docs/releases/v2.12.1.md new file mode 100644 index 0000000..5d9d287 --- /dev/null +++ b/docs/releases/v2.12.1.md @@ -0,0 +1,64 @@ +# NewsAlerts v2.12.1 โ€” Release Notes + +**Release Date:** December 2026 +**Type:** Patch Release (`PATCH` โ€” Comprehensive Stability, Security, Cross-Platform & UI Remediation) +**Single Source of Truth:** `VERSION` (`2.12.1`) + +--- + +## ๐Ÿš€ Overview + +NewsAlerts **v2.12.1** delivers a targeted institutional hardening pass resolving **15 live-verified defects** across the HTTP API, frontend UI controls, hotkey engine, Alpaca & TradingView clients, Telegram worker, caching layers, cross-platform audio, and macOS packaging. + +--- + +## ๐Ÿ› ๏ธ Key Fixes & Hardening + +### 1. Critical UI & API Wiring Fixes +- **Settings Navigation (`#67`)**: Fixed `TypeError` when clicking `#tv-status-badge` or `#watchlist-status-badge` by routing both to `Settings.open("general")` and adding a safe fallback in `Settings.open()`. +- **App Data Folder & Factory Reset APIs (`#68`)**: Wired `POST /api/open_app_dir`, `POST /api/reset_config`, and `GET /api/version` in `app/server.py` and exposed `open_app_dir()` / `reset_config()` in `web/js/util.js`. +- **BamSEC Backend Opt-Out Enforcement (`#69`)**: Fixed `Api.get_bamsec()` to read `self._app.cfg.get()` instead of non-existent `self._app.config`, ensuring disabled BamSEC truly suppresses backend requests. + +### 2. Frontend UX, Hotkeys & Backup Security +- **BamSEC Full-View Search Input (`#70`)**: Scoped search re-rendering to `.bamsec-results-body` so typing in the filings filter box never destroys the `` or drops focus. +- **Pop-Out Tape Watchlist Quick-Add (`#71`)**: Promoted `App.handleAddToWatchlist` into `web/js/util.js` so `+` buttons work identically in both the main window and detached `web/tape.html`, and aligned cache-buster query versions (`?v=8`). +- **Hotkey Engine & Modifier Combos (`#75`)**: Added `toggle_telegram: "Ctrl+Shift+T"` to `DEFAULT_HOTKEYS` and Settings defaults, fixed `"undefined"` blur text, enabled full modifier-key recording & matching (`Ctrl`/`Alt`/`Shift`/`Meta`), and removed hardcoded `Space`/`Enter`/`Escape` bypasses so remapping works cleanly. +- **Settings Save Sync & Safe Backup Export (`#76`)**: Synchronized topbar Mute, Telegram, and Volume widgets immediately on Settings Save, Backup Import, and Factory Reset. Full Backup JSON exports now strip sensitive API keys, Telegram tokens, and TradingView cookies by default (with explicit opt-in checkbox). + +### 3. Backend Concurrency, Feeds, Caching & Cross-Platform Parity +- **Cross-Platform Audio (`#72`)**: Replaced Windows-only default sound path concatenation with OS-native `pathlib.Path` defaults (`.wav` on Windows, `.aiff` on macOS, freedesktop `.oga`/`.wav` on Linux), added `paplay --volume` scaling on Linux, and guarded `sys.stdout` fallback beeps in windowed frozen builds. +- **Thread-Safe `TVClient` (`#73`)**: Migrated `TVClient` from a shared `requests.Session` to version-synchronized thread-local sessions (`threading.local()`), eliminating concurrent `CookieJar` mutation races. +- **Alpaca Live & Paper API Support (`#74`)**: Added automatic paper (`PK...` -> `paper-api.alpaca.markets`) vs live (`AK...` -> `api.alpaca.markets`) endpoint selection with 401/403 fallback, cleared borrow caches on mode/credential updates, and respected strict `mode="alpaca"` without unintended heuristic fallback. +- **Tape Seeding, Limits & Disk I/O (`#77`)**: Silently seeds the initial tape universe on startup/session change to prevent false squeeze bursts, respects user-configured `retention_days` (>= 1) and `max_events` (>= 100), and debounces `tape_history.json` disk writes. +- **Telegram Reliability (`#78`)**: Logged non-200 / `ok=False` responses (with HTTP 429 `retry_after` backoff), re-checked `enabled`/`paused` under lock inside `_worker()` to drop queued alerts when disabled, and URL-encoded/HTML-escaped dynamic fields. +- **Bounded Caches & Priority News Prefetch (`#79`)**: Stopped permanently caching empty stories and transient BamSEC 5xx/429 responses, bounded in-memory caches via LRU `OrderedDict`, and upgraded `NewsPrefetcher` to `queue.PriorityQueue`. +- **macOS Packaging (`#80`)**: Read `VERSION` dynamically in `NewsAlerts.spec` for `CFBundleVersion`/`CFBundleShortVersionString` and updated `scripts/package_macos_dmg.sh` to package `dist/NewsAlerts.app` (and include `VERSION` + `.venv` detection in fallback mode). +- **Security & Resource Cleanup (`#81`)**: Restricted `ast_to_html()` links and `open_url()` to `http://`/`https://`, added localhost `Origin`/`Referer` CSRF protection on mutating `/api/*` `POST` routes, eliminated redundant `POST /api/config` on volume changes, and cleaned up popover listeners and cancelled file inputs. + +--- + +## ๐ŸŽฏ Closed Issues + +- Resolves #67: `fix(ui): Settings.open('tv') crashes on status pill and watchlist badge click` +- Resolves #68: `fix(api): wire open_app_dir and reset_config HTTP routes and frontend API client` +- Resolves #69: `fix(bamsec): backend opt-out check reads non-existent app.config instead of app.cfg` +- Resolves #70: `fix(bamsec): Full-View filings search input destroys itself and loses focus per keystroke` +- Resolves #71: `fix(tape): pop-out tape window watchlist '+' buttons are non-functional` +- Resolves #72: `fix(audio): default sound paths hardcode Windows backslashes and filenames on macOS/Linux` +- Resolves #73: `fix(tv): synchronize requests.Session and CookieJar access across concurrent threads` +- Resolves #74: `fix(borrow): support Alpaca live API endpoints and clear borrow cache on mode/key changes` +- Resolves #75: `fix(hotkeys): add toggle_telegram default, support modifier combos, and fix remapping` +- Resolves #76: `fix(settings): sync topbar alert controls on save and sanitize secrets in backup export` +- Resolves #77: `fix(tape): seed tape on startup to stop squeeze bursts, honor limits, debounce disk writes` +- Resolves #78: `fix(telegram): log API errors, skip queued alerts when disabled, escape chart URLs` +- Resolves #79: `fix(cache): bound in-memory caches, stop caching empty stories, use priority prefetch` +- Resolves #80: `fix(build): read VERSION dynamically in NewsAlerts.spec and fix macOS DMG packaging` +- Resolves #81: `fix(security): validate AST link schemes, guard local POST CSRF, fix volume & DOM leaks` + +--- + +## ๐Ÿงช Verification & Test Suite + +- Added dedicated regression suite in `tests/test_audit_fixes.py` covering all backend, API, security, caching, tape seeding, thread-safety, Alpaca endpoint, and packaging fixes. +- Re-verified all frontend fixes live in Chrome via Chrome DevTools Protocol (CDP) against the isolated worktree server. +- Passed full Python syntax compilation, unit test suite, and secret leak audit. diff --git a/docs/wiki/Keyboard-Shortcuts-&-Hotkeys.md b/docs/wiki/Keyboard-Shortcuts-&-Hotkeys.md index bef7945..1fbc99a 100644 --- a/docs/wiki/Keyboard-Shortcuts-&-Hotkeys.md +++ b/docs/wiki/Keyboard-Shortcuts-&-Hotkeys.md @@ -9,7 +9,7 @@ NewsAlerts is built for rapid keyboard-driven workflow. Use these hotkeys to nav | Shortcut | Action | Description | | :---: | :--- | :--- | | **`M`** | **Mute In-App Audio** | Instantly toggles local terminal audio alert chimes on or off. | -| **Configurable** | **Toggle Telegram Alerts** | Toggles mobile & desktop Telegram push notifications on or off. | +| **`Ctrl+Shift+T`** | **Toggle Telegram Alerts** | Toggles mobile & desktop Telegram push notifications on or off. | | **`T`** | **Pop-Out Tape** | Opens the detached, floating running tape window. | | **`Space`** | **Pause / Resume** | Pauses or resumes real-time tape and screener stream updates. | | **`S`** | **Open Settings** | Launches the modal settings window for feeds, audio, and strategies. | @@ -28,7 +28,7 @@ Starting in **v2.5.0**, hotkeys are fully customizable to user preference: 1. Open **Settings** (press `S` or click the gear icon in the topbar). 2. Click the **Hotkeys** tab. 3. Click any shortcut key badge. The badge will glow green with `Press key...`. -4. Press the key you wish to assign (letters, numbers, `Space`, `Enter`, `Escape`, etc.). +4. Press the key or modifier combination you wish to assign (letters, numbers, `Space`, `Enter`, `Escape`, or combos like `Ctrl+Shift+T`). 5. The shortcut is instantly bound and a confirmation toast appears. 6. Click **Save Settings** in the modal footer to persist your bindings to `config.json`. 7. Need to revert? Click **โ†บ Reset Defaults** at the top of the tab anytime. diff --git a/docs/wiki/_Footer.md b/docs/wiki/_Footer.md index d604bce..1219fa8 100644 --- a/docs/wiki/_Footer.md +++ b/docs/wiki/_Footer.md @@ -1,7 +1,7 @@ ---

- NewsAlerts v2.12.0 ยท Institutional Trading Terminal ยท Maintained by @mlgitdev ยท GitHub Repository ยท Wiki Home + NewsAlerts v2.12.1 ยท Institutional Trading Terminal ยท Maintained by @mlgitdev ยท GitHub Repository ยท Wiki Home

diff --git a/scripts/package_macos_dmg.sh b/scripts/package_macos_dmg.sh index 62444c2..a2aa2f9 100644 --- a/scripts/package_macos_dmg.sh +++ b/scripts/package_macos_dmg.sh @@ -18,17 +18,22 @@ STAGING_DIR="dmg-staging" APP_DIR="${STAGING_DIR}/NewsAlerts.app" rm -rf "$STAGING_DIR" NewsAlerts-macOS-arm64.dmg -mkdir -p "${APP_DIR}/Contents/MacOS" -mkdir -p "${APP_DIR}/Contents/Resources" +# Prefer standalone PyInstaller bundle when available; otherwise stage runtime resources +if [ -d "dist/NewsAlerts.app" ]; then + echo "[+] Packaging standalone PyInstaller bundle dist/NewsAlerts.app..." + cp -R "dist/NewsAlerts.app" "${APP_DIR}" +else + mkdir -p "${APP_DIR}/Contents/MacOS" + mkdir -p "${APP_DIR}/Contents/Resources" -# Copy assets and runtime dependencies -if [ -f "assets/icon.icns" ]; then - cp assets/icon.icns "${APP_DIR}/Contents/Resources/icon.icns" -fi -cp -r app web assets requirements.txt run_app.py "${APP_DIR}/Contents/Resources/" + # Copy assets, VERSION SSOT, and runtime dependencies + if [ -f "assets/icon.icns" ]; then + cp assets/icon.icns "${APP_DIR}/Contents/Resources/icon.icns" + fi + cp -r app web assets requirements.txt run_app.py VERSION "${APP_DIR}/Contents/Resources/" -# Generate Info.plist -cat << EOF > "${APP_DIR}/Contents/Info.plist" + # Generate Info.plist + cat << EOF > "${APP_DIR}/Contents/Info.plist" @@ -55,14 +60,18 @@ cat << EOF > "${APP_DIR}/Contents/Info.plist" EOF -# Generate executable binary launcher script -cat << 'EOF' > "${APP_DIR}/Contents/MacOS/NewsAlerts" + # Generate executable binary launcher script (prefer bundled venv if present) + cat << 'EOF' > "${APP_DIR}/Contents/MacOS/NewsAlerts" #!/usr/bin/env bash DIR="$(cd "$(dirname "$0")/../Resources" && pwd)" cd "$DIR" +if [ -x "$DIR/.venv/bin/python" ]; then + exec "$DIR/.venv/bin/python" "$DIR/run_app.py" "$@" +fi exec python3 "$DIR/run_app.py" "$@" EOF -chmod +x "${APP_DIR}/Contents/MacOS/NewsAlerts" + chmod +x "${APP_DIR}/Contents/MacOS/NewsAlerts" +fi # Symlink /Applications for drag-and-drop installer ln -s /Applications "${STAGING_DIR}/Applications" diff --git a/tests/test_audit_fixes.py b/tests/test_audit_fixes.py new file mode 100644 index 0000000..da2a4ee --- /dev/null +++ b/tests/test_audit_fixes.py @@ -0,0 +1,301 @@ +"""Regression tests covering verified audit fixes (Issues #67 - #81).""" +from __future__ import annotations + +import io +import json +import threading +import time +import unittest +from pathlib import Path +from unittest.mock import MagicMock, patch + +from app.api import Api +from app.bamsec import BamSECService +from app.borrow import ALPACA_LIVE_API, ALPACA_PAPER_API, BorrowService, alpaca_trading_base +from app.config import DEFAULT_HOTKEYS, _default_sound_path +from app.news import AlpacaNews, NewsProvider, NewsService, ast_to_html +from app.screener import NewsPrefetcher +from app.server import make_app +from app.sounds import SoundPlayer +from app.tape import TapeWorker +from app.telegram import TelegramService +from app.tv_client import TVClient + + +def _wsgi_call(app, method: str, path: str, body: bytes = b"", headers: dict | None = None): + status_line = [] + environ = { + "REQUEST_METHOD": method, + "PATH_INFO": path, + "QUERY_STRING": "", + "CONTENT_LENGTH": str(len(body)), + "CONTENT_TYPE": "application/json", + "wsgi.input": io.BytesIO(body), + "wsgi.errors": io.StringIO(), + "wsgi.version": (1, 0), + "wsgi.multithread": False, + "wsgi.multiprocess": False, + "wsgi.run_once": False, + "wsgi.url_scheme": "http", + "SERVER_NAME": "127.0.0.1", + "SERVER_PORT": "49281", + } + for k, v in (headers or {}).items(): + environ["HTTP_" + k.upper().replace("-", "_")] = v + + def start_response(status, _headers, exc_info=None): + status_line.append(status) + + chunks = app(environ, start_response) + raw = b"".join(chunks).decode("utf-8", errors="replace") + return status_line[0] if status_line else "", raw + + +class TestServerRoutesAndCsrf(unittest.TestCase): + def setUp(self): + self.web_dir = Path(__file__).resolve().parent.parent / "web" + self.api = MagicMock() + self.api.open_app_dir.return_value = {"ok": True, "path": "/tmp/na"} + self.api.reset_config.return_value = {"alerts": {"mute": False}} + self.api.get_version.return_value = {"version": "2.12.1"} + self.api.clear_tape.return_value = True + self.app = make_app(self.api, self.web_dir) + + def test_open_app_dir_and_reset_config_routes_wired(self): + st1, body1 = _wsgi_call(self.app, "POST", "/api/open_app_dir", headers={"Origin": "http://127.0.0.1:49281"}) + self.assertTrue(st1.startswith("200")) + self.assertTrue(json.loads(body1)["ok"]) + self.api.open_app_dir.assert_called_once() + + st2, body2 = _wsgi_call(self.app, "POST", "/api/reset_config", headers={"Origin": "http://localhost:49281"}) + self.assertTrue(st2.startswith("200")) + self.assertEqual(json.loads(body2)["alerts"]["mute"], False) + self.api.reset_config.assert_called_once() + + st3, body3 = _wsgi_call(self.app, "GET", "/api/version") + self.assertTrue(st3.startswith("200")) + self.assertEqual(json.loads(body3)["version"], "2.12.1") + + def test_cross_origin_post_blocked_by_csrf_guard(self): + st, _ = _wsgi_call(self.app, "POST", "/api/clear_tape", headers={"Origin": "https://evil.example"}) + self.assertTrue(st.startswith("403")) + self.api.clear_tape.assert_not_called() + + st_ref, _ = _wsgi_call(self.app, "POST", "/api/clear_tape", headers={"Referer": "https://evil.example/page"}) + self.assertTrue(st_ref.startswith("403")) + self.api.clear_tape.assert_not_called() + + +class TestBamSECOptOutRealCfg(unittest.TestCase): + def test_get_bamsec_reads_app_cfg_not_app_config(self): + class RealCfgApp: + def __init__(self, enabled: bool): + self.cfg = MagicMock() + self.cfg.get.return_value = {"news": {"bamsec_enabled": enabled}} + self.bamsec = MagicMock() + self.bamsec.get_filings.return_value = {"ticker": "AAPL", "total": 10} + + app_off = RealCfgApp(False) + res_off = Api(app_off).get_bamsec("AAPL") + self.assertTrue(res_off.get("disabled")) + app_off.bamsec.get_filings.assert_not_called() + + app_on = RealCfgApp(True) + res_on = Api(app_on).get_bamsec("AAPL") + self.assertEqual(res_on["total"], 10) + app_on.bamsec.get_filings.assert_called_once_with("AAPL", force=False) + + +class TestCrossPlatformAudioAndHotkeys(unittest.TestCase): + def test_default_hotkeys_includes_toggle_telegram(self): + self.assertIn("toggle_telegram", DEFAULT_HOTKEYS) + self.assertEqual(DEFAULT_HOTKEYS["toggle_telegram"], "Ctrl+Shift+T") + + @patch("app.config.sys.platform", "darwin") + @patch("app.config.MEDIA", "/System/Library/Sounds") + def test_macos_sound_path_has_no_windows_backslash(self): + p = _default_sound_path("Windows Ding.wav", "Ping.aiff", ()) + self.assertNotIn("\\", p) + self.assertTrue(p.endswith("Ping.aiff")) + + def test_sound_fallback_handles_none_stdout(self): + sp = SoundPlayer(volume=80) + with patch("app.sounds.sys.platform", "linux"), \ + patch("app.sounds.shutil.which", return_value=None), \ + patch("app.sounds.sys.stdout", None): + self.assertFalse(sp.play("/nonexistent.wav", force=True)) + + +class TestTVClientThreadSafety(unittest.TestCase): + @patch.object(TVClient, "check_auth", return_value={}) + def test_thread_local_sessions_isolated_and_cookie_synced(self, _mock_auth): + client = TVClient("sid_initial", "sig_initial") + main_sess = client._session() + other_sessions = [] + + def worker(): + other_sessions.append(client._session()) + + t = threading.Thread(target=worker) + t.start() + t.join() + + self.assertEqual(len(other_sessions), 1) + self.assertIsNot(main_sess, other_sessions[0]) + self.assertEqual(other_sessions[0].cookies.get("sessionid"), "sid_initial") + + # Updating cookies bumps version and refreshes thread-local session lazily + client.set_cookies("sid_updated", "sig_updated") + self.assertEqual(client._session().cookies.get("sessionid"), "sid_updated") + + +class TestBorrowAlpacaRoutingAndCache(unittest.TestCase): + def test_alpaca_trading_base_selects_paper_vs_live(self): + self.assertEqual(alpaca_trading_base("PK123456"), ALPACA_PAPER_API) + self.assertEqual(alpaca_trading_base("AK987654"), ALPACA_LIVE_API) + + def test_switching_to_heuristic_clears_alpaca_cache(self): + bs = BorrowService(key_id="", secret_key="", mode="auto") + bs._cache["AAPL"] = {"status": "easy", "label": "ETB", "source": "alpaca"} + bs.update_credentials("", "", mode="heuristic") + res = bs.get_status("AAPL", float_shares=1_000_000) + self.assertEqual(res["source"], "heuristic") + self.assertEqual(res["status"], "hard") + + +class TestTapeSeedingAndLimits(unittest.TestCase): + @patch("app.tape.S.market_state", return_value="regular") + @patch("app.tape.S.current_session", return_value="regular") + def test_first_tick_seeds_silently_without_squeeze_storm(self, _sess, _mkt): + cfg = MagicMock() + cfg.get.return_value = { + "tape": { + "universe": {"price_min": 1, "price_max": 500, "chg_min": 1, "vol_min": 20e3, "limit": 400}, + "cooldown_sec": 30, + "max_events": 250, + "retention_days": 1, + "enabled": ["Squeeze Alert - Up 10% in 5min"], + "strategies": [ + {"name": "Squeeze Alert - Up 10% in 5min", "family": "squeeze", "trigger": "squeeze", "up_pct": 10, "window_min": 5} + ], + }, + "alerts": {"mute": False, "tape_sound_enabled": False, "telegram_enabled": False, "telegram_tape_enabled": False}, + } + client = MagicMock() + client.scan.return_value = [{ + "ticker": "NASDAQ:GAPPED", + "name": "GAPPED", + "close": 11.2, + "change": 12.0, + "volume": 500_000, + "high": 11.25, + "low": 10.0, + "float_shares_outstanding": 5_000_000, + "relative_volume_10d_calc": 4.0, + "average_volume_10d_calc": 100_000, + "price_52_week_high": 20.0, + "price_52_week_low": 5.0, + "ATR": 1.0, + "change|5": 0.0, + "change|15": 0.0, + "gap": 12.0, + }] + emit = MagicMock() + tw = TapeWorker(cfg, client, MagicMock(), emit) + tw.events = [] + tw.tick() + self.assertTrue(tw._seeded) + emit.assert_not_called() + self.assertEqual(len(tw.events), 0) + + +class TestTelegramSecurityAndWorker(unittest.TestCase): + def test_send_new_symbol_alert_escapes_ticker_and_borrow(self): + tg = TelegramService(bot_token="tok", chat_id="123", enabled=True, paused=False) + tg._queue = MagicMock() + tg.send_new_symbol_alert( + "Test ", + "regular", + {"ticker": 'NASDAQ:A"B', "symbol": "A", "desc": "Co", "sp": 5.0, "sc": 10.0, "borrow": {"status": "custom", "label": "X"}}, + ) + tg._queue.put.assert_called_once() + sent = tg._queue.put.call_args[0][0] + self.assertIn("NASDAQ:A%22B", sent) + self.assertIn("<b>X</b>", sent) + + +class TestCachesPriorityAndAstSecurity(unittest.TestCase): + def test_ast_to_html_rejects_javascript_urls(self): + out_bad = ast_to_html({"type": "url", "params": {"url": "javascript:alert(1)", "linkText": "Bad"}}) + self.assertEqual(out_bad, "Bad") + self.assertNotIn("javascript:", out_bad) + + out_good = ast_to_html({"type": "url", "params": {"url": "https://example.com/a", "linkText": "Good"}}) + self.assertIn('href="https://example.com/a"', out_good) + + def test_news_service_does_not_permanently_cache_empty_story_and_bounds_cache(self): + class Flaky(NewsProvider): + def __init__(self): + self.calls = 0 + + def headlines(self, ticker): + return [{"id": ticker, "title": ticker, "published": time.time(), "provider": "tv"}] + + def story(self, story_id): + self.calls += 1 + if self.calls == 1: + return {"html": "", "source_url": ""} + return {"html": "

OK

", "source_url": "https://example.com"} + + fp = Flaky() + ns = NewsService(fp, max_cache=2, max_stories=2) + s1 = ns.story("s1") + s2 = ns.story("s1") + self.assertEqual(s1["html"], "") + self.assertEqual(s2["html"], "

OK

") + self.assertEqual(fp.calls, 2) + + ns.get("T1") + ns.get("T2") + ns.get("T3") + self.assertEqual(len(ns._cache), 2) + self.assertNotIn("T1", ns._cache) + + def test_bamsec_does_not_cache_503(self): + svc = BamSECService(ttl=120.0, max_cache=2) + with patch("app.bamsec.requests.get") as mget: + mget.return_value = MagicMock(status_code=503, url="https://www.bamsec.com/search?q=ERR") + svc.get_filings("ERR") + svc.get_filings("ERR") + self.assertEqual(mget.call_count, 2) + + def test_news_prefetcher_prioritizes_urgent_tickers(self): + np = NewsPrefetcher(MagicMock()) + np.want("A") + np.want("B") + np.want("URGENT", priority=True) + order = [np.q.get_nowait()[2], np.q.get_nowait()[2], np.q.get_nowait()[2]] + self.assertEqual(order, ["URGENT", "A", "B"]) + + def test_alpaca_news_bounds_story_cache(self): + an = AlpacaNews("k", "s", max_stories=2) + an._stories["1"] = {"html": "1"} + an._stories["2"] = {"html": "2"} + an._stories["3"] = {"html": "3"} + while len(an._stories) > an._max_stories: + an._stories.popitem(last=False) + self.assertEqual(list(an._stories.keys()), ["2", "3"]) + + +class TestPackagingVersionSync(unittest.TestCase): + def test_spec_reads_version_dynamically_and_dmg_copies_version(self): + root = Path(__file__).resolve().parent.parent + spec_txt = (root / "NewsAlerts.spec").read_text(encoding="utf-8") + dmg_txt = (root / "scripts" / "package_macos_dmg.sh").read_text(encoding="utf-8") + self.assertNotIn("'CFBundleVersion': '2.9.0'", spec_txt) + self.assertIn("'CFBundleVersion': app_version", spec_txt) + self.assertIn("VERSION", dmg_txt) + + +if __name__ == "__main__": + unittest.main() diff --git a/web/index.html b/web/index.html index e0eac9f..472c767 100644 --- a/web/index.html +++ b/web/index.html @@ -6,7 +6,7 @@ - +
@@ -222,11 +222,11 @@

Settings & Data Sources

- - - - - - + + + + + + diff --git a/web/js/app.js b/web/js/app.js index d50332f..560a994 100644 --- a/web/js/app.js +++ b/web/js/app.js @@ -42,7 +42,7 @@ } const tvBadge = U.$("#tv-status-badge"); if (tvBadge) { - tvBadge.onclick = () => Settings.open("tv"); + tvBadge.onclick = () => Settings.open("general"); } setTapePopped(state.tape_popped); @@ -185,10 +185,11 @@ clearTimeout(_volDebounceTimer); if (save) { + App._lastSave = Date.now(); App.api().set_volume(vol).catch(() => {}); - App.saveConfig(true); } else { _volDebounceTimer = setTimeout(() => { + App._lastSave = Date.now(); App.api().set_volume(vol).catch(() => {}); }, 40); } @@ -279,6 +280,7 @@ App.updateMuteBtn = updateMuteBtn; App.updateTelegramBtn = updateTelegramBtn; + App.renderVolume = renderVolume; function onConfig(c) { App.config = c; @@ -504,11 +506,41 @@ }); } + function parseHotkeySpec(spec) { + const raw = String(spec || "").trim(); + if (!raw) return null; + const parts = raw.split("+").map((p) => p.trim()).filter(Boolean); + if (!parts.length) return null; + let ctrl = false, alt = false, shift = false, meta = false; + let key = ""; + for (const part of parts) { + const lo = part.toLowerCase(); + if (lo === "ctrl" || lo === "control") ctrl = true; + else if (lo === "alt" || lo === "option") alt = true; + else if (lo === "shift") shift = true; + else if (lo === "meta" || lo === "cmd" || lo === "command") meta = true; + else key = part === " " ? "Space" : part; + } + if (!key) return null; + return { ctrl, alt, shift, meta, key: key.toLowerCase() }; + } + + function matchesHotkeyEvent(e, spec) { + const parsed = parseHotkeySpec(spec); + if (!parsed) return false; + const normKey = (e.key === " " ? "Space" : e.key).toLowerCase(); + if (normKey !== parsed.key) return false; + if (!!e.ctrlKey !== parsed.ctrl) return false; + if (!!e.altKey !== parsed.alt) return false; + if (!!e.metaKey !== parsed.meta) return false; + if (!!e.shiftKey !== parsed.shift) return false; + return true; + } + + App.matchesHotkeyEvent = matchesHotkeyEvent; + function initHotkeys() { document.addEventListener("keydown", (e) => { - // Do not intercept if modifier keys like Ctrl / Alt / Meta are held - if (e.ctrlKey || e.altKey || e.metaKey) return; - const tag = document.activeElement ? document.activeElement.tagName : ""; const isEditable = /INPUT|SELECT|TEXTAREA/.test(tag) || (document.activeElement && document.activeElement.isContentEditable); @@ -516,13 +548,11 @@ const matchKey = (action, defaultKey) => { const configured = (hk[action] !== undefined && hk[action] !== "") ? hk[action] : defaultKey; if (!configured) return false; - const normKey = e.key === " " ? "Space" : e.key; - const normCfg = configured === " " ? "Space" : configured; - return normKey.toLowerCase() === normCfg.toLowerCase(); + return matchesHotkeyEvent(e, configured); }; - // ESCAPE key / configured close_modal: always allow Esc to close modal/drawer/story or unfocus active input - if (matchKey("close_modal", "Escape") || e.key === "Escape") { + // ESCAPE key / configured close_modal: always allow close_modal to close modal/drawer/story or unfocus active input + if (matchKey("close_modal", "Escape")) { if (isEditable) { document.activeElement.blur(); e.preventDefault(); @@ -577,7 +607,7 @@ } // Telegram Alerts Toggle - if (matchKey("toggle_telegram", "")) { + if (matchKey("toggle_telegram", "Ctrl+Shift+T")) { e.preventDefault(); toggleTelegram(); const isEnabled = App.config?.alerts?.telegram_enabled !== false; @@ -600,7 +630,7 @@ } // Space / configured pause_tape: Pause / Resume tape stream - if (matchKey("pause_tape", "Space") || e.key === " ") { + if (matchKey("pause_tape", "Space")) { e.preventDefault(); Tape.setPaused(!Tape.paused); U.toast( @@ -636,7 +666,7 @@ } // Focus / expand first catalyst story - if (matchKey("focus_story", "Enter") || e.key === "Enter") { + if (matchKey("focus_story", "Enter")) { if (window.News && News.openFirstStory && News.openFirstStory()) { e.preventDefault(); } @@ -690,7 +720,7 @@ badge.textContent = "Local"; badge.className = "watchlist-status-badge local"; badge.title = "TradingView session not active โ€” using local watchlist (Click for Settings)"; - badge.onclick = () => Settings.open("tv"); + badge.onclick = () => Settings.open("general"); } } } catch (e) { diff --git a/web/js/news.js b/web/js/news.js index 1124fdb..1403f6d 100644 --- a/web/js/news.js +++ b/web/js/news.js @@ -579,10 +579,6 @@ placeholder: "Filter filings (e.g. shelf, dividend)...", value: News.bamsecSearchTerm || "" }); - searchInput.oninput = () => { - News.bamsecSearchTerm = searchInput.value.toLowerCase().trim(); - News.renderBamsecFullView(); - }; const extBtn = U.el("button", { class: "btn-bamsec-link", @@ -602,7 +598,6 @@ const ownCount = all.filter((f) => f.group === "ownership").length; const finCount = all.filter((f) => f.group === "financial").length; - const currentFilter = News.bamsecFilter || "all"; const pillFilters = [ ["all", `All (${total})`], ["news", `News 8-K/6-K (${newsCount})`], @@ -611,41 +606,63 @@ ["financial", `Financials (${finCount})`], ]; - const pillsWrap = U.el("div", { class: "bamsec-pills" }, - pillFilters.map(([fVal, fLabel]) => { - const p = U.el("button", { + const pillsWrap = U.el("div", { class: "bamsec-pills" }); + const resultsWrap = U.el("div", { class: "bamsec-results-body" }); + + const renderResults = () => { + const currentFilter = News.bamsecFilter || "all"; + pillsWrap.replaceChildren( + ...pillFilters.map(([fVal, fLabel]) => U.el("button", { class: "bamsec-pill" + (currentFilter === fVal ? " active" : ""), onclick: () => { News.bamsecFilter = fVal; - News.renderBamsecFullView(); + renderResults(); } - }, fLabel); - return p; - }) - ); - - const term = News.bamsecSearchTerm || ""; - let matched = all; - if (currentFilter !== "all") { - matched = matched.filter((f) => f.group === currentFilter); - } - if (term) { - matched = matched.filter((f) => ( - f.title.toLowerCase().includes(term) || - f.form.toLowerCase().includes(term) || - (f.category && f.category.toLowerCase().includes(term)) - )); - } + }, fLabel)) + ); - const sections = []; - const cats = data.categories || {}; - const catNames = Object.keys(cats); + const term = (News.bamsecSearchTerm || "").toLowerCase().trim(); + let matched = all; + if (currentFilter !== "all") { + matched = matched.filter((f) => f.group === currentFilter); + } + if (term) { + matched = matched.filter((f) => ( + f.title.toLowerCase().includes(term) || + f.form.toLowerCase().includes(term) || + (f.category && f.category.toLowerCase().includes(term)) + )); + } - if (catNames.length && currentFilter === "all" && !term) { - for (const cName of catNames) { - const cItems = cats[cName] || []; - if (!cItems.length) continue; - const cRows = cItems.map((f) => U.el("div", { + const sections = []; + const cats = data.categories || {}; + const catNames = Object.keys(cats); + + if (catNames.length && currentFilter === "all" && !term) { + for (const cName of catNames) { + const cItems = cats[cName] || []; + if (!cItems.length) continue; + const cRows = cItems.map((f) => U.el("div", { + class: "bamsec-filing-row", + title: `[${f.form}] ${f.title} (${f.date}) โ€” Click to view on BamSEC`, + onclick: () => App.api().open_url(f.url) + }, + U.el("span", { class: `tag-form ${f.group}` }, f.form), + U.el("span", { class: "bamsec-filing-title" }, f.title), + U.el("span", { class: "bamsec-filing-date" }, f.date), + U.el("span", { class: "bamsec-filing-link" }, "โ†—") + )); + + sections.push(U.el("div", { class: "bamsec-cat-section" }, + U.el("div", { class: "bamsec-cat-head" }, + U.el("span", {}, cName), + U.el("span", { class: "muted num" }, `${cItems.length}`) + ), + U.el("div", {}, ...cRows) + )); + } + } else { + const rows = matched.map((f) => U.el("div", { class: "bamsec-filing-row", title: `[${f.form}] ${f.title} (${f.date}) โ€” Click to view on BamSEC`, onclick: () => App.api().open_url(f.url) @@ -657,31 +674,20 @@ )); sections.push(U.el("div", { class: "bamsec-cat-section" }, - U.el("div", { class: "bamsec-cat-head" }, - U.el("span", {}, cName), - U.el("span", { class: "muted num" }, `${cItems.length}`) - ), - U.el("div", {}, ...cRows) + rows.length ? rows : U.el("div", { class: "muted", style: "padding:12px 4px;font-size:12px" }, "No matching filings found.") )); } - } else { - const rows = matched.map((f) => U.el("div", { - class: "bamsec-filing-row", - title: `[${f.form}] ${f.title} (${f.date}) โ€” Click to view on BamSEC`, - onclick: () => App.api().open_url(f.url) - }, - U.el("span", { class: `tag-form ${f.group}` }, f.form), - U.el("span", { class: "bamsec-filing-title" }, f.title), - U.el("span", { class: "bamsec-filing-date" }, f.date), - U.el("span", { class: "bamsec-filing-link" }, "โ†—") - )); - sections.push(U.el("div", { class: "bamsec-cat-section" }, - rows.length ? rows : U.el("div", { class: "muted", style: "padding:12px 4px;font-size:12px" }, "No matching filings found.") - )); - } + resultsWrap.replaceChildren(...sections); + }; + + searchInput.oninput = () => { + News.bamsecSearchTerm = searchInput.value; + renderResults(); + }; - News.fullView.replaceChildren(fullHead, pillsWrap, ...sections); + renderResults(); + News.fullView.replaceChildren(fullHead, pillsWrap, resultsWrap); }, toggleDrawer(forceOpen) { diff --git a/web/js/settings.js b/web/js/settings.js index 914f014..b1c9a75 100644 --- a/web/js/settings.js +++ b/web/js/settings.js @@ -20,19 +20,28 @@ const body = U.$("#settings-body"); const tabs = U.$$("#settings-tabs button"); const show = (name) => { - tabs.forEach((b) => b.classList.toggle("active", b.dataset.tab === name)); - body.replaceChildren(Settings["tab_" + name](c)); + const resolved = typeof Settings["tab_" + name] === "function" ? name : "general"; + tabs.forEach((b) => b.classList.toggle("active", b.dataset.tab === resolved)); + body.replaceChildren(Settings["tab_" + resolved](c)); }; tabs.forEach((b) => (b.onclick = () => show(b.dataset.tab))); show(initialTab || "general"); bg.classList.add("show"); - U.$("#settings-save").onclick = () => { - App.config = c; App.saveConfig(true); Settings.applyUi(); bg.classList.remove("show"); + const syncAllUi = () => { + Settings.applyUi(); + if (App.updateMuteBtn) App.updateMuteBtn(); + if (App.updateTelegramBtn) App.updateTelegramBtn(); + if (App.renderVolume && App.config?.alerts?.volume !== undefined) App.renderVolume(App.config.alerts.volume); if (App.updateFilterBannedButton) App.updateFilterBannedButton(); Screener.renderBar(); Screener.renderTable(); Tape.renderAll(); News.syncTools(); if (window.News && News.renderHead) News.renderHead(); if (window.News && News.onConfigChanged) News.onConfigChanged(); }; + Settings._syncAllUi = syncAllUi; + U.$("#settings-save").onclick = () => { + App.config = c; App.saveConfig(true); bg.classList.remove("show"); + syncAllUi(); + }; U.$("#settings-cancel").onclick = () => Settings.close(); U.$("#settings-close").onclick = () => Settings.close(); }, @@ -499,6 +508,7 @@ } const DEFAULTS = { mute: "m", + toggle_telegram: "Ctrl+Shift+T", popout_tape: "t", pause_tape: "Space", settings: "s", @@ -593,7 +603,7 @@ keyBtn.onblur = () => { keyBtn.classList.remove("recording"); - keyBtn.value = c.hotkeys[item.key] || DEFAULTS[item.key]; + keyBtn.value = c.hotkeys[item.key] || DEFAULTS[item.key] || ""; }; keyBtn.onkeydown = (e) => { @@ -602,9 +612,17 @@ if (["Control", "Alt", "Shift", "Meta"].includes(e.key)) return; - let captured = e.key; - if (captured === " ") captured = "Space"; - else if (captured.length === 1) captured = captured.toUpperCase(); + const mods = []; + if (e.ctrlKey) mods.push("Ctrl"); + if (e.altKey) mods.push("Alt"); + if (e.shiftKey) mods.push("Shift"); + if (e.metaKey) mods.push("Meta"); + + let keyPart = e.key; + if (keyPart === " ") keyPart = "Space"; + else if (keyPart.length === 1) keyPart = keyPart.toUpperCase(); + + const captured = mods.length ? `${mods.join("+")}+${keyPart}` : keyPart; c.hotkeys[item.key] = captured; keyBtn.value = captured; @@ -678,27 +696,53 @@ ); // Card 1: Full Configuration Backup + const includeSecretsCb = U.el("input", { type: "checkbox", id: "backup-include-secrets", style: "cursor:pointer;" }); + const includeSecretsLbl = U.el("label", { + for: "backup-include-secrets", + style: "display:flex;align-items:center;gap:6px;font-size:11.5px;color:var(--muted);margin-bottom:8px;cursor:pointer;" + }, includeSecretsCb, "Include API keys, Telegram tokens & TV cookies (sensitive)"); + + const sanitizeBackupConfig = (rawCfg) => { + const clean = JSON.parse(JSON.stringify(rawCfg)); + if (clean.tv) { + clean.tv.sessionid = ""; + clean.tv.sessionid_sign = ""; + } + if (clean.borrow) { + clean.borrow.alpaca_key_id = ""; + clean.borrow.alpaca_secret_key = ""; + } + if (clean.alerts) { + clean.alerts.telegram_bot_token = ""; + clean.alerts.telegram_chat_id = ""; + } + return clean; + }; + const fullCard = U.el("div", { class: "backup-card" }, U.el("div", { class: "backup-card-head" }, U.el("div", { class: "backup-card-title" }, "๐Ÿ’พ Full Application Backup"), U.el("div", { class: "backup-card-badge" }, "Complete State") ), U.el("div", { class: "backup-card-desc" }, - "Exports all screeners, sound alert configs, tape universe thresholds, hotkeys, and strategies into a single restore file."), + "Exports all screeners, sound alert configs, tape universe thresholds, hotkeys, and strategies into a single restore file (credentials stripped by default)."), + includeSecretsLbl, U.el("div", { class: "backup-card-actions" }, U.el("button", { class: "btn sm primary", onclick: () => { const dt = new Date().toISOString().slice(0, 10); + const exportCfg = includeSecretsCb.checked ? c : sanitizeBackupConfig(c); const payload = { app: "NewsAlerts", type: "full_backup", - version: App.version || "2.7.0", + version: App.version || "2.12.1", + credentials_included: !!includeSecretsCb.checked, exported_at: new Date().toISOString(), - config: c, + config: exportCfg, }; Settings.exportJson(`newsalerts_backup_${dt}.json`, payload); - U.toast("alert", "โœ“ Backup Exported", `Saved full configuration backup as newsalerts_backup_${dt}.json`); + U.toast("alert", "โœ“ Backup Exported", `Saved configuration backup as newsalerts_backup_${dt}.json`); } }, "๐Ÿ’พ Export Full Backup (.json)"), U.el("button", { @@ -718,11 +762,7 @@ Object.assign(c, cfg); App.config = c; App.saveConfig(true); - Settings.applyUi(); - Screener.renderBar(); - Screener.renderTable(); - Tape.renderAll(); - News.syncTools(); + if (Settings._syncAllUi) Settings._syncAllUi(); U.toast("alert", "โœ“ Backup Restored", `Successfully imported configuration from ${filename}.`); // Re-render current tab const body = U.$("#settings-body"); @@ -790,11 +830,7 @@ if (fresh) { Object.assign(c, fresh); App.config = fresh; - Settings.applyUi(); - Screener.renderBar(); - Screener.renderTable(); - Tape.renderAll(); - News.syncTools(); + if (Settings._syncAllUi) Settings._syncAllUi(); U.toast("alert", "โ†บ Factory Reset", "Terminal configuration successfully restored to factory defaults."); const body = U.$("#settings-body"); if (body) body.replaceChildren(Settings.tab_backup(c)); @@ -879,10 +915,14 @@ fileInput.accept = ".json,application/json"; fileInput.style.display = "none"; document.body.appendChild(fileInput); + const cleanup = () => { + if (fileInput.parentNode) fileInput.parentNode.removeChild(fileInput); + }; + fileInput.addEventListener("cancel", cleanup); fileInput.onchange = (e) => { const file = e.target.files && e.target.files[0]; if (!file) { - document.body.removeChild(fileInput); + cleanup(); return; } const reader = new FileReader(); @@ -893,12 +933,12 @@ } catch (err) { callback(err, null, file.name); } finally { - document.body.removeChild(fileInput); + cleanup(); } }; reader.onerror = (err) => { callback(err, null, file.name); - document.body.removeChild(fileInput); + cleanup(); }; reader.readAsText(file); }; diff --git a/web/js/tape.js b/web/js/tape.js index b2d256f..11591c8 100644 --- a/web/js/tape.js +++ b/web/js/tape.js @@ -73,12 +73,17 @@ if (opts.popout) { document.addEventListener("keydown", (e) => { - if (e.ctrlKey || e.altKey || e.metaKey) return; if (/INPUT|SELECT|TEXTAREA/.test(document.activeElement?.tagName) || document.activeElement?.isContentEditable) return; const hk = App.config?.hotkeys || {}; - const pauseKey = (hk.pause_tape || "Space").toLowerCase(); - const normKey = (e.key === " " ? "Space" : e.key).toLowerCase(); - if (normKey === pauseKey || e.key === " ") { + const pauseSpec = (hk.pause_tape !== undefined && hk.pause_tape !== "") ? hk.pause_tape : "Space"; + const parts = String(pauseSpec).split("+").map((p) => p.trim().toLowerCase()).filter(Boolean); + const wantCtrl = parts.includes("ctrl") || parts.includes("control"); + const wantAlt = parts.includes("alt") || parts.includes("option"); + const wantShift = parts.includes("shift"); + const wantMeta = parts.includes("meta") || parts.includes("cmd") || parts.includes("command"); + const wantKey = parts.filter((p) => !["ctrl", "control", "alt", "option", "shift", "meta", "cmd", "command"].includes(p)).pop(); + const normKey = (e.key === " " ? "space" : e.key.toLowerCase()); + if (wantKey && normKey === wantKey && !!e.ctrlKey === wantCtrl && !!e.altKey === wantAlt && !!e.shiftKey === wantShift && !!e.metaKey === wantMeta) { e.preventDefault(); Tape.setPaused(!Tape.paused); } diff --git a/web/js/util.js b/web/js/util.js index c482c4e..f9e40dd 100644 --- a/web/js/util.js +++ b/web/js/util.js @@ -92,6 +92,8 @@ headers: { "Content-Type": "application/json" }, body: JSON.stringify({ enabled }), }).then((r) => r.json()), + open_app_dir: () => fetch("/api/open_app_dir", { method: "POST" }).then((r) => r.json()), + reset_config: () => fetch("/api/reset_config", { method: "POST" }).then((r) => r.json()), }; @@ -122,9 +124,71 @@ }; if (immediate) go(); else App._saveT = setTimeout(go, 250); }, + async handleAddToWatchlist(btn, symbol) { + if (!symbol || !btn) return; + if (btn.classList.contains("adding") || btn.classList.contains("flicker-green") || btn.classList.contains("flicker-red")) { + return; + } + const select = U.$("#watchlist-select"); + const activeId = select ? select.value : (App.config?.watchlist?.active_id || ""); + const origText = btn.textContent; + btn.classList.add("adding"); + + try { + const res = await App.api().add_to_watchlist(activeId, symbol); + btn.classList.remove("adding"); + + if (res && res.ok) { + btn.classList.add("flicker-green"); + btn.textContent = "โœ“"; + if (select && select.options[select.selectedIndex] && !res.already_exists) { + const opt = select.options[select.selectedIndex]; + const m = opt.textContent.match(/^(.*?)\s*\((\d+)\)$/); + if (m) { + opt.textContent = `${m[1]} (${parseInt(m[2], 10) + 1})`; + } + } + setTimeout(() => { + btn.classList.remove("flicker-green"); + btn.textContent = origText; + }, 3000); + } else { + btn.classList.add("flicker-red"); + btn.textContent = "โœ•"; + setTimeout(() => { + btn.classList.remove("flicker-red"); + btn.textContent = origText; + }, 3000); + U.toast( + "err", + "โš ๏ธ Failed to Add to Watchlist", + res?.message || res?.error || "Could not add symbol to TradingView watchlist. Please check session cookies.", + null, + 5000 + ); + } + } catch (err) { + btn.classList.remove("adding"); + btn.classList.add("flicker-red"); + btn.textContent = "โœ•"; + setTimeout(() => { + btn.classList.remove("flicker-red"); + btn.textContent = origText; + }, 3000); + U.toast( + "err", + "โš ๏ธ Failed to Add to Watchlist", + String(err.message || err), + null, + 5000 + ); + } + }, }; window.App = App; + const _popCleanups = []; + const U = { $: (s, el = document) => el.querySelector(s), $$: (s, el = document) => Array.from(el.querySelectorAll(s)), @@ -219,7 +283,13 @@ } else box.textContent = (symbol || "?")[0]; return box; }, - closePops() { U.$$(".pop").forEach((p) => p.remove()); }, + closePops() { + while (_popCleanups.length) { + const fn = _popCleanups.pop(); + try { fn(); } catch (e) {} + } + U.$$(".pop").forEach((p) => p.remove()); + }, pop(anchor, content, opts = {}) { U.closePops(); const p = U.el("div", { class: "pop" }); @@ -231,11 +301,22 @@ if (y + p.offsetHeight > innerHeight - 8) y = Math.max(8, r.top - p.offsetHeight - 6); x = Math.min(Math.max(8, x), innerWidth - p.offsetWidth - 8); p.style.left = x + "px"; p.style.top = y + "px"; - setTimeout(() => { - const close = (e) => { - if (!p.contains(e.target)) { p.remove(); document.removeEventListener("mousedown", close); opts.onClose && opts.onClose(); } - }; - document.addEventListener("mousedown", close); + let closed = false; + const close = (e) => { + if (!closed && !p.contains(e.target)) { + closed = true; + p.remove(); + document.removeEventListener("mousedown", close); + opts.onClose && opts.onClose(); + } + }; + const timer = setTimeout(() => { + if (!closed) document.addEventListener("mousedown", close); + }, 0); + _popCleanups.push(() => { + closed = true; + clearTimeout(timer); + document.removeEventListener("mousedown", close); }); return p; }, diff --git a/web/tape.html b/web/tape.html index 6220fa1..fafb1cc 100644 --- a/web/tape.html +++ b/web/tape.html @@ -6,7 +6,7 @@ - +
@@ -17,8 +17,8 @@
- - + +