|
| 1 | +"""Bootstrap real RSS and Reddit sources for local development.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from django.conf import settings |
| 6 | +from django.core.management.base import BaseCommand, CommandError |
| 7 | + |
| 8 | +from ingestion.tasks import run_ingestion |
| 9 | +from projects.model_support import SourcePluginName |
| 10 | +from projects.models import Project, SourceConfig |
| 11 | + |
| 12 | + |
| 13 | +class Command(BaseCommand): |
| 14 | + help = ( |
| 15 | + "Create or reactivate RSS and Reddit source configs for one project, " |
| 16 | + "optionally queueing ingestion immediately." |
| 17 | + ) |
| 18 | + |
| 19 | + def add_arguments(self, parser): |
| 20 | + parser.add_argument( |
| 21 | + "--project-id", |
| 22 | + type=int, |
| 23 | + help="Project ID that should own the bootstrapped source configs.", |
| 24 | + ) |
| 25 | + parser.add_argument( |
| 26 | + "--project-name", |
| 27 | + help="Project name that should own the bootstrapped source configs.", |
| 28 | + ) |
| 29 | + parser.add_argument( |
| 30 | + "--rss-feed", |
| 31 | + action="append", |
| 32 | + default=[], |
| 33 | + help=( |
| 34 | + "RSS feed URL to add. Repeat the flag or pass a comma-separated list." |
| 35 | + ), |
| 36 | + ) |
| 37 | + parser.add_argument( |
| 38 | + "--subreddit", |
| 39 | + action="append", |
| 40 | + default=[], |
| 41 | + help=("Subreddit to add. Repeat the flag or pass a comma-separated list."), |
| 42 | + ) |
| 43 | + parser.add_argument( |
| 44 | + "--reddit-listing", |
| 45 | + default="both", |
| 46 | + choices=("new", "hot", "both"), |
| 47 | + help="Listing mode to use for bootstrapped Reddit sources.", |
| 48 | + ) |
| 49 | + parser.add_argument( |
| 50 | + "--reddit-limit", |
| 51 | + type=int, |
| 52 | + default=25, |
| 53 | + help="Per-listing fetch limit for bootstrapped Reddit sources.", |
| 54 | + ) |
| 55 | + parser.add_argument( |
| 56 | + "--run-now", |
| 57 | + action="store_true", |
| 58 | + help="Queue ingestion immediately for every source config touched.", |
| 59 | + ) |
| 60 | + |
| 61 | + def handle(self, *args, **options): |
| 62 | + project = self._get_project(options) |
| 63 | + rss_feeds = self._split_values(options["rss_feed"]) |
| 64 | + subreddits = self._split_values(options["subreddit"]) |
| 65 | + reddit_limit = int(options["reddit_limit"]) |
| 66 | + |
| 67 | + if reddit_limit <= 0: |
| 68 | + raise CommandError("--reddit-limit must be a positive integer.") |
| 69 | + if not rss_feeds and not subreddits: |
| 70 | + raise CommandError( |
| 71 | + "Provide at least one --rss-feed or --subreddit value to bootstrap." |
| 72 | + ) |
| 73 | + |
| 74 | + created_count = 0 |
| 75 | + reactivated_count = 0 |
| 76 | + updated_count = 0 |
| 77 | + touched_source_ids: list[int] = [] |
| 78 | + |
| 79 | + for feed_url in rss_feeds: |
| 80 | + source_config, outcome = self._upsert_rss_source(project, feed_url) |
| 81 | + touched_source_ids.append(int(source_config.pk)) |
| 82 | + if outcome == "created": |
| 83 | + created_count += 1 |
| 84 | + elif outcome == "reactivated": |
| 85 | + reactivated_count += 1 |
| 86 | + elif outcome == "updated": |
| 87 | + updated_count += 1 |
| 88 | + |
| 89 | + for subreddit in subreddits: |
| 90 | + source_config, outcome = self._upsert_reddit_source( |
| 91 | + project, |
| 92 | + subreddit, |
| 93 | + listing=options["reddit_listing"], |
| 94 | + limit=reddit_limit, |
| 95 | + ) |
| 96 | + touched_source_ids.append(int(source_config.pk)) |
| 97 | + if outcome == "created": |
| 98 | + created_count += 1 |
| 99 | + elif outcome == "reactivated": |
| 100 | + reactivated_count += 1 |
| 101 | + elif outcome == "updated": |
| 102 | + updated_count += 1 |
| 103 | + |
| 104 | + queued_count = 0 |
| 105 | + if options["run_now"]: |
| 106 | + for source_config_id in touched_source_ids: |
| 107 | + if settings.CELERY_TASK_ALWAYS_EAGER: |
| 108 | + run_ingestion(source_config_id) |
| 109 | + else: |
| 110 | + run_ingestion.delay(source_config_id) |
| 111 | + queued_count += 1 |
| 112 | + |
| 113 | + self.stdout.write( |
| 114 | + self.style.SUCCESS( |
| 115 | + f"Bootstrapped {len(touched_source_ids)} source config(s) for project {project.name}." |
| 116 | + ) |
| 117 | + ) |
| 118 | + self.stdout.write(f"Created: {created_count}") |
| 119 | + self.stdout.write(f"Reactivated: {reactivated_count}") |
| 120 | + self.stdout.write(f"Updated: {updated_count}") |
| 121 | + if options["run_now"]: |
| 122 | + self.stdout.write(f"Queued ingestions: {queued_count}") |
| 123 | + |
| 124 | + def _get_project(self, options) -> Project: |
| 125 | + """Resolve the project from either ID or exact name.""" |
| 126 | + |
| 127 | + project_id = options.get("project_id") |
| 128 | + project_name = (options.get("project_name") or "").strip() |
| 129 | + if bool(project_id) == bool(project_name): |
| 130 | + raise CommandError("Pass exactly one of --project-id or --project-name.") |
| 131 | + |
| 132 | + if project_id: |
| 133 | + try: |
| 134 | + return Project.objects.get(pk=project_id) |
| 135 | + except Project.DoesNotExist as exc: |
| 136 | + raise CommandError( |
| 137 | + f"Project with id {project_id} does not exist." |
| 138 | + ) from exc |
| 139 | + |
| 140 | + try: |
| 141 | + return Project.objects.get(name=project_name) |
| 142 | + except Project.DoesNotExist as exc: |
| 143 | + raise CommandError( |
| 144 | + f"Project named '{project_name}' does not exist." |
| 145 | + ) from exc |
| 146 | + |
| 147 | + @staticmethod |
| 148 | + def _split_values(raw_values: list[str]) -> list[str]: |
| 149 | + """Split repeated or comma-delimited CLI values into a clean list.""" |
| 150 | + |
| 151 | + normalized_values: list[str] = [] |
| 152 | + seen_values: set[str] = set() |
| 153 | + for raw_value in raw_values: |
| 154 | + for item in raw_value.split(","): |
| 155 | + normalized_item = item.strip() |
| 156 | + if not normalized_item or normalized_item in seen_values: |
| 157 | + continue |
| 158 | + seen_values.add(normalized_item) |
| 159 | + normalized_values.append(normalized_item) |
| 160 | + return normalized_values |
| 161 | + |
| 162 | + def _upsert_rss_source( |
| 163 | + self, |
| 164 | + project: Project, |
| 165 | + feed_url: str, |
| 166 | + ) -> tuple[SourceConfig, str]: |
| 167 | + """Create or reactivate one RSS source config.""" |
| 168 | + |
| 169 | + source_config = SourceConfig.objects.filter( |
| 170 | + project=project, |
| 171 | + plugin_name=SourcePluginName.RSS, |
| 172 | + config__feed_url=feed_url, |
| 173 | + ).first() |
| 174 | + if source_config is None: |
| 175 | + source_config = SourceConfig.objects.create( |
| 176 | + project=project, |
| 177 | + plugin_name=SourcePluginName.RSS, |
| 178 | + config={"feed_url": feed_url}, |
| 179 | + is_active=True, |
| 180 | + ) |
| 181 | + return source_config, "created" |
| 182 | + if not source_config.is_active: |
| 183 | + source_config.is_active = True |
| 184 | + source_config.save(update_fields=["is_active"]) |
| 185 | + return source_config, "reactivated" |
| 186 | + return source_config, "unchanged" |
| 187 | + |
| 188 | + def _upsert_reddit_source( |
| 189 | + self, |
| 190 | + project: Project, |
| 191 | + subreddit: str, |
| 192 | + *, |
| 193 | + listing: str, |
| 194 | + limit: int, |
| 195 | + ) -> tuple[SourceConfig, str]: |
| 196 | + """Create, reactivate, or refresh one Reddit source config.""" |
| 197 | + |
| 198 | + desired_config = { |
| 199 | + "subreddit": subreddit, |
| 200 | + "listing": listing, |
| 201 | + "limit": limit, |
| 202 | + } |
| 203 | + source_config = SourceConfig.objects.filter( |
| 204 | + project=project, |
| 205 | + plugin_name=SourcePluginName.REDDIT, |
| 206 | + config__subreddit=subreddit, |
| 207 | + ).first() |
| 208 | + if source_config is None: |
| 209 | + source_config = SourceConfig.objects.create( |
| 210 | + project=project, |
| 211 | + plugin_name=SourcePluginName.REDDIT, |
| 212 | + config=desired_config, |
| 213 | + is_active=True, |
| 214 | + ) |
| 215 | + return source_config, "created" |
| 216 | + |
| 217 | + update_fields: list[str] = [] |
| 218 | + outcome = "unchanged" |
| 219 | + if source_config.config != desired_config: |
| 220 | + source_config.config = desired_config |
| 221 | + update_fields.append("config") |
| 222 | + outcome = "updated" |
| 223 | + if not source_config.is_active: |
| 224 | + source_config.is_active = True |
| 225 | + update_fields.append("is_active") |
| 226 | + outcome = "reactivated" if outcome == "unchanged" else outcome |
| 227 | + if update_fields: |
| 228 | + source_config.save(update_fields=update_fields) |
| 229 | + return source_config, outcome |
0 commit comments