File size: 9,132 Bytes
94b42f2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
import sqlite3
import logging
import os
import json
import re

logger = logging.getLogger(__name__)
DB_PATH = "data/bot_data.db"
SEEN_NEWS_FILE = "data/seen_news.json"
_seen_news_cache = {}

def load_seen_news():
    global _seen_news_cache
    try:
        from content.remote_storage import pull_from_gist
        pulled = pull_from_gist("seen_news.json")
        if pulled and isinstance(pulled, dict):
            _seen_news_cache = pulled
            logger.info(f"Loaded {len(_seen_news_cache)} seen news items from Gist.")
            # Sync to SQLite
            conn = sqlite3.connect(DB_PATH)
            cursor = conn.cursor()
            for t, l in _seen_news_cache.items():
                cursor.execute("INSERT OR IGNORE INTO seen_news (title, link) VALUES (?, ?)", (t, l))
            conn.commit()
            conn.close()
            return
    except Exception as e:
        logger.error(f"Error loading seen news from Gist: {e}")

    # Fallback to local
    if os.path.exists(SEEN_NEWS_FILE):
        try:
            with open(SEEN_NEWS_FILE, "r") as f:
                _seen_news_cache = json.load(f)
        except Exception as e:
            logger.error(f"Local seen news load error: {e}")
            _seen_news_cache = {}

# Ensure database is initialised before calling load_seen_news
def init_db():
    os.makedirs("data", exist_ok=True)
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    
    # Leaderboard table
    # We track scores per user per channel to keep it fair
    cursor.execute("""

        CREATE TABLE IF NOT EXISTS leaderboard (

            user_id INTEGER,

            channel_id TEXT,

            username TEXT,

            full_name TEXT,

            score INTEGER DEFAULT 0,

            streak INTEGER DEFAULT 0,

            last_streak_date TEXT,

            last_active TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

            PRIMARY KEY (user_id, channel_id)

        )

    """)
    
    # News tracker table to avoid duplicates
    # Uses title as unique identifier for permanent deduplication
    cursor.execute("""

        CREATE TABLE IF NOT EXISTS seen_news (

            title TEXT PRIMARY KEY,

            link TEXT UNIQUE,

            fetch_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP

        )

    """)

    # Poll tracker to know which option is correct for a given poll_id
    cursor.execute("""

        CREATE TABLE IF NOT EXISTS poll_tracker (

            poll_id TEXT PRIMARY KEY,

            channel_id TEXT,

            message_id INTEGER,

            correct_index INTEGER,

            explanation TEXT

        )

    """)
    
    conn.commit()
    conn.close()
    
    # Now load the Gist-synced cache after DB init
    load_seen_news()

def update_score(user_id, channel_id, username, full_name, points=1):
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("""

            INSERT INTO leaderboard (user_id, channel_id, username, full_name, score)

            VALUES (?, ?, ?, ?, ?)

            ON CONFLICT(user_id, channel_id) DO UPDATE SET

                score = score + ?,

                username = ?,

                full_name = ?,

                last_active = CURRENT_TIMESTAMP

        """, (user_id, channel_id, username, full_name, points, points, username, full_name))
        conn.commit()
        conn.close()
    except Exception as e:
        logger.error(f"DB Error (update_score): {e}")

def get_top_students(channel_id, limit=10):
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("""

            SELECT username, full_name, score FROM leaderboard

            WHERE channel_id = ?

            ORDER BY score DESC, last_active DESC

            LIMIT ?

        """, (channel_id, limit))
        rows = cursor.fetchall()
        conn.close()
        return rows
    except Exception as e:
        logger.error(f"DB Error (get_top_students): {e}")
        return []

def clear_weekly_scores():
    """Reset scores for the new week (run by scheduler)"""
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("UPDATE leaderboard SET score = 0")
        conn.commit()
        conn.close()
    except Exception as e:
        logger.error(f"DB Error (clear_scores): {e}")

