File size: 8,086 Bytes
c8c30b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
"""
Keyword Rank Tracker — checks where our domains appear in DuckDuckGo
search results for a curated keyword list, records daily positions in
GCS (rank_tracker.json), sends a Telegram summary with change alerts,
and exposes the latest table to /analytics via latest_positions().

No paid APIs: DuckDuckGo's HTML endpoint tolerates a handful of
well-paced queries from datacenter IPs (Google blocks those hard).
DDG results are powered by Bing and correlate loosely with Google —
good enough to watch brand-term rankings and catch SEO regressions.
"""
import json
import os
import re
import time
import urllib.parse
import urllib.request
import urllib.error
from datetime import datetime, timezone, timedelta

from modules.storage import load_json, save_json
from modules.telegram_alert import send_telegram_message

HISTORY_FILE = "rank_tracker.json"
MAX_HISTORY = 90
FETCH_TIMEOUT = 30
# DuckDuckGo trips its "anomaly" bot-check after a handful of rapid
# queries — pace hard (one query every ~15s keeps a daily 10-keyword run
# under the anomaly threshold).
PAUSE_SECONDS_DDG = 15.0
# Brave Search API free tier allows 1 query/sec.
PAUSE_SECONDS_BRAVE = 1.5

# (keyword, [target domains]) — brand and discovery terms for every
# site in the family. Positions are 1-based; None = not in top results.
KEYWORDS = [
    ("flask factory", ["flaskfactory.ai"]),
    ("flaskfactory", ["flaskfactory.ai"]),
    ("flask development service", ["flaskfactory.ai"]),
    ("zojax", ["zojax.com", "www.zojax.com"]),
    ("django zojax", ["django.zojax.com"]),
    ("wordpress zojax", ["wordpress.zojax.com"]),
    ("blind monkeys", ["blindmonkeys.org"]),
    ("blind monkeys crypto", ["blindmonkeys.org"]),
    ("crypto grid scanner", ["blindmonkeys.org"]),
    ("gyumri coffee", ["gyumri.coffee"]),
]

_RESULT_A = re.compile(
    r'<a[^>]+class="result__a"[^>]*href="([^"]+)"|'
    r'<a[^>]+href="([^"]+)"[^>]*class="result__a"')


def _now_iso():
    return datetime.now(timezone.utc).isoformat(timespec="seconds")


def _fetch_page(form):
    """POST one query page to DuckDuckGo's HTML endpoint, return URLs in order."""
    data = urllib.parse.urlencode(form).encode("utf-8")
    req = urllib.request.Request(
        "https://html.duckduckgo.com/html/",
        data=data,
        headers={
            "User-Agent": ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
                           "AppleWebKit/537.36 (KHTML, like Gecko) "
                           "Chrome/131.0.0.0 Safari/537.36"),
            "Content-Type": "application/x-www-form-urlencoded",
            "Accept": "text/html",
        })
    with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT) as resp:
        html = resp.read().decode("utf-8", "replace")
    urls = []
    for m in _RESULT_A.finditer(html):
        href = m.group(1) or m.group(2) or ""
        if "uddg=" in href:
            qs = urllib.parse.parse_qs(urllib.parse.urlparse(href).query)
            url = urllib.parse.unquote(qs.get("uddg", [""])[0])
        elif href.startswith("http"):
            url = href
        else:
            continue
        urls.append(url)
    return urls


def _fetch_result_urls(query, pages=1):
    """Fetch up to `pages` result pages (~10 results each) in rank order."""
    ordered, seen = [], set()
    for i in range(pages):
        try:
            page = _fetch_page({"q": query, "s": i * 30, "dc": i * 30})
        except Exception:
            break
        fresh = 0
        for u in page:
            if u not in seen:
                seen.add(u)
                ordered.append(u)
                fresh += 1
        if not fresh:
            break
        time.sleep(1.0)
    return ordered


