1
0
Fork 0
mirror of https://github.com/Lynnesbian/FediBooks/ synced 2024-11-17 13:18:59 +00:00
FediBooks/app/service.py

92 lines
2.2 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
import json
import MySQLdb
2019-09-17 09:06:40 +00:00
from mastodon import Mastodon
import requests
2019-09-06 02:38:50 +00:00
import functions
cfg = json.load(open('config.json'))
2019-09-17 09:06:40 +00:00
def update_icon(bot):
try:
db = MySQLdb.connect(
host = cfg['db_host'],
user=cfg['db_user'],
passwd=cfg['db_pass'],
db=cfg['db_name'],
use_unicode=True,
charset="utf8mb4"
)
except:
print("Failed to connect to database.")
return
url = "https://{}".format(bot['handle'].split("@")[2])
try:
r = requests.head(url, timeout=10, allow_redirects = True)
if r.status_code != 200:
raise
except:
2020-05-27 11:59:29 +00:00
print("{} is down - can't update icon for {}.".format(url, bot['handle']))
return
2019-09-17 09:06:40 +00:00
client = Mastodon(
client_id = bot['client_id'],
client_secret = bot['client_secret'],
access_token = bot['secret'],
api_base_url = url
2019-09-17 09:06:40 +00:00
)
2019-09-17 09:06:40 +00:00
c = db.cursor()
try:
avatar = client.account_verify_credentials()['avatar']
except:
c.execute("UPDATE bots SET icon_update_time = CURRENT_TIMESTAMP() WHERE handle = %s", (bot['handle'],))
db.commit()
c.close()
return
2019-09-17 09:06:40 +00:00
c.execute("UPDATE bots SET icon = %s, icon_update_time = CURRENT_TIMESTAMP() WHERE handle = %s", (avatar, bot['handle']))
db.commit()
c.close()
2019-09-17 09:06:40 +00:00
print("Establishing DB connection")
db = MySQLdb.connect(
host = cfg['db_host'],
user=cfg['db_user'],
passwd=cfg['db_pass'],
2019-09-10 12:21:22 +00:00
db=cfg['db_name'],
use_unicode=True,
charset="utf8mb4"
)
print("Cleaning up database")
# delete any fedi accounts we no longer need
2019-09-06 02:38:50 +00:00
cursor = db.cursor()
cursor.execute("DELETE FROM fedi_accounts WHERE handle NOT IN (SELECT fedi_id FROM bot_learned_accounts)")
2019-09-11 05:35:09 +00:00
db.commit()
2019-09-06 02:47:39 +00:00
2019-09-07 03:31:11 +00:00
print("Generating posts")
2019-09-17 09:06:40 +00:00
cursor.execute("SELECT handle FROM bots WHERE enabled = TRUE AND TIMESTAMPDIFF(MINUTE, last_post, CURRENT_TIMESTAMP()) >= post_frequency")
2020-01-20 02:56:24 +00:00
# cursor.execute("SELECT handle FROM bots WHERE enabled = TRUE")
2019-09-07 03:31:11 +00:00
bots = cursor.fetchall()
functions.do_in_pool(functions.make_post, bots, 15)
2019-09-07 03:31:11 +00:00
2019-09-17 09:06:40 +00:00
print("Updating cached icons")
dc = db.cursor(MySQLdb.cursors.DictCursor)
dc.execute("""
SELECT handle, instance_type, client_id, client_secret, secret
FROM bots
INNER JOIN credentials
ON bots.credentials_id = credentials.id
WHERE TIMESTAMPDIFF(HOUR, icon_update_time, CURRENT_TIMESTAMP()) > 2""")
bots = dc.fetchall()
functions.do_in_pool(update_icon, bots)
2019-09-11 05:23:00 +00:00
db.commit()