Module: Web API Details

Tasks

Background task management for long-running operations

CancelToken

Source code in webapi/api/tasks.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class CancelToken:
    def __init__(self):
        """ Thread-safe cancellation token. This basically just has a lock and a status
            indicating whether the job should be cancelled or not. Jobs use this to figure
            out whether the web cancel button has been clicked.
        """
        self._cancelled = False
        self._lock = threading.Lock()

    def cancel(self):
        with self._lock:
            self._cancelled = True

    def is_cancelled(self):
        with self._lock:
            return self._cancelled

__init__()

Thread-safe cancellation token. This basically just has a lock and a status indicating whether the job should be cancelled or not. Jobs use this to figure out whether the web cancel button has been clicked.

Source code in webapi/api/tasks.py
18
19
20
21
22
23
24
def __init__(self):
    """ Thread-safe cancellation token. This basically just has a lock and a status
        indicating whether the job should be cancelled or not. Jobs use this to figure
        out whether the web cancel button has been clicked.
    """
    self._cancelled = False
    self._lock = threading.Lock()

cancel_job(job_id, timeout=10.0)

Cancel a running job

Parameters:

Name Type Description Default
job_id str

ID of the job to cancel

required
timeout float

Maximum time to wait for cancellation (seconds)

10.0

Returns:

Type Description
Dict[str, Any]

Dict with success status and message

Source code in webapi/api/tasks.py
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
def cancel_job(job_id: str, timeout: float = 10.0) -> Dict[str, Any]:
    """
    Cancel a running job

    Args:
        job_id: ID of the job to cancel
        timeout: Maximum time to wait for cancellation (seconds)

    Returns:
        Dict with success status and message
    """
    job = jobs.get(job_id)
    if not job:
        return {'success': False, 'error': 'Job not found'}

    if job['status'] != 'running':
        return {'success': False, 'error': f"Job is not running (status: {job['status']})"}

    # Signal cancellation
    cancel_token = job.get('cancel_token')
    if cancel_token:
        cancel_token.cancel()

    # Wait for thread to finish
    thread = job.get('thread')
    if thread and thread.is_alive():
        thread.join(timeout=timeout)

        if thread.is_alive():
            # Thread didn't stop in time
            return {
                'success': False,
                'error': f'Job did not stop within {timeout} seconds',
                'partial_results': job.get('result')
            }

    # Get partial results from progress
    partial_results = {}
    if job.get('progress_obj'):
        partial_results = job['progress_obj'].get_snapshot()

    return {
        'success': True,
        'message': 'Job cancelled successfully',
        'partial_results': partial_results
    }

get_job_status(job_id)

Get the status of a job

Source code in webapi/api/tasks.py
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
def get_job_status(job_id: str) -> Dict[str, Any]:
    """Get the status of a job"""
    job = jobs.get(job_id)
    if not job:
        return {'status': 'not_found'}

    result = {
        'job_id': job_id,
        'status': job['status'],
        'started_at': job.get('started_at')
    }

    # Add progress if running or complete (for final status)
    if job.get('progress_obj'):
        result['progress'] = job['progress_obj'].get_snapshot()

    # Add result if complete or cancelled
    if job['status'] in ['complete', 'cancelled']:
        result['result'] = job.get('result')

    # Add error if failed
    if job['status'] == 'error':
        result['error'] = job.get('error')

    return result

run_async(func, *args, progress_obj=FetchProgress(), **kwargs)

Run a function asynchronously and return a job ID

Parameters:

Name Type Description Default
func Callable

Function to execute.

required
*args

Positional arguments for the function

()
progress_obj FetchProgress

Optional progress tracking object

FetchProgress()
**kwargs

Keyword arguments for the function

{}

Returns:

Type Description
str

Job ID string

Source code in webapi/api/tasks.py
 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
def run_async(func: Callable, *args,
    progress_obj:FetchProgress=FetchProgress(),
    **kwargs) -> str:
    """
    Run a function asynchronously and return a job ID

    Args:
        func: Function to execute.
        *args: Positional arguments for the function
        progress_obj: Optional progress tracking object
        **kwargs: Keyword arguments for the function

    Returns:
        Job ID string
    """
    job_id = str(uuid4())
    cancel_token = CancelToken()

    jobs[job_id] = {
        'status': 'running',
        'progress_obj': progress_obj,
        'cancel_token': cancel_token,
        'thread': None,
        'result': None,
        'error': None,
        'started_at': datetime.now().isoformat()
    }

    def worker():
        """ The code that a
        """
        try:
            sig = inspect.signature(func)
            params = sig.parameters

            # Build kwargs based on what function accepts
            call_kwargs = dict(kwargs)
            if 'cancel_token' in params:
                call_kwargs['cancel_token'] = cancel_token
            if 'progress' in params and progress_obj is not None:
                call_kwargs['progress'] = progress_obj

            result = func(*args, **call_kwargs)

            # Check if cancelled during execution
            if cancel_token.is_cancelled():
                jobs[job_id]['status'] = 'cancelled'
                jobs[job_id]['result'] = result  # Partial results
            else:
                jobs[job_id]['status'] = 'complete'
                jobs[job_id]['result'] = result

            jobs[job_id]['error'] = None
            jobs[job_id]['started_at'] = jobs[job_id]['started_at']
        except Exception as e:
            jobs[job_id] = {
                'status': 'error',
                'progress_obj': progress_obj,
                'cancel_token': cancel_token,
                'thread': None,
                'result': None,
                'error': str(e),
                'started_at': jobs[job_id]['started_at']
            }

    thread = threading.Thread(target=worker, daemon=True)
    jobs[job_id]['thread'] = thread
    thread.start()

    return job_id

