File size: 10,094 Bytes
25f22bf
 
c7d5529
25f22bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6431ea5
25f22bf
 
 
 
6431ea5
25f22bf
 
 
 
 
 
 
2c79ca6
25f22bf
 
2c79ca6
25f22bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3c29fcc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25f22bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
from flask import Blueprint, request, jsonify, current_app
from flask_jwt_extended import jwt_required, get_jwt_identity
from backend.services.content_service import ContentService
import pandas as pd

sources_bp = Blueprint('sources', __name__)

@sources_bp.route('/', methods=['OPTIONS'])
@sources_bp.route('', methods=['OPTIONS'])
def handle_options():
    """Handle OPTIONS requests for preflight CORS checks."""
    return '', 200

@sources_bp.route('/', methods=['GET'])
@sources_bp.route('', methods=['GET'])
@jwt_required()
def get_sources():
    """
    Get all sources for the current user.
    
    Returns:
        JSON: List of sources
    """
    try:
        user_id = get_jwt_identity()
        
        # Check if Supabase client is initialized
        if not hasattr(current_app, 'supabase') or current_app.supabase is None:
            # Add CORS headers to error response
            response_data = jsonify({
                'success': False,
                'message': 'Database connection not initialized'
            })
            response_data.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
            response_data.headers.add('Access-Control-Allow-Credentials', 'true')
            return response_data, 500
        
        # Fetch sources from Supabase
        response = (
            current_app.supabase
            .table("Source")
            .select("*")
            .eq("user_id", user_id)
            .execute()
        )
        
        sources = response.data if response.data else []
        
        # Add CORS headers explicitly
        response_data = jsonify({
            'success': True,
            'sources': sources
        })
        response_data.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
        response_data.headers.add('Access-Control-Allow-Credentials', 'true')
        return response_data, 200
        
    except Exception as e:
        current_app.logger.error(f"Get sources error: {str(e)}")
        # Add CORS headers to error response
        response_data = jsonify({
            'success': False,
            'message': 'An error occurred while fetching sources'
        })
        response_data.headers.add('Access-Control-Allow-Origin', 'http://localhost:3000')
        response_data.headers.add('Access-Control-Allow-Credentials', 'true')
        return response_data, 500

@sources_bp.route('/', methods=['POST'])
@sources_bp.route('', methods=['POST'])
@jwt_required()
def add_source():
    """
    Add a new source for the current user.
    
    Request Body:
        source (str): Source URL
        
    Returns:
        JSON: Add source result
    """
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        # Validate required fields
        if not data or 'source' not in data:
            return jsonify({
                'success': False,
                'message': 'Source URL is required'
            }), 400
        
        source_url = data['source']
        
        # Use content service to add source
        try:
            content_service = ContentService()
            result = content_service.add_rss_source(source_url, user_id)
            
            return jsonify({
                'success': True,
                'message': result
            }), 201
        except Exception as e:
            # If content service fails, just store in database directly
            current_app.logger.warning(f"Content service failed, storing in database directly: {str(e)}")
            
            # Store source directly in Supabase
            # Corrected column name from 'url' to 'source' to match the database schema
            response = (
                current_app.supabase
                .table("Source")
                .insert({
                    "source": source_url, # Changed 'url' to 'source'
                    "user_id": user_id,
                    "created_at": "now()"
                })
                .execute()
            )
            
            if response.data:
                # Return the newly created source data
                return jsonify({
                    'success': True,
                    'source': response.data[0]  # Return the first (and should be only) created source
                }), 201
            else:
                raise Exception("Failed to store source in database")
        
    except Exception as e:
        current_app.logger.error(f"Add source error: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'An error occurred while adding source: {str(e)}'
        }), 500

@sources_bp.route('/<source_id>', methods=['OPTIONS'])
def handle_source_options(source_id):
    """Handle OPTIONS requests for preflight CORS checks for specific source."""
    return '', 200

@sources_bp.route('/keyword-analysis', methods=['OPTIONS'])
def handle_keyword_analysis_options():
    """Handle OPTIONS requests for preflight CORS checks for keyword analysis."""
    return '', 200


