Add sum Items, clean UP
This commit is contained in:
@@ -0,0 +1,135 @@
|
||||
import sys
|
||||
import socket
|
||||
import subprocess
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
import smtplib
|
||||
import os
|
||||
from email.message import EmailMessage
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
# Define server details
|
||||
host = "front"
|
||||
port = 993
|
||||
|
||||
# Function to send an email notification
|
||||
def send_email(subject, body, to_email):
|
||||
smtp_server = os.getenv('SMTP_SERVER')
|
||||
smtp_port = int(os.getenv('SMTP_PORT', 587))
|
||||
smtp_user = os.getenv('SMTP_USER')
|
||||
smtp_password = os.getenv('SMTP_PASSWORD')
|
||||
from_email = os.getenv('FROM_EMAIL')
|
||||
|
||||
msg = EmailMessage()
|
||||
msg.set_content(body)
|
||||
msg['Subject'] = subject
|
||||
msg['From'] = from_email
|
||||
msg['To'] = to_email
|
||||
|
||||
try:
|
||||
with smtplib.SMTP(smtp_server, smtp_port) as server:
|
||||
server.starttls()
|
||||
server.login(smtp_user, smtp_password)
|
||||
server.send_message(msg)
|
||||
print(f"Error notification sent to {to_email}")
|
||||
except Exception as e:
|
||||
print(f"Failed to send email: {e}")
|
||||
|
||||
# Check if mail server is active
|
||||
try:
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(1)
|
||||
result = sock.connect_ex((host, port))
|
||||
if result != 0:
|
||||
print(f"Fehler beim Verbinden zu {host} auf Port {port}") # --- E-Mail senden
|
||||
except Exception as e:
|
||||
print(f"Fehler beim Verbinden zu {host} auf Port {port}: {e}") # --- E-Mail senden
|
||||
finally:
|
||||
sock.close()
|
||||
|
||||
# Prepare SQLite database connection
|
||||
db_path = "imapsync_results.db"
|
||||
conn = sqlite3.connect(db_path)
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Create tables if not exists
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS sync_results (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
email TEXT,
|
||||
messages_transferred INTEGER,
|
||||
date TEXT
|
||||
)
|
||||
''')
|
||||
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
email TEXT UNIQUE,
|
||||
password TEXT,
|
||||
domain TEXT
|
||||
)
|
||||
''')
|
||||
|
||||
# Fetch user data from the SQLite database
|
||||
cursor.execute("SELECT email, password, domain FROM users")
|
||||
users = cursor.fetchall()
|
||||
|
||||
if not users:
|
||||
print("No users found in the database.")
|
||||
sys.exit(1)
|
||||
|
||||
# Process each user
|
||||
for user in users:
|
||||
username, password, domain = user
|
||||
local_part = username.split('@')[0]
|
||||
|
||||
# Command for imapsync
|
||||
command = [
|
||||
"imapsync",
|
||||
"--host1", domain,
|
||||
"--user1", username,
|
||||
"--password1", password,
|
||||
"--host2", "180.1.1.164",
|
||||
"--user2", "archiv@archiv.trendsetzer.eu",
|
||||
"--password2", "pass",
|
||||
"--subfolder2", f"{local_part}",
|
||||
"--regextrans2", "s/^(.*)$/\\1/",
|
||||
"--nolog"
|
||||
]
|
||||
|
||||
# Run the command and capture the output
|
||||
try:
|
||||
result = subprocess.run(command, capture_output=True, text=True)
|
||||
output = result.stdout
|
||||
|
||||
# Check for EXIT_AUTHENTICATION_FAILURE_USER error
|
||||
if "EXIT_AUTHENTICATION_FAILURE_USER" in output:
|
||||
subject = f"Authentication Failure for {username}"
|
||||
body = f"An authentication failure occurred for user {username} during IMAP sync."
|
||||
send_email(subject, body, os.getenv('TO_EMAIL'))
|
||||
|
||||
# Find and extract the "Messages transferred" line
|
||||
for line in output.splitlines():
|
||||
if "Messages transferred" in line:
|
||||
transferred_messages = line.split(":")[-1].strip()
|
||||
transferred_count = int(transferred_messages)
|
||||
current_date = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# Insert result into SQLite database
|
||||
cursor.execute('''
|
||||
INSERT INTO sync_results (email, messages_transferred, date)
|
||||
VALUES (?, ?, ?)
|
||||
''', (username, transferred_count, current_date))
|
||||
conn.commit()
|
||||
print(f"Data inserted for {username}: {transferred_count} messages on {current_date}")
|
||||
break
|
||||
else:
|
||||
print(f"No 'Messages transferred' line found for {username}.")
|
||||
except Exception as e:
|
||||
print(f"Error running imapsync for {username}: {e}")
|
||||
|
||||
# Close database connection
|
||||
conn.close()
|
||||
@@ -0,0 +1,3 @@
|
||||
requests
|
||||
pandas
|
||||
streamlit
|
||||
@@ -0,0 +1,122 @@
|
||||
import streamlit as st
|
||||
import sqlite3
|
||||
import pandas as pd
|
||||
|
||||
def fetch_data_from_db(db_path, table_name):
|
||||
conn = sqlite3.connect(db_path)
|
||||
query = f"SELECT * FROM {table_name}"
|
||||
df = pd.read_sql_query(query, conn)
|
||||
conn.close()
|
||||
return df
|
||||
|
||||
def insert_user_into_db(db_path, email, password, domain):
|
||||
conn = sqlite3.connect(db_path)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO users (email, password, domain)
|
||||
VALUES (?, ?, ?)
|
||||
''', (email, password, domain))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def delete_user_from_db(db_path, email):
|
||||
conn = sqlite3.connect(db_path)
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
DELETE FROM users WHERE email = ?
|
||||
''', (email,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def main():
|
||||
st.set_page_config(page_title="Archiv Manager")
|
||||
st.title("IMAPSync Manager")
|
||||
|
||||
db_path = "/app/db/imapsync_results.db"
|
||||
|
||||
# Sidebar for navigation with buttons and unique keys
|
||||
st.sidebar.title("Navigation")
|
||||
add_user = st.sidebar.button("Add User", key="add_user_button")
|
||||
view_users = st.sidebar.button("View Users", key="view_users_button")
|
||||
delete_user = st.sidebar.button("Delete User", key="delete_user_button")
|
||||
st.sidebar.markdown(
|
||||
'<a href="http://180.1.1.164:8000" target="_blank"><button style="background-color: LightGray; color: black; border: none; padding: 8px 16px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin: 4px 2px; cursor: pointer;">View Mails</button></a>',
|
||||
unsafe_allow_html=True
|
||||
)
|
||||
|
||||
# Use session state to keep track of the selected page
|
||||
if 'page' not in st.session_state:
|
||||
st.session_state.page = 'View Users'
|
||||
|
||||
if add_user:
|
||||
st.session_state.page = 'Add User'
|
||||
elif view_users:
|
||||
st.session_state.page = 'View Users'
|
||||
elif delete_user:
|
||||
st.session_state.page = 'Delete User'
|
||||
|
||||
if st.session_state.page == "Add User":
|
||||
st.header("Add a New User")
|
||||
new_email = st.text_input("Email:")
|
||||
new_password = st.text_input("Password:", type="password")
|
||||
new_domain = st.text_input("Domain:")
|
||||
|
||||
if st.button("Add User", key="submit_add_user"):
|
||||
if new_email and new_password and new_domain:
|
||||
insert_user_into_db(db_path, new_email, new_password, new_domain)
|
||||
st.success(f"User {new_email} added successfully!")
|
||||
else:
|
||||
st.error("Please fill in all fields.")
|
||||
|
||||
elif st.session_state.page == "View Users":
|
||||
st.header("IMAPSync Users and Email Transfer Results")
|
||||
|
||||
# Fetch users and email transfer data
|
||||
users_df = fetch_data_from_db(db_path, "users")
|
||||
results_df = fetch_data_from_db(db_path, "sync_results")
|
||||
|
||||
if users_df.empty:
|
||||
st.write("No user data available in the database.")
|
||||
else:
|
||||
emails = users_df['email'].unique().tolist()
|
||||
emails.insert(0, "All")
|
||||
selected_email = st.selectbox("Filter by Email:", options=emails)
|
||||
|
||||
if selected_email == "All":
|
||||
filtered_users_df = users_df
|
||||
else:
|
||||
filtered_users_df = users_df[users_df['email'] == selected_email]
|
||||
|
||||
st.dataframe(filtered_users_df)
|
||||
|
||||
# Display email transfer results if available
|
||||
if not results_df.empty:
|
||||
if selected_email == "All":
|
||||
st.write("Email Transfer Results:")
|
||||
st.dataframe(results_df)
|
||||
else:
|
||||
filtered_results_df = results_df[results_df['email'] == selected_email]
|
||||
if not filtered_results_df.empty:
|
||||
st.write(f"Email Transfer Results for {selected_email}:")
|
||||
st.dataframe(filtered_results_df)
|
||||
else:
|
||||
st.write(f"No transfer data found for {selected_email}.")
|
||||
else:
|
||||
st.write("No email transfer results available.")
|
||||
|
||||
elif st.session_state.page == "Delete User":
|
||||
st.header("Delete a User")
|
||||
|
||||
df = fetch_data_from_db(db_path, "users")
|
||||
|
||||
if df.empty:
|
||||
st.write("No data available in the database.")
|
||||
else:
|
||||
user_to_delete = st.selectbox("Select User to Delete:", df['email'].unique())
|
||||
|
||||
if st.button("Delete User", key="confirm_delete_user"):
|
||||
delete_user_from_db(db_path, user_to_delete)
|
||||
st.success(f"User {user_to_delete} deleted successfully!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user