Slixfeed/slixfeed.py

763 lines
25 KiB
Python
Raw Normal View History

2022-06-21 16:27:32 +02:00
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
2022-09-24 21:01:57 +02:00
import os
2022-06-21 16:27:32 +02:00
from argparse import ArgumentParser
from asyncio.exceptions import IncompleteReadError
from datetime import date
from getpass import getpass
from http.client import IncompleteRead
from urllib import error
import asyncio
import logging
import sqlite3
from sqlite3 import Error
import sys
2022-09-24 21:01:57 +02:00
import aiohttp
from bs4 import BeautifulSoup
import feedparser
import slixmpp
DBLOCK = asyncio.Lock()
2022-07-11 18:50:54 +02:00
2022-06-24 10:44:36 +02:00
class Slixfeed(slixmpp.ClientXMPP):
2022-06-21 16:27:32 +02:00
"""
Slixmpp bot that will send updates of feeds it
receives.
"""
def __init__(self, jid, password):
slixmpp.ClientXMPP.__init__(self, jid, password)
# The session_start event will be triggered when
# the bot establishes its connection with the server
# and the XML streams are ready for use. We want to
# listen for this event so that we we can initialize
# our roster.
self.add_event_handler("session_start", self.start)
2022-06-24 10:44:36 +02:00
self.add_event_handler("session_start", self.send_updates)
2022-09-24 21:01:57 +02:00
self.add_event_handler("session_start", self.check_updates)
2022-06-21 16:27:32 +02:00
# The message event is triggered whenever a message
# stanza is received. Be aware that that includes
# MUC messages and error messages.
self.add_event_handler("message", self.message)
2022-07-11 18:50:54 +02:00
self.add_event_handler("disconnected", self.reconnect)
2022-06-21 16:27:32 +02:00
async def start(self, event):
"""
Process the session_start event.
Typical actions for the session_start event are
requesting the roster and broadcasting an initial
presence stanza.
Arguments:
event -- An empty dictionary. The session_start
event does not provide any additional
data.
"""
self.send_presence()
await self.get_roster()
2022-08-05 09:55:03 +02:00
async def message(self, msg):
2022-06-21 16:27:32 +02:00
"""
Process incoming message stanzas. Be aware that this also
includes MUC messages and error messages. It is usually
a good idea to check the messages's type before processing
or sending replies.
Arguments:
msg -- The received message stanza. See the documentation
for stanza objects and the Message stanza to see
how it may be used.
"""
if msg['type'] in ('chat', 'normal'):
message = " ".join(msg['body'].split())
2022-08-04 20:31:23 +02:00
if message.lower().startswith('help'):
2022-07-19 11:01:03 +02:00
print("COMMAND: help")
print("ACCOUNT: " + str(msg['from']))
2022-06-21 22:39:29 +02:00
action = print_help()
2022-06-24 10:44:36 +02:00
# NOTE: Might not need it
2022-08-04 20:31:23 +02:00
elif message.lower().startswith('feed recent '):
2022-07-11 18:50:54 +02:00
print("COMMAND: feed recent")
print("ACCOUNT: " + str(msg['from']))
2022-09-24 21:01:57 +02:00
action = await initdb(msg['from'].bare, last_entries, message[12:])
2022-08-04 20:31:23 +02:00
elif message.lower().startswith('feed search '):
2022-07-11 18:50:54 +02:00
print("COMMAND: feed search")
print("ACCOUNT: " + str(msg['from']))
2022-09-24 21:01:57 +02:00
action = await initdb( msg['from'].bare, search_entries, message[12:])
2022-08-04 20:31:23 +02:00
elif message.lower().startswith('feed list'):
2022-07-11 18:50:54 +02:00
print("COMMAND: feed list")
print("ACCOUNT: " + str(msg['from']))
2022-09-24 21:01:57 +02:00
action = await initdb(msg['from'].bare, list_subscriptions)
2022-08-04 20:31:23 +02:00
elif message.lower().startswith('feed add '):
2022-07-11 18:50:54 +02:00
print("COMMAND: feed add")
print("ACCOUNT: " + str(msg['from']))
2022-09-24 21:01:57 +02:00
action = await initdb(msg['from'].bare, add_feed, message[9:])
2022-08-04 20:31:23 +02:00
elif message.lower().startswith('feed remove '):
2022-07-11 18:50:54 +02:00
print("COMMAND: feed remove")
print("ACCOUNT: " + str(msg['from']))
2022-09-24 21:01:57 +02:00
action = await initdb(msg['from'].bare, remove_feed, message[12:])
2022-08-04 20:31:23 +02:00
elif message.lower().startswith('feed status '):
2022-07-11 18:50:54 +02:00
print("COMMAND: feed status")
print("ACCOUNT: " + str(msg['from']))
2022-09-24 21:01:57 +02:00
action = await initdb(msg['from'].bare, toggle_status, message[12:])
2022-08-04 20:31:23 +02:00
elif message.lower().startswith('enable'):
2022-07-20 17:46:20 +02:00
print("COMMAND: enable")
2022-07-11 18:50:54 +02:00
print("ACCOUNT: " + str(msg['from']))
2022-09-24 21:01:57 +02:00
action = toggle_state(msg['from'].bare, True)
2022-08-04 20:31:23 +02:00
elif message.lower().startswith('disable'):
2022-07-20 17:46:20 +02:00
print("COMMAND: disable")
2022-07-11 18:50:54 +02:00
print("ACCOUNT: " + str(msg['from']))
2022-09-24 21:01:57 +02:00
action = toggle_state(msg['from'].bare, False)
2022-06-24 10:44:36 +02:00
else:
2022-09-24 21:01:57 +02:00
action = 'Unknown command. Press "help" for list of commands'
2022-06-21 16:27:32 +02:00
msg.reply(action).send()
2022-09-24 21:01:57 +02:00
async def check_updates(self, event):
while True:
print("Checking update")
db_dir = get_default_dbdir()
if not os.path.isdir(db_dir):
msg = ("Slixfeed can not work without a database. \n"
"To create a database, follow these steps: \n"
"Add Slixfeed contact to your roster \n"
"Send a feed to the bot by: \n"
"feed add https://reclaimthenet.org/feed/")
print(msg)
else:
files = os.listdir(db_dir)
for file in files:
jid = file[:-3]
await initdb(jid, download_updates)
await asyncio.sleep(9)
2022-06-24 10:44:36 +02:00
async def send_updates(self, event):
2022-08-14 19:30:35 +02:00
while True:
2022-06-24 10:44:36 +02:00
db_dir = get_default_dbdir()
if not os.path.isdir(db_dir):
2022-06-30 17:50:19 +02:00
msg = ("Slixfeed can not work without a database. \n"
"To create a database, follow these steps: \n"
"Add Slixfeed contact to your roster \n"
"Send a feed to the bot by: \n"
"feed add https://reclaimthenet.org/feed/")
2022-06-24 10:44:36 +02:00
print(msg)
else:
os.chdir(db_dir)
files = os.listdir()
for file in files:
2022-06-30 17:17:46 +02:00
if not file.endswith('.db-jour.db'):
jid = file[:-3]
2022-09-24 21:01:57 +02:00
new = await initdb(
jid,
get_unread
)
2022-06-30 17:17:46 +02:00
if new:
2022-09-24 21:01:57 +02:00
msg = self.make_message(
mto=jid,
mbody=new,
mtype='chat'
)
2022-06-30 17:17:46 +02:00
msg.send()
await asyncio.sleep(60 * 3)
2022-06-24 10:44:36 +02:00
2022-07-20 17:46:20 +02:00
2022-06-21 22:39:29 +02:00
def print_help():
2022-06-24 10:44:36 +02:00
msg = ("Slixfeed - News syndication bot for Jabber/XMPP \n"
"\n"
"DESCRIPTION: \n"
" Slixfeed is an aggregator bot for online news feeds. \n"
"\n"
"BASIC USAGE: \n"
2022-07-20 17:46:20 +02:00
" enable \n"
2022-06-30 17:17:46 +02:00
" Send updates. \n"
2022-07-20 17:46:20 +02:00
" disable \n"
" Stop sending updates. \n"
2022-06-24 10:44:36 +02:00
" feed list \n"
" List subscriptions list. \n"
"\n"
"EDIT OPTIONS: \n"
" feed add URL \n"
" Add URL to the subscriptions list. \n"
" feed remove ID \n"
" Remove feed from subscription list. \n"
" feed status ID \n"
" Toggle update status of feed. \n"
"\n"
"SEARCH OPTIONS: \n"
" feed search TEXT \n"
" Search news items by given keywords. \n"
" feed recent N \n"
2022-07-20 17:46:20 +02:00
" List recent N news items (up to 50 items). \n"
2022-06-24 10:44:36 +02:00
"\n"
"DOCUMENTATION: \n"
2022-06-30 17:50:19 +02:00
" Slixfeed \n"
" https://gitgud.io/sjehuda/slixfeed \n"
2022-06-24 10:44:36 +02:00
" Slixmpp \n"
2022-06-30 17:50:19 +02:00
" https://slixmpp.readthedocs.io/ \n"
" feedparser \n"
" https://pythonhosted.org/feedparser")
2022-06-21 22:39:29 +02:00
return msg
2022-09-24 21:01:57 +02:00
2022-06-21 16:27:32 +02:00
# Function from buku
# https://github.com/jarun/buku
# Arun Prakash Jana (jarun)
# Dmitry Marakasov (AMDmi3)
def get_default_dbdir():
"""Determine the directory path where dbfile will be stored.
If $XDG_DATA_HOME is defined, use it
else if $HOME exists, use it
else if the platform is Windows, use %APPDATA%
else use the current directory.
Returns
-------
str
Path to database file.
"""
# data_home = xdg.BaseDirectory.xdg_data_home
data_home = os.environ.get('XDG_DATA_HOME')
if data_home is None:
if os.environ.get('HOME') is None:
if sys.platform == 'win32':
data_home = os.environ.get('APPDATA')
if data_home is None:
return os.path.abspath('.')
else:
return os.path.abspath('.')
else:
data_home = os.path.join(os.environ.get('HOME'), '.local', 'share')
return os.path.join(data_home, 'slixfeed')
2022-09-24 21:01:57 +02:00
2022-06-21 16:27:32 +02:00
# TODO Perhaps this needs to be executed
# just once per program execution
2022-09-24 21:01:57 +02:00
async def initdb(jid, callback, message=None):
2022-06-21 16:27:32 +02:00
db_dir = get_default_dbdir()
if not os.path.isdir(db_dir):
os.mkdir(db_dir)
2022-09-24 21:01:57 +02:00
db_file = os.path.join(db_dir, r"{}.db".format(jid))
create_tables(db_file)
if message:
return await callback(db_file, message)
2022-06-21 16:27:32 +02:00
else:
2022-09-24 21:01:57 +02:00
return await callback(db_file)
def create_tables(db_file):
with create_connection(db_file) as conn:
feeds_table_sql = """
CREATE TABLE IF NOT EXISTS feeds (
id integer PRIMARY KEY,
name text,
address text NOT NULL,
enabled integer NOT NULL,
scanned text,
updated text,
status integer,
valid integer
); """
entries_table_sql = """
CREATE TABLE IF NOT EXISTS entries (
id integer PRIMARY KEY,
title text NOT NULL,
summary text NOT NULL,
link text NOT NULL,
source text,
read integer
); """
c = conn.cursor()
c.execute(feeds_table_sql)
c.execute(entries_table_sql)
2022-06-21 16:27:32 +02:00
def create_connection(db_file):
"""
Create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
print(e)
return conn
2022-09-24 21:01:57 +02:00
async def download_updates(db_file):
with create_connection(db_file) as conn:
urls = await get_subscriptions(conn)
for url in urls:
source = url[0]
res = await download_feed(source)
sql = "UPDATE feeds SET status = :status, scanned = :scanned WHERE address = :url"
async with DBLOCK:
with conn:
2022-08-17 15:32:25 +02:00
cur = conn.cursor()
cur.execute(sql, {"status": res[1], "scanned": date.today(), "url": source})
2022-09-24 21:01:57 +02:00
if res[0]:
try:
feed = feedparser.parse(res[0])
if feed.bozo:
bozo = ("WARNING: Bozo detected for feed <{}>. "
"For more information, visit "
"https://pythonhosted.org/feedparser/bozo.html"
.format(source))
print(bozo)
valid = 0
else:
valid = 1
sql = "UPDATE feeds SET valid = :validity WHERE address = :url"
async with DBLOCK:
with conn:
2022-09-24 21:01:57 +02:00
cur = conn.cursor()
2022-08-17 15:32:25 +02:00
cur.execute(sql, {"validity": valid, "url": source})
2022-09-24 21:01:57 +02:00
except (IncompleteReadError, IncompleteRead, error.URLError) as e:
print(e)
return
# TODO Place these couple of lines back down
# NOTE Need to correct the SQL statement to do so
entries = feed.entries
length = len(entries)
async with DBLOCK:
with conn:
2022-08-17 15:32:25 +02:00
await remove_entry(conn, source, length)
2022-09-24 21:01:57 +02:00
for entry in entries:
if entry.has_key("title"):
title = entry.title
else:
title = feed["feed"]["title"]
link = source if not entry.link else entry.link
with conn:
2022-09-24 21:01:57 +02:00
exist = await check_entry(conn, title, link)
if not exist:
if entry.has_key("summary"):
summary = entry.summary
# Remove HTML tags
summary = BeautifulSoup(summary, "lxml").text
# TODO Limit text length
summary = summary.replace("\n\n", "\n")[:300] + " ‍⃨"
else:
summary = '*** No summary ***'
#print('~~~~~~summary not in entry')
entry = (title, summary, link, source, 0);
async with DBLOCK:
with conn:
2022-08-17 15:32:25 +02:00
await add_entry(conn, entry)
await set_date(conn, source)
2022-09-24 21:01:57 +02:00
async def download_feed(url):
async with aiohttp.ClientSession() as session:
async with session.get(url) as response:
2022-08-09 12:24:36 +02:00
status = response.status
2022-07-19 11:01:03 +02:00
if response.status == 200:
2022-08-09 12:24:36 +02:00
doc = await response.text()
2022-09-24 21:01:57 +02:00
return [doc, status]
2022-08-09 12:24:36 +02:00
else:
2022-09-24 21:01:57 +02:00
return [False, status]
2022-09-24 21:01:57 +02:00
async def check_feed(conn, url):
2022-06-21 16:27:32 +02:00
"""
Check whether a feed exists
Query for feeds by url
:param conn:
:param url:
:return: row
"""
2022-09-24 21:01:57 +02:00
cur = conn.cursor()
sql = "SELECT id FROM feeds WHERE address = ?"
cur.execute(sql, (url,))
return cur.fetchone()
2022-06-21 16:27:32 +02:00
2022-09-24 21:01:57 +02:00
async def add_feed(db_file, url):
2022-06-21 16:27:32 +02:00
"""
Add a new feed into the feeds table
:param conn:
:param feed:
:return: string
"""
2022-09-24 21:01:57 +02:00
#TODO consider async with DBLOCK
#conn = create_connection(db_file)
with create_connection(db_file) as conn:
exist = await check_feed(conn, url)
if not exist:
res = await download_feed(url)
else:
return "News source is already listed in the subscription list"
async with DBLOCK:
with create_connection(db_file) as conn:
cur = conn.cursor()
2022-08-17 15:32:25 +02:00
if res[0]:
feed = feedparser.parse(res[0])
if feed.bozo:
feed = (url, 1, res[1], 0)
sql = """INSERT INTO feeds(address,enabled,status,valid)
VALUES(?,?,?,?) """
cur.execute(sql, feed)
bozo = ("WARNING: Bozo detected. Failed to load URL.")
print(bozo)
return "Failed to parse URL as feed"
else:
title = feed["feed"]["title"]
feed = (title, url, 1, res[1], 1)
sql = """INSERT INTO feeds(name,address,enabled,status,valid)
VALUES(?,?,?,?,?) """
cur.execute(sql, feed)
else:
2022-08-09 12:24:36 +02:00
feed = (url, 1, res[1], 0)
2022-09-24 21:01:57 +02:00
sql = "INSERT INTO feeds(address,enabled,status,valid) VALUES(?,?,?,?) "
2022-08-09 12:24:36 +02:00
cur.execute(sql, feed)
2022-08-17 15:32:25 +02:00
return "Failed to get URL. HTTP Error {}".format(res[1])
2022-06-21 16:27:32 +02:00
2022-09-24 21:01:57 +02:00
source = title if title else '<' + url + '>'
msg = 'News source "{}" has been added to subscriptions list'.format(source)
return msg
async def remove_feed(db_file, ix):
2022-06-21 16:27:32 +02:00
"""
Delete a feed by feed id
2022-07-20 17:46:20 +02:00
:param conn:
2022-06-21 16:27:32 +02:00
:param id: id of the feed
:return: string
"""
2022-09-24 21:01:57 +02:00
with create_connection(db_file) as conn:
2022-08-17 15:32:25 +02:00
cur = conn.cursor()
sql = "SELECT address FROM feeds WHERE id = ?"
2022-09-24 21:01:57 +02:00
url = cur.execute(sql, (ix,))
2022-08-17 15:32:25 +02:00
for i in url:
url = i[0]
sql = "DELETE FROM entries WHERE source = ?"
cur.execute(sql, (url,))
sql = "DELETE FROM feeds WHERE id = ?"
2022-09-24 21:01:57 +02:00
cur.execute(sql, (ix,))
2022-08-17 15:32:25 +02:00
return """News source <{}> has been removed from subscriptions list
""".format(url)
2022-06-21 16:27:32 +02:00
2022-09-24 21:01:57 +02:00
async def get_unread(db_file):
2022-06-21 16:27:32 +02:00
"""
Check read status of entry
2022-07-20 17:46:20 +02:00
:param conn:
2022-06-21 16:27:32 +02:00
:param id: id of the entry
:return: string
"""
2022-09-24 21:01:57 +02:00
async with DBLOCK:
with create_connection(db_file) as conn:
entry = []
cur = conn.cursor()
sql = "SELECT id FROM entries WHERE read = 0"
ix = cur.execute(sql).fetchone()
if ix is None:
return False
ix = ix[0]
sql = "SELECT title FROM entries WHERE id = :id"
cur.execute(sql, (ix,))
title = cur.fetchone()[0]
entry.append(title)
sql = "SELECT summary FROM entries WHERE id = :id"
cur.execute(sql, (ix,))
summary = cur.fetchone()[0]
entry.append(summary)
sql = "SELECT link FROM entries WHERE id = :id"
cur.execute(sql, (ix,))
link = cur.fetchone()[0]
entry.append(link)
entry = "{}\n\n{}\n\nLink to article:\n{}".format(entry[0], entry[1], entry[2])
await mark_as_read(cur, ix)
2022-07-11 18:50:54 +02:00
return entry
2022-06-21 16:27:32 +02:00
2022-09-24 21:01:57 +02:00
async def mark_as_read(cur, ix):
2022-06-21 16:27:32 +02:00
"""
Set read status of entry
2022-09-24 21:01:57 +02:00
:param cur:
:param ix: index of the entry
2022-06-21 16:27:32 +02:00
"""
2022-09-24 21:01:57 +02:00
sql = "UPDATE entries SET summary = '', read = 1 WHERE id = ?"
cur.execute(sql, (ix,))
2022-08-09 12:24:36 +02:00
# TODO mark_all_read for entries of feed
2022-09-24 21:01:57 +02:00
async def toggle_status(db_file, ix):
2022-06-21 16:27:32 +02:00
"""
Set status of feed
2022-07-20 17:46:20 +02:00
:param conn:
2022-06-21 16:27:32 +02:00
:param id: id of the feed
:return: string
"""
2022-09-24 21:01:57 +02:00
async with DBLOCK:
with create_connection(db_file) as conn:
cur = conn.cursor()
sql = "SELECT name FROM feeds WHERE id = :id"
cur.execute(sql, (ix,))
title = cur.fetchone()[0]
sql = "SELECT enabled FROM feeds WHERE id = ?"
# NOTE [0][1][2]
cur.execute(sql, (ix,))
status = cur.fetchone()[0]
# FIXME always set to 1
# NOTE Maybe because is not integer
# TODO Reset feed table before further testing
if status == 1:
status = 0
notice = "News updates for '{}' are now disabled".format(title)
else:
status = 1
notice = "News updates for '{}' are now enabled".format(title)
sql = "UPDATE feeds SET enabled = :status WHERE id = :id"
cur.execute(sql, {"status": status, "id": ix})
return notice
2022-06-21 16:27:32 +02:00
2022-09-24 21:01:57 +02:00
def toggle_state(jid, state):
2022-07-20 17:46:20 +02:00
"""
Set status of update
:param jid: jid of the user
:param state: boolean
:return:
"""
db_dir = get_default_dbdir()
2022-09-24 21:01:57 +02:00
db_file = os.path.join(db_dir, r"{}.db".format(jid))
bk_file = os.path.join(db_dir, r"{}.db.bak".format(jid))
2022-07-20 17:46:20 +02:00
if state:
2022-09-24 21:01:57 +02:00
if os.path.exists(db_file):
2022-07-20 17:46:20 +02:00
return "Updates are already enabled"
2022-09-24 21:01:57 +02:00
elif os.path.exists(bk_file):
2022-07-20 17:46:20 +02:00
os.renames(bk_file, db_file)
return "Updates are now enabled"
else:
2022-09-24 21:01:57 +02:00
if os.path.exists(bk_file):
2022-07-20 17:46:20 +02:00
return "Updates are already disabled"
2022-09-24 21:01:57 +02:00
elif os.path.exists(db_file):
2022-07-20 17:46:20 +02:00
os.renames(db_file, bk_file)
return "Updates are now disabled"
2022-09-24 21:01:57 +02:00
2022-07-20 17:46:20 +02:00
2022-08-05 09:55:03 +02:00
async def set_date(conn, url):
2022-06-21 16:27:32 +02:00
"""
Set last update date of feed
:param url: url of the feed
:return:
"""
today = date.today()
cur = conn.cursor()
sql = "UPDATE feeds SET updated = :today WHERE address = :url"
cur.execute(sql, {"today": today, "url": url})
2022-09-24 21:01:57 +02:00
2022-06-21 16:27:32 +02:00
2022-08-05 09:55:03 +02:00
async def get_subscriptions(conn):
2022-06-21 16:27:32 +02:00
"""
Query feeds
:param conn:
:return: rows (tuple)
"""
2022-07-13 16:32:07 +02:00
cur = conn.cursor()
2022-08-09 12:24:36 +02:00
sql = "SELECT address FROM feeds WHERE enabled = 1"
2022-06-21 16:27:32 +02:00
result = cur.execute(sql)
return result
2022-09-24 21:01:57 +02:00
async def list_subscriptions(db_file):
2022-06-21 16:27:32 +02:00
"""
Query feeds
:param conn:
:return: rows (string)
"""
2022-09-24 21:01:57 +02:00
with create_connection(db_file) as conn:
cur = conn.cursor()
sql = "SELECT name, address, updated, id, enabled FROM feeds"
results = cur.execute(sql)
feeds_list = "List of subscriptions: \n"
counter = 0
for result in results:
counter += 1
feeds_list += """\n{} \n{} \nLast updated: {} \nID: {} [{}]
""".format(str(result[0]), str(result[1]), str(result[2]),
str(result[3]), str(result[4]))
if counter:
return feeds_list + "\n Total of {} subscriptions".format(counter)
else:
2022-06-30 18:21:22 +02:00
msg = ("List of subscriptions is empty. \n"
2022-07-20 17:46:20 +02:00
"To add feed, send a message as follows: \n"
2022-06-30 18:21:22 +02:00
"feed add URL \n"
2022-07-20 17:46:20 +02:00
"Example: \n"
2022-06-30 18:21:22 +02:00
"feed add https://reclaimthenet.org/feed/")
return msg
2022-06-21 16:27:32 +02:00
2022-09-24 21:01:57 +02:00
async def last_entries(db_file, num):
2022-07-20 17:46:20 +02:00
"""
Query feeds
:param conn:
:param num: integer
:return: rows (string)
"""
2022-07-20 20:44:44 +02:00
num = int(num)
if num > 50:
num = 50
elif num < 1:
num = 1
2022-09-24 21:01:57 +02:00
with create_connection(db_file) as conn:
cur = conn.cursor()
sql = "SELECT title, link FROM entries ORDER BY ROWID DESC LIMIT {}".format(num)
results = cur.execute(sql)
2022-07-20 17:46:20 +02:00
titles_list = "Recent {} titles: \n".format(num)
for result in results:
2022-09-24 21:01:57 +02:00
titles_list += "\n{} \n{}".format(str(result[0]), str(result[1]))
2022-07-20 17:46:20 +02:00
return titles_list
2022-09-24 21:01:57 +02:00
async def search_entries(db_file, query):
2022-07-20 20:32:30 +02:00
"""
Query feeds
:param conn:
:param query: string
:return: rows (string)
"""
2022-07-20 20:39:12 +02:00
if len(query) < 2:
return "Please enter at least 2 characters to search"
2022-09-24 21:01:57 +02:00
with create_connection(db_file) as conn:
cur = conn.cursor()
sql = "SELECT title, link FROM entries WHERE title LIKE '%{}%' LIMIT 50".format(query)
results = cur.execute(sql)
2022-07-20 20:32:30 +02:00
results_list = "Search results for '{}': \n".format(query)
counter = 0
for result in results:
counter += 1
results_list += """\n{} \n{}
""".format(str(result[0]), str(result[1]))
if counter:
return results_list + "\n Total of {} results".format(counter)
else:
2022-07-20 20:39:12 +02:00
return "No results found for: {}".format(query)
2022-07-20 20:32:30 +02:00
2022-09-24 21:01:57 +02:00
2022-08-05 09:55:03 +02:00
async def check_entry(conn, title, link):
2022-06-21 16:27:32 +02:00
"""
Check whether an entry exists
Query entries by title and link
:param conn:
:param link:
:param title:
:return: row
"""
2022-07-13 16:32:07 +02:00
cur = conn.cursor()
2022-06-21 16:27:32 +02:00
sql = "SELECT id FROM entries WHERE title = :title and link = :link"
cur.execute(sql, {"title": title, "link": link})
return cur.fetchone()
2022-09-24 21:01:57 +02:00
2022-08-05 09:55:03 +02:00
async def add_entry(conn, entry):
2022-06-21 16:27:32 +02:00
"""
Add a new entry into the entries table
:param conn:
:param entry:
:return:
"""
sql = """ INSERT INTO entries(title,summary,link,source,read)
VALUES(?,?,?,?,?) """
cur = conn.cursor()
cur.execute(sql, entry)
2022-09-24 21:01:57 +02:00
2022-06-21 16:27:32 +02:00
2022-08-05 09:55:03 +02:00
async def remove_entry(conn, source, length):
2022-06-21 16:27:32 +02:00
"""
Maintain list of entries
Check the number returned by feed and delete
existing entries up to the same returned amount
:param conn:
:param source:
:param length:
:return:
"""
cur = conn.cursor()
# FIXED
# Dino empty titles are not counted https://dino.im/index.xml
# SOLVED
# Add text if is empty
# title = '*** No title ***' if not entry.title else entry.title
sql = "SELECT count(id) FROM entries WHERE source = ?"
count = cur.execute(sql, (source,))
count = cur.fetchone()[0]
limit = count - length
if limit:
limit = limit;
2022-06-24 10:44:36 +02:00
sql = """DELETE FROM entries WHERE id IN (
SELECT id FROM entries
WHERE source = :source
ORDER BY id
ASC LIMIT :limit)"""
2022-06-21 16:27:32 +02:00
cur.execute(sql, {"source": source, "limit": limit})
2022-09-24 21:01:57 +02:00
2022-06-21 16:27:32 +02:00
if __name__ == '__main__':
# Setup the command line arguments.
2022-06-24 10:44:36 +02:00
parser = ArgumentParser(description=Slixfeed.__doc__)
2022-06-21 16:27:32 +02:00
# Output verbosity options.
2022-09-24 21:01:57 +02:00
parser.add_argument(
"-q", "--quiet", help="set logging to ERROR",
action="store_const", dest="loglevel",
const=logging.ERROR, default=logging.INFO
)
parser.add_argument(
"-d", "--debug", help="set logging to DEBUG",
action="store_const", dest="loglevel",
const=logging.DEBUG, default=logging.INFO
)
2022-06-21 16:27:32 +02:00
# JID and password options.
parser.add_argument("-j", "--jid", dest="jid",
help="JID to use")
parser.add_argument("-p", "--password", dest="password",
help="password to use")
args = parser.parse_args()
# Setup logging.
logging.basicConfig(level=args.loglevel,
format='%(levelname)-8s %(message)s')
if args.jid is None:
args.jid = input("Username: ")
if args.password is None:
args.password = getpass("Password: ")
2022-06-24 10:44:36 +02:00
# Setup the Slixfeed and register plugins. Note that while plugins may
2022-06-21 16:27:32 +02:00
# have interdependencies, the order in which you register them does
# not matter.
2022-06-24 10:44:36 +02:00
xmpp = Slixfeed(args.jid, args.password)
2022-06-21 16:27:32 +02:00
xmpp.register_plugin('xep_0004') # Data Forms
2022-07-19 11:01:03 +02:00
xmpp.register_plugin('xep_0030') # Service Discovery
xmpp.register_plugin('xep_0045') # Multi-User Chat
2022-06-21 16:27:32 +02:00
xmpp.register_plugin('xep_0060') # PubSub
xmpp.register_plugin('xep_0199') # XMPP Ping
# Connect to the XMPP server and start processing XMPP stanzas.
xmpp.connect()
xmpp.process()