fix(social-audit): Use SocialMediaAuditor for comprehensive audit
- Import and use SocialMediaAuditor from scripts/social_media_audit.py - Audit now scans website HTML for social media links - Discovers profiles via Brave Search API (if configured) - Fetches Google Business Profile data via Google Places API - Saves discovered profiles to database Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
parent
cadf91b481
commit
deed279521
119
app.py
119
app.py
@ -4166,8 +4166,11 @@ def api_social_audit_trigger():
|
||||
"""
|
||||
API: Trigger Social Media audit for a company.
|
||||
|
||||
This endpoint verifies social media profile URLs and updates their status.
|
||||
It checks if URLs are valid and accessible.
|
||||
This endpoint performs a comprehensive social media audit:
|
||||
- Scans company website for social media links
|
||||
- Searches for profiles via Brave Search API (if configured)
|
||||
- Fetches Google Business Profile data
|
||||
- Updates database with discovered profiles
|
||||
|
||||
Request JSON body:
|
||||
- company_id: Company ID (integer) OR
|
||||
@ -4179,9 +4182,22 @@ def api_social_audit_trigger():
|
||||
|
||||
Rate limited to 10 requests per hour per user.
|
||||
"""
|
||||
import requests as http_requests
|
||||
# Import the SocialMediaAuditor from scripts
|
||||
try:
|
||||
import sys
|
||||
from pathlib import Path
|
||||
scripts_dir = Path(__file__).parent / 'scripts'
|
||||
if str(scripts_dir) not in sys.path:
|
||||
sys.path.insert(0, str(scripts_dir))
|
||||
from social_media_audit import SocialMediaAuditor
|
||||
except ImportError as e:
|
||||
logger.error(f"Failed to import SocialMediaAuditor: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Usługa audytu Social Media jest niedostępna. Sprawdź konfigurację serwera.'
|
||||
}), 503
|
||||
|
||||
# Admin or company owner check
|
||||
# Parse request data
|
||||
data = request.get_json()
|
||||
if not data:
|
||||
return jsonify({
|
||||
@ -4222,74 +4238,67 @@ def api_social_audit_trigger():
|
||||
|
||||
logger.info(f"Social Media audit triggered by {current_user.email} for company: {company.name} (ID: {company.id})")
|
||||
|
||||
# Get existing social media profiles
|
||||
profiles = db.query(CompanySocialMedia).filter(
|
||||
CompanySocialMedia.company_id == company.id
|
||||
).all()
|
||||
# Prepare company dict for auditor
|
||||
company_dict = {
|
||||
'id': company.id,
|
||||
'name': company.name,
|
||||
'slug': company.slug,
|
||||
'website': company.website,
|
||||
'address_city': company.address_city or 'Wejherowo'
|
||||
}
|
||||
|
||||
verified_count = 0
|
||||
errors = []
|
||||
|
||||
# Verify each profile URL
|
||||
for profile in profiles:
|
||||
# Initialize auditor and run audit
|
||||
try:
|
||||
response = http_requests.head(
|
||||
profile.url,
|
||||
timeout=10,
|
||||
allow_redirects=True,
|
||||
headers={'User-Agent': 'Mozilla/5.0 (compatible; NordaBizBot/1.0)'}
|
||||
)
|
||||
auditor = SocialMediaAuditor()
|
||||
audit_result = auditor.audit_company(company_dict)
|
||||
|
||||
if response.status_code == 200:
|
||||
profile.is_valid = True
|
||||
profile.check_status = 'ok'
|
||||
verified_count += 1
|
||||
elif response.status_code in [301, 302, 303, 307, 308]:
|
||||
profile.is_valid = True
|
||||
profile.check_status = 'redirect'
|
||||
verified_count += 1
|
||||
elif response.status_code == 404:
|
||||
profile.is_valid = False
|
||||
profile.check_status = '404'
|
||||
else:
|
||||
profile.is_valid = True # Assume valid if we get any response
|
||||
profile.check_status = f'http_{response.status_code}'
|
||||
verified_count += 1
|
||||
# Check for errors
|
||||
if audit_result.get('errors') and not audit_result.get('social_media') and not audit_result.get('website'):
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Audyt nie powiódł się: {", ".join(audit_result["errors"][:3])}',
|
||||
'company_id': company.id,
|
||||
'company_name': company.name
|
||||
}), 422
|
||||
|
||||
profile.last_checked_at = datetime.now()
|
||||
# Save result to database
|
||||
saved = auditor.save_audit_result(audit_result)
|
||||
|
||||
except http_requests.exceptions.Timeout:
|
||||
profile.check_status = 'timeout'
|
||||
profile.last_checked_at = datetime.now()
|
||||
errors.append(f'{profile.platform}: timeout')
|
||||
except http_requests.exceptions.ConnectionError:
|
||||
profile.check_status = 'connection_error'
|
||||
profile.last_checked_at = datetime.now()
|
||||
errors.append(f'{profile.platform}: connection error')
|
||||
except Exception as e:
|
||||
profile.check_status = 'error'
|
||||
profile.last_checked_at = datetime.now()
|
||||
errors.append(f'{profile.platform}: {str(e)[:50]}')
|
||||
if not saved:
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': 'Audyt został wykonany, ale nie udało się zapisać wyników do bazy danych.',
|
||||
'company_id': company.id,
|
||||
'company_name': company.name
|
||||
}), 500
|
||||
|
||||
db.commit()
|
||||
# Get count of social media profiles found
|
||||
social_media_found = audit_result.get('social_media', {})
|
||||
platforms_count = len(social_media_found)
|
||||
|
||||
# Calculate score
|
||||
all_platforms = ['facebook', 'instagram', 'linkedin', 'youtube', 'twitter', 'tiktok']
|
||||
profiles_dict = {p.platform: p for p in profiles}
|
||||
platforms_with_profiles = len([p for p in all_platforms if p in profiles_dict])
|
||||
score = int((platforms_with_profiles / len(all_platforms)) * 100)
|
||||
score = int((platforms_count / len(all_platforms)) * 100)
|
||||
|
||||
return jsonify({
|
||||
'success': True,
|
||||
'message': f'Audyt Social Media zakończony. Zweryfikowano {verified_count} z {len(profiles)} profili.',
|
||||
'message': f'Audyt Social Media zakończony. Znaleziono {platforms_count} profili.',
|
||||
'company_id': company.id,
|
||||
'company_name': company.name,
|
||||
'profiles_count': len(profiles),
|
||||
'verified_count': verified_count,
|
||||
'profiles_found': platforms_count,
|
||||
'platforms': list(social_media_found.keys()),
|
||||
'score': score,
|
||||
'errors': errors if errors else None
|
||||
'google_reviews': audit_result.get('google_reviews', {}),
|
||||
'errors': audit_result.get('errors') if audit_result.get('errors') else None
|
||||
}), 200
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Social Media audit error for company {company.id}: {e}")
|
||||
return jsonify({
|
||||
'success': False,
|
||||
'error': f'Błąd podczas audytu: {str(e)}'
|
||||
}), 500
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Social Media audit error for company {slug or company_id}: {e}")
|
||||
db.rollback()
|
||||
|
||||
Loading…
Reference in New Issue
Block a user