187 Zeilen
6.2 KiB
Python
187 Zeilen
6.2 KiB
Python
"""
|
|
Export Accounts Use Case - Exportiert Account-Daten in verschiedene Formate
|
|
"""
|
|
|
|
import logging
|
|
import csv
|
|
import json
|
|
from io import StringIO
|
|
from typing import List, Dict, Any, Optional
|
|
from datetime import datetime
|
|
|
|
logger = logging.getLogger("export_accounts_use_case")
|
|
|
|
|
|
class ExportAccountsUseCase:
|
|
"""
|
|
Use Case für Account-Export.
|
|
Exportiert Account-Daten in verschiedene Formate (CSV, JSON).
|
|
"""
|
|
|
|
def __init__(self, db_manager):
|
|
self.db_manager = db_manager
|
|
|
|
def execute(self,
|
|
platform: Optional[str] = None,
|
|
format: str = 'csv',
|
|
include_passwords: bool = True) -> bytes:
|
|
"""
|
|
Exportiert Account-Daten.
|
|
|
|
Args:
|
|
platform: Filter für spezifische Plattform (None = alle)
|
|
format: Export-Format ('csv' oder 'json')
|
|
include_passwords: Ob Passwörter inkludiert werden sollen
|
|
|
|
Returns:
|
|
Exportierte Daten als Bytes
|
|
"""
|
|
# Hole Account-Daten
|
|
if platform and platform.lower() not in ["all", ""]:
|
|
accounts = self.db_manager.get_accounts_by_platform(platform.lower())
|
|
else:
|
|
accounts = self.db_manager.get_all_accounts()
|
|
|
|
if not accounts:
|
|
logger.warning(f"Keine Accounts gefunden für Export (platform: {platform})")
|
|
return b""
|
|
|
|
# Exportiere basierend auf Format
|
|
if format.lower() == 'csv':
|
|
result = self._export_csv(accounts, include_passwords)
|
|
elif format.lower() == 'json':
|
|
result = self._export_json(accounts, include_passwords)
|
|
else:
|
|
raise ValueError(f"Unsupported format: {format}")
|
|
|
|
logger.info(f"Exported {len(accounts)} accounts as {format}")
|
|
return result
|
|
|
|
def _export_csv(self, accounts: List[Dict[str, Any]], include_passwords: bool) -> bytes:
|
|
"""
|
|
Exportiert Accounts als CSV.
|
|
|
|
Args:
|
|
accounts: Liste der Account-Daten
|
|
include_passwords: Ob Passwörter inkludiert werden sollen
|
|
|
|
Returns:
|
|
CSV-Daten als Bytes
|
|
"""
|
|
output = StringIO()
|
|
|
|
# Definiere Header basierend auf Passwort-Einstellung
|
|
headers = [
|
|
'Plattform',
|
|
'Benutzername',
|
|
'E-Mail',
|
|
'Handynummer',
|
|
'Name',
|
|
'Geburtstag',
|
|
'Erstellt am'
|
|
]
|
|
|
|
if include_passwords:
|
|
headers.insert(2, 'Passwort')
|
|
|
|
writer = csv.DictWriter(output, fieldnames=headers)
|
|
writer.writeheader()
|
|
|
|
# Schreibe Account-Daten
|
|
for account in accounts:
|
|
row = {
|
|
'Plattform': account.get('platform', ''),
|
|
'Benutzername': account.get('username', ''),
|
|
'E-Mail': account.get('email', ''),
|
|
'Handynummer': account.get('phone', ''),
|
|
'Name': account.get('full_name', ''),
|
|
'Geburtstag': account.get('birthday', ''),
|
|
'Erstellt am': account.get('created_at', '')
|
|
}
|
|
|
|
if include_passwords:
|
|
row['Passwort'] = account.get('password', '')
|
|
|
|
writer.writerow(row)
|
|
|
|
return output.getvalue().encode('utf-8-sig') # UTF-8 mit BOM für Excel
|
|
|
|
def _export_json(self, accounts: List[Dict[str, Any]], include_passwords: bool) -> bytes:
|
|
"""
|
|
Exportiert Accounts als JSON.
|
|
|
|
Args:
|
|
accounts: Liste der Account-Daten
|
|
include_passwords: Ob Passwörter inkludiert werden sollen
|
|
|
|
Returns:
|
|
JSON-Daten als Bytes
|
|
"""
|
|
export_data = {
|
|
'export_date': datetime.now().isoformat(),
|
|
'account_count': len(accounts),
|
|
'accounts': []
|
|
}
|
|
|
|
for account in accounts:
|
|
account_data = {
|
|
'platform': account.get('platform', ''),
|
|
'username': account.get('username', ''),
|
|
'email': account.get('email', ''),
|
|
'phone': account.get('phone', ''),
|
|
'full_name': account.get('full_name', ''),
|
|
'birthday': account.get('birthday', ''),
|
|
'created_at': account.get('created_at', '')
|
|
}
|
|
|
|
if include_passwords:
|
|
account_data['password'] = account.get('password', '')
|
|
|
|
export_data['accounts'].append(account_data)
|
|
|
|
return json.dumps(export_data, ensure_ascii=False, indent=2).encode('utf-8')
|
|
|
|
def execute_with_accounts(self,
|
|
accounts: List[Dict[str, Any]],
|
|
format: str = 'csv',
|
|
include_passwords: bool = True) -> bytes:
|
|
"""
|
|
Exportiert spezifische Account-Daten.
|
|
|
|
Args:
|
|
accounts: Liste der zu exportierenden Accounts
|
|
format: Export-Format ('csv' oder 'json')
|
|
include_passwords: Ob Passwörter inkludiert werden sollen
|
|
|
|
Returns:
|
|
Exportierte Daten als Bytes
|
|
"""
|
|
if not accounts:
|
|
logger.warning("Keine Accounts zum Export übergeben")
|
|
return b""
|
|
|
|
# Exportiere basierend auf Format
|
|
if format.lower() == 'csv':
|
|
result = self._export_csv(accounts, include_passwords)
|
|
elif format.lower() == 'json':
|
|
result = self._export_json(accounts, include_passwords)
|
|
else:
|
|
raise ValueError(f"Unsupported format: {format}")
|
|
|
|
logger.info(f"Exported {len(accounts)} specific accounts as {format}")
|
|
return result
|
|
|
|
def get_export_filename(self, platform: Optional[str], format: str) -> str:
|
|
"""
|
|
Generiert einen passenden Dateinamen für den Export.
|
|
|
|
Args:
|
|
platform: Plattform-Filter
|
|
format: Export-Format
|
|
|
|
Returns:
|
|
Vorgeschlagener Dateiname
|
|
"""
|
|
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
|
platform_str = platform.lower() if platform else 'alle'
|
|
return f"accounts_{platform_str}_{timestamp}.{format}" |