|
| 1 | +""" |
| 2 | +A nice little admin interface for migrating courses and libraries from modulstore to Learning Core. |
| 3 | +""" |
| 4 | +import logging |
| 5 | + |
| 6 | +from django import forms |
| 7 | +from django.contrib import admin, messages |
| 8 | +from django.contrib.admin.helpers import ActionForm |
| 9 | +from django.db import models |
| 10 | + |
| 11 | + |
| 12 | +from opaque_keys import InvalidKeyError |
| 13 | +from opaque_keys.edx.locator import LibraryCollectionLocator, LibraryLocatorV2 |
| 14 | +from user_tasks.models import UserTaskStatus |
| 15 | + |
| 16 | +from openedx.core.types.http import AuthenticatedHttpRequest |
| 17 | + |
| 18 | +from . import api |
| 19 | +from .data import CompositionLevel, RepeatHandlingStrategy |
| 20 | +from .models import ModulestoreSource, ModulestoreMigration, ModulestoreBlockSource, ModulestoreBlockMigration |
| 21 | + |
| 22 | + |
| 23 | +log = logging.getLogger(__name__) |
| 24 | + |
| 25 | + |
| 26 | +class StartMigrationTaskForm(ActionForm): |
| 27 | + """ |
| 28 | + Params for start_migration_task admin adtion, displayed next the "Go" button. |
| 29 | + """ |
| 30 | + target_key = forms.CharField(label="Target library or collection key →", required=False) |
| 31 | + repeat_handling_strategy = forms.ChoiceField( |
| 32 | + label="How to handle existing content? →", |
| 33 | + choices=RepeatHandlingStrategy.supported_choices, |
| 34 | + required=False, |
| 35 | + ) |
| 36 | + preserve_url_slugs = forms.BooleanField(label="Preserve current slugs? →", required=False, initial=True) |
| 37 | + forward_to_target = forms.BooleanField(label="Forward references? →", required=False) |
| 38 | + composition_level = forms.ChoiceField( |
| 39 | + label="Aggregate up to →", choices=CompositionLevel.supported_choices, required=False |
| 40 | + ) |
| 41 | + |
| 42 | + |
| 43 | +def task_status_details(obj: ModulestoreMigration) -> str: |
| 44 | + """ |
| 45 | + Return the state and, if available, details of the status of the migration. |
| 46 | + """ |
| 47 | + details: str | None = None |
| 48 | + if obj.task_status.state == UserTaskStatus.FAILED: |
| 49 | + # Calling fail(msg) from a task should automatically generates an "Error" artifact with that msg. |
| 50 | + # https://django-user-tasks.readthedocs.io/en/latest/user_tasks.html#user_tasks.models.UserTaskStatus.fail |
| 51 | + if error_artifacts := obj.task_status.artifacts.filter(name="Error"): |
| 52 | + if error_text := error_artifacts.order_by("-created").first().text: |
| 53 | + details = error_text |
| 54 | + elif obj.task_status.state == UserTaskStatus.SUCCEEDED: |
| 55 | + details = f"Migrated {obj.block_migrations.count()} blocks" |
| 56 | + return f"{obj.task_status.state}: {details}" if details else obj.task_status.state |
| 57 | + |
| 58 | + |
| 59 | +migration_admin_fields = ( |
| 60 | + "target", |
| 61 | + "target_collection", |
| 62 | + "task_status", |
| 63 | + # The next line works, but django-stubs incorrectly thinks that these should all be strings, |
| 64 | + # so we will need to use type:ignore below. |
| 65 | + task_status_details, |
| 66 | + "composition_level", |
| 67 | + "repeat_handling_strategy", |
| 68 | + "preserve_url_slugs", |
| 69 | + "change_log", |
| 70 | + "staged_content", |
| 71 | +) |
| 72 | + |
| 73 | + |
| 74 | +class ModulestoreMigrationInline(admin.TabularInline): |
| 75 | + """ |
| 76 | + Readonly table within the ModulestoreSource page; each row is a Migration from this Source. |
| 77 | + """ |
| 78 | + model = ModulestoreMigration |
| 79 | + fk_name = "source" |
| 80 | + show_change_link = True |
| 81 | + readonly_fields = migration_admin_fields # type: ignore[assignment] |
| 82 | + ordering = ("-task_status__created",) |
| 83 | + |
| 84 | + def has_add_permission(self, _request, _obj): |
| 85 | + return False |
| 86 | + |
| 87 | + |
| 88 | +class ModulestoreBlockSourceInline(admin.TabularInline): |
| 89 | + """ |
| 90 | + Readonly table within the ModulestoreSource page; each row is a BlockSource. |
| 91 | + """ |
| 92 | + model = ModulestoreBlockSource |
| 93 | + fk_name = "overall_source" |
| 94 | + readonly_fields = ( |
| 95 | + "key", |
| 96 | + "forwarded" |
| 97 | + ) |
| 98 | + |
| 99 | + def has_add_permission(self, _request, _obj): |
| 100 | + return False |
| 101 | + |
| 102 | + |
| 103 | +@admin.register(ModulestoreSource) |
| 104 | +class ModulestoreSourceAdmin(admin.ModelAdmin): |
| 105 | + """ |
| 106 | + Admin interface for source legacy libraries and courses. |
| 107 | + """ |
| 108 | + readonly_fields = ("forwarded",) |
| 109 | + list_display = ("id", "key", "forwarded") |
| 110 | + actions = ["start_migration_task"] |
| 111 | + action_form = StartMigrationTaskForm |
| 112 | + inlines = [ModulestoreMigrationInline, ModulestoreBlockSourceInline] |
| 113 | + |
| 114 | + @admin.action(description="Start migration for selected sources") |
| 115 | + def start_migration_task( |
| 116 | + self, |
| 117 | + request: AuthenticatedHttpRequest, |
| 118 | + queryset: models.QuerySet[ModulestoreSource], |
| 119 | + ) -> None: |
| 120 | + """ |
| 121 | + Start a migration for each selected source |
| 122 | + """ |
| 123 | + form = StartMigrationTaskForm(request.POST) |
| 124 | + form.is_valid() |
| 125 | + target_key_string = form.cleaned_data['target_key'] |
| 126 | + if not target_key_string: |
| 127 | + messages.add_message(request, messages.ERROR, "Target key is required") |
| 128 | + return |
| 129 | + try: |
| 130 | + target_library_key = LibraryLocatorV2.from_string(target_key_string) |
| 131 | + target_collection_slug = None |
| 132 | + except InvalidKeyError: |
| 133 | + try: |
| 134 | + target_collection_key = LibraryCollectionLocator.from_string(target_key_string) |
| 135 | + target_library_key = target_collection_key.lib_key |
| 136 | + target_collection_slug = target_collection_key.collection_id |
| 137 | + except InvalidKeyError: |
| 138 | + messages.add_message(request, messages.ERROR, f"Invalid target key: {target_key_string}") |
| 139 | + return |
| 140 | + started = 0 |
| 141 | + total = 0 |
| 142 | + for source in queryset: |
| 143 | + total += 1 |
| 144 | + try: |
| 145 | + api.start_migration_to_library( |
| 146 | + user=request.user, |
| 147 | + source_key=source.key, |
| 148 | + target_library_key=target_library_key, |
| 149 | + target_collection_slug=target_collection_slug, |
| 150 | + composition_level=form.cleaned_data['composition_level'], |
| 151 | + repeat_handling_strategy=form.cleaned_data['repeat_handling_strategy'], |
| 152 | + preserve_url_slugs=form.cleaned_data['preserve_url_slugs'], |
| 153 | + forward_source_to_target=form.cleaned_data['forward_to_target'], |
| 154 | + ) |
| 155 | + except Exception as exc: # pylint: disable=broad-except |
| 156 | + message = f"Failed to start migration {source.key} -> {target_key_string}" |
| 157 | + messages.add_message(request, messages.ERROR, f"{message}: {exc}") |
| 158 | + log.exception(message) |
| 159 | + continue |
| 160 | + started += 1 |
| 161 | + click_in = "Click into the source objects to see migration details." |
| 162 | + |
| 163 | + if not started: |
| 164 | + messages.add_message(request, messages.WARNING, f"Failed to start {total} migration(s).") |
| 165 | + if started < total: |
| 166 | + messages.add_message(request, messages.WARNING, f"Started {started} of {total} migration(s). {click_in}") |
| 167 | + else: |
| 168 | + messages.add_message(request, messages.INFO, f"Started {started} migration(s). {click_in}") |
| 169 | + |
| 170 | + |
| 171 | +class ModulestoreBlockMigrationInline(admin.TabularInline): |
| 172 | + """ |
| 173 | + Readonly table witin the Migration admin; each row is a block |
| 174 | + """ |
| 175 | + model = ModulestoreBlockMigration |
| 176 | + fk_name = "overall_migration" |
| 177 | + readonly_fields = ( |
| 178 | + "source", |
| 179 | + "target", |
| 180 | + "change_log_record", |
| 181 | + ) |
| 182 | + list_display = ("id", *readonly_fields) |
| 183 | + |
| 184 | + |
| 185 | +@admin.register(ModulestoreMigration) |
| 186 | +class ModulestoreMigrationAdmin(admin.ModelAdmin): |
| 187 | + """ |
| 188 | + Readonly admin page for viewing Migrations |
| 189 | + """ |
| 190 | + readonly_fields = ("source", *migration_admin_fields) # type: ignore[assignment] |
| 191 | + list_display = ("id", "source", *migration_admin_fields) # type: ignore[assignment] |
| 192 | + inlines = [ModulestoreBlockMigrationInline] |
0 commit comments