refactors
This commit is contained in:
@@ -0,0 +1,134 @@
|
||||
"""
|
||||
Sync Metadata Service
|
||||
Fetches WordPress site structure (post types, taxonomies, counts) without publishing content
|
||||
"""
|
||||
import logging
|
||||
import requests
|
||||
from typing import Dict, Any
|
||||
from django.utils import timezone
|
||||
|
||||
from igny8_core.business.integration.models import SiteIntegration
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SyncMetadataService:
|
||||
"""
|
||||
Service for syncing WordPress site metadata (counts only, no content publishing)
|
||||
"""
|
||||
|
||||
def sync_wordpress_structure(
|
||||
self,
|
||||
integration: SiteIntegration
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Fetch WordPress site structure (post types, taxonomies, counts).
|
||||
Does NOT publish or sync any content.
|
||||
|
||||
Args:
|
||||
integration: SiteIntegration instance
|
||||
|
||||
Returns:
|
||||
dict: {
|
||||
'success': True/False,
|
||||
'post_types': {...},
|
||||
'taxonomies': {...},
|
||||
'message': '...'
|
||||
}
|
||||
"""
|
||||
try:
|
||||
# Get WordPress site URL and API key
|
||||
site_url = integration.config_json.get('site_url', '')
|
||||
credentials = integration.get_credentials()
|
||||
api_key = credentials.get('api_key', '')
|
||||
|
||||
if not site_url:
|
||||
return {
|
||||
'success': False,
|
||||
'error': 'Missing site_url in integration config'
|
||||
}
|
||||
|
||||
if not api_key:
|
||||
return {
|
||||
'success': False,
|
||||
'error': 'Missing api_key in integration credentials'
|
||||
}
|
||||
|
||||
# Call WordPress metadata endpoint
|
||||
metadata_url = f"{site_url}/wp-json/igny8/v1/site-metadata/"
|
||||
headers = {
|
||||
'X-IGNY8-API-Key': api_key,
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
|
||||
logger.info(f"[SyncMetadataService] Fetching metadata from: {metadata_url}")
|
||||
|
||||
response = requests.get(
|
||||
metadata_url,
|
||||
headers=headers,
|
||||
timeout=30
|
||||
)
|
||||
|
||||
if response.status_code != 200:
|
||||
logger.error(f"[SyncMetadataService] WordPress returned {response.status_code}: {response.text[:500]}")
|
||||
return {
|
||||
'success': False,
|
||||
'error': f'WordPress API error: {response.status_code}',
|
||||
'details': response.text[:500]
|
||||
}
|
||||
|
||||
# Parse response
|
||||
data = response.json()
|
||||
|
||||
if not data.get('success'):
|
||||
return {
|
||||
'success': False,
|
||||
'error': data.get('error', 'Unknown error'),
|
||||
'message': data.get('message', '')
|
||||
}
|
||||
|
||||
metadata = data.get('data', {})
|
||||
|
||||
# Update integration last sync time
|
||||
integration.last_sync_at = timezone.now()
|
||||
integration.sync_status = 'success'
|
||||
integration.save(update_fields=['last_sync_at', 'sync_status'])
|
||||
|
||||
logger.info(f"[SyncMetadataService] Successfully fetched metadata:")
|
||||
logger.info(f" - Post types: {len(metadata.get('post_types', {}))}")
|
||||
logger.info(f" - Taxonomies: {len(metadata.get('taxonomies', {}))}")
|
||||
|
||||
return {
|
||||
'success': True,
|
||||
'post_types': metadata.get('post_types', {}),
|
||||
'taxonomies': metadata.get('taxonomies', {}),
|
||||
'plugin_connection_enabled': metadata.get('plugin_connection_enabled', False),
|
||||
'two_way_sync_enabled': metadata.get('two_way_sync_enabled', False),
|
||||
'message': 'WordPress site structure synced successfully',
|
||||
'last_sync_at': integration.last_sync_at.isoformat()
|
||||
}
|
||||
|
||||
except requests.exceptions.Timeout:
|
||||
logger.error(f"[SyncMetadataService] Timeout connecting to WordPress")
|
||||
integration.sync_status = 'failed'
|
||||
integration.save(update_fields=['sync_status'])
|
||||
return {
|
||||
'success': False,
|
||||
'error': 'Timeout connecting to WordPress (30s)'
|
||||
}
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error(f"[SyncMetadataService] Request error: {str(e)}")
|
||||
integration.sync_status = 'failed'
|
||||
integration.save(update_fields=['sync_status'])
|
||||
return {
|
||||
'success': False,
|
||||
'error': f'Connection error: {str(e)}'
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"[SyncMetadataService] Error syncing metadata: {str(e)}", exc_info=True)
|
||||
integration.sync_status = 'failed'
|
||||
integration.save(update_fields=['sync_status'])
|
||||
return {
|
||||
'success': False,
|
||||
'error': str(e)
|
||||
}
|
||||
@@ -223,17 +223,24 @@ class IntegrationViewSet(SiteSectorModelViewSet):
|
||||
|
||||
Request body:
|
||||
{
|
||||
"direction": "both", # 'both', 'to_external', 'from_external'
|
||||
"direction": "metadata", # 'metadata', 'both', 'to_external', 'from_external'
|
||||
"content_types": ["blog_post", "page"] # Optional
|
||||
}
|
||||
"""
|
||||
integration = self.get_object()
|
||||
|
||||
direction = request.data.get('direction', 'both')
|
||||
direction = request.data.get('direction', 'metadata')
|
||||
content_types = request.data.get('content_types')
|
||||
|
||||
sync_service = SyncService()
|
||||
result = sync_service.sync(integration, direction=direction, content_types=content_types)
|
||||
# Handle metadata-only sync (for "Sync Now" button)
|
||||
if direction == 'metadata':
|
||||
from igny8_core.business.integration.services.sync_metadata_service import SyncMetadataService
|
||||
metadata_service = SyncMetadataService()
|
||||
result = metadata_service.sync_wordpress_structure(integration)
|
||||
else:
|
||||
# Full content sync (legacy behavior)
|
||||
sync_service = SyncService()
|
||||
result = sync_service.sync(integration, direction=direction, content_types=content_types)
|
||||
|
||||
response_status = status.HTTP_200_OK if result.get('success') else status.HTTP_400_BAD_REQUEST
|
||||
return success_response(result, request=request, status_code=response_status)
|
||||
|
||||
@@ -151,9 +151,10 @@ def wordpress_status_webhook(request):
|
||||
if post_url:
|
||||
content.external_url = post_url
|
||||
|
||||
# Only update IGNY8 status if WordPress status changed from draft to publish
|
||||
if post_status == 'publish' and old_status != 'published':
|
||||
content.status = 'published'
|
||||
# FIXED: Always update status when WordPress status differs
|
||||
if content.status != igny8_status:
|
||||
content.status = igny8_status
|
||||
logger.info(f"[wordpress_status_webhook] Status updated: {old_status} → {content.status}")
|
||||
|
||||
# Update WordPress status in metadata
|
||||
if not content.metadata:
|
||||
|
||||
Reference in New Issue
Block a user