summaryrefslogtreecommitdiff
path: root/db.py
blob: c83e8eed756c6b7f1d11ffaa5a24da3d7923a34a (plain)
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
#!/usr/bin/python3
# -*- coding: utf-8 -*-


from config import max_age
import sqlite3
import time
import tweepy


class LikeMemory():
    """Track all liked Tweets."""

    def __init__(self, api):
        """Build the Python object."""

        self._api = api

        self._db = sqlite3.connect('HTT.db', detect_types=sqlite3.PARSE_DECLTYPES)

        sqlite3.register_adapter(bool, int)
        sqlite3.register_converter("BOOLEAN", lambda v: bool(int(v)))

        sql = '''
            CREATE TABLE IF NOT EXISTS LikedTweets(
                sid INTEGER PRIMARY KEY,
                username TEXT,
                timestamp INTEGER,
                purged BOOLEAN
            )
        '''

        cursor = self._db.cursor()
        cursor.execute(sql)
        self._db.commit()


    def save_liked_status(self, sid, username):
        """Remember a given liked status."""

        timestamp = int(time.time())

        values = (sid, username, timestamp, False)

        cursor = self._db.cursor()
        cursor.execute('INSERT INTO LikedTweets VALUES (?, ?, ?, ?)', values)
        self._db.commit()


    def purge_old_status(self):
        """Purge old seen statuses."""

        timestamp = int(time.time()) - max_age * 24 * 60 * 60

        values = (timestamp, False)

        cursor = self._db.cursor()
        cursor.execute('SELECT sid FROM LikedTweets WHERE timestamp < ? AND purged = ?', values)

        rows = cursor.fetchall()

        for row in rows:

            sid = row[0]

            try:

                self._api.destroy_favorite(sid)

            # tweepy.error.TweepError: [{'code': 144, 'message': 'No status found with that ID.'}]
            except tweepy.error.TweepError as err:

                pass

            values = (True, sid)

            cursor = self._db.cursor()
            cursor.execute('UPDATE LikedTweets SET purged = ? WHERE sid = ?', values)

        self._db.commit()

        print('Purged %d liked Tweet%s!' % (len(rows), '' if len(rows) <= 1 else 's'))