def is_news_seen(title):
    """Check if a news item with this exact title has been posted before (case & space insensitive)."""
    cleaned_title = re.sub(r'\s+', ' ', title).strip().lower()
    
    # 1. Check local cache memory
    for cached_title in _seen_news_cache:
        if re.sub(r'\s+', ' ', cached_title).strip().lower() == cleaned_title:
            return True
            
    # 2. Check local database
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("SELECT title FROM seen_news")
        rows = cursor.fetchall()
        conn.close()
        for (t,) in rows:
            if re.sub(r'\s+', ' ', t).strip().lower() == cleaned_title:
                return True
    except Exception as e:
        logger.error(f"Error checking seen news in SQLite: {e}")
        
    return False

def mark_news_seen(title, link=""):
    """Mark a news item as seen. Uses title as unique identifier."""
    # Update local cache memory
    _seen_news_cache[title] = link
    
    # Save to local file
    try:
        os.makedirs("data", exist_ok=True)
        with open(SEEN_NEWS_FILE, "w") as f:
            json.dump(_seen_news_cache, f, indent=2)
    except Exception as e:
        logger.error(f"Error saving seen news to local JSON: {e}")
        
    # Push to Gist
    try:
        from content.remote_storage import push_to_gist
        push_to_gist("seen_news.json", _seen_news_cache)
    except Exception as e:
        logger.error(f"Error pushing seen news to Gist: {e}")

    # Save to SQLite
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        cursor.execute("INSERT OR IGNORE INTO seen_news (title, link) VALUES (?, ?)", (title, link))
        conn.commit()
        conn.close()
    except Exception as e:
        logger.error(f"Error marking news seen in SQLite: {e}")

def track_poll(poll_id, channel_id, message_id, correct_index, explanation=None):
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("INSERT INTO poll_tracker (poll_id, channel_id, message_id, correct_index, explanation) VALUES (?, ?, ?, ?, ?)", 
                   (poll_id, channel_id, message_id, correct_index, explanation))
    conn.commit()
    conn.close()

def get_poll_data(poll_id):
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("SELECT channel_id, message_id, correct_index FROM poll_tracker WHERE poll_id = ?", (poll_id,))
    res = cursor.fetchone()
    conn.close()
    return res  # returns (channel_id, message_id, correct_index) or None

def get_poll_explanation(poll_id):
    conn = sqlite3.connect(DB_PATH)
    cursor = conn.cursor()
    cursor.execute("SELECT explanation FROM poll_tracker WHERE poll_id = ?", (poll_id,))
    res = cursor.fetchone()
    conn.close()
    return res[0] if res else None

def update_streak(user_id, channel_id):
    """

    Update user's daily streak.

    Returns (new_streak, increased)

    """
    from datetime import datetime
    today = datetime.now().strftime("%Y-%m-%d")
    yesterday = (datetime.now().timestamp() - 86400)
    yesterday_str = datetime.fromtimestamp(yesterday).strftime("%Y-%m-%d")
    
    try:
        conn = sqlite3.connect(DB_PATH)
        cursor = conn.cursor()
        
        # Get current streak info
        cursor.execute("SELECT streak, last_streak_date FROM leaderboard WHERE user_id = ? AND channel_id = ?", (user_id, channel_id))
        row = cursor.fetchone()
        
        if not row:
            # New user entry will be handled by update_score, but we can init here
            cursor.execute("INSERT OR IGNORE INTO leaderboard (user_id, channel_id, streak, last_streak_date) VALUES (?, ?, ?, ?)", 
                           (user_id, channel_id, 1, today))
            conn.commit()
            conn.close()
            return 1, True
        
        streak, last_date = row
        
        if last_date == today:
            conn.close()
            return streak, False # Already updated today
        
        if last_date == yesterday_str:
            new_streak = streak + 1
        else:
            new_streak = 1 # Streak broken
            
        cursor.execute("UPDATE leaderboard SET streak = ?, last_streak_date = ? WHERE user_id = ? AND channel_id = ?", 
                       (new_streak, today, user_id, channel_id))
        conn.commit()
        conn.close()
        return new_streak, True
    except Exception as e:
        logger.error(f"DB Error (update_streak): {e}")
        return 0, False