imap-archiver/server.py

64 lines
2.0 KiB
Python

import json
import sqlite3
from datetime import datetime
from pathlib import Path
import magic
from flask import Flask, render_template, send_from_directory
app = Flask(__name__)
def get_db_connection():
conn = sqlite3.connect('emails.db')
conn.row_factory = sqlite3.Row
return conn
def dict_from_row(row):
return dict(zip(row.keys(), row))
@app.route('/')
def index():
conn = get_db_connection()
folders = conn.execute('SELECT name, table_name FROM folders_mapping').fetchall()
syncs = conn.execute('SELECT * FROM syncs ORDER BY timestamp DESC').fetchall()
conn.close()
syncs = [dict_from_row(sync) for sync in syncs]
for sync in syncs:
sync['timestamp'] = datetime.fromtimestamp(sync['timestamp']).strftime('%Y-%m-%d %H:%M:%S')
return render_template('index.html', folders=folders, syncs=syncs)
@app.route('/folder/<table_name>')
def folder(table_name):
conn = get_db_connection()
emails = conn.execute(f'SELECT * FROM {table_name} ORDER BY timestamp DESC').fetchall()
conn.close()
emails = [dict_from_row(email) for email in emails]
for email in emails:
email['timestamp'] = datetime.fromtimestamp(email['timestamp']).strftime('%Y-%m-%d %H:%M:%S')
return render_template('folder.html', emails=emails, table_name=table_name)
@app.route('/email/<table_name>/<id>')
def email(table_name, id):
conn = get_db_connection()
email = conn.execute(f'SELECT * FROM {table_name} WHERE id = ?', (id,)).fetchone()
conn.close()
email = dict_from_row(email)
email['timestamp'] = datetime.fromtimestamp(email['timestamp']).strftime('%Y-%m-%d %H:%M:%S')
attachments = json.loads(email['attachments'])
return render_template('email.html', email=email, attachments=attachments)
@app.route('/attachments/<path:filename>')
def download_file(filename):
mimetype = magic.from_file(str(Path('attachments', filename)), mime=True)
return send_from_directory('attachments', filename, mimetype=mimetype)
if __name__ == '__main__':
app.run(host='0.0.0.0', debug=True)