File size: 11,070 Bytes
0a08a10
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
/**
 * URL Form Handler
 * Handles the submission of the URL form using AJAX to prevent page refreshes
 */

document.addEventListener('DOMContentLoaded', function() {
    // Get form elements
    const urlForm = document.getElementById('urlForm');
    const urlInput = document.getElementById('urlInput');
    const loadingIndicator = document.getElementById('loading');
    const resultsSection = document.getElementById('results-section');
    const errorContainer = document.getElementById('errorContainer');
    const errorMessage = document.getElementById('errorMessage');
    const errorDetails = document.getElementById('errorDetails');
    const dismissErrorBtn = document.getElementById('dismissError');
    
    console.log('URL Form Handler initialized');
    
    // Add event listener to the form
    if (urlForm) {
        console.log('URL form found, adding submit handler');
        
        urlForm.addEventListener('submit', function(e) {
            e.preventDefault();
            console.log('Form submission intercepted');
            
            const url = urlInput.value.trim();
            if (!url) {
                console.log('Empty URL, aborting');
                return;
            }
            
            // Clear any previous errors
            hideError();
            
            // Show loading indicator
            if (loadingIndicator) {
                loadingIndicator.style.display = 'block';
            }
            
            // Hide results section if visible
            if (resultsSection) {
                resultsSection.style.display = 'none';
            }
            
            console.log('Analyzing URL:', url);
            
            // Prepare the request data
            const requestData = {
                url: url
            };
            
            // Make AJAX request
            fetch('/predict', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(requestData)
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! Status: ${response.status}`);
                }
                console.log('Response received:', response.status);
                return response.json().catch(error => {
                    console.error('Error parsing JSON response:', error);
                    throw new Error('Invalid JSON response from server');
                });
            })
            .then(data => {
                console.log('Analysis result:', data);
                
                // Hide loading indicator
                if (loadingIndicator) {
                    loadingIndicator.style.display = 'none';
                }
                
                // Enhanced error detection: Check for error status or missing required fields
                if (data.status === "error" || (!data.score && !data.fraud_score)) {
                    console.error('Server error or incomplete data:', data);
                    let errorMsg = data.message || 'Incomplete data received from server';
                    let detailMsg = data.traceback || 'The response is missing required fields';
                    
                    if (data.error) {
                        errorMsg = data.error;
                    }
                    
                    showError(errorMsg, detailMsg);
                    return;
                }
                
                // Make sure we have the minimum data needed to display results
                try {
                    // Display results using the displayResults function
                    if (window.displayResults && typeof window.displayResults.displayAllResults === 'function') {
                        window.displayResults.displayAllResults(data);
                        
                        // Show the results section
                        if (resultsSection) {
                            resultsSection.style.display = 'block';
                            resultsSection.scrollIntoView({ behavior: 'smooth' });
                        }
                    } else {
                        console.error('displayResults function not available');
                        // Update analyzed URL in the results
                        const analyzedUrlElement = document.getElementById('analyzed-url');
                        if (analyzedUrlElement) {
                            analyzedUrlElement.textContent = url;
                        }
                        
                        // If displayResults is not available, show the results section at minimum
                        if (resultsSection) {
                            resultsSection.style.display = 'block';
                            resultsSection.scrollIntoView({ behavior: 'smooth' });
                        }
                    }
                } catch (displayError) {
                    console.error('Error displaying results:', displayError);
                    showError('Error displaying results', 'An error occurred while rendering the analysis results. Please try again.');
                }
            })
            .catch(error => {
                console.error('Error analyzing URL:', error);
                
                // Hide loading indicator
                if (loadingIndicator) {
                    loadingIndicator.style.display = 'none';
                }
                
                // More detailed error message
                let errorDetails = 'Please check your connection and try again';
                if (error.message) {
                    errorDetails = `Error details: ${error.message}`;
                }
                
                // Show error message
                showError('An error occurred while analyzing the URL', errorDetails);
            });
        });
    } else {
        console.warn('URL form not found in the document');
    }
    
    // Error handling functions
    function showError(message, details = '') {
        if (errorContainer && errorMessage && errorDetails) {
            errorMessage.textContent = message || 'An error occurred';
            errorDetails.textContent = details || 'Please try again or check your connection';
            errorContainer.style.display = 'block';
            
            // Auto-scroll to error message
            errorContainer.scrollIntoView({ behavior: 'smooth' });
        } else {
            console.error('Error message elements not found');
            alert(message || 'An error occurred');
        }
    }
    
    function hideError() {
        if (errorContainer) {
            errorContainer.style.display = 'none';
        }
    }
    
    // Add event listener to dismiss error button
    if (dismissErrorBtn) {
        dismissErrorBtn.addEventListener('click', hideError);
    }
    
    // Add connection test functionality
    // Check for test button in error message
    const testConnectionBtn = document.createElement('button');
    testConnectionBtn.id = 'testConnectionBtn';
    testConnectionBtn.className = 'btn btn-outline-primary btn-sm ms-2';
    testConnectionBtn.textContent = 'Test Connection';
    testConnectionBtn.style.marginLeft = '8px';
    
    // Add it to the error container if it exists
    if (errorContainer && !document.getElementById('testConnectionBtn')) {
        const errorActions = document.createElement('div');
        errorActions.className = 'error-actions';
        errorActions.style.marginTop = '15px';
        errorActions.style.display = 'flex';
        errorActions.style.justifyContent = 'flex-end';
        
        errorActions.appendChild(testConnectionBtn);
        
        if (dismissErrorBtn) {
            dismissErrorBtn.style.marginLeft = '8px';
            errorActions.appendChild(dismissErrorBtn);
        }
        
        errorContainer.appendChild(errorActions);
    }
    
    // Add event listener for connection test
    testConnectionBtn.addEventListener('click', function() {
        console.log('Testing connection to backend...');
        
        // Show a small loading indicator in the button
        testConnectionBtn.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> Testing...';
        testConnectionBtn.disabled = true;
        
        // Test basic connection with simple GET request
        fetch('/debug-connection')
            .then(response => response.json())
            .then(data => {
                console.log('Connection test GET result:', data);
                
                // Now try a POST request with actual payload
                return fetch('/debug-connection', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({test: true, timestamp: new Date().toISOString()})
                });
            })
            .then(response => response.json())
            .then(data => {
                console.log('Connection test POST result:', data);
                
                // Show success message
                testConnectionBtn.innerHTML = '<i class="fas fa-check"></i> Connection OK';
                testConnectionBtn.className = 'btn btn-success btn-sm ms-2';
                
                // Reset after a delay
                setTimeout(() => {
                    testConnectionBtn.textContent = 'Test Connection';
                    testConnectionBtn.className = 'btn btn-outline-primary btn-sm ms-2';
                    testConnectionBtn.disabled = false;
                    
                    // Update error message
                    errorMessage.textContent = 'Connection to server is working';
                    errorDetails.textContent = 'Try submitting your URL again. If the error persists, the issue may be with processing your specific URL.';
                }, 2000);
            })
            .catch(error => {
                console.error('Connection test failed:', error);
                
                // Show error
                testConnectionBtn.innerHTML = '<i class="fas fa-times"></i> Failed';
                testConnectionBtn.className = 'btn btn-danger btn-sm ms-2';
                
                // Reset after a delay
                setTimeout(() => {
                    testConnectionBtn.textContent = 'Test Connection';
                    testConnectionBtn.className = 'btn btn-outline-primary btn-sm ms-2';
                    testConnectionBtn.disabled = false;
                    
                    // Update error message with more details
                    errorMessage.textContent = 'Connection to server failed';
                    errorDetails.textContent = `Error details: ${error.message}. Please check your network connection or server status.`;
                }, 2000);
            });
    });
});