2017-06-25 00:02:34 +02:00
|
|
|
from config import config
|
|
|
|
from titanembeds.database import DatabaseInterface, Guilds, Messages
|
|
|
|
import asyncio
|
|
|
|
import sys
|
|
|
|
import logging
|
|
|
|
import json
|
2017-09-22 03:18:30 +02:00
|
|
|
import gc
|
2018-06-25 08:56:33 +02:00
|
|
|
import random
|
2017-06-25 00:02:34 +02:00
|
|
|
from asyncio_extras import threadpool
|
|
|
|
logging.basicConfig(filename='titanbot.log',level=logging.INFO,format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
|
|
|
|
logging.getLogger('TitanBot')
|
|
|
|
logging.getLogger('sqlalchemy')
|
|
|
|
|
|
|
|
###########################
|
|
|
|
# Cleanup DB Messages #
|
|
|
|
# #
|
|
|
|
# Cleans the database #
|
|
|
|
# messages store #
|
|
|
|
###########################
|
|
|
|
|
2018-06-28 07:29:52 +02:00
|
|
|
class TitanCleanupDB:
|
2017-06-25 00:02:34 +02:00
|
|
|
def __init__(self):
|
|
|
|
super().__init__()
|
2018-06-28 07:29:52 +02:00
|
|
|
self.loop = asyncio.get_event_loop()
|
2017-06-25 00:02:34 +02:00
|
|
|
self.database = DatabaseInterface(self)
|
2018-06-25 08:56:33 +02:00
|
|
|
self.logger = logging.getLogger("titan_cleanupdb")
|
|
|
|
self.logger.setLevel(logging.DEBUG)
|
|
|
|
fh = logging.FileHandler("titan_cleanupdb.log")
|
|
|
|
fh.setLevel(logging.DEBUG)
|
|
|
|
session_id = str(random.randrange(100))
|
|
|
|
formatter = logging.Formatter("%(asctime)s - {0} - %(levelname)s - %(message)s".format(session_id))
|
|
|
|
fh.setFormatter(formatter)
|
|
|
|
self.logger.addHandler(fh)
|
|
|
|
consoleHandler = logging.StreamHandler()
|
|
|
|
consoleHandler.setFormatter(formatter)
|
|
|
|
self.logger.addHandler(consoleHandler)
|
|
|
|
self.logger.info("Initialized Database Cleaning Class with session id of " + session_id)
|
2017-06-25 00:02:34 +02:00
|
|
|
|
|
|
|
def _cleanup(self):
|
|
|
|
try:
|
|
|
|
self.loop.run_until_complete(self.logout())
|
|
|
|
except: # Can be ignored
|
|
|
|
pass
|
|
|
|
pending = asyncio.Task.all_tasks()
|
|
|
|
gathered = asyncio.gather(*pending)
|
|
|
|
try:
|
|
|
|
gathered.cancel()
|
|
|
|
self.loop.run_until_complete(gathered)
|
|
|
|
gathered.exception()
|
|
|
|
except: # Can be ignored
|
|
|
|
pass
|
|
|
|
|
|
|
|
def run(self):
|
|
|
|
try:
|
2018-06-28 07:33:11 +02:00
|
|
|
self.loop.run_until_complete(self.start_cleanup())
|
2018-06-28 07:29:52 +02:00
|
|
|
except Exception as e:
|
|
|
|
print("Error!", e)
|
2017-06-25 00:02:34 +02:00
|
|
|
finally:
|
|
|
|
try:
|
|
|
|
self._cleanup()
|
|
|
|
except Exception as e:
|
|
|
|
print("Error in cleanup:", e)
|
|
|
|
self.loop.close()
|
|
|
|
|
2018-06-28 07:33:11 +02:00
|
|
|
async def start_cleanup(self):
|
2017-06-25 00:02:34 +02:00
|
|
|
print('Titan [DiscordBot] [UTILITY: Cleanup database messages]')
|
|
|
|
print('------')
|
|
|
|
|
|
|
|
try:
|
2018-06-25 08:56:33 +02:00
|
|
|
self.database.connect(config["database-uri"])
|
2017-06-25 00:02:34 +02:00
|
|
|
except Exception:
|
|
|
|
self.logger.error("Unable to connect to specified database!")
|
|
|
|
traceback.print_exc()
|
|
|
|
return
|
|
|
|
|
|
|
|
print("working on this...")
|
2018-06-25 08:56:33 +02:00
|
|
|
with self.database.get_session() as session:
|
|
|
|
guilds = session.query(Guilds).all()
|
2018-06-25 09:37:40 +02:00
|
|
|
guilds_new = []
|
2018-06-25 08:56:33 +02:00
|
|
|
count = 0
|
|
|
|
for guild in guilds:
|
2018-06-25 09:37:40 +02:00
|
|
|
guilds_new.append(guild)
|
|
|
|
for guild in guilds_new:
|
2018-06-25 08:56:33 +02:00
|
|
|
count += 1
|
|
|
|
self.logger.info("[{}] snowflake-{} name-{}".format(count, guild.guild_id, guild.name))
|
|
|
|
try:
|
|
|
|
channelsjson = json.loads(guild.channels)
|
|
|
|
except:
|
|
|
|
continue
|
|
|
|
active_channels = []
|
|
|
|
for channel in channelsjson:
|
|
|
|
chanid = channel["id"]
|
|
|
|
active_channels.append(chanid)
|
|
|
|
keep_these = session.query(Messages.message_id).filter(Messages.channel_id == chanid).order_by(Messages.timestamp.desc()).limit(50)
|
|
|
|
d = session.query(Messages).filter(Messages.channel_id == chanid, ~Messages.message_id.in_(keep_these)).delete(synchronize_session=False)
|
2017-09-22 03:18:30 +02:00
|
|
|
session.commit()
|
2018-06-25 08:56:33 +02:00
|
|
|
self.logger.info(" --{} [{}]".format(channel["name"], d))
|
|
|
|
d = session.query(Messages).filter(Messages.guild_id == guild.guild_id, ~Messages.channel_id.in_(active_channels)).delete(synchronize_session=False)
|
|
|
|
session.commit()
|
|
|
|
self.logger.info(" INACTIVE {}".format(d))
|
2018-06-25 08:59:47 +02:00
|
|
|
self.logger.info("done!")
|
2017-06-25 00:02:34 +02:00
|
|
|
|
|
|
|
def main():
|
|
|
|
print("Starting...")
|
2018-06-28 07:29:52 +02:00
|
|
|
te = TitanCleanupDB()
|
2017-06-25 00:02:34 +02:00
|
|
|
te.run()
|
|
|
|
gc.collect()
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
2018-03-03 04:59:40 +01:00
|
|
|
main()
|