def _brave_search(query, count=20):
    """Brave Search API (free tier: 2,000 queries/month). Returns result
    URLs in rank order, or None if no BRAVE_API_KEY is configured."""
    key = os.environ.get("BRAVE_API_KEY", "").strip()
    if not key:
        return None
    req = urllib.request.Request(
        "https://api.search.brave.com/res/v1/web/search?"
        + urllib.parse.urlencode({"q": query, "count": count}),
        headers={"X-Subscription-Token": key, "Accept": "application/json"})
    with urllib.request.urlopen(req, timeout=FETCH_TIMEOUT) as resp:
        data = json.loads(resp.read().decode("utf-8"))
    urls = []
    for w in (data.get("web") or {}).get("results") or []:
        u = w.get("url") or ""
        if u.startswith("http"):
            urls.append(u)
    return urls


def _find_position(urls, domain):
    """1-based position of the first result hosted on domain (or subdomain)."""
    dom = domain.lower()
    for i, u in enumerate(urls, 1):
        try:
            host = urllib.parse.urlparse(u).netloc.lower().split(":")[0]
        except Exception:
            continue
        if host == dom or host.endswith("." + dom):
            return i
    return None


def latest_positions():
    """Latest snapshot for the analytics API."""
    history = load_json(HISTORY_FILE, default=[])
    if not history:
        return {"checked_at": None, "keywords": []}
    last = history[-1]
    prev = history[-2] if len(history) >= 2 else None
    out = []
    for kw, domains in KEYWORDS:
        cur = (last.get("results") or {}).get(kw) or {}
        pre = ((prev or {}).get("results") or {}).get(kw) or {}
        rows = []
        for dom in domains:
            pos = cur.get(dom)
            old = pre.get(dom)
            change = None
            if pos is not None and old is not None:
                change = old - pos  # positive = moved up
            rows.append({"domain": dom, "position": pos, "change": change})
        out.append({"keyword": kw, "rows": rows})
    return {"checked_at": last.get("checked_at"), "keywords": out,
            "error": last.get("error")}


def _summary_lines(results, prev_results):
    """Telegram body: one line per keyword, with change markers."""
    lines = []
    for kw, domains in KEYWORDS:
        cur = results.get(kw) or {}
        pre = (prev_results or {}).get(kw) or {}
        parts = []
        for dom in domains:
            pos = cur.get(dom)
            old = pre.get(dom)
            mark = ""
            if pos is not None and old is not None:
                if pos < old:
                    mark = " ▲%d" % (old - pos)
                elif pos > old:
                    mark = " ▼%d" % (pos - old)
            parts.append("%s #%s%s" % (dom, pos if pos is not None else "—", mark))
        lines.append("%s: %s" % (kw, " · ".join(parts)))
    return lines


def run_rank_check():
    """Fetch current rankings, store them, alert Telegram. Returns summary."""
    history = load_json(HISTORY_FILE, default=[])
    prev_results = (history[-1] or {}).get("results") if history else None
    engine = "brave" if os.environ.get("BRAVE_API_KEY", "").strip() else "duckduckgo"
    pause = PAUSE_SECONDS_BRAVE if engine == "brave" else PAUSE_SECONDS_DDG
    results, errors = {}, []
    for kw, domains in KEYWORDS:
        try:
            if engine == "brave":
                urls = _brave_search(kw) or []
            else:
                urls = _fetch_result_urls(kw)
            results[kw] = {d: _find_position(urls, d) for d in domains}
            if not urls:
                errors.append(kw)
        except Exception:
            errors.append(kw)
            results[kw] = {}
        time.sleep(pause)

    entry = {"checked_at": _now_iso(), "engine": engine,
             "results": results, "error": ", ".join(errors) if errors else None}
    history.append(entry)
    save_json(HISTORY_FILE, history[-MAX_HISTORY:])

    body = _summary_lines(results, prev_results)
    header = "📈 Rank Tracker (DuckDuckGo)"
    if errors:
        body.append("(no results returned for: %s)" % ", ".join(errors))
    send_telegram_message("\n".join([header] + body))

    ranked = sum(1 for kw in KEYWORDS for d in results.get(kw, {}).values()
                 if d is not None)
    return {"ok": not errors, "keywords": len(KEYWORDS),
            "ranked": ranked, "errors": errors}