Progress

Progress tracking for long-running fetch operations

FetchProgress

Thread-safe progress tracker for fetch operations

Source code in webapi/api/progress.py
 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
class FetchProgress:
    """Thread-safe progress tracker for fetch operations"""

    def __init__(self, max_toots: int = 2000):
        self.servers_todo = 0
        self.servers_done = 0
        self.servers_fail = 0
        self.total_toots = 0
        self.max_toots = max_toots
        self.current_server: Optional[str] = None
        self.server_status: Dict[str, dict] = {}  # uri -> {'state': str, 'toots': int}
        self._lock = threading.Lock()

    def update(self, todo: int, done: int, fail: int, toots: int, current: Optional[str] = None):
        """Update progress metrics (thread-safe)"""
        with self._lock:
            self.servers_todo = todo
            self.servers_done = done
            self.servers_fail = fail
            self.total_toots = toots
            self.current_server = current

    def start_server(self, uri: str):
        """Mark a server as started (thread-safe)"""
        with self._lock:
            self.server_status[uri] = {'state': 'running', 'toots': 0}

    def update_server_progress(self, uri: str, toot_count: int):
        """Update toot count for a running server (thread-safe)"""
        with self._lock:
            if uri in self.server_status:
                self.server_status[uri]['toots'] = toot_count

    def complete_server(self, uri: str, final_count: int, failed: bool = False):
        """Mark a server as completed or failed (thread-safe)"""
        with self._lock:
            self.server_status[uri] = {
                'state': 'failed' if failed else 'done',
                'toots': final_count if not failed else 0
            }

    def get_snapshot(self) -> dict:
        """Get current progress as a dict (thread-safe)"""
        with self._lock:
            total = self.servers_done + self.servers_fail + self.servers_todo
            completed = self.servers_done + self.servers_fail
            progress_percent = int((completed / total * 100)) if total > 0 else 0

            return {
                'servers_todo': self.servers_todo,
                'servers_done': self.servers_done,
                'servers_fail': self.servers_fail,
                'total_servers': total,
                'completed_servers': completed,
                'progress_percent': progress_percent,
                'total_toots': self.total_toots,
                'max_toots': self.max_toots,
                'current_server': self.current_server,
                'server_status': dict(self.server_status)  # Copy for safety
            }

complete_server(uri, final_count, failed=False)

Mark a server as completed or failed (thread-safe)

Source code in webapi/api/progress.py
42
43
44
45
46
47
48
def complete_server(self, uri: str, final_count: int, failed: bool = False):
    """Mark a server as completed or failed (thread-safe)"""
    with self._lock:
        self.server_status[uri] = {
            'state': 'failed' if failed else 'done',
            'toots': final_count if not failed else 0
        }

get_snapshot()

Get current progress as a dict (thread-safe)

Source code in webapi/api/progress.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def get_snapshot(self) -> dict:
    """Get current progress as a dict (thread-safe)"""
    with self._lock:
        total = self.servers_done + self.servers_fail + self.servers_todo
        completed = self.servers_done + self.servers_fail
        progress_percent = int((completed / total * 100)) if total > 0 else 0

        return {
            'servers_todo': self.servers_todo,
            'servers_done': self.servers_done,
            'servers_fail': self.servers_fail,
            'total_servers': total,
            'completed_servers': completed,
            'progress_percent': progress_percent,
            'total_toots': self.total_toots,
            'max_toots': self.max_toots,
            'current_server': self.current_server,
            'server_status': dict(self.server_status)  # Copy for safety
        }

start_server(uri)

Mark a server as started (thread-safe)

Source code in webapi/api/progress.py
31
32
33
34
def start_server(self, uri: str):
    """Mark a server as started (thread-safe)"""
    with self._lock:
        self.server_status[uri] = {'state': 'running', 'toots': 0}

update(todo, done, fail, toots, current=None)

Update progress metrics (thread-safe)

Source code in webapi/api/progress.py
22
23
24
25
26
27
28
29
def update(self, todo: int, done: int, fail: int, toots: int, current: Optional[str] = None):
    """Update progress metrics (thread-safe)"""
    with self._lock:
        self.servers_todo = todo
        self.servers_done = done
        self.servers_fail = fail
        self.total_toots = toots
        self.current_server = current

update_server_progress(uri, toot_count)

Update toot count for a running server (thread-safe)

Source code in webapi/api/progress.py
36
37
38
39
40
def update_server_progress(self, uri: str, toot_count: int):
    """Update toot count for a running server (thread-safe)"""
    with self._lock:
        if uri in self.server_status:
            self.server_status[uri]['toots'] = toot_count

Routes

API routes for Mastoscore Web API

cancel_fetch_job()

Cancel a running fetch job

