aboutsummarybugs & patchesrefslogtreecommitdiffstats
path: root/src/discord_image_bridge
diff options
context:
space:
mode:
Diffstat (limited to 'src/discord_image_bridge')
-rw-r--r--src/discord_image_bridge/__init__.py59
1 files changed, 59 insertions, 0 deletions
diff --git a/src/discord_image_bridge/__init__.py b/src/discord_image_bridge/__init__.py
index 6372865..eb95623 100644
--- a/src/discord_image_bridge/__init__.py
+++ b/src/discord_image_bridge/__init__.py
@@ -6,6 +6,10 @@ if not os.path.isdir(dir):
os.chdir(dir)
print(os.getcwd())
+from logging import WARNING
+import magic
+from urllib.parse import quote
+
import cherrypy
from .dbpool import DBPoolManager
@@ -14,6 +18,61 @@ from .discord import DiscordWsManager
class Root(object):
def __init__(self,dbpool:DBPoolManager):
self.dbpool=dbpool
+
+ @cherrypy.expose
+ def default(self, *args, **kwargs):
+ if len(args)<2:
+ cherrypy.response.status=400
+ return "Not enough arguments. Please provide seq and filename."
+
+ seq=args[0]
+ if not seq.isdigit():
+ cherrypy.response.status=400
+ return "Seq is not a valid int."
+ seq=int(seq)
+
+ fname=args[1]
+
+ with self.dbpool.get_connection() as conn, conn.cursor() as cur:
+ cur.execute("SELECT hash, channel, message, id FROM attachments WHERE seq=? AND filename=?",(seq,fname))
+ match=cur.fetchone()
+ if not match:
+ cherrypy.response.status=404
+ return "Seq/filename combination not found."
+
+ hash=match[0]
+ osname=os.path.join(hash[:2],hash)
+ if not os.path.isfile(osname):
+ from . import utils
+ ohash, realname=utils.download_uncached(*match[1:4])
+ if not fname==realname:
+ cherrypy.log(
+ "!! Filename changed! We know it as %s, discord knows it as %s !!"%(fname, realname),
+ severity=WARNING
+ )
+ if not hash==ohash:
+ cherrypy.log("Wrong hash! Expected %s, got %s"%(hash,ohash))
+ cherrypy.log("Fname=%s"%fname)
+ cherrypy.response.status=500
+ return "Got wrong content hash, not serving for the sake of security"
+
+ fd=open(osname, 'rb')
+ cherrypy.response.headers["Content-Type"]=magic.from_descriptor(fd.fileno(), mime=True)
+ fd.seek(0)
+ return fd
+
+ @cherrypy.expose
+ def get_url(self, attachment_id:int):
+ with self.dbpool.get_connection() as conn, conn.cursor() as cur:
+ cur.execute("SELECT seq, filename FROM attachments WHERE id=?",(attachment_id,))
+ data=cur.fetchone()
+ if not data:
+ cherrypy.response.status=404
+ return
+ domain=cherrypy.request.base
+ url=domain+"/"+str(data[0])+'/'+quote(data[1],safe='')
+ return url
+
@cherrypy.expose
def index(self):