|
25 | 25 | """Redirector functions and rules.""" |
26 | 26 |
|
27 | 27 | from flask import Blueprint, abort, current_app, redirect |
| 28 | +from invenio_pidstore.errors import PIDDoesNotExistError, ResolverError |
28 | 29 | from sqlalchemy.orm.exc import NoResultFound |
29 | 30 |
|
| 31 | +from cds.modules.records.resolver import record_resolver |
| 32 | +from cds.modules.records.utils import is_project_record |
| 33 | + |
30 | 34 | from .resolver import get_pid_by_legacy_recid |
31 | 35 |
|
32 | 36 | HTTP_MOVED_PERMANENTLY = 301 |
@@ -58,3 +62,41 @@ def legacy_record_embed_redirect(legacy_id): |
58 | 62 |
|
59 | 63 | url_path = f"{current_app.config['SITE_URL']}/record/{pid.pid_value}/embed" |
60 | 64 | return redirect(url_path, HTTP_MOVED_PERMANENTLY) |
| 65 | + |
| 66 | + |
| 67 | +@blueprint.route("/record/<legacy_id>/files/<file_name>", strict_slashes=False) |
| 68 | +def legacy_record_file_redirect(legacy_id, file_name): |
| 69 | + """Redirect legacy recid file to new file download link.""" |
| 70 | + |
| 71 | + def _find_file_url(record): |
| 72 | + for file_ in record.get("_files", []): |
| 73 | + if file_.get("key") == file_name: |
| 74 | + return (file_.get("links", {}).get("self")) |
| 75 | + return None |
| 76 | + |
| 77 | + try: |
| 78 | + pid = get_pid_by_legacy_recid(legacy_id) |
| 79 | + _, record = record_resolver.resolve(pid_value=pid.pid_value) |
| 80 | + except (NoResultFound, PIDDoesNotExistError, ResolverError, KeyError, TypeError): |
| 81 | + abort(404) |
| 82 | + |
| 83 | + # Video record, try to get the file from the record |
| 84 | + if not is_project_record(record): |
| 85 | + url = _find_file_url(record) |
| 86 | + if url: |
| 87 | + return redirect(url, HTTP_MOVED_PERMANENTLY) |
| 88 | + abort(404) |
| 89 | + |
| 90 | + # Project record, try to get the file from the video records |
| 91 | + for video in record.get("videos", []): |
| 92 | + try: |
| 93 | + video_pid = video["$ref"].rstrip("/").split("/")[-1] |
| 94 | + _, video_record = record_resolver.resolve(pid_value=video_pid) |
| 95 | + except (PIDDoesNotExistError, ResolverError, KeyError, TypeError): |
| 96 | + continue |
| 97 | + |
| 98 | + url = _find_file_url(video_record) |
| 99 | + if url: |
| 100 | + return redirect(url, HTTP_MOVED_PERMANENTLY) |
| 101 | + |
| 102 | + abort(404) |
0 commit comments