diff options
| -rw-r--r-- | src/discord_image_bridge/utils.py | 20 |
1 files changed, 16 insertions, 4 deletions
diff --git a/src/discord_image_bridge/utils.py b/src/discord_image_bridge/utils.py index 55a2b14..d24ce58 100644 --- a/src/discord_image_bridge/utils.py +++ b/src/discord_image_bridge/utils.py @@ -21,13 +21,21 @@ def download_and_cache(url, filename): fname=os.path.join(hash[:2],hash) with open(fname,'wb') as fd: fd.write(resp.content) + size=fd.tell() + + with _values.dbpool.get_connection() as conn, conn.cursor() as cur: + cur.execute("INSERT INTO cache VALUES (?,?,?)",(hash, size, int(time()))) + conn.commit() + return hash, fname + except FileExistsError: - return hash, fname + pass except OSError as e: cherrypy.log("Error writing "+filename+" to disk: "+repr(e)) return None, None + def download_uncached(channel, msgid, attachmentid): status,data=discord.channel_message_get(channel_id=channel, message_id=msgid) for attachment in data["attachments"]: @@ -36,16 +44,20 @@ def download_uncached(channel, msgid, attachmentid): return (None, None) def clear_cache(): - ttl=os.getenv("BRIDGE_CACHE_TIME",3600*24*7) + ttl=int(os.getenv("BRIDGE_CACHE_TIME",3600*24*7)) cherrypy.log("Clearing cache") c=0 + before=int(time())-ttl with _values.dbpool.get_connection() as conn, conn.cursor() as cur: - cur.execute("SELECT hash FROM cache WHERE fetched<?",(int(time())-ttl)) - for (hash) in cur: + cur.execute("SELECT hash FROM cache WHERE fetched<?",(before,)) + for (hash,) in cur: + print(hash) path=os.path.join(hash[:2],hash) if os.path.exists(path): c+=1 os.remove(path) + cur.execute("DELETE FROM cache WHERE fetched<?",(before,)) + conn.commit() cherrypy.log("%d files removed"%c) def on_ready(plugin:discord.DiscordWsManager, client:discord.DiscordWsClient): |
