|
import sqlite3 |
|
from datetime import datetime |
|
|
|
class Database: |
|
def __init__(self): |
|
self.db_name = 'feed.db' |
|
self.create_tables() |
|
|
|
def create_tables(self): |
|
conn = sqlite3.connect(self.db_name) |
|
c = conn.cursor() |
|
c.executescript(""" |
|
CREATE TABLE IF NOT EXISTS feed ( |
|
id INTEGER PRIMARY KEY NOT NULL UNIQUE, |
|
url TEXT NOT NULL UNIQUE, |
|
enabled INTEGER NOT NULL, |
|
updated_at TIMESTAMP |
|
); |
|
CREATE TABLE IF NOT EXISTS urls ( |
|
url TEXT PRIMARY KEY NOT NULL UNIQUE, |
|
feed_id INTEGER NOT NULL, |
|
message_id INTEGER NOT NULL, |
|
created_at TIMESTAMP, |
|
FOREIGN KEY(feed_id) REFERENCES feed(id) |
|
); |
|
""") |
|
conn.commit() |
|
conn.close() |
|
|
|
def get_feed(self, enabled_only = 0): |
|
conn = sqlite3.connect(self.db_name, detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES) |
|
conn.row_factory = sqlite3.Row |
|
c = conn.cursor() |
|
sql = " WHERE enabled = 1" if enabled_only else "" |
|
c.execute("SELECT * FROM feed" + sql) |
|
result = c.fetchall() |
|
conn.close() |
|
return result |
|
|
|
# Adds new items to database, enables or disables them based on current state of configuration |
|
def sync_feed(self, config_feed): |
|
db_feed = {} |
|
for feed_row in self.get_feed(): |
|
db_feed[feed_row['url']] = feed_row['enabled'] |
|
|
|
to_enable = set() |
|
to_add = set() |
|
for feed_row in config_feed: |
|
if not feed_row.get('enabled', True): |
|
continue |
|
url = feed_row['url'] |
|
if url in db_feed: |
|
if not db_feed[url]: |
|
to_enable.add(url) |
|
db_feed.pop(url) |
|
else: |
|
to_add.add((url, 1, datetime.now().replace(year=2013))) |
|
to_disable = list(db_feed.keys()) |
|
|
|
conn = sqlite3.connect(self.db_name) |
|
c = conn.cursor() |
|
if to_add: |
|
c.executemany('INSERT INTO feed(url, enabled, updated_at) VALUES (?,?,?)', to_add) |
|
if to_enable: |
|
c.execute('UPDATE feed SET enabled = 1 WHERE url IN (%s)' % ','.join('?' * len(to_enable)), list(to_enable)) |
|
if to_disable: |
|
c.execute('UPDATE feed SET enabled = 0 WHERE url IN (%s)' % ','.join('?' * len(to_disable)), to_disable) |
|
conn.commit() |
|
conn.close() |
|
|
|
def update_feed(self, url): |
|
conn = sqlite3.connect(self.db_name) |
|
c = conn.cursor() |
|
c.execute('UPDATE feed SET updated_at = ? WHERE url = ?', (datetime.now(), url)) |
|
conn.commit() |
|
conn.close() |
|
|
|
|
|
def is_url_exists(self, url): |
|
conn = sqlite3.connect(self.db_name) |
|
c = conn.cursor() |
|
c.execute("SELECT EXISTS(SELECT 1 FROM urls WHERE url=?)", (url, )) |
|
result = c.fetchone()[0] |
|
conn.close() |
|
return result |
|
|
|
def add_urls(self, urls): |
|
if not urls: |
|
return |
|
conn = sqlite3.connect(self.db_name) |
|
c = conn.cursor() |
|
sql = 'INSERT INTO urls(url, feed_id, message_id, created_at) VALUES (?,?,?,?)' |
|
c.executemany(sql, urls) |
|
conn.commit() |
|
conn.close() |