Source code in webapi/api/routes.py
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
@api_bp.route('/fetch/cancel', methods=['POST'])
def cancel_fetch_job():
    """Cancel a running fetch job"""
    from .tasks import cancel_job

    data = request.get_json()
    job_id = data.get('job_id') if data else None

    if not job_id:
        return jsonify({'error': 'job_id parameter required'}), 400

    try:
        result = cancel_job(job_id, timeout=10.0)

        if result['success']:
            return jsonify({
                'success': True,
                'job_id': job_id,
                'message': result['message'],
                'partial_results': result.get('partial_results', {})
            }), 200
        else:
            return jsonify({
                'success': False,
                'job_id': job_id,
                'error': result['error'],
                'partial_results': result.get('partial_results', {})
            }), 400

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

check_blog_ready()

Check if blog post has been generated

Source code in webapi/api/routes.py
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
@api_bp.route('/blog/ready', methods=['POST'])
def check_blog_ready():
    """Check if blog post has been generated"""
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')

        blog_file = DATA_DIR / year / month / day / 'index.md'

        if blog_file.exists():
            return jsonify({
                'ready': True,
                'config_file': config_file,
                'blog_file': str(blog_file.relative_to(PROJECT_ROOT)),
                'message': 'Blog post is ready'
            }), 200
        else:
            return jsonify({
                'ready': False,
                'config_file': config_file,
                'message': 'Blog post not found'
            }), 404
    except Exception as e:
        return jsonify({
            'error': str(e)
        }), 500

check_fetch_ready()

Check if fetched data is ready for analysis

Source code in webapi/api/routes.py
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
302
@api_bp.route('/fetch/ready', methods=['POST'])
def check_fetch_ready():
    """Check if fetched data is ready for analysis"""
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        # Read config to get hashtag and date
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        hashtag = config.get('mastoscore', 'hashtag')
        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')

        # Check for data-HASHTAG-fetch.json in data/YYYY/MM/DD/
        data_file = DATA_DIR / year / month / day / f'data-{hashtag}-fetch.json'

        if data_file.exists():
            return jsonify({
                'ready': True,
                'config_file': config_file,
                'data_file': str(data_file.relative_to(PROJECT_ROOT)),
                'message': 'Fetch data is ready'
            }), 200
        else:
            return jsonify({
                'ready': False,
                'config_file': config_file,
                'expected_file': str(data_file.relative_to(PROJECT_ROOT)),
                'message': 'Fetch data not found'
            }), 404

    except Exception as e:
        return jsonify({'error': str(e)}), 500

check_poster_exists()

Check if thumb.jpg exists for the configuration