@sources_bp.route('/keyword-analysis', methods=['POST'])
@jwt_required()
def analyze_keyword():
    """
    Analyze keyword frequency in RSS feeds and posts.
    
    Request Body:
        keyword (str): The keyword to analyze
        date_range (str): The date range to analyze ('daily', 'weekly', 'monthly'), default is 'monthly'
        
    Returns:
        JSON: Keyword frequency analysis data
    """
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        # Validate required fields
        if not data or 'keyword' not in data:
            return jsonify({
                'success': False,
                'message': 'Keyword is required'
            }), 400
        
        keyword = data['keyword']
        date_range = data.get('date_range', 'monthly')  # Default to monthly
        
        # Validate date_range parameter
        valid_date_ranges = ['daily', 'weekly', 'monthly']
        if date_range not in valid_date_ranges:
            return jsonify({
                'success': False,
                'message': f'Invalid date_range. Must be one of: {valid_date_ranges}'
            }), 400
        
        # Use content service to analyze keyword
        try:
            content_service = ContentService()
            analysis_data = content_service.analyze_keyword_frequency(keyword, user_id, date_range)
            
            return jsonify({
                'success': True,
                'data': analysis_data,
                'keyword': keyword,
                'date_range': date_range
            }), 200
        except Exception as e:
            current_app.logger.error(f"Keyword analysis error: {str(e)}")
            return jsonify({
                'success': False,
                'message': f'An error occurred during keyword analysis: {str(e)}'
            }), 500
        
    except Exception as e:
        current_app.logger.error(f"Analyze keyword error: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'An error occurred while analyzing keyword: {str(e)}'
        }), 500


@sources_bp.route('/keyword-frequency-pattern', methods=['POST'])
@jwt_required()
def analyze_keyword_frequency_pattern():
    """
    Analyze keyword frequency pattern in RSS feeds and posts.
    Determines if keyword follows a daily, weekly, monthly, or rare pattern based on recency and frequency.
    
    Request Body:
        keyword (str): The keyword to analyze
        
    Returns:
        JSON: Keyword frequency pattern analysis data
    """
    try:
        user_id = get_jwt_identity()
        data = request.get_json()
        
        # Validate required fields
        if not data or 'keyword' not in data:
            return jsonify({
                'success': False,
                'message': 'Keyword is required'
            }), 400
        
        keyword = data['keyword']
        
        # Use content service to analyze keyword frequency pattern
        try:
            content_service = ContentService()
            analysis_result = content_service.analyze_keyword_frequency_pattern(keyword, user_id)
            
            return jsonify({
                'success': True,
                'data': analysis_result,
                'keyword': keyword
            }), 200
        except Exception as e:
            current_app.logger.error(f"Keyword frequency pattern analysis error: {str(e)}")
            return jsonify({
                'success': False,
                'message': f'An error occurred during keyword frequency pattern analysis: {str(e)}'
            }), 500
        
    except Exception as e:
        current_app.logger.error(f"Analyze keyword frequency pattern error: {str(e)}")
        return jsonify({
            'success': False,
            'message': f'An error occurred while analyzing keyword frequency pattern: {str(e)}'
        }), 500


@sources_bp.route('/<source_id>', methods=['DELETE'])
@jwt_required()
def delete_source(source_id):
    """
    Delete a source.
    
    Path Parameters:
        source_id (str): Source ID
        
    Returns:
        JSON: Delete source result
    """
    try:
        user_id = get_jwt_identity()
        
        # Delete source from Supabase
        response = (
            current_app.supabase
            .table("Source")
            .delete()
            .eq("id", source_id)
            .eq("user_id", user_id)
            .execute()
        )
        
        if response.data:
            return jsonify({
                'success': True,
                'message': 'Source deleted successfully'
            }), 200
        else:
            return jsonify({
                'success': False,
                'message': 'Source not found or unauthorized'
            }), 404
        
    except Exception as e:
        current_app.logger.error(f"Delete source error: {str(e)}")
        return jsonify({
            'success': False,
            'message': 'An error occurred while deleting source'
        }), 500