Source code in webapi/api/routes.py
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
@api_bp.route('/blog/poster', methods=['POST'])
def check_poster_exists():
    """Check if thumb.jpg exists for the configuration"""
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')

        thumb_path = DATA_DIR / year / month / day / 'thumb.jpg'

        if thumb_path.exists():
            return jsonify({
                'exists': True,
                'config_file': config_file,
                'poster_path': str(thumb_path.relative_to(PROJECT_ROOT)),
                'message': 'Poster exists'
            }), 200
        else:
            return jsonify({
                'exists': False,
                'config_file': config_file,
                'message': 'Poster not found'
            }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

create_config(name)

Create new configuration file

Source code in webapi/api/routes.py
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
@api_bp.route('/config/<path:name>', methods=['POST'])
def create_config(name):
    """Create new configuration file"""
    try:
        config_path = PROJECT_ROOT / name

        # Get config data from request
        data = request.get_json()
        if not data or 'config' not in data:
            return jsonify({'error': 'No configuration data provided'}), 400

        overwrite = data.get('overwrite', False)

        if config_path.exists() and not overwrite:
            return jsonify({'error': 'Configuration already exists'}), 409

        # Create parent directories if needed
        config_path.parent.mkdir(parents=True, exist_ok=True)

        # Write config file
        config = ConfigParser()
        for section, values in data['config'].items():
            config.add_section(section)
            for key, value in values.items():
                config.set(section, key, str(value))

        with open(config_path, 'w') as f:
            config.write(f)

        return jsonify({
            'success': True,
            'path': str(config_path.relative_to(PROJECT_ROOT))
        }), 201

    except PermissionError:
        return jsonify({'error': 'Permission denied'}), 403
    except Exception as e:
        return jsonify({'error': str(e)}), 500

delete_config(name)

Delete configuration file

Source code in webapi/api/routes.py
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
@api_bp.route('/config/<path:name>', methods=['DELETE'])
def delete_config(name):
    """Delete configuration file"""
    try:
        config_path = PROJECT_ROOT / name

        if not config_path.exists():
            return jsonify({'error': 'Configuration not found'}), 404

        if not config_path.is_file():
            return jsonify({'error': 'Path is not a file'}), 400

        if not os.access(config_path, os.W_OK):
            return jsonify({'error': 'Permission denied'}), 403

        config_path.unlink()

        return jsonify({'success': True})

    except PermissionError:
        return jsonify({'error': 'Permission denied'}), 403
    except Exception as e:
        return jsonify({'error': str(e)}), 500

get_blog_content()

Get blog post content

Source code in webapi/api/routes.py
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
@api_bp.route('/blog/content', methods=['POST'])
def get_blog_content():
    """Get blog post content"""
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')

        blog_file = DATA_DIR / year / month / day / 'index.md'

        if not blog_file.exists():
            return jsonify({'error': 'Blog post not found'}), 404

        content = blog_file.read_text(encoding='utf-8')
        modified_time = blog_file.stat().st_mtime

        return jsonify({
            'content': content,
            'modified': modified_time,
            'config_file': config_file,
            'blog_file': str(blog_file.relative_to(PROJECT_ROOT))
        }), 200
    except Exception as e:
        return jsonify({
            'error': str(e)
        }), 500

get_blog_posts()

Get posted URLs from posts.json

Source code in webapi/api/routes.py
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
@api_bp.route('/blog/posts', methods=['POST'])
def get_blog_posts():
    """Get posted URLs from posts.json"""
    import logging
    import json

    logger = logging.getLogger(__name__)
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        hashtag = config.get('mastoscore', 'hashtag')
        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')

        posts_file = DATA_DIR / year / month / day / f'data-{hashtag}-posts.json'

        if not posts_file.exists():
            return jsonify({
                'exists': False,
                'config_file': config_file,
                'message': 'Posts not found'
            }), 404

        with open(posts_file, 'r') as f:
            posts_data = json.load(f)

        return jsonify({
            'exists': True,
            'config_file': config_file,
            'posts': posts_data
        }), 200
    except Exception as e:
        logger.error(f"Error getting posts: {e}", exc_info=True)
        return jsonify({'error': str(e)}), 500
        return send_file(thumb_path, mimetype='image/jpeg')
    except Exception as e:
        logger.error(f"Error getting poster image: {e}", exc_info=True)
        return jsonify({'error': str(e)}), 500

get_config(name)

Get specific configuration file

Source code in webapi/api/routes.py
 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
@api_bp.route('/config/<path:name>', methods=['GET'])
def get_config(name):
    """Get specific configuration file"""
    try:
        config_path = PROJECT_ROOT / name

        if not config_path.exists():
            return jsonify({'error': 'Configuration not found'}), 404

        if not config_path.is_file():
            return jsonify({'error': 'Path is not a file'}), 400

        if not os.access(config_path, os.R_OK):
            return jsonify({'error': 'Permission denied'}), 403

        # Read the config file
        config = ConfigParser()
        config.read(config_path)

        # Convert to dict
        config_dict = {}
        for section in config.sections():
            config_dict[section] = dict(config.items(section))

        return jsonify({'config': config_dict})

    except PermissionError:
        return jsonify({'error': 'Permission denied'}), 403
    except Exception as e:
        return jsonify({'error': str(e)}), 500

get_graph_description()

Get generated graph description text

Source code in webapi/api/routes.py
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
@api_bp.route('/graph/description', methods=['POST'])
def get_graph_description():
    """Get generated graph description text"""
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        # Read config to get hashtag and date
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        hashtag = config.get('mastoscore', 'hashtag')
        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')

        # Description file location: data/YYYY/MM/DD/HASHTAG-YYYYMMDD.txt
        filename = f'{hashtag}-{year}{month}{day}.txt'
        desc_file = DATA_DIR / year / month / day / filename

        if not desc_file.exists():
            return jsonify({'error': 'Graph description not found'}), 404

        with open(desc_file, 'r') as f:
            description = f.read()

        return jsonify({
            'description': description,
            'config_file': config_file
        }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

get_graph_image()

Get generated graph image

Source code in webapi/api/routes.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
@api_bp.route('/graph/image', methods=['POST'])
def get_graph_image():
    """Get generated graph image"""
    from flask import send_file
    import logging

    logger = logging.getLogger(__name__)
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        # Read config to get hashtag and date
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        hashtag = config.get('mastoscore', 'hashtag')
        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')

        # Graph file location: data/YYYY/MM/DD/HASHTAG-YYYYMMDD.png
        filename = f'{hashtag}-{year}{month}{day}.png'
        graph_file = DATA_DIR / year / month / day / filename

        if not graph_file.exists():
            return jsonify({'error': 'Graph image not found'}), 404

        return send_file(graph_file, mimetype='image/png')
    except Exception as e:
        logger.error(f"Error getting graph image: {e}", exc_info=True)
        return jsonify({'error': str(e)}), 500

get_job_status_route(job_id)

Get status of a running job

Source code in webapi/api/routes.py
1157
1158
1159
1160
1161
1162
1163
@api_bp.route('/jobs/<job_id>', methods=['GET'])
def get_job_status_route(job_id):
    """Get status of a running job"""
    from .tasks import get_job_status

    status = get_job_status(job_id)
    return jsonify(status)

get_poster_image()

Get poster image file

Source code in webapi/api/routes.py
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
@api_bp.route('/blog/poster/image', methods=['POST'])
def get_poster_image():
    """Get poster image file"""
    from flask import send_file
    import logging

    logger = logging.getLogger(__name__)
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')

        thumb_path = DATA_DIR / year / month / day / 'thumb.jpg'

        if not thumb_path.exists():
            return jsonify({'error': 'Poster image not found'}), 404

        return send_file(thumb_path, mimetype='image/jpeg')
    except Exception as e:
        logger.error(f"Error getting poster image: {e}", exc_info=True)
        return jsonify({'error': str(e)}), 500

get_results(config_name)

Get analysis results for a configuration

Source code in webapi/api/routes.py
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
@api_bp.route('/results/<config_name>', methods=['GET'])
def get_results(config_name):
    """Get analysis results for a configuration"""
    return jsonify({
        'results': {
            'preamble': 'Analysis results',
            'num_toots': 'Found 100 toots',
            'most_toots': 'User posted 10 toots',
            'unique_ids': 50,
            'top_n': 3,
            'hashtag': 'example',
            'generated': '2026-02-02T10:00:00Z'
        }
    })

get_wordcloud_description()

Get generated wordcloud description text

Source code in webapi/api/routes.py
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
@api_bp.route('/wordcloud/description', methods=['POST'])
def get_wordcloud_description():
    """Get generated wordcloud description text"""
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        # Read config to get hashtag and date
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        hashtag = config.get('mastoscore', 'hashtag')
        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')
        hashtag_fix = config.get('wordcloud', 'hashtag_fix', fallback='remove')

        # Description file location: data/YYYY/MM/DD/wordcloud-HASHTAG-YYYYMMDD-{hashtag_fix}.txt
        filename = f'wordcloud-{hashtag}-{year}{month}{day}-{hashtag_fix}.txt'
        desc_file = DATA_DIR / year / month / day / filename

        if not desc_file.exists():
            return jsonify({'error': 'Wordcloud description not found'}), 404

        with open(desc_file, 'r') as f:
            description = f.read()

        return jsonify({
            'description': description,
            'config_file': config_file
        }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

get_wordcloud_image()

Get generated wordcloud image

Source code in webapi/api/routes.py
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
@api_bp.route('/wordcloud/image', methods=['POST'])
def get_wordcloud_image():
    """Get generated wordcloud image"""
    from flask import send_file
    import logging

    logger = logging.getLogger(__name__)

    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        # Read config to get hashtag and date
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        hashtag = config.get('mastoscore', 'hashtag')
        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')
        hashtag_fix = config.get('wordcloud', 'hashtag_fix', fallback='remove')

        # Wordcloud file location: data/YYYY/MM/DD/wordcloud-HASHTAG-YYYYMMDD-{hashtag_fix}.png
        filename = f'wordcloud-{hashtag}-{year}{month}{day}-{hashtag_fix}.png'
        wordcloud_file = DATA_DIR / year / month / day / filename

        if not wordcloud_file.exists():
            return jsonify({'error': 'Wordcloud image not found'}), 404

        return send_file(wordcloud_file, mimetype='image/png')
    except Exception as e:
        logger.error(f"Error getting wordcloud image: {e}", exc_info=True)
        return jsonify({'error': str(e)}), 500

list_configs()

List available configuration files

Source code in webapi/api/routes.py
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
@api_bp.route('/config/list', methods=['GET'])
def list_configs():
    """List available configuration files"""
    try:
        if not INI_DIR.exists():
            return jsonify({
                'configs': [],
                'error': 'Configuration directory does not exist'
            }), 404

        if not os.access(INI_DIR, os.R_OK):
            return jsonify({
                'configs': [],
                'error': 'Permission denied reading configuration directory'
            }), 403

        configs = []
        # Recursively find all .ini files
        for ini_file in INI_DIR.rglob('*.ini'):
            try:
                # Get relative path from ini directory
                rel_path = ini_file.relative_to(PROJECT_ROOT)

                # Try to read basic info from the config
                config = ConfigParser()
                config.read(ini_file)

                hashtag = config.get('mastoscore', 'hashtag', fallback=None) if config.has_section('mastoscore') else None

                configs.append({
                    'name': ini_file.stem,
                    'path': str(rel_path),
                    'hashtag': hashtag,
                    'modified': ini_file.stat().st_mtime
                })
            except PermissionError:
                # Skip files we can't read
                continue
            except Exception:
                # Skip malformed files
                continue

        return jsonify({'configs': configs})

    except PermissionError:
        return jsonify({
            'configs': [],
            'error': 'Permission denied accessing configuration directory'
        }), 403
    except Exception as e:
        return jsonify({
            'configs': [],
            'error': str(e)
        }), 500

reset_fetch_data()

Delete all fetch data files for a configuration

Source code in webapi/api/routes.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
@api_bp.route('/fetch/reset', methods=['POST'])
def reset_fetch_data():
    """Delete all fetch data files for a configuration"""
    from mastoscore.config import read_config
    from mastoscore.fetch import reset_fetch

    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = read_config(str(config_path))
        if config is None:
            return jsonify({'error': 'Failed to read config file'}), 400

        result = reset_fetch(config)

        if result['count'] == 0:
            return jsonify({
                'success': True,
                'config_file': config_file,
                'files_deleted': [],
                'total_size': 0,
                'message': 'No fetch data found to delete'
            }), 200

        # Convert absolute paths to relative and format response
        files_info = [
            {
                'path': str(Path(f['path']).relative_to(PROJECT_ROOT)),
                'size': f['size']
            }
            for f in result['files_deleted']
        ]

        return jsonify({
            'success': True,
            'config_file': config_file,
            'files_deleted': files_info,
            'total_size': result['total_size'],
            'message': f"Deleted {result['count']} files ({result['total_size']:,} bytes)"
        }), 200

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

run_analyse()

Execute analyse operation

Source code in webapi/api/routes.py
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
@api_bp.route('/analyse', methods=['POST'])
def run_analyse():
    """Execute analyse operation"""
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        # Read config using mastoscore's config module
        from mastoscore.config import read_config

        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = read_config(str(config_path))
        if config is None:
            return jsonify({'error': 'Failed to read config file'}), 400

        hashtag = config.get('mastoscore', 'hashtag')
        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')

        # Check if fetch data exists
        fetch_file = DATA_DIR / year / month / day / f'data-{hashtag}-fetch.json'
        if not fetch_file.exists():
            return jsonify({
                'success': False,
                'error': 'Fetch data not found',
                'expected_file': str(fetch_file.relative_to(PROJECT_ROOT))
            }), 404

        # Check if analysis already exists
        analysis_file = DATA_DIR / year / month / day / f'data-{hashtag}-analysis.json'
        if analysis_file.exists():
            import json
            with open(analysis_file, 'r') as f:
                results = json.load(f)
            return jsonify({
                'success': True,
                'cached': True,
                'results': results,
                'message': 'Analysis results loaded from cache'
            }), 200

        # Run analysis
        from mastoscore.analyse import analyse
        result = analyse(config)

        return jsonify({
            'success': True,
            'cached': False,
            'results': result,
            'message': 'Analysis completed successfully'
        }), 200

    except Exception as e:
        import traceback
        error_details = traceback.format_exc()
        print(f"Error in analyse: {error_details}")
        return jsonify({
            'success': False,
            'error': str(e),
            'traceback': error_details
        }), 500
    return jsonify({
        'success': True,
        'config_file': config_file,
        'message': 'Analysis completed successfully'
    }), 200

run_blog()

Execute blog generation

Source code in webapi/api/routes.py
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
@api_bp.route('/blog', methods=['POST'])
def run_blog():
    """Execute blog generation"""
    data = request.get_json()
    config_file = data.get('config_file') if data else None
    copy_files = data.get('copyFiles', False)
    tags = data.get('tags', [])

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        from mastoscore.blog import blog
        from mastoscore.config import read_config

        config_path = str(PROJECT_ROOT / config_file)
        config = read_config(config_path)

        if config is None:
            return jsonify({
                'success': False,
                'error': 'Failed to read config file'
            }), 400

        result = blog(config, copy_files=copy_files, additional_tags=tags)

        return jsonify({
            'success': result,
            'config_file': config_file,
            'message': 'Blog post generated successfully' if result else 'Blog generation failed'
        }), 200 if result else 500
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

run_fetch()

Execute fetch operation asynchronously

Source code in webapi/api/routes.py
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
@api_bp.route('/fetch', methods=['POST'])
def run_fetch():
    """Execute fetch operation asynchronously"""
    from .tasks import run_async
    from .progress import FetchProgress

    data = request.get_json()
    config_file = data.get('config_file') if data else None
    use_mock = data.get('mock', False)

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        if use_mock:
            # Use mock fetch for testing
            from .mock_fetch import mock_fetch
            progress = FetchProgress(max_toots=200)  # Mock uses 200 max
            job_id = run_async(mock_fetch, None, progress_obj=progress)
        else:
            # Real fetch
            from mastoscore.config import read_config
            from mastoscore.fetch import fetch

            config_path = PROJECT_ROOT / config_file
            if not config_path.exists():
                return jsonify({'error': 'Config file not found'}), 404

            config = read_config(str(config_path))
            if config is None:
                return jsonify({'error': 'Failed to read config file'}), 400

            # Get max toots from config
            max_toots = config.getint('mastoscore', 'max', fallback=2000)
            progress = FetchProgress(max_toots=max_toots)

            job_id = run_async(fetch, config, progress_obj=progress)

        return jsonify({
            'job_id': job_id,
            'status': 'running',
            'config_file': config_file
        }), 202

    except Exception as e:
        return jsonify({'error': str(e)}), 500

run_graph()

Execute graph generation

Source code in webapi/api/routes.py
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
@api_bp.route('/graph', methods=['POST'])
def run_graph():
    """Execute graph generation"""
    import logging

    logger = logging.getLogger(__name__)
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        from mastoscore.graph import graph
        from mastoscore.config import read_config

        config_path = str(PROJECT_ROOT / config_file)
        config = read_config(config_path)

        if config is None:
            return jsonify({
                'success': False,
                'error': 'Failed to read config file'
            }), 400

        graph(config)

        return jsonify({
            'success': True,
            'config_file': config_file,
            'message': 'Graph generated successfully'
        }), 200
    except Exception as e:
        logger.error(f"Error generating graph: {e}", exc_info=True)
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

run_post()

Execute post operation (posts text and graphs)

Source code in webapi/api/routes.py
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
@api_bp.route('/post', methods=['POST'])
def run_post():
    """Execute post operation (posts text and graphs)"""
    from .tasks import run_async

    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        from mastoscore.config import read_config
        from mastoscore.post import post_all

        config_path = str(PROJECT_ROOT / config_file)
        config = read_config(config_path)

        if config is None:
            return jsonify({'error': 'Failed to read config file'}), 400

        job_id = run_async(post_all, config)

        return jsonify({
            'job_id': job_id,
            'status': 'running',
            'config_file': config_file
        }), 202
    except Exception as e:
        return jsonify({'error': str(e)}), 500

run_wordcloud()

Execute wordcloud generation

Source code in webapi/api/routes.py
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
@api_bp.route('/wordcloud', methods=['POST'])
def run_wordcloud():
    """Execute wordcloud generation"""
    data = request.get_json()
    config_file = data.get('config_file') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    try:
        from mastoscore.wordcloud import write_wordcloud
        from mastoscore.config import read_config

        config_path = str(PROJECT_ROOT / config_file)
        config = read_config(config_path)

        if config is None:
            return jsonify({
                'success': False,
                'error': 'Failed to read config file'
            }), 400

        write_wordcloud(config)

        return jsonify({
            'success': True,
            'config_file': config_file,
            'message': 'Wordcloud generated successfully'
        }), 200
    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

search_movie_posters()

Search for movie posters using TMDb API

Source code in webapi/api/routes.py
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
@api_bp.route('/blog/search-posters', methods=['POST'])
def search_movie_posters():
    """Search for movie posters using TMDb API"""
    import os
    import re
    import requests

    data = request.get_json()
    config_file = data.get('config_file') if data else None
    search_query = data.get('query') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400

    # Check for TMDb API key
    tmdb_api_key = os.getenv('TMDB_API_KEY')
    if not tmdb_api_key or tmdb_api_key == 'your_tmdb_api_key_here':
        return jsonify({'error': 'TMDb API key not configured in .env file'}), 500

    try:
        # If no query provided, get episode title from config
        if not search_query:
            config_path = PROJECT_ROOT / config_file
            if not config_path.exists():
                return jsonify({'error': 'Config file not found'}), 404

            config = ConfigParser()
            config.read(config_path)

            # Get episode title (e.g., "Planet Earth (1974)")
            search_query = config.get('mastoscore', 'episode_title', fallback=None)
            if not search_query:
                return jsonify({'error': 'episode_title not found in config'}), 400

        # Parse title and year from search_query
        match = re.search(r'^(.+?)\s*\((\d{4})\)\s*$', search_query)
        if match:
            title = match.group(1).strip()
            year = match.group(2)
        else:
            # No year found, use entire string as title
            title = search_query.strip()
            year = None

        # Call TMDb API to search for movie
        search_url = 'https://api.themoviedb.org/3/search/movie'
        params = {
            'api_key': tmdb_api_key,
            'query': title
        }
        if year:
            params['year'] = year

        response = requests.get(search_url, params=params, timeout=10)
        response.raise_for_status()

        search_results = response.json()

        # Format poster results (limit to top 5)
        posters = []
        for result in search_results.get('results', [])[:5]:
            if result.get('poster_path'):
                movie_id = result['id']

                # Fetch detailed movie info including keywords
                details_url = f'https://api.themoviedb.org/3/movie/{movie_id}'
                details_params = {
                    'api_key': tmdb_api_key,
                    'append_to_response': 'keywords'
                }

                try:
                    details_response = requests.get(details_url, params=details_params, timeout=10)
                    details_response.raise_for_status()
                    details = details_response.json()

                    # Extract keywords
                    keywords = []
                    if 'keywords' in details and 'keywords' in details['keywords']:
                        keywords = [kw['name'] for kw in details['keywords']['keywords'][:10]]  # Limit to 10
                except Exception as e:
                    # If keywords fetch fails, continue without them
                    keywords = []

                posters.append({
                    'id': str(movie_id),
                    'title': result['title'],
                    'poster_path': result['poster_path'],
                    'poster_url': f"https://image.tmdb.org/t/p/w342{result['poster_path']}",
                    'year': result.get('release_date', '')[:4] if result.get('release_date') else '',
                    'overview': result.get('overview', ''),
                    'keywords': keywords
                })

        return jsonify({
            'posters': posters,
            'config_file': config_file,
            'search_title': title,
            'search_year': year
        }), 200
    except requests.RequestException as e:
        return jsonify({
            'error': f'TMDb API request failed: {str(e)}'
        }), 500
    except Exception as e:
        return jsonify({
            'error': str(e)
        }), 500

select_movie_poster()

Download and save selected movie poster as thumb.jpg

Source code in webapi/api/routes.py
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
@api_bp.route('/blog/select-poster', methods=['POST'])
def select_movie_poster():
    """Download and save selected movie poster as thumb.jpg"""
    import requests

    data = request.get_json()
    config_file = data.get('config_file') if data else None
    poster_url = data.get('poster_url') if data else None

    if not config_file:
        return jsonify({'error': 'config_file parameter required'}), 400
    if not poster_url:
        return jsonify({'error': 'poster_url parameter required'}), 400

    try:
        config_path = PROJECT_ROOT / config_file
        if not config_path.exists():
            return jsonify({'error': 'Config file not found'}), 404

        config = ConfigParser()
        config.read(config_path)

        year = config.get('mastoscore', 'event_year')
        month = config.get('mastoscore', 'event_month')
        day = config.get('mastoscore', 'event_day')

        thumb_path = DATA_DIR / year / month / day / 'thumb.jpg'

        # Download image from poster_url
        response = requests.get(poster_url, timeout=30)
        response.raise_for_status()

        # Save as thumb.jpg
        with open(thumb_path, 'wb') as f:
            f.write(response.content)

        return jsonify({
            'success': True,
            'config_file': config_file,
            'thumb_file': str(thumb_path.relative_to(PROJECT_ROOT)),
            'message': 'Poster saved successfully'
        }), 200
    except requests.RequestException as e:
        return jsonify({
            'error': f'Failed to download poster: {str(e)}'
        }), 500
    except Exception as e:
        return jsonify({
            'error': str(e)
        }), 500

serve_graph(filename)

Serve generated graph images

Source code in webapi/api/routes.py
1183
1184
1185
1186
@api_bp.route('/graphs/<path:filename>', methods=['GET'])
def serve_graph(filename):
    """Serve generated graph images"""
    return jsonify({'error': 'Not implemented'}), 404

update_config(name)

Update existing configuration file

Source code in webapi/api/routes.py
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
@api_bp.route('/config/<path:name>', methods=['PUT'])
def update_config(name):
    """Update existing configuration file"""
    try:
        config_path = PROJECT_ROOT / name

        if not config_path.exists():
            return jsonify({'error': 'Configuration not found'}), 404

        if not os.access(config_path, os.W_OK):
            return jsonify({'error': 'Permission denied'}), 403

        # Get config data from request
        data = request.get_json()
        if not data or 'config' not in data:
            return jsonify({'error': 'No configuration data provided'}), 400

        # Write config file
        config = ConfigParser()
        for section, values in data['config'].items():
            config.add_section(section)
            for key, value in values.items():
                config.set(section, key, str(value))

        with open(config_path, 'w') as f:
            config.write(f)

        return jsonify({
            'success': True,
            'path': str(config_path.relative_to(PROJECT_ROOT))
        })

    except PermissionError:
        return jsonify({'error': 'Permission denied'}), 403
    except Exception as e:
        return jsonify({'error': str(e)}), 500

Mock Fetching

Mock fetch function for frontend testing

mock_fetch(config, progress=None, cancel_token=None)

Mock fetch that simulates 40-60 servers with random domain names

Source code in webapi/api/mock_fetch.py
 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
def mock_fetch(config, progress=None, cancel_token=None):
    """Mock fetch that simulates 40-60 servers with random domain names"""
    # Random number of servers between 40 and 60
    num_servers = random.randint(40, 60)

    # Generate random server URIs using Faker
    server_uris = [f"https://{fake.domain_name()}" for _ in range(num_servers)]

    servers_todo = num_servers
    servers_done = 0
    servers_fail = 0
    total_toots = 0
    servers_lock = threading.Lock()

    # Initialize all servers as pending in progress
    if progress:
        # Set max_toots for scaling (simulate 200 toots per server max)
        progress.max_toots = 200
        for uri in server_uris:
            with servers_lock:
                progress.server_status[uri] = {'state': 'pending', 'toots': 0}

    # Update initial progress
    if progress:
        progress.update(servers_todo, servers_done, servers_fail, total_toots)

    with ThreadPoolExecutor(max_workers=5) as executor:
        futures = {}

        # Submit initial batch
        for i in range(min(5, num_servers)):
            if cancel_token and cancel_token.is_cancelled():
                break
            uri = server_uris[i]
            future = executor.submit(mock_fetch_single_server, uri, cancel_token, progress)
            futures[future] = i

        # Process completions
        while futures:
            done, pending = wait(futures.keys(), return_when=FIRST_COMPLETED)

            for future in done:
                if cancel_token and cancel_token.is_cancelled():
                    futures.clear()
                    break

                server_idx = futures[future]
                result = future.result()

                if result is None:  # Cancelled
                    continue

                server_uri, toot_count, _ = result

                with servers_lock:
                    servers_todo -= 1
                    if toot_count is None:
                        servers_fail += 1
                    else:
                        servers_done += 1
                        total_toots += toot_count

                    # Update overall progress
                    if progress:
                        progress.update(servers_todo, servers_done, servers_fail, total_toots, server_uri)

                    # Submit next server if available
                    next_idx = servers_done + servers_fail
                    if next_idx < num_servers and not (cancel_token and cancel_token.is_cancelled()):
                        next_uri = server_uris[next_idx]
                        new_future = executor.submit(mock_fetch_single_server, next_uri, cancel_token, progress)
                        futures[new_future] = next_idx

                del futures[future]

    return {
        "servers_done": servers_done,
        "servers_fail": servers_fail,
        "total_toots": total_toots,
        "duration_seconds": 0
    }

mock_fetch_single_server(server_uri, cancel_token=None, progress=None)

Simulate fetching from one server with paginated progress

Source code in webapi/api/mock_fetch.py
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
def mock_fetch_single_server(server_uri, cancel_token=None, progress=None):
    """Simulate fetching from one server with paginated progress"""

    # Mark as started
    if progress:
        progress.start_server(server_uri)

    # 25% failure rate - fail immediately
    if random.random() < 0.25:
        if progress:
            progress.complete_server(server_uri, 0, failed=True)
        return (server_uri, None, None)

    # Simulate fetching 3-5 pages of 40 toots each
    num_pages = random.randint(3, 5)
    total_toots = 0

    for page in range(num_pages):
        # Check cancellation
        if cancel_token and cancel_token.is_cancelled():
            if progress:
                progress.complete_server(server_uri, total_toots, failed=False)
            return (server_uri, total_toots, [])

        # Simulate page fetch delay (0.3-1.0 seconds per page)
        time.sleep(random.uniform(0.3, 1.0))

        # Add 40 toots for this page
        page_toots = 40
        total_toots += page_toots

        # Update progress
        if progress:
            progress.update_server_progress(server_uri, total_toots)

    # Mark as complete
    if progress:
        progress.complete_server(server_uri, total_toots, failed=False)

    return (server_uri, total_toots, [])