From 069322247d1b89640fb2b345750df66869ac0859 Mon Sep 17 00:00:00 2001 From: milanmajchrak <90026355+milanmajchrak@users.noreply.github.com> Date: Thu, 16 Jul 2026 09:05:05 +0200 Subject: [PATCH 001/109] UFAL/CLARIN-DSpace upgrade v9 (#1316) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * Port CLARIN frontend image assets (mime icons, flags, branding) First tranche of the CLARIN-DSpace 7.6.x -> 9.3 dspace-angular port. Adds CLARIN/LINDAT image assets that are net-new vs vanilla 9.3 (none of these dirs exist upstream), so this is purely additive and build-safe: - src/assets/images/mime/ (file-type icons for item/bitstream display) - src/assets/images/flags/ (country/language flags) - src/assets/images/item-types/, footer/, static-pages/ - LINDAT branding: lindat-logo-new-sm.png, lindat_color_line.png, target.png, info.png, spinning.gif Feature modules that consume these assets follow in subsequent tranches (see CLARIN_DSPACE_V9_PROGRESS.md §6e for the frontend plan). Co-Authored-By: Claude Opus 4.8 * Port CLARIN frontend core layer (models + data services) to angular 9 Second tranche of the dspace-angular 7.6.x -> 9.3 CLARIN port: the core data layer that the feature modules depend on. Type-checks clean (tsc) and passes lint (0 errors) on v9. - shared/clarin: models, resource-types, serializers, constants for the license framework (ClarinLicense/Label/ResourceMapping/CLRUA), user metadata/registration, verification token, matomo report subscription, featured services, bitstream auth. - core/data + core/data/clarin: data services for the above + handle / epic-handle / metadata-bitstream / metadata-value / bitstream-checksum. - core/handle, core/epicHandle, core/metadata: handle + epic-handle + metadata models, resource-types and serializers. v9 migration applied: - @dataService decorator import repointed from core/data/base/data-service.decorator to core/cache/builders/build-decorators (moved upstream in v8/9; still used for HAL resolution) - decorator kept. - eslint --fix for v9 style (import order etc.). Deferred (need the clarin-item-box-view feature): bitstream-url-serializer + shared/clarin-shared-util. Feature modules (clarin-licenses, handle-page, login, share-submission, ...) follow in subsequent tranches. See CLARIN_DSPACE_V9_PROGRESS.md §6e. Co-Authored-By: Claude Opus 4.8 * Port CLARIN clarin-licenses feature module to angular 9 (standalone) Third FE tranche: the flagship CLARIN license admin/listing feature, migrated from the 7.x NgModule pattern to v9 standalone components. ng build passes (module is lazy-loaded so the whole chain incl. the core layer is validated); lint clean (0 errors). - 5 components -> standalone (clarin-license-page, clarin-license-table, clarin-all-licenses-page, define-license-form, define-license-label-form) with explicit imports (CommonModule, TranslateModule, FormsModule/ReactiveFormsModule, NgbDropdownModule, ThemedLoadingComponent, PaginationComponent + the pipes below). - 6 custom CLARIN pipes ported + made standalone (shared/utils): char-to-end (dsAddChar), clarin-extended-license, clarin-license-checked, clarin-license-label-radio-value, clarin-license-required-info(+checked). - clarin-license-routes.ts (replaces clarin-license.module.ts + clarin-license-routing.module.ts) using v9 function resolver/guard (i18nBreadcrumbResolver / siteAdministratorGuard). - LICENSES_MODULE_PATH / LICENSES_MANAGE_TABLE_PATH added to app-routing-paths.ts and the /licenses lazy route wired into app-routes.ts. Consumes the core layer from the previous tranche. See CLARIN_DSPACE_V9_PROGRESS.md §6e. Co-Authored-By: Claude Opus 4.8 * Fix clarin-licenses templates for v9 lint gate (control-flow, dsBtnDisabled, ===) Follow-up to the clarin-licenses port: the CI gate `ng lint --quiet` also lints templates (which a scoped .ts-only eslint run missed). Applied the v9 template requirements so both `ng build` and full `ng lint --quiet` pass (0 errors): - *ngIf/*ngFor -> @if/@for via @angular/core:control-flow migration (@angular-eslint/template/prefer-control-flow). - == -> === in templates (@angular-eslint/template/eqeqeq). - disabled/[disabled] on + + + + @if (loading && configFiles.length === 0) { +
+
+ {{ 'admin.update-config.loading' | translate }} +
+

{{ 'admin.update-config.loading-files' | translate }}

+
+ } + + +
+
+
+ + {{ 'admin.update-config.file-selection.title' | translate }} +
+

+ {{ 'admin.update-config.description' | translate }} +

+ +
+
+ + +
+ @if (selectedFile) { +
+
+
+ + {{ 'admin.update-config.file-info.title' | translate }} +
+ + {{ 'admin.update-config.file-info.name' | translate }}: {{ selectedFile.fileName }}
+ {{ 'admin.update-config.file-info.size' | translate }}: {{ selectedFile.size | number }} {{ 'admin.update-config.file-info.bytes' | translate }}
+ {{ 'admin.update-config.file-info.modified' | translate }}: {{ selectedFile.lastModified | date:'short' }}
+ {{ 'admin.update-config.file-info.status' | translate }}: + {{ 'admin.update-config.file-info.ready' | translate }} +
+
+
+ } +
+
+
+ + + @if (loading && selectedFile) { +
+
+ {{ 'admin.update-config.loading' | translate }} +
+

{{ 'admin.update-config.loading-content' | translate }}

+
+ } + + + @if (selectedFile && !loading) { +
+
+
+
+ + {{ 'admin.update-config.editor.title' | translate }}: {{ selectedFile.fileName }} +
+ +
+ + + +
+
+ +
+ +
+ {{ 'admin.update-config.editor.notice.title' | translate }}
+ {{ 'admin.update-config.editor.notice.description' | translate:{ fileName: selectedFile?.fileName } }} +
+
+
+ @if (hasUnsavedChanges()) { +
+ + {{ 'admin.update-config.validation.unsaved-changes' | translate }} +
+ } +
+ +
+ + + + + {{ fileContent.length }} {{ 'admin.update-config.editor.characters' | translate }} + +
+
+
+ } + + + + + \ No newline at end of file diff --git a/src/app/admin/admin-update-config/admin-update-config.component.scss b/src/app/admin/admin-update-config/admin-update-config.component.scss new file mode 100644 index 00000000000..57fd5e4111c --- /dev/null +++ b/src/app/admin/admin-update-config/admin-update-config.component.scss @@ -0,0 +1,142 @@ +.container-fluid { + padding: 1rem; +} + +.card { + border: none; + box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075); + border-radius: 0.5rem; +} + +.card-title { + color: #495057; + font-weight: 600; +} + +.config-editor { + font-family: 'Courier New', Courier, monospace; + font-size: 0.875rem; + line-height: 1.5; + background-color: #f8f9fa; + border: 1px solid #dee2e6; + resize: vertical; + min-height: 300px; +} + +.config-editor:focus { + background-color: #ffffff; + border-color: #80bdff; + box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25); + outline: none; +} + +.config-editor.is-invalid { + border-color: #dc3545; + background-color: #fff5f5; +} + +.config-editor.is-invalid:focus { + border-color: #dc3545; + box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25); +} + +.form-control.is-invalid { + border-color: #dc3545; + background-image: none; +} + +.form-control.is-invalid:focus { + border-color: #dc3545; + box-shadow: 0 0 0 0.2rem rgba(220, 53, 69, 0.25); +} + +.alert { + border: none; + border-radius: 0.375rem; +} + +.alert-info { + background-color: #e7f3ff; + border-left: 4px solid #17a2b8; + color: #0c5460; +} + +.alert-danger { + background-color: #f8d7da; + border-left: 4px solid #dc3545; + color: #721c24; +} + +.alert-warning { + background-color: #fff3cd; + border-left: 4px solid #ffc107; + color: #856404; +} + +.badge { + font-size: 0.75rem; + font-weight: 500; +} + +.btn { + border-radius: 0.375rem; + font-weight: 500; +} + +.btn:disabled { + opacity: 0.65; +} + +.btn-sm { + padding: 0.375rem 0.75rem; + font-size: 0.875rem; +} + +.form-select { + border-radius: 0.375rem; +} + +.form-select:focus { + border-color: #80bdff; + box-shadow: 0 0 0 0.2rem rgba(0, 123, 255, 0.25); +} + +/* Loading spinner animation */ +.fa-spin { + animation: fa-spin 2s infinite linear; +} + +@keyframes fa-spin { + 0% { + transform: rotate(0deg); + } + 100% { + transform: rotate(359deg); + } +} + +/* Responsive adjustments */ +@media (max-width: 768px) { + .container-fluid { + padding: 0.5rem; + } + + .alert.d-flex { + flex-direction: column; + align-items: flex-start !important; + } + + .alert.d-flex > div:last-child { + margin-top: 1rem; + width: 100%; + } + + .btn-sm { + width: 100%; + margin-bottom: 0.5rem; + } + + .btn-sm:last-child { + margin-bottom: 0; + } +} \ No newline at end of file diff --git a/src/app/admin/admin-update-config/admin-update-config.component.ts b/src/app/admin/admin-update-config/admin-update-config.component.ts new file mode 100644 index 00000000000..68ec37f4ee4 --- /dev/null +++ b/src/app/admin/admin-update-config/admin-update-config.component.ts @@ -0,0 +1,243 @@ +import { + DatePipe, + DecimalPipe, +} from '@angular/common'; +import { + ChangeDetectorRef, + Component, + OnInit, +} from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { + TranslateModule, + TranslateService, +} from '@ngx-translate/core'; + +import { BtnDisabledDirective } from '../../shared/btn-disabled.directive'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { + AdminUpdateConfigService, + ConfigFile, +} from './admin-update-config.service'; + +@Component({ + selector: 'ds-admin-update-config', + templateUrl: './admin-update-config.component.html', + styleUrls: ['./admin-update-config.component.scss'], + imports: [BtnDisabledDirective, + DatePipe, + DecimalPipe, + FormsModule, + TranslateModule, + ], +}) +export class AdminUpdateConfigComponent implements OnInit { + + /** + * Available config files + */ + configFiles: ConfigFile[] = []; + + /** + * Currently selected file + */ + selectedFile: ConfigFile | null = null; + + /** + * Current file content + */ + fileContent = ''; + + /** + * Original file content for reset functionality + */ + originalContent = ''; + + /** + * Whether we're currently loading data + */ + loading = false; + + /** + * Whether we're currently saving + */ + saving = false; + + + + constructor( + private configService: AdminUpdateConfigService, + private notificationsService: NotificationsService, + private translateService: TranslateService, + private cdr: ChangeDetectorRef, + ) { } + + ngOnInit(): void { + this.loadConfigFiles(); + } + + /** + * Load available config files + */ + loadConfigFiles(): void { + this.loading = true; + this.configService.getConfigFiles().subscribe({ + next: (files) => { + this.configFiles = files; + this.loading = false; + this.cdr.detectChanges(); // Force change detection + }, + error: (error: unknown) => { + this.loading = false; + this.notificationsService.error( + this.translateService.instant('admin.update-config.error.load-files.title'), + this.translateService.instant('admin.update-config.error.load-files.message'), + ); + this.cdr.detectChanges(); // Force change detection + }, + }); + } + + /** + * Handle file selection from dropdown + */ + onFileSelect(file: ConfigFile): void { + if (!file) { + this.selectedFile = null; + this.fileContent = ''; + this.originalContent = ''; + this.cdr.detectChanges(); // Force change detection when clearing selection + return; + } + + this.selectedFile = file; + this.cdr.detectChanges(); // Force change detection when file is selected + this.loadFileContent(file.fileName); + } + + /** + * Load content of selected config file (instant loading!) + */ + loadFileContent(filename: string): void { + this.loading = true; + this.cdr.detectChanges(); // Force change detection to show loading spinner + + // Instant subscription - no delays! + this.configService.getConfigFileContent(filename).subscribe({ + next: (content) => { + this.fileContent = content; + this.originalContent = content; + this.loading = false; + this.cdr.detectChanges(); // Force change detection to hide loading spinner + }, + error: (error: unknown) => { + this.loading = false; + this.notificationsService.error( + this.translateService.instant('admin.update-config.error.load-content.title'), + this.translateService.instant('admin.update-config.error.load-content.message', { fileName: filename }), + ); + this.cdr.detectChanges(); // Force change detection on error + }, + }); + } + + /** + * Handle content changes in the editor + */ + onContentChange(): void { + // Content changed + } + + /** + * Save the current config file + */ + saveFile(): void { + if (!this.selectedFile || this.saving) { + return; + } + + this.saving = true; + this.cdr.detectChanges(); // Force change detection to show saving state + + this.configService.saveConfigFile(this.selectedFile.fileName, this.fileContent).subscribe({ + next: (result) => { + this.saving = false; + this.originalContent = this.fileContent; + + this.notificationsService.success( + this.translateService.instant('admin.update-config.success.save.title'), + this.translateService.instant('admin.update-config.success.save.message', { fileName: this.selectedFile?.fileName }), + ); + + this.loadConfigFiles(); + this.cdr.detectChanges(); // Force change detection after save + }, + error: (error: unknown) => { + this.saving = false; + this.notificationsService.error( + this.translateService.instant('admin.update-config.error.save.title'), + this.translateService.instant('admin.update-config.error.save.message', { fileName: this.selectedFile?.fileName }), + ); + this.cdr.detectChanges(); // Force change detection on error + }, + }); + } + + /** + * Reset content to original version + */ + resetContent(): void { + this.fileContent = this.originalContent; + } + + /** + * Reset to original file + */ + resetToOriginalFile(): void { + if (!this.selectedFile) { + return; + } + + this.loading = true; + this.cdr.detectChanges(); // Force change detection to show loading state + + this.configService.reloadOriginalContent(this.selectedFile.fileName).subscribe({ + next: (originalContent) => { + this.fileContent = originalContent; + this.originalContent = originalContent; + this.loading = false; + + this.notificationsService.success( + this.translateService.instant('admin.update-config.success.reload.title'), + this.translateService.instant('admin.update-config.success.reload.message', { fileName: this.selectedFile?.fileName }), + ); + this.cdr.detectChanges(); // Force change detection after reload + }, + error: (error: unknown) => { + this.loading = false; + this.notificationsService.error( + this.translateService.instant('admin.update-config.error.reload.title'), + this.translateService.instant('admin.update-config.error.reload.message'), + ); + this.cdr.detectChanges(); // Force change detection on error + }, + }); + } + + /** + * Check if content has unsaved changes + */ + hasUnsavedChanges(): boolean { + return this.fileContent !== this.originalContent; + } + + /** + * Get placeholder text for file selection + */ + getFileSelectionText(): string { + if (this.configFiles.length === 0) { + return this.translateService.instant('admin.update-config.select.no-files'); + } + return this.translateService.instant('admin.update-config.select.choose-file'); + } +} diff --git a/src/app/admin/admin-update-config/admin-update-config.service.ts b/src/app/admin/admin-update-config/admin-update-config.service.ts new file mode 100644 index 00000000000..a6e3cd9b13e --- /dev/null +++ b/src/app/admin/admin-update-config/admin-update-config.service.ts @@ -0,0 +1,107 @@ +import { + HttpClient, + HttpHeaders, +} from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Observable } from 'rxjs'; +import { + catchError, + map, +} from 'rxjs/operators'; + +import { RESTURLCombiner } from '../../core/url-combiner/rest-url-combiner'; + +export interface ConfigFile { + fileName: string; + size: number; + lastModified: string; + type: string; + _links: { + self: { href: string }; + content: { href: string }; + }; +} + +export interface SaveResponse { + success?: boolean; + message: string; + file?: string; + timestamp?: string; + backup?: string; +} + +@Injectable({ providedIn: 'root' }) +export class AdminUpdateConfigService { + private readonly apiBaseUrl: string; + + constructor(private http: HttpClient) { + // Use DSpace's REST URL combiner to build proper backend URL + this.apiBaseUrl = new RESTURLCombiner('admin', 'configfiles').toString(); + } + + /** + * Get list of available configuration files from backend API + */ + getConfigFiles(): Observable { + return this.http.get(this.apiBaseUrl).pipe( + map(files => { + // Transform API response to match our ConfigFile interface + return files.map(file => ({ + fileName: file.fileName || file.name || file.id || file.identifier, + size: file.size || 0, + lastModified: file.lastModified || file.modified || new Date().toISOString(), + type: file.type || 'application/xml', + _links: file._links || { + self: { href: `${this.apiBaseUrl}/${file.fileName || file.name || file.id || file.identifier}` }, + content: { href: `${this.apiBaseUrl}/${file.fileName || file.name || file.id || file.identifier}/content` }, + }, + })); + }), + catchError((error: unknown) => { + throw error; + }), + ); + } + + /** + * Get content of a specific config file from backend API + */ + getConfigFileContent(filename: string): Observable { + return this.http.get(`${this.apiBaseUrl}/${filename}/content`, { + responseType: 'text', + headers: new HttpHeaders({ + 'Accept': 'text/plain', + }), + }); + } + + /** + * Save config file content to backend API + */ + saveConfigFile(filename: string, content: string): Observable { + return this.http.put(`${this.apiBaseUrl}/${filename}/content`, content, { + headers: new HttpHeaders({ + 'Content-Type': 'text/plain', + // Note: CSRF token should be handled automatically by Angular interceptors + }), + }); + } + + + + /** + * Reload original file content from backend API + */ + reloadOriginalContent(filename: string): Observable { + return this.getConfigFileContent(filename); + } + + /** + * Get metadata for a specific config file + */ + getConfigFile(filename: string): Observable { + return this.http.get(`${this.apiBaseUrl}/${filename}`); + } + + +} diff --git a/src/app/app-routes.ts b/src/app/app-routes.ts index 17f8bb5443d..d7de123cc46 100644 --- a/src/app/app-routes.ts +++ b/src/app/app-routes.ts @@ -16,6 +16,7 @@ import { INFO_MODULE_PATH, INTERNAL_SERVER_ERROR, LEGACY_BITSTREAM_MODULE_PATH, + LICENSES_MODULE_PATH, PROFILE_MODULE_PATH, REGISTER_PATH, REQUEST_COPY_MODULE_PATH, @@ -33,7 +34,9 @@ import { endUserAgreementCurrentUserGuard } from './core/end-user-agreement/end- import { reloadGuard } from './core/reload/reload.guard'; import { forgotPasswordCheckGuard } from './core/rest-property/forgot-password-check-guard.guard'; import { ServerCheckGuard } from './core/server-check/server-check.guard'; +import { EPIC_HANDLE_TABLE_MODULE_PATH } from './epic-handle/epic-handle-routing-paths'; import { ThemedForbiddenComponent } from './forbidden/themed-forbidden.component'; +import { HANDLE_TABLE_MODULE_PATH } from './handle-page/handle-page-routing-paths'; import { homePageResolver } from './home-page/home-page.resolver'; import { ITEM_MODULE_PATH } from './item-page/item-page-routing-paths'; import { provideSuggestionNotificationsState } from './notifications/provide-suggestion-notifications-state'; @@ -41,6 +44,7 @@ import { ThemedPageErrorComponent } from './page-error/themed-page-error.compone import { ThemedPageInternalServerErrorComponent } from './page-internal-server-error/themed-page-internal-server-error.component'; import { ThemedPageNotFoundComponent } from './pagenotfound/themed-pagenotfound.component'; import { PROCESS_MODULE_PATH } from './process-page/process-page-routing.paths'; +import { STATIC_PAGE_PATH } from './static-page/static-page-routing-paths'; import { viewTrackerResolver } from './statistics/angulartics/dspace/view-tracker.resolver'; import { provideSubmissionState } from './submission/provide-submission-state'; import { SUGGESTION_MODULE_PATH } from './suggestions-page/suggestions-page-routing-paths'; @@ -146,7 +150,6 @@ export const APP_ROUTES: Route[] = [ path: 'mydspace', loadChildren: () => import('./my-dspace-page/my-dspace-page-routes') .then((m) => m.ROUTES), - data: { enableRSS: true }, providers: [provideSuggestionNotificationsState()], canActivate: [authenticatedGuard, endUserAgreementCurrentUserGuard], }, @@ -154,7 +157,7 @@ export const APP_ROUTES: Route[] = [ path: 'search', loadChildren: () => import('./search-page/search-page-routes') .then((m) => m.ROUTES), - data: { enableRSS: true }, + // CLARIN/LINDAT: production shows the RSS button only on home and comcol pages canActivate: [endUserAgreementCurrentUserGuard], }, { @@ -167,7 +170,6 @@ export const APP_ROUTES: Route[] = [ path: ADMIN_MODULE_PATH, loadChildren: () => import('./admin/admin-routes') .then((m) => m.ROUTES), - data: { enableRSS: true }, canActivate: [siteAdministratorGuard, endUserAgreementCurrentUserGuard], }, { @@ -214,7 +216,6 @@ export const APP_ROUTES: Route[] = [ providers: [provideSubmissionState()], loadChildren: () => import('./workflowitems-edit-page/workflowitems-edit-page-routes') .then((m) => m.ROUTES), - data: { enableRSS: true }, canActivate: [endUserAgreementCurrentUserGuard], }, { @@ -267,6 +268,37 @@ export const APP_ROUTES: Route[] = [ loadChildren: () => import('./access-control/access-control-routes').then((m) => m.ROUTES), canActivate: [groupAdministratorGuard, endUserAgreementCurrentUserGuard], }, + { + path: LICENSES_MODULE_PATH, + loadChildren: () => import('./clarin-licenses/clarin-license-routes').then((m) => m.ROUTES), + }, + { + path: HANDLE_TABLE_MODULE_PATH, + loadChildren: () => import('./handle-page/handle-page-routes').then((m) => m.ROUTES), + canActivate: [siteAdministratorGuard, endUserAgreementCurrentUserGuard], + }, + { + path: EPIC_HANDLE_TABLE_MODULE_PATH, + loadChildren: () => import('./epic-handle/epic-handle-routes').then((m) => m.ROUTES), + canActivate: [siteAdministratorGuard, endUserAgreementCurrentUserGuard], + }, + { + path: 'share-submission', + loadChildren: () => import('./share-submission/share-submission-routes').then((m) => m.ROUTES), + canActivate: [authenticatedGuard, endUserAgreementCurrentUserGuard], + }, + { + path: 'contact', + loadChildren: () => import('./contact-page/contact-page-routes').then((m) => m.ROUTES), + }, + { + path: 'contract', + loadChildren: () => import('./license-contract-page/license-contract-page-routes').then((m) => m.ROUTES), + }, + { + path: STATIC_PAGE_PATH, + loadChildren: () => import('./static-page/static-page-routes').then((m) => m.ROUTES), + }, { path: 'subscriptions', loadChildren: () => import('./subscriptions-page/subscriptions-page-routes') diff --git a/src/app/app-routing-paths.ts b/src/app/app-routing-paths.ts index 7b2c2d81ce0..600868759d7 100644 --- a/src/app/app-routing-paths.ts +++ b/src/app/app-routing-paths.ts @@ -160,5 +160,21 @@ export const EDIT_ITEM_PATH = 'edit-items'; export function getEditItemPageRoute() { return `/${EDIT_ITEM_PATH}`; } + +// CLARIN: distribution-license contract page +export const CONTRACT_PAGE_MODULE_PATH = 'contract'; +export function getLicenseContractPagePath() { + return `/${CONTRACT_PAGE_MODULE_PATH}`; +} export const CORRECTION_TYPE_PATH = 'corrections'; + +export const LICENSES_MODULE_PATH = 'licenses'; +export function getLicensesModulePath() { + return `/${LICENSES_MODULE_PATH}`; +} + +export const LICENSES_MANAGE_TABLE_PATH = 'manage-table'; +export function getLicensesManageTablePath() { + return `/${LICENSES_MANAGE_TABLE_PATH}`; +} diff --git a/src/app/app.config.ts b/src/app/app.config.ts index 34feeef3251..33a5f830c10 100644 --- a/src/app/app.config.ts +++ b/src/app/app.config.ts @@ -8,6 +8,7 @@ import { import { NoPreloading, provideRouter, + UrlSerializer, withComponentInputBinding, withEnabledBlockingInitialNavigation, withInMemoryScrolling, @@ -65,6 +66,7 @@ import { } from './core/provide-core'; import { ClientCookieService } from './core/services/client-cookie.service'; import { ListableModule } from './core/shared/listable.module'; +import { BitstreamUrlSerializer } from './core/url-serializer/bitstream-url-serializer'; import { XsrfInterceptor } from './core/xsrf/xsrf.interceptor'; import { LOGIN_METHOD_FOR_DECORATOR_MAP } from './external-log-in/decorators/external-log-in.methods-decorator'; import { RootModule } from './root.module'; @@ -127,6 +129,11 @@ export const commonAppConfig: ApplicationConfig = { provide: RouterStateSerializer, useClass: DSpaceRouterStateSerializer, }, + // CLARIN: percent-encode the filename segment of /bitstream/ download URLs + { + provide: UrlSerializer, + useClass: BitstreamUrlSerializer, + }, ClientCookieService, // register AuthInterceptor as HttpInterceptor { diff --git a/src/app/app.menus.ts b/src/app/app.menus.ts index e63b948c2f7..c9f2ffc738c 100644 --- a/src/app/app.menus.ts +++ b/src/app/app.menus.ts @@ -11,6 +11,7 @@ import { MenuRoute } from './shared/menu/menu-route.model'; import { AccessControlMenuProvider } from './shared/menu/providers/access-control.menu'; import { AdminSearchMenuProvider } from './shared/menu/providers/admin-search.menu'; import { BrowseMenuProvider } from './shared/menu/providers/browse.menu'; +import { ClarinAdminMenuProvider } from './shared/menu/providers/clarin-admin.menu'; import { CoarNotifyMenuProvider } from './shared/menu/providers/coar-notify.menu'; import { SubscribeMenuProvider } from './shared/menu/providers/comcol-subscribe.menu'; import { CommunityListMenuProvider } from './shared/menu/providers/community-list.menu'; @@ -72,6 +73,8 @@ export const MENUS = buildMenuStructure({ HealthMenuProvider, SystemWideAlertMenuProvider, CoarNotifyMenuProvider, + // CLARIN/LINDAT: handle table, ePIC handles, license administration + ClarinAdminMenuProvider, ], [MenuID.DSO_EDIT]: [ DsoOptionMenuProvider.withSubs([ diff --git a/src/app/bitstream-page/bitstream-page-routes.ts b/src/app/bitstream-page/bitstream-page-routes.ts index 05de91d5003..7ffb2938a50 100644 --- a/src/app/bitstream-page/bitstream-page-routes.ts +++ b/src/app/bitstream-page/bitstream-page-routes.ts @@ -11,6 +11,7 @@ import { BitstreamAuthorizationsComponent } from './bitstream-authorizations/bit import { BitstreamDownloadPageComponent } from './bitstream-download-page/bitstream-download-page.component'; import { bitstreamPageResolver } from './bitstream-page.resolver'; import { bitstreamPageAuthorizationsGuard } from './bitstream-page-authorizations.guard'; +import { ClarinBitstreamDownloadPageComponent } from './clarin-bitstream-download-page/clarin-bitstream-download-page.component'; import { ThemedEditBitstreamPageComponent } from './edit-bitstream-page/themed-edit-bitstream-page.component'; import { legacyBitstreamURLRedirectGuard } from './legacy-bitstream-url-redirect.guard'; @@ -35,8 +36,9 @@ export const ROUTES: Route[] = [ }, { // Resolve angular bitstream download URLs + // CLARIN: license-gated download (shows license agreement / token-expired / auth-denied before download) path: ':id/download', - component: BitstreamDownloadPageComponent, + component: ClarinBitstreamDownloadPageComponent, resolve: { bitstream: bitstreamPageResolver, }, diff --git a/src/app/bitstream-page/clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component.html b/src/app/bitstream-page/clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component.html new file mode 100644 index 00000000000..42c007da8a1 --- /dev/null +++ b/src/app/bitstream-page/clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component.html @@ -0,0 +1,3 @@ +
+

{{'clarin.bitstream.authorization.denied.message' | translate:{bitstream: (bitstream$ | async)?.name} }}

+
diff --git a/src/app/bitstream-page/clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component.scss b/src/app/bitstream-page/clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component.scss new file mode 100644 index 00000000000..c5f6a0c13fd --- /dev/null +++ b/src/app/bitstream-page/clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component.scss @@ -0,0 +1,5 @@ +.bg-clarin-red { + background-color: var(--lt-clarin-red-bg); + border-color: var(--lt-clarin-red-border); + color: var(--lt-clarin-red-text); +} diff --git a/src/app/bitstream-page/clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component.ts b/src/app/bitstream-page/clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component.ts new file mode 100644 index 00000000000..0c65033bbd8 --- /dev/null +++ b/src/app/bitstream-page/clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component.ts @@ -0,0 +1,28 @@ +import { AsyncPipe } from '@angular/common'; +import { + Component, + Input, +} from '@angular/core'; +import { TranslateModule } from '@ngx-translate/core'; +import { Observable } from 'rxjs'; + +import { Bitstream } from '../../core/shared/bitstream.model'; + +/** + * This component shows error that the READ access to the bitstream is denied. + */ +@Component({ + imports: [ + AsyncPipe, + TranslateModule, + ], + selector: 'ds-clarin-bitstream-authorization-denied', + templateUrl: './clarin-bitstream-authorization-denied.component.html', + styleUrls: ['./clarin-bitstream-authorization-denied.component.scss'], +}) +export class ClarinBitstreamAuthorizationDeniedComponent { + + @Input() + bitstream$: Observable; + +} diff --git a/src/app/bitstream-page/clarin-bitstream-download-page/clarin-bitstream-download-page.component.html b/src/app/bitstream-page/clarin-bitstream-download-page/clarin-bitstream-download-page.component.html new file mode 100644 index 00000000000..63306003f58 --- /dev/null +++ b/src/app/bitstream-page/clarin-bitstream-download-page/clarin-bitstream-download-page.component.html @@ -0,0 +1,22 @@ +
+ @if ((downloadStatus | async) === 'Success') { +
+

{{'bitstream.download.page' | translate:{bitstream: (bitstream$ | async)?.name} }}

+
+ } + @if ((downloadStatus | async) === 'MissingLicenseAgreementException') { + + + } + @if ((downloadStatus | async) === 'DownloadTokenExpiredException') { + + + } + @if ((downloadStatus | async) === 'Authorization denied') { + + + } +
diff --git a/src/app/bitstream-page/clarin-bitstream-download-page/clarin-bitstream-download-page.component.scss b/src/app/bitstream-page/clarin-bitstream-download-page/clarin-bitstream-download-page.component.scss new file mode 100644 index 00000000000..5133bc82d9a --- /dev/null +++ b/src/app/bitstream-page/clarin-bitstream-download-page/clarin-bitstream-download-page.component.scss @@ -0,0 +1,3 @@ +/** + The file for styling the `clarin-bitstream-download-page.component`. + */ diff --git a/src/app/bitstream-page/clarin-bitstream-download-page/clarin-bitstream-download-page.component.ts b/src/app/bitstream-page/clarin-bitstream-download-page/clarin-bitstream-download-page.component.ts new file mode 100644 index 00000000000..a0fe36f7cac --- /dev/null +++ b/src/app/bitstream-page/clarin-bitstream-download-page/clarin-bitstream-download-page.component.ts @@ -0,0 +1,220 @@ +import { AsyncPipe } from '@angular/common'; +import { + Component, + OnInit, +} from '@angular/core'; +import { + ActivatedRoute, + Router, +} from '@angular/router'; +import { TranslateModule } from '@ngx-translate/core'; +import isEqual from 'lodash/isEqual'; +import { + BehaviorSubject, + combineLatest as observableCombineLatest, + Observable, + of, +} from 'rxjs'; +import { + filter, + map, + switchMap, + take, +} from 'rxjs/operators'; +import { + hasCompleted, + hasFailed, + RequestEntryState, +} from 'src/app/core/data/request-entry-state.model'; +import { redirectOn4xx } from 'src/app/core/shared/authorized.operators'; + +import { getForbiddenRoute } from '../../app-routing-paths'; +import { AuthService } from '../../core/auth/auth.service'; +import { RemoteDataBuildService } from '../../core/cache/builders/remote-data-build.service'; +import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; +import { FeatureID } from '../../core/data/feature-authorization/feature-id'; +import { RemoteData } from '../../core/data/remote-data'; +import { GetRequest } from '../../core/data/request.models'; +import { RequestService } from '../../core/data/request.service'; +import { HardRedirectService } from '../../core/services/hard-redirect.service'; +import { Bitstream } from '../../core/shared/bitstream.model'; +import { AuthrnBitstream } from '../../core/shared/clarin/bitstream-authorization.model'; +import { + AUTHORIZATION_DENIED_EXCEPTION, + DOWNLOAD_TOKEN_EXPIRED_EXCEPTION, + HTTP_STATUS_UNAUTHORIZED, + MISSING_LICENSE_AGREEMENT_EXCEPTION, +} from '../../core/shared/clarin/constants'; +import { FileService } from '../../core/shared/file.service'; +import { HALEndpointService } from '../../core/shared/hal-endpoint.service'; +import { getRemoteDataPayload } from '../../core/shared/operators'; +import { + hasValue, + isEmpty, + isNotEmpty, + isNotNull, + isUndefined, +} from '../../shared/empty.util'; +import { ClarinBitstreamAuthorizationDeniedComponent } from '../clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component'; +import { ClarinBitstreamTokenExpiredComponent } from '../clarin-bitstream-token-expired/clarin-bitstream-token-expired.component'; +import { ClarinLicenseAgreementPageComponent } from '../clarin-license-agreement-page/clarin-license-agreement-page.component'; + +/** + * `//download` page + * This component decides if the bitstream will be downloaded or if the user must fill in some user metadata or + * if the path contains `dtoken` parameter the component tries to download the bitstream with the token. + */ +@Component({ + imports: [ + AsyncPipe, + ClarinBitstreamAuthorizationDeniedComponent, + ClarinBitstreamTokenExpiredComponent, + ClarinLicenseAgreementPageComponent, + TranslateModule, + ], + selector: 'ds-clarin-bitstream-download-page', + templateUrl: './clarin-bitstream-download-page.component.html', + styleUrls: ['./clarin-bitstream-download-page.component.scss'], +}) +export class ClarinBitstreamDownloadPageComponent implements OnInit { + + bitstream$: Observable; + bitstreamRD$: Observable>; + downloadStatus: BehaviorSubject = new BehaviorSubject(''); + zipDownloadLink: BehaviorSubject = new BehaviorSubject(''); + dtoken: string; + + constructor( + protected route: ActivatedRoute, + protected router: Router, + protected auth: AuthService, + protected authorizationService: AuthorizationDataService, + protected hardRedirectService: HardRedirectService, + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected halService: HALEndpointService, + protected fileService: FileService, + ) { } + + ngOnInit(): void { + // Get dtoken + this.dtoken = isUndefined(this.route.snapshot.queryParams.dtoken) ? null : this.route.snapshot.queryParams.dtoken; + + if (isUndefined(this.bitstreamRD$)) { + this.bitstreamRD$ = this.route.data.pipe( + filter((data) => hasValue(data.bitstream)), + map((data) => data.bitstream)); + } + + this.bitstream$ = this.bitstreamRD$.pipe( + redirectOn4xx(this.router, this.auth), + getRemoteDataPayload(), + ); + + this.bitstream$.pipe( + switchMap((bitstream: Bitstream) => { + let authorizationUrl = ''; + // Get Authorization Bitstream endpoint url + authorizationUrl = this.halService.getRootHref() + '/' + AuthrnBitstream.type.value + '/' + bitstream.uuid; + + // Add token to the url or not + authorizationUrl = isNotEmpty(this.dtoken) ? authorizationUrl + '?dtoken=' + this.dtoken : authorizationUrl; + + const requestId = this.requestService.generateRequestId(); + const headRequest = new GetRequest(requestId, authorizationUrl); + this.requestService.send(headRequest); + + const clarinIsAuthorized$ = this.rdbService.buildFromRequestUUID(requestId); + // Clarin authorization will check dtoken parameter from the request + const dtoken = isNotEmpty(this.dtoken) ? '?dtoken=' + this.dtoken : ''; + const isAuthorized$ = this.authorizationService.isAuthorized(FeatureID.CanDownload, isNotEmpty(bitstream) ? bitstream.self + dtoken : undefined, undefined, false); + const isLoggedIn$ = this.auth.isAuthenticated(); + return observableCombineLatest([clarinIsAuthorized$, isAuthorized$, isLoggedIn$, of(bitstream)]); + }), + filter(([clarinIsAuthorized, isAuthorized, isLoggedIn, bitstream]: [RemoteData, boolean, boolean, Bitstream]) => hasValue(isAuthorized) && hasValue(isLoggedIn) && hasValue(clarinIsAuthorized) && hasCompleted(clarinIsAuthorized.state)), + take(1), + switchMap(([clarinIsAuthorized, isAuthorized, isLoggedIn, bitstream]: [RemoteData, boolean, boolean, Bitstream]) => { + const isAuthorizedByClarin = this.processClarinAuthorization(clarinIsAuthorized); + if (isAuthorizedByClarin && isAuthorized && isLoggedIn) { + return this.fileService.retrieveFileDownloadLink(bitstream._links.content.href).pipe( + filter((fileLink) => hasValue(fileLink)), + take(1), + map((fileLink) => { + return [isAuthorizedByClarin, isAuthorized, isLoggedIn, bitstream, fileLink]; + })); + } else { + return [[isAuthorizedByClarin, isAuthorized, isLoggedIn, bitstream, '']]; + } + }), + ).subscribe(([isAuthorizedByClarin, isAuthorized, isLoggedIn, bitstream, fileLink]: [boolean, boolean, boolean, Bitstream, string]) => { + let bitstreamURL = bitstream._links.content.href; + // Clarin Authorization is approving the user by token + if (isAuthorizedByClarin) { + if (fileLink.includes('authentication-token')) { + fileLink = isNotNull(this.dtoken) ? fileLink + '&dtoken=' + this.dtoken : fileLink; + } else { + fileLink = isNotNull(this.dtoken) ? fileLink + '?dtoken=' + this.dtoken : fileLink; + } + bitstreamURL = isNotNull(this.dtoken) ? bitstreamURL + '?dtoken=' + this.dtoken : bitstreamURL; + } + if (isNotEmpty(this.zipDownloadLink.getValue())) { + const authToken = fileLink.substring(fileLink.indexOf('authentication-token')); + const currentZipDownloadLink = this.zipDownloadLink.getValue(); + const separator = currentZipDownloadLink.includes('?') ? '&' : '?'; + fileLink = currentZipDownloadLink + separator + authToken; + bitstreamURL = this.zipDownloadLink.getValue(); + } + // fileLink = 'http://localhost:8080/server/api/core/bitstreams/d9a41f84-a470-495a-8821-20e0a18e9276/content'; + // bitstreamURL = 'http://localhost:8080/server/api/core/bitstreams/d9a41f84-a470-495a-8821-20e0a18e9276/content'; + if ((isAuthorized || isAuthorizedByClarin) && isLoggedIn && isNotEmpty(fileLink)) { + this.downloadStatus.next(RequestEntryState.Success); + window.location.replace(fileLink); + } else if ((isAuthorized || isAuthorizedByClarin) && !isLoggedIn) { + this.downloadStatus.next(RequestEntryState.Success); + window.location.replace(bitstreamURL); + } else if (!(isAuthorized || isAuthorizedByClarin) && isLoggedIn && + this.downloadStatus.value === (RequestEntryState.Error as string)) { + // this.downloadStatus is `ERROR` - no CLARIN exception is thrown up + this.downloadStatus.next(HTTP_STATUS_UNAUTHORIZED.toString()); + this.router.navigateByUrl(getForbiddenRoute(), { skipLocationChange: true }); + } else if (!(isAuthorized || isAuthorizedByClarin) && !isLoggedIn && isEmpty(this.downloadStatus.value)) { + this.auth.setRedirectUrl(this.router.url); + this.router.navigateByUrl('login'); + } + }); + } + + /** + * Check if the response contains error: MissingLicenseAgreementException or DownloadTokenExpiredException and + * show components. + */ + processClarinAuthorization(requestEntry: RemoteData) { + if (isEqual(requestEntry?.statusCode, 200)) { + // User is authorized -> start downloading + this.downloadStatus.next(RequestEntryState.Success); + return true; + } else if (hasFailed(requestEntry.state)) { + // User is not authorized + if (requestEntry?.statusCode === HTTP_STATUS_UNAUTHORIZED) { + switch (requestEntry?.errorMessage) { + case MISSING_LICENSE_AGREEMENT_EXCEPTION: + // Show License Agreement page with required user data for the current license + this.downloadStatus.next(MISSING_LICENSE_AGREEMENT_EXCEPTION); + return false; + case DOWNLOAD_TOKEN_EXPIRED_EXCEPTION: + // Token is expired or wrong -> try to download without token + this.downloadStatus.next(DOWNLOAD_TOKEN_EXPIRED_EXCEPTION); + return false; + default: + if (requestEntry?.errorMessage && requestEntry?.errorMessage.startsWith(AUTHORIZATION_DENIED_EXCEPTION)) { + this.downloadStatus.next(AUTHORIZATION_DENIED_EXCEPTION); + } + return false; + } + } + // Another failure reason show error page + this.downloadStatus.next(RequestEntryState.Error); + return false; + } + } +} diff --git a/src/app/bitstream-page/clarin-bitstream-token-expired/clarin-bitstream-token-expired.component.html b/src/app/bitstream-page/clarin-bitstream-token-expired/clarin-bitstream-token-expired.component.html new file mode 100644 index 00000000000..ec0a094f6f2 --- /dev/null +++ b/src/app/bitstream-page/clarin-bitstream-token-expired/clarin-bitstream-token-expired.component.html @@ -0,0 +1,5 @@ +
+
+

{{'clarin.bitstream.expired.dtoken.message' | translate}}

+
+
diff --git a/src/app/bitstream-page/clarin-bitstream-token-expired/clarin-bitstream-token-expired.component.scss b/src/app/bitstream-page/clarin-bitstream-token-expired/clarin-bitstream-token-expired.component.scss new file mode 100644 index 00000000000..c5f6a0c13fd --- /dev/null +++ b/src/app/bitstream-page/clarin-bitstream-token-expired/clarin-bitstream-token-expired.component.scss @@ -0,0 +1,5 @@ +.bg-clarin-red { + background-color: var(--lt-clarin-red-bg); + border-color: var(--lt-clarin-red-border); + color: var(--lt-clarin-red-text); +} diff --git a/src/app/bitstream-page/clarin-bitstream-token-expired/clarin-bitstream-token-expired.component.ts b/src/app/bitstream-page/clarin-bitstream-token-expired/clarin-bitstream-token-expired.component.ts new file mode 100644 index 00000000000..9d25367059f --- /dev/null +++ b/src/app/bitstream-page/clarin-bitstream-token-expired/clarin-bitstream-token-expired.component.ts @@ -0,0 +1,45 @@ +import { + Component, + Input, + OnInit, +} from '@angular/core'; +import { TranslateModule } from '@ngx-translate/core'; +import { Observable } from 'rxjs'; +import { take } from 'rxjs/operators'; + +import { getBitstreamDownloadRoute } from '../../app-routing-paths'; +import { HardRedirectService } from '../../core/services/hard-redirect.service'; +import { Bitstream } from '../../core/shared/bitstream.model'; + +/** + * This component shows error that the download token is expired and redirect the user to the Item View page + * after 5 seconds. + */ +@Component({ + imports: [ + TranslateModule, + ], + selector: 'ds-clarin-bitstream-token-expired', + templateUrl: './clarin-bitstream-token-expired.component.html', + styleUrls: ['./clarin-bitstream-token-expired.component.scss'], +}) +export class ClarinBitstreamTokenExpiredComponent implements OnInit { + + @Input() + bitstream$: Observable; + + constructor( + private hardRedirectService: HardRedirectService, + ) { } + + ngOnInit(): void { + setTimeout(() => { + this.bitstream$.pipe(take(1)) + .subscribe(bitstream => { + const bitstreamDownloadPath = getBitstreamDownloadRoute(bitstream); + this.hardRedirectService.redirect(bitstreamDownloadPath); + }); + }, + 5000); + } +} diff --git a/src/app/bitstream-page/clarin-license-agreement-page/clarin-license-agreement-page.component.html b/src/app/bitstream-page/clarin-license-agreement-page/clarin-license-agreement-page.component.html new file mode 100644 index 00000000000..50cd9e9727e --- /dev/null +++ b/src/app/bitstream-page/clarin-license-agreement-page/clarin-license-agreement-page.component.html @@ -0,0 +1,126 @@ +
+
+
+ +
+
+
+
+
{{'clarin.license.agreement.header.info' | translate}}
+
+
+
+
+
+
+ {{clarinLicense?.name}} + @if (clarinLicense?.name === LICENSE_NAME_SEZNAM) { +
+
+ } +
+
+
+
+
+
+ {{'clarin.license.agreement.signer.header.info.0' | translate}} + {{'clarin.license.agreement.signer.header.info.1' | translate}} + {{'clarin.license.agreement.signer.header.info.2' | translate}} +
+
+
+
+ + + @if (currentUser$ | async) { + + + + + } + @if (currentUser$ | async) { + + + + + } + + + + + @if (((currentUser$ | async) ?? null) === null || (userMetadata$ | async)) { + @for (requiredInfo of requiredInfo$ | async; track requiredInfo) { + + + + + } + } + + + + + + + + + +
{{'clarin.license.agreement.signer.name' | translate}}
{{'clarin.license.agreement.signer.id' | translate}}
{{'clarin.license.agreement.item.handle' | translate}}
{{'clarin.license.agreement.signer.' + requiredInfo.name | translate}} + +
{{'clarin.license.agreement.bitstream.name' | translate}}
{{'clarin.license.agreement.signer.ip.address' | translate}}
+
+
+
+
+
+
+
{{'clarin.license.agreement.token.info' | translate}}
+
+
+
+
+
+
+
+
+
{{'clarin.license.agreement.warning' | translate}}
+
+
+
+
+
+
+
+ +
+
+ @if (error$.value.length !== 0) { +
+
+
+
+
{{'clarin.license.agreement.error.message.cannot.download.0' | translate}} + + {{'clarin.license.agreement.error.message.cannot.download.1' | translate}} + +
+
+
+
+
+ } +
diff --git a/src/app/bitstream-page/clarin-license-agreement-page/clarin-license-agreement-page.component.scss b/src/app/bitstream-page/clarin-license-agreement-page/clarin-license-agreement-page.component.scss new file mode 100644 index 00000000000..a4da3d1827a --- /dev/null +++ b/src/app/bitstream-page/clarin-license-agreement-page/clarin-license-agreement-page.component.scss @@ -0,0 +1,25 @@ +.bg-clarin-yellow { + background-color: var(--lt-clarin-yellow-bg); + border-color: var(--lt-clarin-yellow-border); +} + +.bg-clarin-red { + background-color: var(--lt-clarin-red-bg); + border-color: var(--lt-clarin-red-border); + color: var(--lt-clarin-red-text); +} + +.bg-clarin-blue { + background-color: var(--lt-clarin-blue-bg); + border-color: var(--lt-clarin-blue-border); + color: var(--lt-clarin-blue-text); +} + +.max-width { + width: 100%; + +} + +.border-gray { + border: 1px solid var(--lt-clarin-gray-border); +} diff --git a/src/app/bitstream-page/clarin-license-agreement-page/clarin-license-agreement-page.component.ts b/src/app/bitstream-page/clarin-license-agreement-page/clarin-license-agreement-page.component.ts new file mode 100644 index 00000000000..632a3429153 --- /dev/null +++ b/src/app/bitstream-page/clarin-license-agreement-page/clarin-license-agreement-page.component.ts @@ -0,0 +1,568 @@ +import { AsyncPipe } from '@angular/common'; +import { HttpClient } from '@angular/common/http'; +import { + Component, + Input, + OnInit, +} from '@angular/core'; +import { Router } from '@angular/router'; +import { + TranslateModule, + TranslateService, +} from '@ngx-translate/core'; +import cloneDeep from 'lodash/cloneDeep'; +import isEqual from 'lodash/isEqual'; +import { + BehaviorSubject, + firstValueFrom, + Observable, + of, +} from 'rxjs'; +import { + filter, + finalize, + switchMap, + take, +} from 'rxjs/operators'; +import { hasFailed } from 'src/app/core/data/request-entry-state.model'; + +import { AuthService } from '../../core/auth/auth.service'; +import { RemoteDataBuildService } from '../../core/cache/builders/remote-data-build.service'; +import { RequestParam } from '../../core/cache/models/request-param.model'; +import { BundleDataService } from '../../core/data/bundle-data.service'; +import { ClarinLicenseResourceMappingService } from '../../core/data/clarin/clarin-license-resource-mapping-data.service'; +import { ClarinUserMetadataDataService } from '../../core/data/clarin/clarin-user-metadata.service'; +import { ClarinUserRegistrationDataService } from '../../core/data/clarin/clarin-user-registration.service'; +import { ConfigurationDataService } from '../../core/data/configuration-data.service'; +import { FindListOptions } from '../../core/data/find-list-options.model'; +import { ItemDataService } from '../../core/data/item-data.service'; +import { + buildPaginatedList, + PaginatedList, +} from '../../core/data/paginated-list.model'; +import { RemoteData } from '../../core/data/remote-data'; +import { + GetRequest, + PostRequest, +} from '../../core/data/request.models'; +import { RequestService } from '../../core/data/request.service'; +import { HttpOptions } from '../../core/dspace-rest/dspace-rest.service'; +import { EPerson } from '../../core/eperson/models/eperson.model'; +import { HardRedirectService } from '../../core/services/hard-redirect.service'; +import { Bitstream } from '../../core/shared/bitstream.model'; +import { ClarinLicense } from '../../core/shared/clarin/clarin-license.model'; +import { ClarinLicenseRequiredInfo } from '../../core/shared/clarin/clarin-license.resource-type'; +import { ClarinLicenseResourceMapping } from '../../core/shared/clarin/clarin-license-resource-mapping.model'; +import { ClarinUserMetadata } from '../../core/shared/clarin/clarin-user-metadata.model'; +import { CLARIN_USER_METADATA_MANAGE } from '../../core/shared/clarin/clarin-user-metadata.resource-type'; +import { ClarinUserRegistration } from '../../core/shared/clarin/clarin-user-registration.model'; +import { ConfigurationProperty } from '../../core/shared/configuration-property.model'; +import { FileService } from '../../core/shared/file.service'; +import { HALEndpointService } from '../../core/shared/hal-endpoint.service'; +import { Item } from '../../core/shared/item.model'; +import { + getFirstCompletedRemoteData, + getFirstSucceededRemoteListPayload, +} from '../../core/shared/operators'; +import { getItemPageRoute } from '../../item-page/item-page-routing-paths'; +import { HELP_DESK_PROPERTY } from '../../item-page/tombstone/tombstone.constants'; +import { BtnDisabledDirective } from '../../shared/btn-disabled.directive'; +import { + hasValue, + isEmpty, + isNotEmpty, +} from '../../shared/empty.util'; +import { HtmlContentService } from '../../shared/html-content.service'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { ClarinSafeHtmlPipe } from '../../shared/utils/clarin-safehtml.pipe'; +import { followLink } from '../../shared/utils/follow-link-config.model'; +import { VarDirective } from '../../shared/utils/var.directive'; + +/** + * The component shows the user's filled in user metadata and the user can fill in other required user metadata. + * The user must to approve his user metadata to download the bitstream. + */ +@Component({ + imports: [ + AsyncPipe, + BtnDisabledDirective, + ClarinSafeHtmlPipe, + TranslateModule, + VarDirective, + ], + selector: 'ds-clarin-license-agreement-page', + templateUrl: './clarin-license-agreement-page.component.html', + styleUrls: ['./clarin-license-agreement-page.component.scss'], +}) +export class ClarinLicenseAgreementPageComponent implements OnInit { + + @Input() + bitstream$: Observable; + + /** + * The user IP Address which is loaded from `http://api.ipify.org/?format=json` + */ + ipAddress$: BehaviorSubject = new BehaviorSubject(null); + + /** + * The item where is the bitstream attached to. + */ + item$: BehaviorSubject = new BehaviorSubject(null); + + /** + * The object where are stored the user's e-mail and organization data. + */ + userRegistration$: BehaviorSubject = new BehaviorSubject(null); + + /** + * The object where are stored the user's metadata. + */ + userMetadata$: BehaviorSubject> = new BehaviorSubject>(null); + + /** + * By resourceMapping get the ClarinLicense object. + */ + resourceMapping$: BehaviorSubject = new BehaviorSubject(null); + + /** + * The Clarin License which is attached to the bitstream. + */ + clarinLicense$: BehaviorSubject = new BehaviorSubject(null); + + /** + * The current user object. + */ + currentUser$: BehaviorSubject = new BehaviorSubject(null); + + /** + * Required info for downloading the bitstream. + */ + requiredInfo$: BehaviorSubject = new BehaviorSubject(null); + + /** + * Errors which occurs by loading the data for the user approval. + */ + error$: BehaviorSubject = new BehaviorSubject([]); + + /** + * The mail for the help desk is loaded from the server. + */ + helpDesk$: Observable>; + + /** + * The Seznam dataset license content. It is shown directly in this approval page. + */ + LICENSE_NAME_SEZNAM = 'Seznam Dataset Licence'; + + /** + * The path to the Seznam dataset license content. + */ + LICENSE_PATH_SEZNAM_CZ = 'szn-dataset-licence.html'; + + /** + * The content of the Seznam dataset license. Fetch from the static file. + */ + licenseContentSeznam: BehaviorSubject = new BehaviorSubject(''); + + /** + * Indicates when the submission is in progress and resets after completion + */ + isLoading: BehaviorSubject = new BehaviorSubject(false); + + constructor( + protected clarinLicenseResourceMappingService: ClarinLicenseResourceMappingService, + protected configurationDataService: ConfigurationDataService, + protected bundleService: BundleDataService, + protected userRegistrationService: ClarinUserRegistrationDataService, + protected notificationService: NotificationsService, + protected translateService: TranslateService, + protected itemService: ItemDataService, + protected auth: AuthService, + protected http: HttpClient, + protected router: Router, + protected halService: HALEndpointService, + protected rdbService: RemoteDataBuildService, + private hardRedirectService: HardRedirectService, + private requestService: RequestService, + private clarinUserMetadataDataService: ClarinUserMetadataDataService, + private htmlContentService: HtmlContentService, + protected fileService: FileService, + protected notificationsService: NotificationsService) { } + + ngOnInit(): void { + // Load CurrentItem by bitstreamID to show itemHandle + this.loadCurrentItem(); + // Load helpDeskEmail from configuration property - BE + this.loadHelpDeskEmail(); + // Load IPAddress by API to show user IP Address + this.loadIPAddress(); + // Load License Resource Mapping by bitstreamId and load Clarin License from it + this.loadResourceMappingAndClarinLicense(); + // Load current user + this.loadCurrentUser(); + + if (isEmpty(this.currentUser$?.value)) { + // The user is not signed in + return; + } + + // The user is signed in and has record in the userRegistration + // Load userRegistration and userMetadata from userRegistration repository + this.loadUserRegistrationAndUserMetadata(); + + // Load the Seznam dataset license content + this.loadLicenseContentSeznam(); + } + + /** + * Load the content for the special license. This content is shown directly in this approval page. + */ + loadLicenseContentSeznam() { + this.item$.subscribe((item) => { + if (item?.firstMetadataValue('dc.rights') === this.LICENSE_NAME_SEZNAM) { + this.htmlContentService.getHmtlContentByPathAndLocale(this.LICENSE_PATH_SEZNAM_CZ).then(content => { + this.licenseContentSeznam.next(content); + }); + } + }); + } + + public accept() { + // Check if were filled in every required info + if (!this.checkFilledInRequiredInfo()) { + this.notificationService.error( + this.translateService.instant('clarin.license.agreement.notification.error.required.info')); + return; + } + + this.isLoading.next(true); + + const requestId = this.requestService.generateRequestId(); + // Response type must be `text` because it throws response as error byd status code is 200 (Success). + const requestOptions: HttpOptions = Object.create({ + responseType: 'text', + }); + + // `/core/clarinusermetadatavalues/manage?bitstreamUUID=` + // `/core/clarinusermetadatavalues/manage/zip?itemUUID=` + let url = this.halService.getRootHref() + '/core/' + ClarinUserMetadata.type.value + '/' + + CLARIN_USER_METADATA_MANAGE; + url += this.isDownloadingZIP() ? '/zip?itemUUID=' + this.item$.value.uuid : '?bitstreamUUID=' + + this.getBitstreamUUID(); + if (this.userMetadata$.value?.page) { + // Filter the page array to exclude items with metadataKey "IP" + this.userMetadata$.value.page = + this.userMetadata$.value.page.filter(item => item.metadataKey !== 'IP'); + } + // Add IP address into request. Every restricted download must have stored IP address in the `user_metadata` table. + this.userMetadata$.value?.page.push(Object.assign(new ClarinUserMetadata(), { + type: ClarinUserMetadata.type, + metadataKey: 'IP', + metadataValue: this.ipAddress$.value, + })); + const postRequest = new PostRequest(requestId, url, this.userMetadata$.value?.page, requestOptions); + // Send POST request + this.requestService.send(postRequest); + // Get response + const response = this.rdbService.buildFromRequestUUID(requestId); + // Process response + response + .pipe(getFirstCompletedRemoteData(), finalize(() => this.isLoading.next(false))) + .subscribe(responseRD$ => { + if (hasFailed(responseRD$.state)) { + this.notificationService.error( + this.translateService.instant('clarin.license.agreement.notification.cannot.send.email')); + } + if (isEmpty(responseRD$?.payload)) { + return; + } + const responseStringValue = Object.values(responseRD$.payload).join(''); + // The user will get an email with download link - notification + if (isEqual(responseStringValue, 'checkEmail')) { + this.notificationService.info( + this.translateService.instant('clarin.license.agreement.notification.check.email')); + this.navigateToItemPage(); + return; + } else { + // Or just download the bitstream by download token + const downloadToken = Object.values(responseRD$?.payload).join(''); + void this.redirectToDownload(downloadToken); + } + }); + } + + private navigateToItemPage() { + this.router.navigate([getItemPageRoute(this.item$?.value)]); + } + + private isDownloadingZIP() { + return this.router.routerState.snapshot.url.endsWith('/zip'); + } + + /** + * Redirects to the download link of the bitstream. + * If a download token is provided, it appends it as a query parameter. + * + * @param downloadToken + * @private + */ + private async redirectToDownload(downloadToken?: string): Promise { + try { + const bitstream = await firstValueFrom(this.bitstream$.pipe(take(1))); + + const fileLink = await firstValueFrom( + this.fileService.retrieveFileDownloadLink(bitstream._links.content.href).pipe( + filter(hasValue), + take(1), + ), + ); + + // Determine whether the URL already contains query parameters + const hasQueryParams = fileLink.includes('?'); + const tokenParam = downloadToken ? `${hasQueryParams ? '&' : '?'}dtoken=${downloadToken}` : ''; + + const redirectUrl = `${fileLink}${tokenParam}`; + this.hardRedirectService.redirect(redirectUrl); + } catch (error) { + this.notificationsService.error(this.translateService.instant('clarin-license-agreement-page.download-error')); + } + } + + public getMetadataValueByKey(metadataKey: string) { + let result = ''; + this.userMetadata$.value?.page?.forEach(userMetadata => { + if (userMetadata.metadataKey === metadataKey) { + result = userMetadata.metadataValue; + } + }); + return result; + } + + public setMetadataValue(metadataKey: string, newMetadataValue: string) { + let wasUpdated = false; + let userMetadataList = cloneDeep(this.userMetadata$?.value?.page); + if (isEmpty(userMetadataList)) { + userMetadataList = []; + } + userMetadataList.forEach(userMetadata => { + // Updated the metadataValue for the actual metadataKey + if (userMetadata.metadataKey === metadataKey) { + userMetadata.metadataValue = newMetadataValue; + wasUpdated = true; + } + }); + + // The metadataValue for the actual metadataKey doesn't exist in the userMetadata$, so add there one + if (!wasUpdated) { + userMetadataList.push(Object.assign(new ClarinUserMetadata(), { + type: ClarinUserMetadata.type, + metadataKey: metadataKey, + metadataValue: newMetadataValue, + })); + } + + // Update userMetadata$ with new List + this.userMetadata$.next(buildPaginatedList( + this.userMetadata$?.value?.pageInfo, userMetadataList, false, this.userMetadata$?.value?._links)); + } + + private getBitstreamUUID() { + let bitstreamUUID = ''; + this.bitstream$.pipe(take(1)).subscribe( bitstream => { + bitstreamUUID = bitstream.uuid; + }); + return bitstreamUUID; + } + + private loadResourceMappingAndClarinLicense() { + this.clarinLicenseResourceMappingService.searchBy('byBitstream', + this.createSearchOptions(this.getBitstreamUUID(), null), false, true, + followLink('clarinLicense')) + .pipe( + getFirstSucceededRemoteListPayload()) + .subscribe(resourceMappingList => { + // Every bitstream has only one resourceMapping + const resourceMapping = resourceMappingList?.[0]; + if (isEmpty(resourceMapping)) { + this.error$.value.push('Cannot load the Resource Mapping'); + return; + } + this.resourceMapping$.next(resourceMapping); + + // Load ClarinLicense from resourceMapping + resourceMapping.clarinLicense + .pipe(getFirstCompletedRemoteData()) + .subscribe(clarinLicense => { + if (isEmpty(clarinLicense?.payload)) { + this.error$.value.push('Cannot load the License'); + } + this.clarinLicense$.next(clarinLicense?.payload); + // Load required info from ClarinLicense + // @ts-ignore + this.requiredInfo$.next(clarinLicense?.payload?.requiredInfo); + }); + }); + } + + public shouldSeeSendTokenInfo() { + let shouldSee = false; + this.requiredInfo$?.value?.forEach(requiredInfo => { + if (requiredInfo?.name === 'SEND_TOKEN') { + // We don't want to display SEND_TOKEN as an input field + this.requiredInfo$.next(this.requiredInfo$.value?.filter(item => item.name !== 'SEND_TOKEN')); + shouldSee = true; + } + }); + return shouldSee; + } + + private loadUserRegistrationAndUserMetadata() { + this.userRegistrationService.searchBy('byEPerson', + this.createSearchOptions(null, this.currentUser$.value?.uuid), false, true, + followLink('userMetadata')) + .pipe(getFirstCompletedRemoteData()) + .subscribe(userRegistrationRD$ => { + if (isNotEmpty(this.currentUser$.value?.uuid) && isEmpty(userRegistrationRD$?.payload)) { + this.error$.value.push('Cannot load userRegistration'); + return; + } + // Every user has only one userRegistration record + const userRegistration = userRegistrationRD$?.payload?.page?.[0]; + if (isEmpty(userRegistration)) { + return; + } + this.userRegistration$.next(userRegistration); + + // Load user metadata for the current user only from the last transaction + const params = [ + new RequestParam('userRegUUID', userRegistration.id), + new RequestParam('bitstreamUUID', this.getBitstreamUUID())]; + const paramOptions = Object.assign(new FindListOptions(), { + searchParams: [...params], + }); + this.clarinUserMetadataDataService.searchBy('byUserRegistrationAndBitstream', paramOptions, false) + .pipe( + getFirstCompletedRemoteData()) + .subscribe(userMetadata => { + if (hasFailed(userMetadata.state)) { + this.error$.value.push('Cannot load userMetadata'); + return; + } + this.userMetadata$.next(userMetadata.payload); + }); + }); + } + + private loadCurrentUser() { + this.getCurrentUser().pipe(take(1)).subscribe((user) => { + this.currentUser$.next(user); + }); + } + + private checkFilledInRequiredInfo() { + const areFilledIn = []; + // Every requiredInfo.name === userMetadata.metadataKey must have the value in the userMetadata.metadataValue + this.requiredInfo$?.value?.forEach(requiredInfo => { + let hasMetadataValue = false; + this.userMetadata$?.value?.page?.forEach(userMetadata => { + if (userMetadata.metadataKey === requiredInfo.name) { + if (isNotEmpty(userMetadata.metadataValue)) { + hasMetadataValue = true; + } + } + }); + areFilledIn.push(hasMetadataValue); + }); + + // Some required info wasn't filled in + if (areFilledIn.includes(false)) { + return false; + } + + // Check IP address + if (isEmpty(this.ipAddress$.value)) { + return false; + } + + return true; + } + + private createSearchOptions(bitstreamUUID: string, ePersonUUID: string) { + const params = []; + if (hasValue(bitstreamUUID)) { + params.push(new RequestParam('bitstreamUUID', bitstreamUUID)); + } + if (hasValue(ePersonUUID)) { + params.push(new RequestParam('userUUID', ePersonUUID)); + } + return Object.assign(new FindListOptions(), { + searchParams: [...params], + }); + } + + /** + * Retrieve the current user + */ + private getCurrentUser(): Observable { + return this.auth.isAuthenticated().pipe( + switchMap((authenticated) => { + if (authenticated) { + return this.auth.getAuthenticatedUserFromStore(); + } else { + return of(undefined); + } + }), + ); + } + + /** + * Load the user IP Address by API + * */ + private loadIPAddress() { + const requestId = this.requestService.generateRequestId(); + + const url = this.halService.getRootHref() + '/userinfo/ipaddress'; + const getRequest = new GetRequest(requestId, url); + // Send GET request + this.requestService.send(getRequest); + // Get response + const response = this.rdbService.buildFromRequestUUID(requestId); + response + .pipe(getFirstCompletedRemoteData()) + .subscribe((responseRD$: RemoteData) => { + if (hasFailed(responseRD$.state)) { + this.error$.value.push('Cannot load the IP Address'); + return; + } + if (isEmpty(responseRD$?.payload)) { + return; + } + this.ipAddress$.next(responseRD$?.payload?.ipAddress); + }); + } + + private loadCurrentItem() { + // Load Item from ItemRestRepository - search method + this.itemService.searchBy('byBitstream', + this.createSearchOptions(this.getBitstreamUUID(), null), false, true) + .pipe( + getFirstSucceededRemoteListPayload()) + .subscribe(itemList => { + // The bitstream should be attached only to the one item. + const item = itemList?.[0]; + if (isEmpty(item)) { + this.error$.value.push('Cannot load the Item'); + return; + } + this.item$.next(item); + }); + } + + private loadHelpDeskEmail() { + this.helpDesk$ = this.configurationDataService.findByPropertyName(HELP_DESK_PROPERTY); + } +} + +interface IPAddress { + ipAddress: string; +} diff --git a/src/app/bitstream-page/clarin-zip-download-page/clarin-zip-download-page.component.ts b/src/app/bitstream-page/clarin-zip-download-page/clarin-zip-download-page.component.ts new file mode 100644 index 00000000000..18550ce24bc --- /dev/null +++ b/src/app/bitstream-page/clarin-zip-download-page/clarin-zip-download-page.component.ts @@ -0,0 +1,108 @@ +import { AsyncPipe } from '@angular/common'; +import { + Component, + OnInit, +} from '@angular/core'; +import { + ActivatedRoute, + Router, +} from '@angular/router'; +import { TranslateService } from '@ngx-translate/core'; +import { + BehaviorSubject, + Observable, +} from 'rxjs'; +import { map } from 'rxjs/operators'; + +import { AuthService } from '../../core/auth/auth.service'; +import { RemoteDataBuildService } from '../../core/cache/builders/remote-data-build.service'; +import { BitstreamDataService } from '../../core/data/bitstream-data.service'; +import { AuthorizationDataService } from '../../core/data/feature-authorization/authorization-data.service'; +import { PaginatedList } from '../../core/data/paginated-list.model'; +import { RemoteData } from '../../core/data/remote-data'; +import { RequestService } from '../../core/data/request.service'; +import { HardRedirectService } from '../../core/services/hard-redirect.service'; +import { Bitstream } from '../../core/shared/bitstream.model'; +import { FileService } from '../../core/shared/file.service'; +import { HALEndpointService } from '../../core/shared/hal-endpoint.service'; +import { Item } from '../../core/shared/item.model'; +import { getFirstCompletedRemoteData } from '../../core/shared/operators'; +import { + hasValue, + isUndefined, +} from '../../shared/empty.util'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { createSuccessfulRemoteDataObject$ } from '../../shared/remote-data.utils'; +import { ClarinBitstreamAuthorizationDeniedComponent } from '../clarin-bitstream-authorization-denied/clarin-bitstream-authorization-denied.component'; +import { ClarinBitstreamDownloadPageComponent } from '../clarin-bitstream-download-page/clarin-bitstream-download-page.component'; +import { ClarinBitstreamTokenExpiredComponent } from '../clarin-bitstream-token-expired/clarin-bitstream-token-expired.component'; +import { ClarinLicenseAgreementPageComponent } from '../clarin-license-agreement-page/clarin-license-agreement-page.component'; + +/** + * Fetch ZIP file from the server as a single file into `bitstreamRD$` property which is extended and then call + * `super.ngOnInit()` to continue the parent process. + */ +@Component({ + imports: [ + AsyncPipe, + ClarinBitstreamAuthorizationDeniedComponent, + ClarinBitstreamTokenExpiredComponent, + ClarinLicenseAgreementPageComponent, + TranslateModule, + ], + selector: 'ds-clarin-zip-download-page', + templateUrl: '../clarin-bitstream-download-page/clarin-bitstream-download-page.component.html', + styleUrls: ['../clarin-bitstream-download-page/clarin-bitstream-download-page.component.scss'], +}) +export class ClarinZipDownloadPageComponent extends ClarinBitstreamDownloadPageComponent implements OnInit { + itemRD$: Observable>; + bitstreams$: BehaviorSubject = new BehaviorSubject([]); + + constructor( + protected route: ActivatedRoute, + protected router: Router, + protected auth: AuthService, + protected authorizationService: AuthorizationDataService, + protected hardRedirectService: HardRedirectService, + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected halService: HALEndpointService, + protected fileService: FileService, + protected bitstreamDataService: BitstreamDataService, + protected translateService: TranslateService, + protected notificationsService: NotificationsService, + ) { + super(route, router, auth, authorizationService, hardRedirectService, requestService, rdbService, halService, + fileService); + } + + ngOnInit(): void { + this.itemRD$ = this.route.data.pipe( + map((data) => data.dso)); + + this.itemRD$.subscribe((itemRD: RemoteData) => { + this.bitstreamDataService.findAllByItemAndBundleName(itemRD?.payload, 'ORIGINAL', { + currentPage: 1, + elementsPerPage: 9999, + }).pipe( + getFirstCompletedRemoteData(), + ).subscribe((bitstreamsRD: RemoteData>) => { + if (bitstreamsRD.errorMessage) { + this.notificationsService.error(this.translateService.get('file-section.error.header'), + `${bitstreamsRD.statusCode} ${bitstreamsRD.errorMessage}`); + } else if (hasValue(bitstreamsRD.payload)) { + const current: Bitstream[] = this.bitstreams$.getValue(); + this.bitstreams$.next([...current, ...bitstreamsRD.payload.page]); + this.bitstreamRD$ = createSuccessfulRemoteDataObject$(this.bitstreams$.getValue()[0]); + this.dtoken = isUndefined(this.route.snapshot.queryParams.dtoken) ? null : this.route.snapshot.queryParams.dtoken; + const baseUrl = this.halService.getRootHref() + + `/core/items/${itemRD.payload.uuid}/allzip?handleId=${itemRD?.payload?.handle}`; + // Do not add `dtoken` into the URL if it is null + const dtokenParam = this.dtoken ? `&dtoken=${this.dtoken}` : ''; + this.zipDownloadLink.next(baseUrl + dtokenParam); + super.ngOnInit(); + } + }); + }); + } +} diff --git a/src/app/breadcrumbs/breadcrumbs.component.scss b/src/app/breadcrumbs/breadcrumbs.component.scss index 7da9ad02d8c..b86c3903568 100644 --- a/src/app/breadcrumbs/breadcrumbs.component.scss +++ b/src/app/breadcrumbs/breadcrumbs.component.scss @@ -7,8 +7,9 @@ padding-bottom: calc(var(--ds-content-spacing) / 2); padding-top: calc(var(--ds-content-spacing) / 2); background-color: var(--ds-breadcrumb-bg) !important; - padding-left: calc(var(--bs-spacer) *.75); - padding-right: calc(var(--bs-spacer) *.75); + /* production (v7) breadcrumb side padding is a full spacer (16px) */ + padding-left: var(--bs-spacer); + padding-right: var(--bs-spacer); } li.breadcrumb-item { diff --git a/src/app/change-submitter-page/change-submitter-page.component.html b/src/app/change-submitter-page/change-submitter-page.component.html new file mode 100644 index 00000000000..2b31b81f080 --- /dev/null +++ b/src/app/change-submitter-page/change-submitter-page.component.html @@ -0,0 +1,39 @@ +
+
+

{{'share.submission.page.title' | translate}}

+ @if (sub) { +
+ {{'change.submitter.page.message' | translate}} + {{getName(sub)}} + ({{sub?.email}}) +
+ } + @if (!sub) { +
+ {{'change.submitter.page.cannot.see.submitter.message' | translate}} +
+ } + +
+ {{'change.submitter.page.items.handle.message' | translate}} + {{item?.handle}} +
+
+ {{'change.submitter.page.items.name.message' | translate}} + {{getName(item)}} +
+ +
+ +
+
+
+ + diff --git a/src/app/change-submitter-page/change-submitter-page.component.scss b/src/app/change-submitter-page/change-submitter-page.component.scss new file mode 100644 index 00000000000..46dea8e2a2a --- /dev/null +++ b/src/app/change-submitter-page/change-submitter-page.component.scss @@ -0,0 +1,3 @@ +/** +The file for styling the ChangeSubmitterPageComponent. + */ diff --git a/src/app/change-submitter-page/change-submitter-page.component.ts b/src/app/change-submitter-page/change-submitter-page.component.ts new file mode 100644 index 00000000000..4e2262f15f9 --- /dev/null +++ b/src/app/change-submitter-page/change-submitter-page.component.ts @@ -0,0 +1,202 @@ +import { CommonModule } from '@angular/common'; +import { HttpHeaders } from '@angular/common/http'; +import { + Component, + OnInit, +} from '@angular/core'; +import { ActivatedRoute } from '@angular/router'; +import { + TranslateModule, + TranslateService, +} from '@ngx-translate/core'; +import { + BehaviorSubject, + Observable, +} from 'rxjs'; +import { map } from 'rxjs/operators'; + +import { DSONameService } from '../core/breadcrumbs/dso-name.service'; +import { RemoteDataBuildService } from '../core/cache/builders/remote-data-build.service'; +import { RequestParam } from '../core/cache/models/request-param.model'; +import { RemoteData } from '../core/data/remote-data'; +import { GetRequest } from '../core/data/request.models'; +import { RequestService } from '../core/data/request.service'; +import { HttpOptions } from '../core/dspace-rest/dspace-rest.service'; +import { EPerson } from '../core/eperson/models/eperson.model'; +import { HALEndpointService } from '../core/shared/hal-endpoint.service'; +import { Item } from '../core/shared/item.model'; +import { + getFirstCompletedRemoteData, + getFirstSucceededRemoteDataPayload, + getFirstSucceededRemoteListPayload, +} from '../core/shared/operators'; +import { WorkspaceItem } from '../core/submission/models/workspaceitem.model'; +import { WorkspaceitemDataService } from '../core/submission/workspaceitem-data.service'; +import { hasNoValue } from '../shared/empty.util'; +import { NotificationsService } from '../shared/notifications/notifications.service'; +import { followLink } from '../shared/utils/follow-link-config.model'; +import { VarDirective } from '../shared/utils/var.directive'; + +@Component({ + imports: [CommonModule, + TranslateModule, VarDirective], + selector: 'ds-change-submitter-page', + templateUrl: './change-submitter-page.component.html', + styleUrls: ['./change-submitter-page.component.scss'], +}) +export class ChangeSubmitterPageComponent implements OnInit { + + /** + * Share token from the url. This token is used to retrieve the WorkspaceItem. + */ + private shareToken = ''; + + /** + * WorkspaceItem id from the url. + * This id is used to get authorization rights to call REST API to change the submitter. + */ + private workspaceitemid = ''; + + /** + * BehaviorSubject that contains the submitter of the WorkspaceItem. + */ + submitter: BehaviorSubject = new BehaviorSubject(null); + + /** + * BehaviorSubject that contains the Item. + */ + item: BehaviorSubject = new BehaviorSubject(null); + + /** + * BehaviorSubject that contains the WorkspaceItem. + */ + workspaceItem: BehaviorSubject = new BehaviorSubject(null); + + /** + * Boolean that indicates if the spinner should be shown when the submitter is being changed. + */ + changeSubmitterSpinner = false; + + constructor(private workspaceItemService: WorkspaceitemDataService, + private route: ActivatedRoute, + public dsoNameService: DSONameService, + protected halService: HALEndpointService, + protected rdbService: RemoteDataBuildService, + protected requestService: RequestService, + protected notificationsService: NotificationsService, + protected translate: TranslateService) {} + + ngOnInit(): void { + // Load `share_token` param value from the url + this.shareToken = this.route.snapshot.queryParams.share_token; + // Load `workspaceitem_id` param value from the url + this.workspaceitemid = this.route.snapshot.queryParams.workspaceitemid; + this.loadWorkspaceItemAndAssignSubmitter(this.shareToken); + } + + /** + * Load the WorkspaceItem using the shareToken and assign the submitter from the retrieved WorkspaceItem. + */ + loadWorkspaceItemAndAssignSubmitter(shareToken: string) { + this.findWorkspaceItemByShareToken(shareToken)?.subscribe((workspaceItem: WorkspaceItem) => { + this.workspaceItem.next(workspaceItem); + this.loadItemFromWorkspaceItem(workspaceItem); + this.loadAndAssignSubmitter(workspaceItem); + }); + } + + /** + * Load the Item from the WorkspaceItem and assign it to the item BehaviorSubject. + */ + loadItemFromWorkspaceItem(workspaceItem: WorkspaceItem) { + if (workspaceItem.item instanceof Observable) { + workspaceItem.item + .pipe(getFirstSucceededRemoteDataPayload()) + .subscribe((item: Item) => { + this.item.next(item); + }); + } + } + + /** + * Find a WorkspaceItem by its shareToken. + */ + findWorkspaceItemByShareToken(shareToken: string): Observable { + let requestHeaders = new HttpHeaders(); + const requestOptions: HttpOptions = Object.create({}); + requestHeaders = requestHeaders.append('shareToken', shareToken); + requestOptions.headers = requestHeaders; + + return this.workspaceItemService.searchBy('shareToken', { + searchParams: [Object.assign(new RequestParam('shareToken', shareToken))], + }, false, false, followLink('item'), followLink('submitter')).pipe(getFirstSucceededRemoteListPayload(), + map((workspaceItems: WorkspaceItem[]) => workspaceItems?.[0])); + } + + /** + * Load the submitter from the WorkspaceItem and assign it to the submitter BehaviorSubject. + */ + loadAndAssignSubmitter(workspaceItem: WorkspaceItem) { + if (hasNoValue(workspaceItem)) { + console.error('Cannot load submitter because WorkspaceItem is null or undefined'); + return; + } + + if (workspaceItem.submitter instanceof Observable) { + workspaceItem.submitter + .pipe(getFirstSucceededRemoteDataPayload()) + .subscribe((submitter: any) => { + this.assignSubmitter(submitter); + }); + } else { + this.assignSubmitter(workspaceItem.submitter); + } + } + + /** + * Assign a new submitter to the submitter BehaviorSubject. + */ + assignSubmitter(eperson: EPerson) { + this.submitter.next(eperson); + } + + /** + * Get the name of the submitter or item using the DSONameService. + */ + getName(object: EPerson | Item) { + if (hasNoValue(object)) { + return ''; + } + return this.dsoNameService.getName(object); + } + + /** + * Change the submitter of the WorkspaceItem using the shareToken. This will send a GET request to the backend when + * the submitter of the Item is changed. + */ + changeSubmitter() { + const requestId = this.requestService.generateRequestId(); + + const url = this.halService.getRootHref() + '/submission/setOwner?shareToken=' + this.shareToken + + '&workspaceitemid=' + this.workspaceitemid; + + const getRequest = new GetRequest(requestId, url); + // Send GET request + this.requestService.send(getRequest); + this.changeSubmitterSpinner = true; + // Get response + const response = this.rdbService.buildFromRequestUUID(requestId); + response.pipe(getFirstCompletedRemoteData()).subscribe((rd: RemoteData) => { + if (rd.hasSucceeded) { + this.notificationsService.success( + this.translate.instant('change.submitter.page.changed-successfully')); + // Update the submitter + this.loadWorkspaceItemAndAssignSubmitter(this.shareToken); + } else { + this.notificationsService.error( + this.translate.instant('change.submitter.page.changed-error')); + } + this.changeSubmitterSpinner = false; + }); + } +} diff --git a/src/app/clarin-licenses/clarin-all-licenses-page/clarin-all-licenses-page.component.html b/src/app/clarin-licenses/clarin-all-licenses-page/clarin-all-licenses-page.component.html new file mode 100644 index 00000000000..ccbd804a179 --- /dev/null +++ b/src/app/clarin-licenses/clarin-all-licenses-page/clarin-all-licenses-page.component.html @@ -0,0 +1,44 @@ +
+
+
{{ 'clarin.license.all-page.title' | translate }}
+ @if (isLoading) { + + } + @for (clarinLicense of (licensesRD$ | async); track clarinLicense) { +
+
{{ clarinLicense?.name }}
+
+
+
{{'clarin.license.all-page.source' | translate}}
+ +
+
+
{{'clarin.license.all-page.labels' | translate}}
+ + {{clarinLicense?.clarinLicenseLabel?.title}} + + @for (clarinLicenseLabel of clarinLicense?.extendedClarinLicenseLabels; track clarinLicenseLabel) { + + {{clarinLicenseLabel?.title}} + + } +
+
+
{{'clarin.license.all-page.extra-information' | translate}}
+ @if (!clarinLicense?.requiredInfo) { + {{'clarin.license.all-page.extra-information.default' | translate}} + + } + @for (requiredInformation of getRequiredInfo(clarinLicense); track requiredInformation) { + + {{requiredInformation?.value}} + + } +
+
+
+ } +
+
diff --git a/src/app/clarin-licenses/clarin-all-licenses-page/clarin-all-licenses-page.component.scss b/src/app/clarin-licenses/clarin-all-licenses-page/clarin-all-licenses-page.component.scss new file mode 100644 index 00000000000..df450dd3449 --- /dev/null +++ b/src/app/clarin-licenses/clarin-all-licenses-page/clarin-all-licenses-page.component.scss @@ -0,0 +1,23 @@ +.label-PUB { + background-color: #5cb811 !important; + color: white !important; +} + +.label-RES { + background-color: #c62d1f !important; + color: white !important; +} + +.label-ACA, .label-PDT { + background-color: #ffab23 !important; + color: white !important; +} + +.label-default { + background-color: #999 !important; + color: white !important; +} + +.license-card-border { + border: 1px solid #e3e3e3; +} diff --git a/src/app/clarin-licenses/clarin-all-licenses-page/clarin-all-licenses-page.component.ts b/src/app/clarin-licenses/clarin-all-licenses-page/clarin-all-licenses-page.component.ts new file mode 100644 index 00000000000..b3f79fe7447 --- /dev/null +++ b/src/app/clarin-licenses/clarin-all-licenses-page/clarin-all-licenses-page.component.ts @@ -0,0 +1,97 @@ +import { CommonModule } from '@angular/common'; +import { + Component, + OnInit, +} from '@angular/core'; +import { TranslateModule } from '@ngx-translate/core'; +import { BehaviorSubject } from 'rxjs'; + +import { ClarinLicenseDataService } from '../../core/data/clarin/clarin-license-data.service'; +import { FindListOptions } from '../../core/data/find-list-options.model'; +import { ClarinLicense } from '../../core/shared/clarin/clarin-license.model'; +import { ClarinLicenseRequiredInfo } from '../../core/shared/clarin/clarin-license.resource-type'; +import { ClarinLicenseRequiredInfoSerializer } from '../../core/shared/clarin/clarin-license-required-info-serializer'; +import { getFirstSucceededRemoteListPayload } from '../../core/shared/operators'; +import { ThemedLoadingComponent } from '../../shared/loading/themed-loading.component'; + +@Component({ + imports: [ + CommonModule, + ThemedLoadingComponent, + TranslateModule, + ], + selector: 'ds-clarin-all-licenses-page', + templateUrl: './clarin-all-licenses-page.component.html', + styleUrls: ['./clarin-all-licenses-page.component.scss'], +}) +export class ClarinAllLicensesPageComponent implements OnInit { + + /** + * The list of ClarinLicense object as BehaviorSubject object + */ + licensesRD$: BehaviorSubject = new BehaviorSubject(null); + + /** + * If the request isn't processed show to loading bar. + */ + isLoading = false; + + constructor(private clarinLicenseService: ClarinLicenseDataService) { } + + ngOnInit(): void { + this.loadAllLicenses(); + } + + loadAllLicenses() { + this.isLoading = true; + + const options = new FindListOptions(); + options.currentPage = 0; + // Load all licenses + options.elementsPerPage = 1000; + return this.clarinLicenseService.findAll(options, false) + .pipe(getFirstSucceededRemoteListPayload()) + .subscribe(res => { + this.licensesRD$.next(this.filterLicensesByLicenseLabel(res)); + this.isLoading = false; + }); + } + + /** + * Show PUB licenses at first, then ACA and RES + * @private + */ + private filterLicensesByLicenseLabel(clarinLicensesResponse: ClarinLicense[]) { + // Show PUB licenses as first. + const pubLicenseArray = []; + // Then show ACA and RES licenses. + const acaResLicenseArray = []; + + clarinLicensesResponse?.forEach(clarinLicense => { + if (clarinLicense?.clarinLicenseLabel?.label === 'PUB') { + pubLicenseArray.push(clarinLicense); + } else { + acaResLicenseArray.push(clarinLicense); + } + }); + + // Sort acaResLicenseArray by the license label (ACA, RES) + acaResLicenseArray.sort((a, b) => a.clarinLicenseLabel?.label?.localeCompare(b.clarinLicenseLabel?.label)); + + // Concat two array into one. + return pubLicenseArray.concat(acaResLicenseArray); + } + + /** + * ClarinLicense has RequiredInfo stored as string in the database, convert this string value into + * list of ClarinLicenseRequiredInfo objects. + */ + public getRequiredInfo(clarinLicense: ClarinLicense): ClarinLicenseRequiredInfo[] { + let requiredInfo = clarinLicense.requiredInfo; + if (typeof requiredInfo === 'string') { + requiredInfo = ClarinLicenseRequiredInfoSerializer.Deserialize(requiredInfo); + } + return requiredInfo; + } + +} diff --git a/src/app/clarin-licenses/clarin-license-page/clarin-license-page.component.html b/src/app/clarin-licenses/clarin-license-page/clarin-license-page.component.html new file mode 100644 index 00000000000..8ef9f0b6991 --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-page/clarin-license-page.component.html @@ -0,0 +1,8 @@ +
+
+
+ +
+
+ +
diff --git a/src/app/clarin-licenses/clarin-license-page/clarin-license-page.component.scss b/src/app/clarin-licenses/clarin-license-page/clarin-license-page.component.scss new file mode 100644 index 00000000000..e6b58000c82 --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-page/clarin-license-page.component.scss @@ -0,0 +1,3 @@ +/** + The file for styling `clarin-license-page.component.html`. No styling needed. + */ diff --git a/src/app/clarin-licenses/clarin-license-page/clarin-license-page.component.ts b/src/app/clarin-licenses/clarin-license-page/clarin-license-page.component.ts new file mode 100644 index 00000000000..ef561e5d43e --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-page/clarin-license-page.component.ts @@ -0,0 +1,22 @@ +import { Component } from '@angular/core'; +import { TranslateModule } from '@ngx-translate/core'; + +import { ClarinLicenseTableComponent } from '../clarin-license-table/clarin-license-table.component'; + +/** + * Component which wraps clarin license table into the container + */ +@Component({ + imports: [ + ClarinLicenseTableComponent, + TranslateModule, + ], + selector: 'ds-clarin-license-page', + templateUrl: './clarin-license-page.component.html', + styleUrls: ['./clarin-license-page.component.scss'], +}) +export class ClarinLicensePageComponent { + + // eslint-disable-next-line @typescript-eslint/no-empty-function + constructor() { } +} diff --git a/src/app/clarin-licenses/clarin-license-routes.ts b/src/app/clarin-licenses/clarin-license-routes.ts new file mode 100644 index 00000000000..d654900f48d --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-routes.ts @@ -0,0 +1,27 @@ +import { Route } from '@angular/router'; + +import { LICENSES_MANAGE_TABLE_PATH } from '../app-routing-paths'; +import { i18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.resolver'; +import { siteAdministratorGuard } from '../core/data/feature-authorization/feature-authorization-guard/site-administrator.guard'; +import { ClarinAllLicensesPageComponent } from './clarin-all-licenses-page/clarin-all-licenses-page.component'; +import { ClarinLicensePageComponent } from './clarin-license-page/clarin-license-page.component'; + +/** + * Routes for the CLARIN license pages (public license list + admin manage-table). + * Ported from the 7.x ClarinLicenseRoutingModule to the v9 standalone routes pattern. + */ +export const ROUTES: Route[] = [ + { + path: '', + resolve: { breadcrumb: i18nBreadcrumbResolver }, + component: ClarinAllLicensesPageComponent, + data: { breadcrumbKey: 'licenses' }, + }, + { + path: LICENSES_MANAGE_TABLE_PATH, + component: ClarinLicensePageComponent, + resolve: { breadcrumb: i18nBreadcrumbResolver }, + data: { breadcrumbKey: 'licenses.manage-table' }, + canActivate: [siteAdministratorGuard], + }, +]; diff --git a/src/app/clarin-licenses/clarin-license-table-pagination.ts b/src/app/clarin-licenses/clarin-license-table-pagination.ts new file mode 100644 index 00000000000..52b67ca9aea --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table-pagination.ts @@ -0,0 +1,20 @@ +import { + SortDirection, + SortOptions, +} from '../core/cache/models/sort-options.model'; +import { PaginationComponentOptions } from '../shared/pagination/pagination-component-options.model'; + +/** + * Pagination constants for the clarin license table + */ + +export const paginationID = 'cLicense'; + +// pageSize: 200; get all licenses +export const defaultPagination = Object.assign(new PaginationComponentOptions(), { + id: paginationID, + currentPage: 1, + pageSize: 10, +}); + +export const defaultSortConfiguration = new SortOptions('', SortDirection.DESC); diff --git a/src/app/clarin-licenses/clarin-license-table/clarin-license-table.component.html b/src/app/clarin-licenses/clarin-license-table/clarin-license-table.component.html new file mode 100644 index 00000000000..31b971d1f37 --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table/clarin-license-table.component.html @@ -0,0 +1,90 @@ +
+
+ + + + +
+ +
+
+ + + + + + + + + + + + + + + + @for (cLicense of cLicenses?.page; track cLicense) { + + + + + + + + + + + } + +
{{"clarin-license.table.name" | translate}}{{"clarin-license.table.definition" | translate}}{{"clarin-license.table.confirmation" | translate}}{{"clarin-license.table.required-user-info" | translate}}{{"clarin-license.table.label" | translate}}{{"clarin-license.table.extended-labels" | translate}}{{"clarin-license.table.bitstreams" | translate}}
+ + {{cLicense?.name}}{{cLicense?.definition}}{{cLicense?.confirmation}}{{cLicense?.requiredInfo | dsCLicenseRequiredInfo}}{{cLicense?.clarinLicenseLabel?.label}}{{cLicense?.extendedClarinLicenseLabels | dsExtendedCLicense}}{{cLicense?.bitstreams}}
+ @if (isLoading) { + + } +
+ +
+
+
+ +
+ + +
+
+
+
+ +
+
+ +
+
+
+
+
diff --git a/src/app/clarin-licenses/clarin-license-table/clarin-license-table.component.scss b/src/app/clarin-licenses/clarin-license-table/clarin-license-table.component.scss new file mode 100644 index 00000000000..b4dab6de9bf --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table/clarin-license-table.component.scss @@ -0,0 +1,17 @@ +.table { + table-layout: fixed; + word-wrap: break-word; +} + +.w-20 { + width: 20%; +} + +.w-12 { + width: 12%; +} + +.wm-3p5 { + width: 3.5%; + max-width: 3.5%; +} diff --git a/src/app/clarin-licenses/clarin-license-table/clarin-license-table.component.ts b/src/app/clarin-licenses/clarin-license-table/clarin-license-table.component.ts new file mode 100644 index 00000000000..ce02b6e9ef3 --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table/clarin-license-table.component.ts @@ -0,0 +1,441 @@ +import { CommonModule } from '@angular/common'; +import { + Component, + OnInit, +} from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { + NgbActiveModal, + NgbDropdownModule, + NgbModal, +} from '@ng-bootstrap/ng-bootstrap'; +import { + TranslateModule, + TranslateService, +} from '@ngx-translate/core'; +import cloneDeep from 'lodash/cloneDeep'; +import { + BehaviorSubject, + combineLatest as observableCombineLatest, +} from 'rxjs'; +import { switchMap } from 'rxjs/operators'; + +import { RequestParam } from '../../core/cache/models/request-param.model'; +import { ClarinLicenseDataService } from '../../core/data/clarin/clarin-license-data.service'; +import { ClarinLicenseLabelDataService } from '../../core/data/clarin/clarin-license-label-data.service'; +import { PaginatedList } from '../../core/data/paginated-list.model'; +import { RemoteData } from '../../core/data/remote-data'; +import { PaginationService } from '../../core/pagination/pagination.service'; +import { ClarinLicense } from '../../core/shared/clarin/clarin-license.model'; +import { ClarinLicenseConfirmationSerializer } from '../../core/shared/clarin/clarin-license-confirmation-serializer'; +import { ClarinLicenseLabel } from '../../core/shared/clarin/clarin-license-label.model'; +import { ClarinLicenseLabelExtendedSerializer } from '../../core/shared/clarin/clarin-license-label-extended-serializer'; +import { ClarinLicenseRequiredInfoSerializer } from '../../core/shared/clarin/clarin-license-required-info-serializer'; +import { + getFirstCompletedRemoteData, + getFirstSucceededRemoteData, +} from '../../core/shared/operators'; +import { BtnDisabledDirective } from '../../shared/btn-disabled.directive'; +import { isNull } from '../../shared/empty.util'; +import { ThemedLoadingComponent } from '../../shared/loading/themed-loading.component'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { PaginationComponent } from '../../shared/pagination/pagination.component'; +import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model'; +import { ClarinExtendedLicensePipe } from '../../shared/utils/clarin-extended-license.pipe'; +import { ClarinLicenseRequiredInfoPipe } from '../../shared/utils/clarin-license-required-info.pipe'; +import { VarDirective } from '../../shared/utils/var.directive'; +import { + defaultPagination, + defaultSortConfiguration, +} from '../clarin-license-table-pagination'; +import { DefineLicenseFormComponent } from './modal/define-license-form/define-license-form.component'; +import { DefineLicenseLabelFormComponent } from './modal/define-license-label-form/define-license-label-form.component'; + +/** + * Component for managing clarin licenses and defining clarin license labels. + */ +@Component({ + + imports: [BtnDisabledDirective, + ClarinExtendedLicensePipe, + ClarinLicenseRequiredInfoPipe, + CommonModule, + FormsModule, + NgbDropdownModule, + PaginationComponent, + ThemedLoadingComponent, + TranslateModule, VarDirective], + providers: [NgbActiveModal], + selector: 'ds-clarin-license-table', + templateUrl: './clarin-license-table.component.html', + styleUrls: ['./clarin-license-table.component.scss'], +}) +export class ClarinLicenseTableComponent implements OnInit { + + constructor(private paginationService: PaginationService, + private clarinLicenseService: ClarinLicenseDataService, + private clarinLicenseLabelService: ClarinLicenseLabelDataService, + private modalService: NgbModal, + public activeModal: NgbActiveModal, + private notificationService: NotificationsService, + private translateService: TranslateService) { } + + /** + * The list of ClarinLicense object as BehaviorSubject object + */ + licensesRD$: BehaviorSubject>> = new BehaviorSubject>>(null); + + /** + * The pagination options + * Start at page 1 and always use the set page size + */ + options: PaginationComponentOptions; + + /** + * The license which is currently selected, only one license could be selected + */ + selectedLicense: ClarinLicense; + + /** + * If the request isn't processed show the loading bar. + */ + isLoading = false; + + /** + * License name typed into search input field, it is passed to the BE as searching value. + */ + searchingLicenseName = ''; + + /** + * Stores the previous search term to detect when a new search should reset pagination. + */ + private previousSearchTerm = ''; + + ngOnInit(): void { + this.initializePaginationOptions(); + this.loadAllLicenses(); + } + + // define license + /** + * Pop up the License modal where the user fill in the License data. + */ + openDefineLicenseForm() { + const defineLicenseModalRef = this.modalService.open(DefineLicenseFormComponent); + + defineLicenseModalRef.result.then((result: ClarinLicense) => { + this.defineNewLicense(result); + }).catch((error) => { + console.error(error); + }); + } + + /** + * Send create request to the API with the new License. + * @param clarinLicense from the License modal. + */ + defineNewLicense(clarinLicense: ClarinLicense) { + const successfulMessageContentDef = 'clarin-license.define-license.notification.successful-content'; + const errorMessageContentDef = 'clarin-license.define-license.notification.error-content'; + if (isNull(clarinLicense)) { + this.notifyOperationStatus(clarinLicense, successfulMessageContentDef, errorMessageContentDef); + } + + // convert string value from the form to the number + clarinLicense.confirmation = ClarinLicenseConfirmationSerializer.Serialize(clarinLicense.confirmation); + // convert ClarinLicenseUserInfo.short the string value + if (Array.isArray(clarinLicense.requiredInfo)) { + clarinLicense.requiredInfo = ClarinLicenseRequiredInfoSerializer.Serialize(clarinLicense.requiredInfo); + } + + this.clarinLicenseService.create(clarinLicense) + .pipe(getFirstCompletedRemoteData()) + .subscribe((defineLicenseResponse: RemoteData) => { + // check payload and show error or successful + this.notifyOperationStatus(defineLicenseResponse, successfulMessageContentDef, errorMessageContentDef); + this.loadAllLicenses(); + }); + } + + // edit license + /** + * Pop up the License modal where the user fill in the License data. The modal is the same as the DefineLicenseForm. + */ + openEditLicenseForm() { + if (isNull(this.selectedLicense)) { + return; + } + + // pass the actual clarin license values to the define-clarin-license modal + const editLicenseModalRef = this.modalService.open(DefineLicenseFormComponent); + editLicenseModalRef.componentInstance.name = this.selectedLicense.name; + editLicenseModalRef.componentInstance.definition = this.selectedLicense.definition; + editLicenseModalRef.componentInstance.confirmation = this.selectedLicense.confirmation; + editLicenseModalRef.componentInstance.requiredInfo = this.selectedLicense.requiredInfo; + editLicenseModalRef.componentInstance.extendedClarinLicenseLabels = + this.selectedLicense.extendedClarinLicenseLabels; + editLicenseModalRef.componentInstance.clarinLicenseLabel = + this.selectedLicense.clarinLicenseLabel; + + editLicenseModalRef.result.then((result: ClarinLicense) => { + this.editLicense(result); + }); + } + + /** + * Send put request to the API with updated Clarin License. + * @param clarinLicense from the License modal. + */ + editLicense(clarinLicense: ClarinLicense) { + const successfulMessageContentDef = 'clarin-license.edit-license.notification.successful-content'; + const errorMessageContentDef = 'clarin-license.edit-license.notification.error-content'; + if (isNull(clarinLicense)) { + this.notifyOperationStatus(clarinLicense, successfulMessageContentDef, errorMessageContentDef); + } + + const clarinLicenseObj = new ClarinLicense(); + clarinLicenseObj.name = clarinLicense.name; + // @ts-ignore + clarinLicenseObj.clarinLicenseLabel = this.ignoreIcon(clarinLicense.clarinLicenseLabel); + // @ts-ignore + clarinLicenseObj.extendedClarinLicenseLabels = this.ignoreIcon(clarinLicense.extendedClarinLicenseLabels); + clarinLicenseObj._links = this.selectedLicense._links; + clarinLicenseObj.id = clarinLicense.id; + clarinLicenseObj.confirmation = clarinLicense.confirmation; + // convert ClarinLicenseUserInfo.short the string value + if (Array.isArray(clarinLicense.requiredInfo)) { + clarinLicenseObj.requiredInfo = ClarinLicenseRequiredInfoSerializer.Serialize(clarinLicense.requiredInfo); + } + clarinLicenseObj.definition = clarinLicense.definition; + clarinLicenseObj.bitstreams = clarinLicense.bitstreams; + clarinLicenseObj.type = clarinLicense.type; + + this.clarinLicenseService.put(clarinLicenseObj) + .pipe(getFirstCompletedRemoteData()) + .subscribe((editResponse: RemoteData) => { + // check payload and show error or successful + this.notifyOperationStatus(editResponse, successfulMessageContentDef, errorMessageContentDef); + this.loadAllLicenses(); + }); + } + + /** + * When the Clarin License is editing ignore the Clarin License Label Icons - it throws error on BE, because the icon + * is send as string not as byte array. + * @param clarinLicenses + */ + ignoreIcon(clarinLicenses: ClarinLicenseLabel | ClarinLicenseLabel[]) { + const clarinLicenseUpdatable = cloneDeep(clarinLicenses); + + if (Array.isArray(clarinLicenseUpdatable)) { + clarinLicenseUpdatable.forEach(clarinLicense => { + clarinLicense.icon = []; + }); + } else { + clarinLicenseUpdatable.icon = []; + } + return clarinLicenseUpdatable; + } + + // define license label + /** + * Pop up License Label modal where the user fill in the License Label data. + */ + openDefineLicenseLabelForm() { + const defineLicenseLabelModalRef = this.modalService.open(DefineLicenseLabelFormComponent); + + defineLicenseLabelModalRef.result.then((result: ClarinLicenseLabel) => { + this.defineLicenseLabel(result); + }).catch((error) => { + console.log(error); + }); + } + + /** + * Send create request to the API, the License Label icon is transformed to the byte array. + * @param clarinLicenseLabel object from the License Label modal. + */ + defineLicenseLabel(clarinLicenseLabel: ClarinLicenseLabel) { + const successfulMessageContentDef = 'clarin-license-label.define-license-label.notification.successful-content'; + const errorMessageContentDef = 'clarin-license-label.define-license-label.notification.error-content'; + if (isNull(clarinLicenseLabel)) { + this.notifyOperationStatus(clarinLicenseLabel, successfulMessageContentDef, errorMessageContentDef); + } + + // convert file to the byte array + const reader = new FileReader(); + const fileByteArray = []; + + try { + reader.readAsArrayBuffer(clarinLicenseLabel.icon?.[0]); + } catch (error) { + // Cannot read any icon that means there is no icon + // Create license label without icon + this.createClarinLicenseLabel(clarinLicenseLabel, [], successfulMessageContentDef, errorMessageContentDef); + return; + } + + // Create license label with icon + reader.onerror = (evt) => { + this.notifyOperationStatus(null, successfulMessageContentDef, errorMessageContentDef); + }; + reader.onloadend = (evt) => { + if (evt.target.readyState === FileReader.DONE) { + const arrayBuffer = evt.target.result; + if (arrayBuffer instanceof ArrayBuffer) { + const array = new Uint8Array(arrayBuffer); + for (const item of array) { + fileByteArray.push(item); + } + } + this.createClarinLicenseLabel(clarinLicenseLabel, fileByteArray, successfulMessageContentDef, errorMessageContentDef); + } + }; + } + + /** + * Call BE request to create a clarin license label with or without icon. + * Show response in the notification popup. + */ + createClarinLicenseLabel(clarinLicenseLabel: ClarinLicenseLabel, fileByteArray: any[] = [], + successfulMessageContentDef: any, errorMessageContentDef: any) { + clarinLicenseLabel.icon = fileByteArray; + // convert string value from the form to the boolean + clarinLicenseLabel.extended = ClarinLicenseLabelExtendedSerializer.Serialize(clarinLicenseLabel.extended); + + // create + this.clarinLicenseLabelService.create(clarinLicenseLabel) + .pipe(getFirstCompletedRemoteData()) + .subscribe((defineLicenseLabelResponse: RemoteData) => { + // check payload and show error or successful + this.notifyOperationStatus(defineLicenseLabelResponse, successfulMessageContentDef, errorMessageContentDef); + this.loadAllLicenses(); + }); + } + + // delete license + /** + * Delete selected license. If none license is selected do nothing. + */ + deleteLicense() { + if (isNull(this.selectedLicense?.id)) { + return; + } + this.clarinLicenseService.delete(String(this.selectedLicense.id)) + .pipe(getFirstCompletedRemoteData()) + .subscribe(deleteLicenseResponse => { + const successfulMessageContentDef = 'clarin-license.delete-license.notification.successful-content'; + const errorMessageContentDef = 'clarin-license.delete-license.notification.error-content'; + this.notifyOperationStatus(deleteLicenseResponse, successfulMessageContentDef, errorMessageContentDef); + this.loadAllLicenses(); + }); + } + + /** + * Pop up the notification about the request success. Messages are loaded from the `en.json5`. + * @param operationResponse current response + * @param sucContent successful message name + * @param errContent error message name + */ + notifyOperationStatus(operationResponse, sucContent, errContent) { + if (isNull(operationResponse)) { + this.notificationService.error('', this.translateService.get(errContent)); + return; + } + + if (operationResponse.hasSucceeded) { + this.notificationService.success('', + this.translateService.get(sucContent)); + } else if (operationResponse.isError) { + this.notificationService.error('', + this.translateService.get(errContent)); + } + } + + /** + * Update the page + */ + onPageChange() { + this.loadAllLicenses(); + } + + /** + * Run a search and reset the route-backed pagination when the search term changes. + */ + searchLicenses() { + const hasSearchTermChanged = this.searchingLicenseName !== this.previousSearchTerm; + + if (hasSearchTermChanged) { + this.paginationService.resetPage(this.options.id); + } + + this.loadAllLicenses(hasSearchTermChanged ? 1 : undefined); + this.previousSearchTerm = this.searchingLicenseName; + } + + /** + * Fetch all licenses from the API. + */ + loadAllLicenses(pageOverride?: number) { + this.selectedLicense = null; + this.licensesRD$ = new BehaviorSubject>>(null); + this.isLoading = true; + + // load the current pagination and sorting options + const currentPagination$ = this.getCurrentPagination(); + const currentSort$ = this.getCurrentSort(); + + observableCombineLatest([currentPagination$, currentSort$]).pipe( + switchMap(([currentPagination, currentSort]) => { + return this.clarinLicenseService.searchBy('byNameLike', { + currentPage: pageOverride ?? currentPagination.currentPage, + elementsPerPage: currentPagination.pageSize, + sort: { field: currentSort.field, direction: currentSort.direction }, + searchParams: [new RequestParam('name', this.searchingLicenseName)], + }, false, + ); + }), + getFirstSucceededRemoteData(), + ).subscribe((res: RemoteData>) => { + this.licensesRD$.next(res); + this.isLoading = false; + }); + } + + /** + * Mark the license as selected or unselect if it is already clicked. + * @param clarinLicense + */ + switchSelectedLicense(clarinLicense: ClarinLicense) { + if (isNull(clarinLicense)) { + return; + } + + if (this.selectedLicense?.id === clarinLicense?.id) { + this.selectedLicense = null; + } else { + this.selectedLicense = clarinLicense; + } + } + + /** + * Initialize the pagination options. Set the default values. + */ + private initializePaginationOptions() { + this.options = defaultPagination; + } + + /** + * Get the current pagination options. + */ + private getCurrentPagination() { + return this.paginationService.getCurrentPagination(this.options.id, this.options); + } + + /** + * Get the current sorting options. + */ + private getCurrentSort() { + return this.paginationService.getCurrentSort(this.options.id, defaultSortConfiguration); + } +} diff --git a/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form-validator.ts b/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form-validator.ts new file mode 100644 index 00000000000..4d4749ba617 --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form-validator.ts @@ -0,0 +1,19 @@ +import { + AbstractControl, + ValidationErrors, + ValidatorFn, +} from '@angular/forms'; + +/** + * One non extended License Label must be selected in defining the new License. + * If non license label is selected -> the `submit` button is disabled + */ +export function validateLicenseLabel(): ValidatorFn { + return (control: AbstractControl): ValidationErrors | null => { + if (!control.value) { + return { licenseLabel: true }; + } + + return null; + }; +} diff --git a/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form.component.html b/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form.component.html new file mode 100644 index 00000000000..77eeb374090 --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form.component.html @@ -0,0 +1,71 @@ + diff --git a/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form.component.scss b/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form.component.scss new file mode 100644 index 00000000000..1e3de2c47db --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form.component.scss @@ -0,0 +1,3 @@ +.modal { + display: inline; +} diff --git a/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form.component.ts b/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form.component.ts new file mode 100644 index 00000000000..b742adc47ad --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table/modal/define-license-form/define-license-form.component.ts @@ -0,0 +1,236 @@ + +import { + AfterViewInit, + Component, + Input, + OnInit, +} from '@angular/core'; +import { + FormArray, + FormBuilder, + FormGroup, + ReactiveFormsModule, + Validators, +} from '@angular/forms'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { TranslateModule } from '@ngx-translate/core'; + +import { ClarinLicenseLabelDataService } from '../../../../core/data/clarin/clarin-license-label-data.service'; +import { + CLARIN_LICENSE_CONFIRMATION, + CLARIN_LICENSE_FORM_REQUIRED_OPTIONS, +} from '../../../../core/shared/clarin/clarin-license.resource-type'; +import { ClarinLicenseLabel } from '../../../../core/shared/clarin/clarin-license-label.model'; +import { getFirstSucceededRemoteListPayload } from '../../../../core/shared/operators'; +import { BtnDisabledDirective } from '../../../../shared/btn-disabled.directive'; +import { + isNull, + isUndefined, +} from '../../../../shared/empty.util'; +import { CharToEndPipe } from '../../../../shared/utils/char-to-end.pipe'; +import { ClarinLicenseCheckedPipe } from '../../../../shared/utils/clarin-license-checked.pipe'; +import { ClarinLicenseLabelRadioValuePipe } from '../../../../shared/utils/clarin-license-label-radio-value.pipe'; +import { ClarinLicenseRequiredInfoCheckedPipe } from '../../../../shared/utils/clarin-license-required-info-checked.pipe'; +import { validateLicenseLabel } from './define-license-form-validator'; + +/** + * The component for defining and editing the Clarin License + */ +@Component({ + + imports: [ + BtnDisabledDirective, + CharToEndPipe, + ClarinLicenseCheckedPipe, + ClarinLicenseLabelRadioValuePipe, + ClarinLicenseRequiredInfoCheckedPipe, + ReactiveFormsModule, + TranslateModule, + ], + selector: 'ds-define-license-form', + templateUrl: './define-license-form.component.html', + styleUrls: ['./define-license-form.component.scss'], +}) +export class DefineLicenseFormComponent implements OnInit, AfterViewInit { + + constructor( + public activeModal: NgbActiveModal, + private formBuilder: FormBuilder, + private clarinLicenseLabelService: ClarinLicenseLabelDataService, + ) { + } + + /** + * The `name` of the Clarin License + */ + @Input() + name = ''; + + /** + * The `definition` of the Clarin License + */ + @Input() + definition = ''; + + /** + * The `confirmation` of the Clarin License. This value is converted to the number in the appropriate Serializer + */ + @Input() + confirmation = ''; + + /** + * Selected extended license labels + */ + @Input() + extendedClarinLicenseLabels = []; + + /** + * Selected non extended clarin license label - could be selected only one clarin license label + */ + @Input() + clarinLicenseLabel: ClarinLicenseLabel = null; + + /** + * Selected required info + */ + @Input() + requiredInfo = []; + + /** + * The form with the Clarin License input fields + */ + clarinLicenseForm: FormGroup = null; + + /** + * The possible options for the `confirmation` input field + */ + confirmationOptions: any[] = CLARIN_LICENSE_CONFIRMATION; + + /** + * All non extended Clarin License Labels, admin could select only one Clarin License Label + */ + clarinLicenseLabelOptions: ClarinLicenseLabel[] = []; + + /** + * All extended Clarin License Labels, admin could select multiple Clarin License Labels + */ + extendedClarinLicenseLabelOptions: ClarinLicenseLabel[] = []; + + /** + * All user required info + */ + requiredInfoOptions = CLARIN_LICENSE_FORM_REQUIRED_OPTIONS; + + ngOnInit(): void { + this.createForm(); + // load clarin license labels + this.loadAndAssignClarinLicenseLabels(); + } + + /** + * After init load loadArrayValuesToForm + */ + ngAfterViewInit(): void { + // wait because the form is not loaded immediately after init - do not know why + setTimeout(() => { + this.loadArrayValuesToForm(); + }, + 500); + } + + /** + * Create the clarin license input fields form with init values which are passed from the clarin-license-table + * @private + */ + private createForm() { + this.clarinLicenseForm = this.formBuilder.group({ + name: [this.name, Validators.required], + definition: [this.definition, Validators.required], + confirmation: this.confirmation, + clarinLicenseLabel: [this.clarinLicenseLabel, validateLicenseLabel()], + extendedClarinLicenseLabels: new FormArray([]), + requiredInfo: new FormArray([]), + }); + } + + /** + * Show the selected extended clarin license labels and the required info in the form. + * if the admin is editing the clarin license he must see which extended clarin license labels/required info + * are selected. + * @private + */ + private loadArrayValuesToForm() { + // add passed extendedClarinLicenseLabels to the form because add them to the form in the init is a problem + const extendedClarinLicenseLabels = (this.clarinLicenseForm.controls.extendedClarinLicenseLabels).value as any[]; + this.extendedClarinLicenseLabels?.forEach(extendedClarinLicenseLabel => { + extendedClarinLicenseLabels.push(extendedClarinLicenseLabel); + }); + + // add passed requiredInfo to the form because add them to the form in the init is a problem + const requiredInfoOptions = (this.clarinLicenseForm.controls.requiredInfo).value as any[]; + this.requiredInfo?.forEach(requiredInfo => { + requiredInfoOptions.push(requiredInfo); + }); + } + + /** + * Send form value to the clarin-license-table component where it will be processed + */ + submitForm() { + this.activeModal.close(this.clarinLicenseForm.value); + } + + /** + * Add or remove checkbox value from form array based on the checkbox selection + * @param event + * @param formName + * @param checkBoxValue + */ + changeCheckboxValue(event: any, formName: string, checkBoxValue) { + let form = null; + + Object.keys(this.clarinLicenseForm.controls).forEach( (key, index) => { + if (key === formName) { + form = (this.clarinLicenseForm.controls[key])?.value as any[]; + } + }); + + if (isUndefined(form) || isNull(form)) { + return; + } + + if (event.target.checked) { + form.push(checkBoxValue); + } else { + // Required Info needs to be checked by some other property, because id is glitching + const index = form.findIndex(item => + item && ( + formName === 'requiredInfo' + ? item.name === checkBoxValue.name + : checkBoxValue.id === item.id), + ); + + if (index !== -1) { + form.splice(index, 1); + } + } + } + + /** + * Load all ClarinLicenseLabels and divide them based on the extended property. + * @private + */ + private loadAndAssignClarinLicenseLabels() { + this.clarinLicenseLabelService.findAll({ elementsPerPage: 100 }, false) + .pipe(getFirstSucceededRemoteListPayload()) + .subscribe(res => { + res.forEach(clarinLicenseLabel => { + if (clarinLicenseLabel.extended) { + this.extendedClarinLicenseLabelOptions.push(clarinLicenseLabel); + } else { + this.clarinLicenseLabelOptions.push(clarinLicenseLabel); + } + }); + }); + } +} diff --git a/src/app/clarin-licenses/clarin-license-table/modal/define-license-label-form/define-license-label-form.component.html b/src/app/clarin-licenses/clarin-license-table/modal/define-license-label-form/define-license-label-form.component.html new file mode 100644 index 00000000000..a32569dc10b --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table/modal/define-license-label-form/define-license-label-form.component.html @@ -0,0 +1,44 @@ + diff --git a/src/app/clarin-licenses/clarin-license-table/modal/define-license-label-form/define-license-label-form.component.scss b/src/app/clarin-licenses/clarin-license-table/modal/define-license-label-form/define-license-label-form.component.scss new file mode 100644 index 00000000000..6d6060415fe --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table/modal/define-license-label-form/define-license-label-form.component.scss @@ -0,0 +1,3 @@ +.modal { + display: inline !important; +} diff --git a/src/app/clarin-licenses/clarin-license-table/modal/define-license-label-form/define-license-label-form.component.ts b/src/app/clarin-licenses/clarin-license-table/modal/define-license-label-form/define-license-label-form.component.ts new file mode 100644 index 00000000000..f74909ab62a --- /dev/null +++ b/src/app/clarin-licenses/clarin-license-table/modal/define-license-label-form/define-license-label-form.component.ts @@ -0,0 +1,97 @@ + +import { + Component, + Input, + OnInit, +} from '@angular/core'; +import { + FormBuilder, + FormGroup, + ReactiveFormsModule, + Validators, +} from '@angular/forms'; +import { NgbActiveModal } from '@ng-bootstrap/ng-bootstrap'; +import { TranslateModule } from '@ngx-translate/core'; + +import { BtnDisabledDirective } from '../../../../shared/btn-disabled.directive'; +import { isNotEmpty } from '../../../../shared/empty.util'; +import { CharToEndPipe } from '../../../../shared/utils/char-to-end.pipe'; + +/** + * The component for defining the Clarin License Label + */ +@Component({ + + imports: [ + BtnDisabledDirective, + CharToEndPipe, + ReactiveFormsModule, + TranslateModule, + ], + selector: 'ds-define-license-label-form', + templateUrl: './define-license-label-form.component.html', + styleUrls: ['./define-license-label-form.component.scss'], +}) +export class DefineLicenseLabelFormComponent implements OnInit { + + constructor(public activeModal: NgbActiveModal, + private formBuilder: FormBuilder) { } + + /** + * The `label` of the Clarin License Label. That's the shortcut which is max 5 characters long. + */ + @Input() + label = ''; + + /** + * The `title` of the Clarin License Label. + */ + @Input() + title = ''; + + /** + * The `extended` boolean of the Clarin License Label. + */ + @Input() + extended = ''; + + /** + * The `icon` of the Clarin License Label. This value is converted to the byte array. + */ + @Input() + icon = ''; + + /** + * The form with the Clarin License Label input fields + */ + clarinLicenseLabelForm: FormGroup; + + /** + * Is the Clarin License Label extended or no options. + */ + extendedOptions = ['Yes', 'No']; + + ngOnInit(): void { + this.createForm(); + } + + /** + * Create form for changing license label data. The initial form values are passed from the selected license label + * from the clarin-license-table. + */ + private createForm() { + this.clarinLicenseLabelForm = this.formBuilder.group({ + label: [this.label, [Validators.required, Validators.maxLength(5)]], + title: [this.title, Validators.required], + extended: isNotEmpty(this.extended) ? this.extended : this.extendedOptions[0], + icon: [this.icon], + }); + } + + /** + * Send form value to the clarin-license-table component where it will be processed + */ + submitForm() { + this.activeModal.close(this.clarinLicenseLabelForm.value); + } +} diff --git a/src/app/clarin-navbar-top/clarin-navbar-top.component.html b/src/app/clarin-navbar-top/clarin-navbar-top.component.html new file mode 100644 index 00000000000..aeb0a6b96e2 --- /dev/null +++ b/src/app/clarin-navbar-top/clarin-navbar-top.component.html @@ -0,0 +1,40 @@ +
+
+
+ + {{'language.english' | translate}} + + + {{'language.czech' | translate}} + +
+
+ @if (!authenticatedUser) { + + } + + + @if (authenticatedUser) { + + } +
+
+
+ diff --git a/src/app/clarin-navbar-top/clarin-navbar-top.component.scss b/src/app/clarin-navbar-top/clarin-navbar-top.component.scss new file mode 100644 index 00000000000..28c7d4b1e9b --- /dev/null +++ b/src/app/clarin-navbar-top/clarin-navbar-top.component.scss @@ -0,0 +1,31 @@ +.clarin-top-header { + position: absolute; + width: 100%; + z-index: 12; +} + +.clarin-logout-badge { + background-color: #428bca; + font-size: 13px; + border-top-left-radius: unset; + border-top-right-radius: unset; + display: inherit; + position: relative; + z-index: 2; +} + +.clarin-login-badge { + background-color: #d9534f; + font-size: 16px; + border-top-left-radius: unset; + border-top-right-radius: unset; +} + +.signon:hover { + cursor: pointer; + text-decoration: underline !important; +} + +.language-icon { + cursor: pointer; +} diff --git a/src/app/clarin-navbar-top/clarin-navbar-top.component.ts b/src/app/clarin-navbar-top/clarin-navbar-top.component.ts new file mode 100644 index 00000000000..063638ebe28 --- /dev/null +++ b/src/app/clarin-navbar-top/clarin-navbar-top.component.ts @@ -0,0 +1,115 @@ +import { isPlatformBrowser } from '@angular/common'; +import { + AfterViewInit, + Component, + Inject, + OnInit, + PLATFORM_ID, +} from '@angular/core'; +import { RouterLink } from '@angular/router'; +import { TranslateModule } from '@ngx-translate/core'; +import { take } from 'rxjs/operators'; + +import { AuthService } from '../core/auth/auth.service'; +import { EPerson } from '../core/eperson/models/eperson.model'; +import { LocaleService } from '../core/locale/locale.service'; +import { HALEndpointService } from '../core/shared/hal-endpoint.service'; +import { ScriptLoaderService } from './script-loader-service'; + +/** + * The component which wraps `language` and `login`/`logout + profile` operations in the top navbar. + */ +@Component({ + selector: 'ds-clarin-navbar-top', + templateUrl: './clarin-navbar-top.component.html', + styleUrls: ['./clarin-navbar-top.component.scss'], + imports: [ + RouterLink, + TranslateModule, + ], + providers: [ScriptLoaderService], +}) +export class ClarinNavbarTopComponent implements OnInit, AfterViewInit { + + constructor(private authService: AuthService, + private halService: HALEndpointService, + private scriptLoader: ScriptLoaderService, + private localeService: LocaleService, + @Inject(PLATFORM_ID) private platformId: object) { } + + /** + * The current authenticated user. It is null if the user is not authenticated. + */ + authenticatedUser = null; + + /** + * Becomes true once the AAI/DiscoJuice scripts have loaded and DiscoJuice has bound its click + * handler to the sign-on link. Until then the sign-on link is not clickable, so a click can never + * race ahead of the (asynchronously loaded) DiscoJuice binding and be silently dropped. + */ + scriptsReady = false; + + /** + * The server path e.g., `http://localhost:8080/server/api/` + */ + repositoryPath = ''; + + ngOnInit(): void { + let authenticated = false; + this.loadRepositoryPath(); + this.authService.isAuthenticated() + .pipe(take(1)) + .subscribe( auth => { + authenticated = auth; + }); + + if (authenticated) { + this.authService.getAuthenticatedUserFromStore().subscribe((user: EPerson) => { + this.authenticatedUser = user; + }); + } else { + this.authenticatedUser = null; + } + } + + ngAfterViewInit(): void { + // Load scripts only in the browser and not SSR + if (isPlatformBrowser(this.platformId)) { + this.loadScripts(); + } + } + + loadScripts() { + // DiscoJuice and AAI have no ordering dependency between them (both only need jQuery, which is + // loaded up-front in index.html), so load them in parallel; AAIConfig must run last because it + // calls aai.setup() which uses both. Once AAIConfig has run, DiscoJuice is bound to the sign-on + // link, so mark the link ready (see scriptsReady). + Promise.all([this.loadDiscoJuice(), this.loadAAI()]) + .then(() => this.loadAAIConfig()) + .then(() => { + this.scriptsReady = true; + }) + .catch(error => console.log(error)); + } + + private loadDiscoJuice = (): Promise => { + return this.scriptLoader.load('discojuice'); + }; + + private loadAAI = (): Promise => { + return this.scriptLoader.load('aai'); + }; + + private loadAAIConfig = (): Promise => { + return this.scriptLoader.load('aaiConfig'); + }; + + private loadRepositoryPath() { + this.repositoryPath = this.halService.getRootHref(); + } + + setLanguage(language) { + this.localeService.setCurrentLanguageCode(language); + this.localeService.refreshAfterChangeLanguage(); + } +} diff --git a/src/app/clarin-navbar-top/script-loader-service.ts b/src/app/clarin-navbar-top/script-loader-service.ts new file mode 100644 index 00000000000..7abbc41580e --- /dev/null +++ b/src/app/clarin-navbar-top/script-loader-service.ts @@ -0,0 +1,67 @@ +import { Injectable } from '@angular/core'; + +interface Scripts { + name: string; + src: string; +} + +export const ScriptStore: Scripts[] = [ + { name: 'aai', src: 'aai/aai.js' }, + { name: 'aaiConfig', src: 'aai/aai_config.js' }, + { name: 'discojuice', src: 'aai/discojuice/discojuice.js' }, +]; + +declare let document: any; + +/** + * The class for loading the js files dynamically. The scripts must be loaded by a webpack. + */ +@Injectable() +export class ScriptLoaderService { + + private scripts: any = {}; + + constructor() { + ScriptStore.forEach((script: any) => { + this.scripts[script.name] = { + loaded: false, + src: script.src, + }; + }); + } + + load(...scripts: string[]) { + const promises: any[] = []; + scripts.forEach((script) => promises.push(this.loadScript(script))); + return Promise.all(promises); + } + + loadScript(name: string) { + return new Promise((resolve, reject) => { + if (!this.scripts[name].loaded) { + // load script + const script = document.createElement('script'); + script.type = 'text/javascript'; + script.src = this.scripts[name].src; + if (script.readyState) { // IE + script.onreadystatechange = () => { + if (script.readyState === 'loaded' || script.readyState === 'complete') { + script.onreadystatechange = null; + this.scripts[name].loaded = true; + resolve({ script: name, loaded: true, status: 'Loaded' }); + } + }; + } else { // Others + script.onload = () => { + this.scripts[name].loaded = true; + resolve({ script: name, loaded: true, status: 'Loaded' }); + }; + } + script.onerror = (error: any) => resolve({ script: name, loaded: false, status: 'Loaded' }); + document.getElementsByTagName('head')[0].appendChild(script); + } else { + resolve({ script: name, loaded: true, status: 'Already Loaded' }); + } + }); + } +} diff --git a/src/app/collection-page/collection-page-routes.ts b/src/app/collection-page/collection-page-routes.ts index ce583b2cd58..eab4482cef3 100644 --- a/src/app/collection-page/collection-page-routes.ts +++ b/src/app/collection-page/collection-page-routes.ts @@ -89,6 +89,13 @@ export const ROUTES: Route[] = [ path: '', pathMatch: 'full', component: ComcolSearchSectionComponent, + // CLARIN/LINDAT: the collection landing (Recent Submissions); keep the inherited + // breadcrumb trail visible (a leaf without breadcrumb data hides the whole bar) + data: { + enableRSS: true, + showBreadcrumbs: true, + searchEnabled: false, + }, }, { path: 'search', @@ -101,6 +108,7 @@ export const ROUTES: Route[] = [ breadcrumbKey: 'collection.search', menuRoute: MenuRoute.COLLECTION_PAGE, enableRSS: true, + searchEnabled: true, }, }, { @@ -114,6 +122,7 @@ export const ROUTES: Route[] = [ data: { breadcrumbKey: 'browse.metadata', menuRoute: MenuRoute.COLLECTION_PAGE, + enableRSS: true, }, }, ], diff --git a/src/app/community-page/community-page-routes.ts b/src/app/community-page/community-page-routes.ts index 979525ee1e6..6ec8afa4501 100644 --- a/src/app/community-page/community-page-routes.ts +++ b/src/app/community-page/community-page-routes.ts @@ -79,6 +79,11 @@ export const ROUTES: Route[] = [ path: '', pathMatch: 'full', component: ComcolSearchSectionComponent, + data: { + enableRSS: true, + showBreadcrumbs: true, + searchEnabled: false, + }, }, { path: 'search', @@ -91,18 +96,20 @@ export const ROUTES: Route[] = [ breadcrumbKey: 'community.search', menuRoute: MenuRoute.COMMUNITY_PAGE, enableRSS: true, + searchEnabled: true, }, }, { path: 'subcoms-cols', pathMatch: 'full', component: SubComColSectionComponent, - resolve: { - breadcrumb: i18nBreadcrumbResolver, - }, + // CLARIN/LINDAT: the default landing tab - no extra breadcrumb (v7 lands on the + // root), but keep the inherited trail visible (a leaf without breadcrumb data + // hides the whole bar in BreadcrumbsService) data: { - breadcrumbKey: 'community.subcoms-cols', menuRoute: MenuRoute.COMMUNITY_PAGE, + enableRSS: true, + showBreadcrumbs: true, }, }, { @@ -116,6 +123,7 @@ export const ROUTES: Route[] = [ data: { breadcrumbKey: 'browse.metadata', menuRoute: MenuRoute.COMMUNITY_PAGE, + enableRSS: true, }, }, ], diff --git a/src/app/community-page/sections/sub-com-col-section/sub-collection-list/community-page-sub-collection-list.component.html b/src/app/community-page/sections/sub-com-col-section/sub-collection-list/community-page-sub-collection-list.component.html index 825399c23b2..da77aaf98b6 100644 --- a/src/app/community-page/sections/sub-com-col-section/sub-collection-list/community-page-sub-collection-list.component.html +++ b/src/app/community-page/sections/sub-com-col-section/sub-collection-list/community-page-sub-collection-list.component.html @@ -1,11 +1,12 @@ @if (subCollectionsRD?.hasSucceeded && subCollectionsRD?.payload.totalElements > 0) {
-

{{'community.sub-collection-list.head' | translate}}

+

{{'community.sub-collection-list.head' | translate}}

diff --git a/src/app/community-page/sections/sub-com-col-section/sub-community-list/community-page-sub-community-list.component.html b/src/app/community-page/sections/sub-com-col-section/sub-community-list/community-page-sub-community-list.component.html index 7c3d23b8094..503681b2f6e 100644 --- a/src/app/community-page/sections/sub-com-col-section/sub-community-list/community-page-sub-community-list.component.html +++ b/src/app/community-page/sections/sub-com-col-section/sub-community-list/community-page-sub-community-list.component.html @@ -1,11 +1,12 @@ @if (subCommunitiesRD?.hasSucceeded && subCommunitiesRD?.payload.totalElements > 0) {
-

{{'community.sub-community-list.head' | translate}}

+

{{'community.sub-community-list.head' | translate}}

diff --git a/src/app/contact-page/contact-page-routes.ts b/src/app/contact-page/contact-page-routes.ts new file mode 100644 index 00000000000..ee644e90df9 --- /dev/null +++ b/src/app/contact-page/contact-page-routes.ts @@ -0,0 +1,18 @@ +import { Route } from '@angular/router'; + +import { i18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.resolver'; +import { ThemedContactPageComponent } from './themed-contact-page.component'; + +/** + * Routes for the CLARIN contact page. + * Ported from the 7.x ContactPageRoutingModule to the v9 standalone routes pattern. + */ +export const ROUTES: Route[] = [ + { + path: '', + component: ThemedContactPageComponent, + pathMatch: 'full', + resolve: { breadcrumb: i18nBreadcrumbResolver }, + data: { breadcrumbKey: 'contact-us', title: 'contact-us.title' }, + }, +]; diff --git a/src/app/contact-page/contact-page.component.html b/src/app/contact-page/contact-page.component.html new file mode 100644 index 00000000000..c0c16f11ce8 --- /dev/null +++ b/src/app/contact-page/contact-page.component.html @@ -0,0 +1,21 @@ +
+
+
+

{{'contact-us.title' | translate}}

+
+

{{'contact-us.description' | translate}}

+
+ {{'contact-us.form' | translate}} + {{'contact-us.feedback' | translate}} +
+
+ {{'contact-us.email' | translate}} + @if (emailToContact) { + + } +
+
+
+
+
diff --git a/src/app/contact-page/contact-page.component.scss b/src/app/contact-page/contact-page.component.scss new file mode 100644 index 00000000000..f935af2f83b --- /dev/null +++ b/src/app/contact-page/contact-page.component.scss @@ -0,0 +1,3 @@ +.email-text{ + margin-left: 5rem; +} diff --git a/src/app/contact-page/contact-page.component.ts b/src/app/contact-page/contact-page.component.ts new file mode 100644 index 00000000000..5bd62ef9bbc --- /dev/null +++ b/src/app/contact-page/contact-page.component.ts @@ -0,0 +1,30 @@ +import { + Component, + OnInit, +} from '@angular/core'; +import { RouterModule } from '@angular/router'; +import { TranslateModule } from '@ngx-translate/core'; + +import { ConfigurationDataService } from '../core/data/configuration-data.service'; + +@Component({ + imports: [ + RouterModule, + TranslateModule, + ], + selector: 'ds-base-contact-page', + styleUrls: ['./contact-page.component.scss'], + templateUrl: './contact-page.component.html', +}) +export class ContactPageComponent implements OnInit { + emailToContact: string; + constructor( + private configService: ConfigurationDataService, + ) {} + + ngOnInit(): void { + this.configService.findByPropertyName('lr.help.mail').subscribe(remoteData => { + this.emailToContact = remoteData.payload.values[0]; + }); + } +} diff --git a/src/app/contact-page/themed-contact-page.component.ts b/src/app/contact-page/themed-contact-page.component.ts new file mode 100644 index 00000000000..2c146a2cce6 --- /dev/null +++ b/src/app/contact-page/themed-contact-page.component.ts @@ -0,0 +1,27 @@ +import { Component } from '@angular/core'; + +import { ThemedComponent } from '../shared/theme-support/themed.component'; +import { ContactPageComponent } from './contact-page.component'; + +/** + * Themed wrapper for CollectionPageComponent + */ +@Component({ + selector: 'ds-contact-page', + styleUrls: [], + templateUrl: '../shared/theme-support/themed.component.html', +}) +export class ThemedContactPageComponent extends ThemedComponent { + protected getComponentName(): string { + return 'ContactPageComponent'; + } + + protected importThemedComponent(themeName: string): Promise { + return import(`../../themes/${themeName}/app/contact-page/contact-page.component`); + } + + protected importUnthemedComponent(): Promise { + return import(`./contact-page.component`); + } + +} diff --git a/src/app/core/bitstream-checksum-data.service.ts b/src/app/core/bitstream-checksum-data.service.ts new file mode 100644 index 00000000000..e16956029c5 --- /dev/null +++ b/src/app/core/bitstream-checksum-data.service.ts @@ -0,0 +1,37 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; + +import { NotificationsService } from '../shared/notifications/notifications.service'; +import { dataService } from './cache/builders/build-decorators'; +import { RemoteDataBuildService } from './cache/builders/remote-data-build.service'; +import { ObjectCacheService } from './cache/object-cache.service'; +import { CoreState } from './core-state.model'; +import { BaseDataService } from './data/base/base-data.service'; +import { linkName } from './data/clarin/clrua-data.service'; +import { DefaultChangeAnalyzer } from './data/default-change-analyzer.service'; +import { RequestService } from './data/request.service'; +import { BitstreamChecksum } from './shared/bitstream-checksum.model'; +import { HALEndpointService } from './shared/hal-endpoint.service'; + +/** + * A service responsible for fetching BitstreamChecksum objects from the REST API + */ +@Injectable({ providedIn: 'root' }) +@dataService(BitstreamChecksum.type) +export class BitstreamChecksumDataService extends BaseDataService { + protected linkPath = 'checksum'; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService, + ) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + } +} diff --git a/src/app/core/data/clarin/clarin-license-data.service.ts b/src/app/core/data/clarin/clarin-license-data.service.ts new file mode 100644 index 00000000000..9ed4f6ee8f9 --- /dev/null +++ b/src/app/core/data/clarin/clarin-license-data.service.ts @@ -0,0 +1,103 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { Observable } from 'rxjs'; + +import { NotificationsService } from '../../../shared/notifications/notifications.service'; +import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model'; +import { dataService } from '../../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; +import { RequestParam } from '../../cache/models/request-param.model'; +import { ObjectCacheService } from '../../cache/object-cache.service'; +import { CoreState } from '../../core-state.model'; +import { ClarinLicense } from '../../shared/clarin/clarin-license.model'; +import { HALEndpointService } from '../../shared/hal-endpoint.service'; +import { NoContent } from '../../shared/NoContent.model'; +import { ResourceType } from '../../shared/resource-type'; +import { + CreateData, + CreateDataImpl, +} from '../base/create-data'; +import { + DeleteData, + DeleteDataImpl, +} from '../base/delete-data'; +import { + FindAllData, + FindAllDataImpl, +} from '../base/find-all-data'; +import { IdentifiableDataService } from '../base/identifiable-data.service'; +import { + PutData, + PutDataImpl, +} from '../base/put-data'; +import { + SearchData, + SearchDataImpl, +} from '../base/search-data'; +import { DefaultChangeAnalyzer } from '../default-change-analyzer.service'; +import { FindListOptions } from '../find-list-options.model'; +import { PaginatedList } from '../paginated-list.model'; +import { RemoteData } from '../remote-data'; +import { RequestService } from '../request.service'; + +export const linkName = 'clarinlicenses'; +export const AUTOCOMPLETE = new ResourceType(linkName); + +/** + * A service responsible for fetching/sending license data from/to the Clarin License REST API + */ +@Injectable({ providedIn: 'root' }) +@dataService(ClarinLicense.type) +export class ClarinLicenseDataService extends IdentifiableDataService implements CreateData, PutData, DeleteData, SearchData, FindAllData { + protected linkPath = linkName; + private createData: CreateData; + private putData: PutData; + private deleteData: DeleteData; + private searchData: SearchData; + private findAllData: FindAllData; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService, + ) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + + this.searchData = new SearchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + this.createData = new CreateDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive); + this.putData = new PutDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + this.deleteData = new DeleteDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive, this.constructIdEndpoint); + this.findAllData = new FindAllDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + } + + put(object: ClarinLicense): Observable> { + return this.putData.put(object); + } + + create(object: ClarinLicense, ...params: RequestParam[]): Observable> { + return this.createData.create(object, ...params); + } + + delete(objectId: string, copyVirtualMetadata?: string[]): Observable> { + return this.deleteData.delete(objectId, copyVirtualMetadata); + } + + deleteByHref(href: string, copyVirtualMetadata?: string[]): Observable> { + return this.deleteData.deleteByHref(href, copyVirtualMetadata); + } + + searchBy(searchMethod: string, options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig[]): Observable>> { + return this.searchData.searchBy(searchMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } + + findAll(options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig[]): Observable>> { + return this.findAllData.findAll(options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } + +} diff --git a/src/app/core/data/clarin/clarin-license-label-data.service.ts b/src/app/core/data/clarin/clarin-license-label-data.service.ts new file mode 100644 index 00000000000..ecb71ef2ec7 --- /dev/null +++ b/src/app/core/data/clarin/clarin-license-label-data.service.ts @@ -0,0 +1,67 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { Observable } from 'rxjs'; +import { FollowLinkConfig } from 'src/app/shared/utils/follow-link-config.model'; + +import { NotificationsService } from '../../../shared/notifications/notifications.service'; +import { dataService } from '../../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; +import { RequestParam } from '../../cache/models/request-param.model'; +import { ObjectCacheService } from '../../cache/object-cache.service'; +import { CoreState } from '../../core-state.model'; +import { ClarinLicenseLabel } from '../../shared/clarin/clarin-license-label.model'; +import { HALEndpointService } from '../../shared/hal-endpoint.service'; +import { ResourceType } from '../../shared/resource-type'; +import { BaseDataService } from '../base/base-data.service'; +import { + CreateData, + CreateDataImpl, +} from '../base/create-data'; +import { + FindAllData, + FindAllDataImpl, +} from '../base/find-all-data'; +import { DefaultChangeAnalyzer } from '../default-change-analyzer.service'; +import { FindListOptions } from '../find-list-options.model'; +import { PaginatedList } from '../paginated-list.model'; +import { RemoteData } from '../remote-data'; +import { RequestService } from '../request.service'; + +export const linkName = 'clarinlicenselabels'; +export const AUTOCOMPLETE = new ResourceType(linkName); + +/** + * A service responsible for fetching/sending data from/to the REST API - vocabularies endpoint + */ +@Injectable({ providedIn: 'root' }) +@dataService(ClarinLicenseLabel.type) +export class ClarinLicenseLabelDataService extends BaseDataService implements CreateData, FindAllData { + protected linkPath = linkName; + private createData: CreateData; + private findAllData: FindAllData; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService, + ) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + + this.findAllData = new FindAllDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + this.createData = new CreateDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive); + } + + findAll(options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig[]): Observable>> { + return this.findAllData.findAll(options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } + + create(object: ClarinLicenseLabel, ...params: RequestParam[]): Observable> { + return this.createData.create(object, ...params); + } +} diff --git a/src/app/core/data/clarin/clarin-license-resource-mapping-data.service.ts b/src/app/core/data/clarin/clarin-license-resource-mapping-data.service.ts new file mode 100644 index 00000000000..23abfc26133 --- /dev/null +++ b/src/app/core/data/clarin/clarin-license-resource-mapping-data.service.ts @@ -0,0 +1,57 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { Observable } from 'rxjs'; + +import { NotificationsService } from '../../../shared/notifications/notifications.service'; +import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model'; +import { dataService } from '../../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; +import { ObjectCacheService } from '../../cache/object-cache.service'; +import { CoreState } from '../../core-state.model'; +import { ClarinLicenseResourceMapping } from '../../shared/clarin/clarin-license-resource-mapping.model'; +import { HALEndpointService } from '../../shared/hal-endpoint.service'; +import { ResourceType } from '../../shared/resource-type'; +import { BaseDataService } from '../base/base-data.service'; +import { + SearchData, + SearchDataImpl, +} from '../base/search-data'; +import { DefaultChangeAnalyzer } from '../default-change-analyzer.service'; +import { FindListOptions } from '../find-list-options.model'; +import { PaginatedList } from '../paginated-list.model'; +import { RemoteData } from '../remote-data'; +import { RequestService } from '../request.service'; + +export const linkName = 'clarinlicenseresourcemappings'; +export const AUTOCOMPLETE = new ResourceType(linkName); + +/** + * A service responsible for fetching/sending clarin license resource mapping from/to the Clarin License + * Resource Mapping REST API + */ +@Injectable({ providedIn: 'root' }) +@dataService(ClarinLicenseResourceMapping.type) +export class ClarinLicenseResourceMappingService extends BaseDataService implements SearchData { + protected linkPath = linkName; + private searchData: SearchData; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService, + ) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + this.searchData = new SearchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + } + + searchBy(searchMethod: string, options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig[]): Observable>> { + return this.searchData.searchBy(searchMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } + +} diff --git a/src/app/core/data/clarin/clarin-user-metadata.service.ts b/src/app/core/data/clarin/clarin-user-metadata.service.ts new file mode 100644 index 00000000000..869a8cef502 --- /dev/null +++ b/src/app/core/data/clarin/clarin-user-metadata.service.ts @@ -0,0 +1,55 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { Observable } from 'rxjs'; + +import { NotificationsService } from '../../../shared/notifications/notifications.service'; +import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model'; +import { dataService } from '../../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; +import { ObjectCacheService } from '../../cache/object-cache.service'; +import { CoreState } from '../../core-state.model'; +import { ClarinUserMetadata } from '../../shared/clarin/clarin-user-metadata.model'; +import { HALEndpointService } from '../../shared/hal-endpoint.service'; +import { ResourceType } from '../../shared/resource-type'; +import { BaseDataService } from '../base/base-data.service'; +import { + SearchData, + SearchDataImpl, +} from '../base/search-data'; +import { DefaultChangeAnalyzer } from '../default-change-analyzer.service'; +import { FindListOptions } from '../find-list-options.model'; +import { PaginatedList } from '../paginated-list.model'; +import { RemoteData } from '../remote-data'; +import { RequestService } from '../request.service'; + +export const linkName = 'clarinusermetadatas'; +export const AUTOCOMPLETE = new ResourceType(linkName); + +/** + * A service responsible for fetching/sending user metadata from/to the Clarin User Metadata + */ +@Injectable({ providedIn: 'root' }) +@dataService(ClarinUserMetadata.type) +export class ClarinUserMetadataDataService extends BaseDataService { + protected linkPath = linkName; + private searchData: SearchData; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService, + ) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + this.searchData = new SearchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + } + + searchBy(searchMethod: string, options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig[]): Observable>> { + return this.searchData.searchBy(searchMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } +} diff --git a/src/app/core/data/clarin/clarin-user-registration.service.ts b/src/app/core/data/clarin/clarin-user-registration.service.ts new file mode 100644 index 00000000000..6f38671a69a --- /dev/null +++ b/src/app/core/data/clarin/clarin-user-registration.service.ts @@ -0,0 +1,55 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { Observable } from 'rxjs'; + +import { NotificationsService } from '../../../shared/notifications/notifications.service'; +import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model'; +import { dataService } from '../../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; +import { ObjectCacheService } from '../../cache/object-cache.service'; +import { CoreState } from '../../core-state.model'; +import { ClarinUserRegistration } from '../../shared/clarin/clarin-user-registration.model'; +import { HALEndpointService } from '../../shared/hal-endpoint.service'; +import { ResourceType } from '../../shared/resource-type'; +import { BaseDataService } from '../base/base-data.service'; +import { + SearchData, + SearchDataImpl, +} from '../base/search-data'; +import { DefaultChangeAnalyzer } from '../default-change-analyzer.service'; +import { FindListOptions } from '../find-list-options.model'; +import { PaginatedList } from '../paginated-list.model'; +import { RemoteData } from '../remote-data'; +import { RequestService } from '../request.service'; + +export const linkName = 'clarinuserregistrations'; +export const AUTOCOMPLETE = new ResourceType(linkName); + +/** + * A service responsible for fetching/sending user registration data from/to the Clarin User Registration REST API + */ +@Injectable({ providedIn: 'root' }) +@dataService(ClarinUserRegistration.type) +export class ClarinUserRegistrationDataService extends BaseDataService implements SearchData { + protected linkPath = linkName; + private searchData: SearchData; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService, + ) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + this.searchData = new SearchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + } + + searchBy(searchMethod: string, options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig[]): Observable>> { + return this.searchData.searchBy(searchMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } +} diff --git a/src/app/core/data/clarin/clarin-verification-token-data.service.ts b/src/app/core/data/clarin/clarin-verification-token-data.service.ts new file mode 100644 index 00000000000..9a3e9049cb9 --- /dev/null +++ b/src/app/core/data/clarin/clarin-verification-token-data.service.ts @@ -0,0 +1,68 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { Observable } from 'rxjs'; + +import { NotificationsService } from '../../../shared/notifications/notifications.service'; +import { FollowLinkConfig } from '../../../shared/utils/follow-link-config.model'; +import { dataService } from '../../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; +import { ObjectCacheService } from '../../cache/object-cache.service'; +import { CoreState } from '../../core-state.model'; +import { ClarinVerificationToken } from '../../shared/clarin/clarin-verification-token.model'; +import { HALEndpointService } from '../../shared/hal-endpoint.service'; +import { NoContent } from '../../shared/NoContent.model'; +import { + DeleteData, + DeleteDataImpl, +} from '../base/delete-data'; +import { IdentifiableDataService } from '../base/identifiable-data.service'; +import { + SearchData, + SearchDataImpl, +} from '../base/search-data'; +import { DefaultChangeAnalyzer } from '../default-change-analyzer.service'; +import { FindListOptions } from '../find-list-options.model'; +import { PaginatedList } from '../paginated-list.model'; +import { RemoteData } from '../remote-data'; +import { RequestService } from '../request.service'; + +export const linkName = 'clarinverificationtokens'; +/** + * A service responsible for fetching/sending license data from/to the ClarinVerificationToken REST API + */ +@Injectable({ providedIn: 'root' }) +@dataService(ClarinVerificationToken.type) +export class ClarinVerificationTokenDataService extends IdentifiableDataService implements SearchData, DeleteData { + protected linkPath = linkName; + private deleteData: DeleteData; + private searchData: SearchData; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService, + ) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + this.searchData = new SearchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + this.deleteData = new DeleteDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive, this.constructIdEndpoint); + } + + delete(objectId: string, copyVirtualMetadata?: string[]): Observable> { + return this.deleteData.delete(objectId, copyVirtualMetadata); + } + + deleteByHref(href: string, copyVirtualMetadata?: string[]): Observable> { + return this.deleteData.deleteByHref(href, copyVirtualMetadata); + } + + searchBy(searchMethod: string, options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig[]): Observable>> { + return this.searchData.searchBy(searchMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } + +} diff --git a/src/app/core/data/clarin/clrua-data.service.ts b/src/app/core/data/clarin/clrua-data.service.ts new file mode 100644 index 00000000000..3c64a8080b8 --- /dev/null +++ b/src/app/core/data/clarin/clrua-data.service.ts @@ -0,0 +1,40 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; + +import { NotificationsService } from '../../../shared/notifications/notifications.service'; +import { dataService } from '../../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; +import { ObjectCacheService } from '../../cache/object-cache.service'; +import { CoreState } from '../../core-state.model'; +import { ClruaModel } from '../../shared/clarin/clrua.model'; +import { HALEndpointService } from '../../shared/hal-endpoint.service'; +import { ResourceType } from '../../shared/resource-type'; +import { BaseDataService } from '../base/base-data.service'; +import { DefaultChangeAnalyzer } from '../default-change-analyzer.service'; +import { RequestService } from '../request.service'; + +export const linkName = 'clarinlruallowances'; +export const AUTOCOMPLETE = new ResourceType(linkName); + +/** + * A service responsible for fetching/sending CLRUA data from/to the Clarin License Resource User Allowance REST API + */ +@Injectable({ providedIn: 'root' }) +@dataService(ClruaModel.type) +export class ClruaDataService extends BaseDataService { + protected linkPath = linkName; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService, + ) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + } +} diff --git a/src/app/core/data/clarin/matomo-report-subscription-data.service.ts b/src/app/core/data/clarin/matomo-report-subscription-data.service.ts new file mode 100644 index 00000000000..f181aa48277 --- /dev/null +++ b/src/app/core/data/clarin/matomo-report-subscription-data.service.ts @@ -0,0 +1,75 @@ +import { Injectable } from '@angular/core'; +import { Observable } from 'rxjs'; +import { + map, + switchMap, + take, +} from 'rxjs/operators'; + +import { dataService } from '../../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.service'; +import { ObjectCacheService } from '../../cache/object-cache.service'; +import { MatomoReportSubscription } from '../../shared/clarin/matomo-report-subscription.model'; +import { HALEndpointService } from '../../shared/hal-endpoint.service'; +import { NoContent } from '../../shared/NoContent.model'; +import { IdentifiableDataService } from '../base/identifiable-data.service'; +import { RemoteData } from '../remote-data'; +import { PostRequest } from '../request.models'; +import { RequestService } from '../request.service'; + +export const MATOMO_SUBSCRIPTION_ENDPOINT = 'matomoreportsubscriptions'; + +@Injectable({ providedIn: 'root' }) +@dataService(MatomoReportSubscription.type) +export class MatomoReportSubscriptionDataService extends IdentifiableDataService { + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected objectCache: ObjectCacheService, + protected halService: HALEndpointService, + ) { + super(MATOMO_SUBSCRIPTION_ENDPOINT, requestService, rdbService, objectCache, halService); + } + + /** + * Get subscription status for an item + */ + getSubscriptionStatus(itemId: string): Observable> { + const endpoint$ = this.halService.getEndpoint(this.linkPath).pipe( + map(endpoint => `${endpoint}/item/${itemId}`), + ); + + return this.findByHref(endpoint$); + } + + /** + * Subscribe to Matomo reports for an item + */ + subscribe(itemId: string): Observable> { + return this.halService.getEndpoint(this.linkPath).pipe( + take(1), + map(endpoint => `${endpoint}/item/${itemId}/subscribe`), + switchMap(endpoint => { + const request = new PostRequest(this.requestService.generateRequestId(), endpoint, null); + this.requestService.send(request, true); + return this.rdbService.buildFromRequestUUID(request.uuid); + }), + ); + } + + /** + * Unsubscribe from Matomo reports for an item + */ + unsubscribe(itemId: string): Observable> { + return this.halService.getEndpoint(this.linkPath).pipe( + take(1), + map(endpoint => `${endpoint}/item/${itemId}/unsubscribe`), + switchMap(endpoint => { + const request = new PostRequest(this.requestService.generateRequestId(), endpoint, null); + this.requestService.send(request, true); + return this.rdbService.buildFromRequestUUID(request.uuid); + }), + ); + } +} diff --git a/src/app/core/data/epic-handle-data.service.ts b/src/app/core/data/epic-handle-data.service.ts new file mode 100644 index 00000000000..080e3aba2d2 --- /dev/null +++ b/src/app/core/data/epic-handle-data.service.ts @@ -0,0 +1,222 @@ +import { + HttpClient, + HttpParams, +} from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { + catchError, + map, + mergeMap, + Observable, + throwError, +} from 'rxjs'; +import { isNotEmpty } from 'src/app/shared/empty.util'; + +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { ObjectCacheService } from '../cache/object-cache.service'; +import { CoreState } from '../core-state.model'; +import { EpicHandle } from '../epicHandle/models/epic-handle.model'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { PageInfo } from '../shared/page-info.model'; +import { FindListOptions } from './find-list-options.model'; +import { RemoteData } from './remote-data'; +import { + DeleteRequest, + PostRequest, + PutRequest, +} from './request.models'; +import { RequestService } from './request.service'; + +export interface EpicHandleResponse { + payload: { + page: EpicHandle[]; + pageInfo: PageInfo; + } +} + +export interface SpringBootPageable { + offset: number; + pageSize: number; + pageNumber: number; +} + +export interface EpicHandleSearchResponse { + content: Array; + pageable: SpringBootPageable + last: boolean; + totalElements: number; + totalPages: number; + numberOfElements: number; +} + +/** + * A service responsible for fetching/sending data from/to the REST API on the metadatafields endpoint + */ +@Injectable({ + providedIn: 'root', +}) +export class EpicHandleDataService { + private linkPath = 'epichandles'; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected http: HttpClient, + protected notificationsService: NotificationsService) { + } + + findAll(options: FindListOptions, prefix: string, urlPattern?: string, totalElements?: number): Observable { + return this.halService.getEndpoint(this.linkPath).pipe( + map(baseUrl => { + const url = `${baseUrl}/${prefix}`; + let params = new HttpParams(); + if (isNotEmpty(urlPattern)) { + params = params.set('url', urlPattern); + } + + if (options.currentPage !== undefined) { + params = params.set('page', String(options.currentPage - 1)); + } + + if (options.elementsPerPage !== undefined) { + params = params.set('size', String(options.elementsPerPage)); + } + + if (totalElements) { + params = params.set('totalElements', String(totalElements)); + } + + return { url, params }; + }), + mergeMap(({ url, params }) => { + return this.http.get(url, { params }); + }), + map(response => { + const handles: EpicHandle[] = response.content || []; + const pageInfo = new PageInfo({ + elementsPerPage: response.pageable?.pageSize || options.elementsPerPage || 10, + totalElements: response.totalElements || 0, + totalPages: response.totalPages || 0, + currentPage: (response.pageable?.pageNumber || 0) + 1, + }); + + + return { + payload: { + page: handles, + pageInfo: pageInfo, + }, + }; + }), + catchError((error: unknown) => { + return throwError(() => error); + }), + ); + } + + create( + prefix: string, + url: string, + subPrefix?: string, + subSuffix?: string, + ): Observable> { + return this.halService.getEndpoint('epichandles').pipe( + map(baseUrl => { + const endpoint = `${baseUrl}/${prefix}`; + let params = new HttpParams().set('url', url); + + if (isNotEmpty(subPrefix)) { + params = params.set('prefix', subPrefix); + } + if (isNotEmpty(subSuffix)) { + params = params.set('suffix', subSuffix); + } + + return { endpoint, params }; + }), mergeMap(({ endpoint, params }) => { + const requestId = this.requestService.generateRequestId(); + const fullUrl = `${endpoint}?${params.toString()}`; + const request = new PostRequest(requestId, fullUrl, null); + this.requestService.send(request); + + return this.rdbService.buildFromRequestUUID(requestId); + }), + catchError((error: unknown) => { + return throwError(() => error); + }), + ); + } + + update( + prefix: string, + suffix: string, + url: string, + ): Observable> { + return this.halService.getEndpoint('epichandles').pipe( + map(baseUrl => { + const endpoint = `${baseUrl}/${prefix}/${suffix}`; + const params = new HttpParams().set('url', url); + return { endpoint, params }; + }), + mergeMap(({ endpoint, params }) => { + const requestId = this.requestService.generateRequestId(); + const fullUrl = `${endpoint}?${params.toString()}`; + const request = new PutRequest(requestId, fullUrl, null); + this.requestService.send(request); + return this.rdbService.buildFromRequestUUID(requestId); + }), + catchError((error: unknown) => { + return throwError(() => error); + }), + ); + } + delete(prefix: string, suffix: string): Observable> { + return this.halService.getEndpoint('epichandles').pipe( + map(baseUrl => `${baseUrl}/${prefix}/${suffix}`), + mergeMap(url => { + const requestId = this.requestService.generateRequestId(); + const request = new DeleteRequest(requestId, url); + this.requestService.send(request); + return this.rdbService.buildFromRequestUUID(requestId); + }), + catchError((error: unknown) => { + return throwError(() => error); + }), + ); + } + + deleteByHandleId(handleId: string): Observable> { + const parts = handleId.split('/'); + if (parts.length !== 2) { + throw new Error('Invalid handle ID format. Expected: prefix/suffix'); + } + return this.delete(parts[0], parts[1]); + } + + + findByPrefixAndSuffix(prefix: string, suffix: string): Observable { + // we search for the handle using the prefix and suffix + return this.halService.getEndpoint('epichandles').pipe( + map(baseUrl => `${baseUrl}/${prefix}/${suffix}`), + mergeMap(url => this.http.get<{id: string; url: string; _links?: any}>(url)), + map(response => { + const handle = new EpicHandle(); + handle.id = response.id; + handle.url = response.url; + handle._links = response._links || { + self: { href: `/server/api/epichandles/${response.id}` }, + }; + return handle; + }), + catchError((error: unknown) => { + return throwError(() => error); + }), + ); + } + +} diff --git a/src/app/core/data/feature-authorization/feature-id.ts b/src/app/core/data/feature-authorization/feature-id.ts index 3d5803b018b..27f07a2dfb7 100644 --- a/src/app/core/data/feature-authorization/feature-id.ts +++ b/src/app/core/data/feature-authorization/feature-id.ts @@ -36,5 +36,6 @@ export enum FeatureID { CanSubscribe = 'canSubscribeDso', CoarNotifyEnabled = 'coarNotifyEnabled', CanSeeQA = 'canSeeQA', - EPersonForgotPassword = 'epersonForgotPassword' + EPersonForgotPassword = 'epersonForgotPassword', + CanManageLicense = 'canManageLicense' } diff --git a/src/app/core/data/handle-data.service.ts b/src/app/core/data/handle-data.service.ts new file mode 100644 index 00000000000..8a637acaf14 --- /dev/null +++ b/src/app/core/data/handle-data.service.ts @@ -0,0 +1,64 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { Observable } from 'rxjs'; + +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; +import { dataService } from '../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { RequestParam } from '../cache/models/request-param.model'; +import { ObjectCacheService } from '../cache/object-cache.service'; +import { CoreState } from '../core-state.model'; +import { Handle } from '../handle/handle.model'; +import { HANDLE } from '../handle/handle.resource-type'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { BaseDataService } from './base/base-data.service'; +import { + CreateData, + CreateDataImpl, +} from './base/create-data'; +import { + FindAllData, + FindAllDataImpl, +} from './base/find-all-data'; +import { DefaultChangeAnalyzer } from './default-change-analyzer.service'; +import { FindListOptions } from './find-list-options.model'; +import { PaginatedList } from './paginated-list.model'; +import { RemoteData } from './remote-data'; +import { RequestService } from './request.service'; + +export const linkName = 'handles'; +/** + * A service responsible for fetching/sending data from/to the REST API on the metadatafields endpoint + */ +@Injectable({ providedIn: 'root' }) +@dataService(HANDLE) +export class HandleDataService extends BaseDataService implements CreateData, FindAllData { + protected linkPath = linkName; + private createData: CreateData; + private findAllData: FindAllData; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + + this.createData = new CreateDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, notificationsService, this.responseMsToLive); + this.findAllData = new FindAllDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + } + + create(object: Handle, ...params: RequestParam[]): Observable> { + return this.createData.create(object, ...params); + } + + findAll(options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig[]): Observable>> { + return this.findAllData.findAll(options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } +} diff --git a/src/app/core/data/lookup-relation.service.ts b/src/app/core/data/lookup-relation.service.ts index 55b68afa652..9262ab90c40 100644 --- a/src/app/core/data/lookup-relation.service.ts +++ b/src/app/core/data/lookup-relation.service.ts @@ -13,6 +13,7 @@ import { takeWhile, } from 'rxjs/operators'; +import { isNotEmpty } from '../../shared/empty.util'; import { RelationshipOptions } from '../../shared/form/builder/models/relationship-options.model'; import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model'; import { PaginatedSearchOptions } from '../../shared/search/models/paginated-search-options.model'; @@ -110,6 +111,26 @@ export class LookupRelationService { ); } + /** + * CLARIN: fetch the actual external source entries (used by the sponsor autocomplete). + * The entry ids come base64-encoded from the REST layer, so they are decoded here. + * @param externalSource External Source + * @param searchOptions Search options to filter results + */ + getExternalResults(externalSource: ExternalSource, searchOptions: PaginatedSearchOptions): Observable> { + const pagination = isNotEmpty(searchOptions.pagination) ? searchOptions.pagination : { pagination: this.singleResultOptions }; + return this.externalSourceService.getExternalSourceEntries(externalSource.id, Object.assign(new PaginatedSearchOptions({}), searchOptions, pagination)).pipe( + getAllSucceededRemoteData(), + getRemoteDataPayload(), + map((list: PaginatedList) => { + list.page.forEach(source => { + source.id = atob(source.id); + }); + return list; + }), + ); + } + /** * Remove cached requests from local results */ diff --git a/src/app/core/data/metadata-bitstream-data.service.ts b/src/app/core/data/metadata-bitstream-data.service.ts new file mode 100644 index 00000000000..55e504c2fa0 --- /dev/null +++ b/src/app/core/data/metadata-bitstream-data.service.ts @@ -0,0 +1,80 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { Observable } from 'rxjs'; + +import { hasValue } from '../../shared/empty.util'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; +import { dataService } from '../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { RequestParam } from '../cache/models/request-param.model'; +import { ObjectCacheService } from '../cache/object-cache.service'; +import { CoreState } from '../core-state.model'; +import { MetadataBitstream } from '../metadata/metadata-bitstream.model'; +import { METADATA_BITSTREAM } from '../metadata/metadata-bitstream.resource-type'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { IdentifiableDataService } from './base/identifiable-data.service'; +import { + SearchData, + SearchDataImpl, +} from './base/search-data'; +import { ChangeAnalyzer } from './change-analyzer'; +import { linkName } from './clarin/clarin-license-data.service'; +import { FindListOptions } from './find-list-options.model'; +import { PaginatedList } from './paginated-list.model'; +import { RemoteData } from './remote-data'; +import { RequestService } from './request.service'; + +/** + * A service responsible for fetching/sending data from/to the REST API on the metadatafields endpoint + */ +@Injectable({ providedIn: 'root' }) +@dataService(METADATA_BITSTREAM) +export class MetadataBitstreamDataService extends IdentifiableDataService implements SearchData { + protected store: Store; + protected http: HttpClient; + protected comparator: ChangeAnalyzer; + protected linkPath = 'metadatabitstreams'; + protected searchByHandleLinkPath = 'byHandle'; + private searchData: SearchData; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected objectCache: ObjectCacheService, + protected halService: HALEndpointService, + protected notificationsService: NotificationsService, + ) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + this.searchData = new SearchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + } + + /** + * Find metadata fields with either the partial metadata field name (e.g. "dc.ti") as query or an exact match to + * at least the schema, element or qualifier + * @param handle optional; an exact match of the prefix of the item identifier (e.g. "123456789/1126") + * @param fileGrpType optional; an exact match of the type of the file(e.g. "TEXT", "THUMBNAIL") + * @param options The options info used to retrieve the fields + * @param useCachedVersionIfAvailable If this is true, the request will only be sent if there's no valid cached version. Defaults to true + * @param reRequestOnStale Whether or not the request should automatically be re-requested after the response becomes stale + * @param linksToFollow List of {@link FollowLinkConfig} that indicate which {@link HALLink}s should be automatically resolved + */ + searchByHandleParams(handle: string, fileGrpType: string, options: FindListOptions = {}, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig[]): Observable> { + const optionParams = Object.assign(new FindListOptions(), options, { + searchParams: [ + new RequestParam('handle', hasValue(handle) ? handle : ''), + new RequestParam( + 'fileGrpType', + hasValue(fileGrpType) ? fileGrpType : '', + ), + ], + }); + return this.searchBy(this.searchByHandleLinkPath, optionParams, useCachedVersionIfAvailable, reRequestOnStale, + ...linksToFollow); + } + + searchBy(searchMethod: string, options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig[]): Observable>> { + return this.searchData.searchBy(searchMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } +} diff --git a/src/app/core/data/metadata-value-data.service.ts b/src/app/core/data/metadata-value-data.service.ts new file mode 100644 index 00000000000..614fa532ca9 --- /dev/null +++ b/src/app/core/data/metadata-value-data.service.ts @@ -0,0 +1,114 @@ +import { HttpClient } from '@angular/common/http'; +import { Injectable } from '@angular/core'; +import { Store } from '@ngrx/store'; +import { + EMPTY, + Observable, +} from 'rxjs'; +import { map } from 'rxjs/operators'; +import { FollowLinkConfig } from 'src/app/shared/utils/follow-link-config.model'; + +import { + isEmpty, + isNotEmpty, +} from '../../shared/empty.util'; +import { NotificationsService } from '../../shared/notifications/notifications.service'; +import { dataService } from '../cache/builders/build-decorators'; +import { RemoteDataBuildService } from '../cache/builders/remote-data-build.service'; +import { RequestParam } from '../cache/models/request-param.model'; +import { ObjectCacheService } from '../cache/object-cache.service'; +import { CoreState } from '../core-state.model'; +import { MetadataValue } from '../metadata/metadata-value.model'; +import { HALEndpointService } from '../shared/hal-endpoint.service'; +import { getFirstSucceededRemoteDataPayload } from '../shared/operators'; +import { ResourceType } from '../shared/resource-type'; +import { VocabularyEntry } from '../submission/vocabularies/models/vocabulary-entry.model'; +import { BaseDataService } from './base/base-data.service'; +import { + SearchData, + SearchDataImpl, +} from './base/search-data'; +import { DefaultChangeAnalyzer } from './default-change-analyzer.service'; +import { FindListOptions } from './find-list-options.model'; +import { PaginatedList } from './paginated-list.model'; +import { RemoteData } from './remote-data'; +import { RequestService } from './request.service'; + +export const linkName = 'metadatavalues'; +export const AUTOCOMPLETE = new ResourceType(linkName); + +/** + * A service responsible for fetching/sending data from/to the REST API - vocabularies endpoint + */ +@Injectable({ providedIn: 'root' }) +@dataService(MetadataValue.type) +export class MetadataValueDataService extends BaseDataService implements SearchData { + protected linkPath = linkName; + private searchData: SearchData; + + constructor( + protected requestService: RequestService, + protected rdbService: RemoteDataBuildService, + protected store: Store, + protected halService: HALEndpointService, + protected objectCache: ObjectCacheService, + protected comparator: DefaultChangeAnalyzer, + protected http: HttpClient, + protected notificationsService: NotificationsService, + ) { + super(linkName, requestService, rdbService, objectCache, halService, undefined); + this.searchData = new SearchDataImpl(this.linkPath, requestService, rdbService, objectCache, halService, this.responseMsToLive); + } + + searchBy(searchMethod: string, options?: FindListOptions, useCachedVersionIfAvailable?: boolean, reRequestOnStale?: boolean, ...linksToFollow: FollowLinkConfig[]): Observable>> { + return this.searchData.searchBy(searchMethod, options, useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } + + /** + * Retrieve the MetadataValue object inside Vocabulary object body + */ + findByMetadataNameAndByValue(metadataName, term = ''): Observable> { + const metadataFields = metadataName?.split('.'); + + const schemaRP = new RequestParam('schema', ''); + const elementRP = new RequestParam('element', ''); + const qualifierRP = new RequestParam('qualifier', ''); + const termRP = new RequestParam('searchValue', term); + + // schema and element are mandatory - cannot be empty + if (isEmpty(metadataFields?.[0]) && isEmpty(metadataFields?.[1])) { + return EMPTY; + } + + // add value to the request params + schemaRP.fieldValue = metadataFields?.[0]; + elementRP.fieldValue = metadataFields?.[1]; + qualifierRP.fieldValue = isNotEmpty(metadataFields?.[2]) ? metadataFields?.[2] : null; + + const optionParams = Object.assign(new FindListOptions(), {}, { + searchParams: [ + schemaRP, + elementRP, + qualifierRP, + termRP, + ], + }); + const remoteData$ = this.searchBy('byValue', optionParams); + + return remoteData$.pipe( + getFirstSucceededRemoteDataPayload(), + map((list: PaginatedList) => { + const vocabularyEntryList: VocabularyEntry[] = []; + list.page.forEach((metadataValue: MetadataValue) => { + const voc: VocabularyEntry = new VocabularyEntry(); + voc.display = metadataValue.value; + voc.value = metadataValue.value; + vocabularyEntryList.push(voc); + }); + // @ts-ignore + list.page = vocabularyEntryList; + return list; + }), + ); + } +} diff --git a/src/app/core/epicHandle/epic-handle.resource-type.ts b/src/app/core/epicHandle/epic-handle.resource-type.ts new file mode 100644 index 00000000000..583ec88b1a2 --- /dev/null +++ b/src/app/core/epicHandle/epic-handle.resource-type.ts @@ -0,0 +1,3 @@ +import { ResourceType } from '../shared/resource-type'; + +export const EPIC_HANDLE = new ResourceType('epichandle'); diff --git a/src/app/core/epicHandle/models/epic-handle.model.ts b/src/app/core/epicHandle/models/epic-handle.model.ts new file mode 100644 index 00000000000..7e4410f3c2f --- /dev/null +++ b/src/app/core/epicHandle/models/epic-handle.model.ts @@ -0,0 +1,38 @@ +import { + autoserialize, + deserialize, +} from 'cerialize'; +import { ListableObject } from 'src/app/shared/object-collection/shared/listable-object.model'; + +import { typedObject } from '../../cache/builders/build-decorators'; +import { CacheableObject } from '../../cache/cacheable-object.model'; +import { GenericConstructor } from '../../shared/generic-constructor'; +import { HALLink } from '../../shared/hal-link.model'; +import { ResourceType } from '../../shared/resource-type'; +import { excludeFromEquals } from '../../utilities/equals.decorators'; +import { EPIC_HANDLE } from '../epic-handle.resource-type'; + +@typedObject +export class EpicHandle extends ListableObject implements CacheableObject { + static type = EPIC_HANDLE; + + @excludeFromEquals + @autoserialize + type: ResourceType; + + @autoserialize + id: string; + + @autoserialize + url: string; + + @deserialize + _links: { + self: HALLink + }; + + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } + +} diff --git a/src/app/core/handle/HandleResourceTypeIdserializer.ts b/src/app/core/handle/HandleResourceTypeIdserializer.ts new file mode 100644 index 00000000000..c4c517c6f51 --- /dev/null +++ b/src/app/core/handle/HandleResourceTypeIdserializer.ts @@ -0,0 +1,43 @@ +import { + COLLECTION, + COMMUNITY, + ITEM, + SITE, +} from './handle.resource-type'; + +/** + * The ResourceTypeId of the Handle is number in the database but in the Handle table the user + * must see meaningful information. This serializer convert that number to the string information and vice versa e.g. + * resourceTypeId: 2 -> resourceTypeId: Item. + */ +export const HandleResourceTypeIdSerializer = { + Serialize(resourceTypeId: string): number { + switch (resourceTypeId) { + case ITEM: + return 2; + case COLLECTION: + return 3; + case COMMUNITY: + return 4; + case SITE: + return 5; + default: + return null; + } + }, + + Deserialize(resourceTypeId: number): string { + switch (resourceTypeId) { + case 2: + return ITEM; + case 3: + return COLLECTION; + case 4: + return COMMUNITY; + case 5: + return SITE; + default: + return null; + } + }, +}; diff --git a/src/app/core/handle/handle.model.ts b/src/app/core/handle/handle.model.ts new file mode 100644 index 00000000000..e2fa68a70a7 --- /dev/null +++ b/src/app/core/handle/handle.model.ts @@ -0,0 +1,74 @@ +import { + autoserialize, + autoserializeAs, + deserialize, +} from 'cerialize'; + +import { ListableObject } from '../../shared/object-collection/shared/listable-object.model'; +import { typedObject } from '../cache/builders/build-decorators'; +import { GenericConstructor } from '../shared/generic-constructor'; +import { HALLink } from '../shared/hal-link.model'; +import { HALResource } from '../shared/hal-resource.model'; +import { ResourceType } from '../shared/resource-type'; +import { excludeFromEquals } from '../utilities/equals.decorators'; +import { HANDLE } from './handle.resource-type'; +import { HandleResourceTypeIdSerializer } from './HandleResourceTypeIdserializer'; + +/** + * Class represents the Handle of the Item/Collection/Community + */ +@typedObject +export class Handle extends ListableObject implements HALResource { + static type = HANDLE; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + /** + * The identifier of this metadata field + */ + @autoserialize + id: number; + + /** + * The qualifier of this metadata field + */ + @autoserialize + handle: string; + + /** + * The url of this metadata field + */ + @autoserialize + url: string; + + @autoserialize + resourceId: string; + + /** + * The element of this metadata field + */ + @autoserializeAs(HandleResourceTypeIdSerializer) + resourceTypeID: string; + + /** + * The {@link HALLink}s for this MetadataField + */ + @deserialize + _links: { + self: HALLink, + }; + + /** + * Method that returns as which type of object this object should be rendered + */ + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } +} + + diff --git a/src/app/core/handle/handle.resource-type.ts b/src/app/core/handle/handle.resource-type.ts new file mode 100644 index 00000000000..d34d2cfa9bd --- /dev/null +++ b/src/app/core/handle/handle.resource-type.ts @@ -0,0 +1,17 @@ +import { ResourceType } from '../shared/resource-type'; + +/** + * The resource type for Handle + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ + +export const HANDLE = new ResourceType('handle'); +export const EPICHANDLE = new ResourceType('epichandle'); +export const SUCCESSFUL_RESPONSE_START_CHAR = '2'; +export const INVALID_RESOURCE_TYPE_ID = -1; +export const COMMUNITY = 'Community'; +export const COLLECTION = 'Collection'; +export const ITEM = 'Item'; +export const SITE = 'Site'; diff --git a/src/app/core/metadata/file-info.model.ts b/src/app/core/metadata/file-info.model.ts new file mode 100644 index 00000000000..22cebf51915 --- /dev/null +++ b/src/app/core/metadata/file-info.model.ts @@ -0,0 +1,15 @@ +import { + autoserialize, + autoserializeAs, +} from 'cerialize'; + +/** + * This class is used to store the information about a file or a directory + */ +export class FileInfo { + @autoserialize name: string; + @autoserialize content: any; + @autoserialize size: string; + @autoserialize isDirectory: boolean; + @autoserializeAs('sub') sub: { [key: string]: FileInfo }; +} diff --git a/src/app/core/metadata/head-tag.service.spec.ts b/src/app/core/metadata/head-tag.service.spec.ts index 48f61b7546f..1140c854662 100644 --- a/src/app/core/metadata/head-tag.service.spec.ts +++ b/src/app/core/metadata/head-tag.service.spec.ts @@ -221,7 +221,7 @@ describe('HeadTagService', () => { })); it('route titles should overwrite dso titles', fakeAsync(() => { - (translateService.get as jasmine.Spy).and.returnValues(of('DSpace :: '), of('Translated Route Title')); + (translateService.get as jasmine.Spy).and.returnValues(of('DSpace ::'), of('Translated Route Title')); (headTagService as any).processRouteChange({ data: { value: { @@ -237,7 +237,7 @@ describe('HeadTagService', () => { })); it('other navigation should add title and description', fakeAsync(() => { - (translateService.get as jasmine.Spy).and.returnValues(of('DSpace :: '), of('Dummy Title'), of('This is a dummy item component for testing!')); + (translateService.get as jasmine.Spy).and.returnValues(of('DSpace ::'), of('Dummy Title'), of('This is a dummy item component for testing!')); (headTagService as any).processRouteChange({ data: { value: { diff --git a/src/app/core/metadata/head-tag.service.ts b/src/app/core/metadata/head-tag.service.ts index 5e147b52949..7047267e42b 100644 --- a/src/app/core/metadata/head-tag.service.ts +++ b/src/app/core/metadata/head-tag.service.ts @@ -153,8 +153,8 @@ export class HeadTagService { const titlePrefix = this.translate.get('repository.title.prefix'); const title = this.translate.get(routeInfo.data.value.title, routeInfo.data.value); combineLatest([titlePrefix, title]).pipe(take(1)).subscribe(([translatedTitlePrefix, translatedTitle]: [string, string]) => { - this.addMetaTag('title', translatedTitlePrefix + translatedTitle); - this.title.setTitle(translatedTitlePrefix + translatedTitle); + this.addMetaTag('title', translatedTitlePrefix + ' ' + translatedTitle); + this.title.setTitle(translatedTitlePrefix + ' ' + translatedTitle); }); } if (routeInfo.data.value.description) { diff --git a/src/app/core/metadata/metadata-bitstream.model.ts b/src/app/core/metadata/metadata-bitstream.model.ts new file mode 100644 index 00000000000..270939ba703 --- /dev/null +++ b/src/app/core/metadata/metadata-bitstream.model.ts @@ -0,0 +1,98 @@ +import { + autoserialize, + autoserializeAs, + deserialize, +} from 'cerialize'; + +import { ListableObject } from '../../shared/object-collection/shared/listable-object.model'; +import { typedObject } from '../cache/builders/build-decorators'; +import { GenericConstructor } from '../shared/generic-constructor'; +import { HALLink } from '../shared/hal-link.model'; +import { HALResource } from '../shared/hal-resource.model'; +import { ResourceType } from '../shared/resource-type'; +import { excludeFromEquals } from '../utilities/equals.decorators'; +import { FileInfo } from './file-info.model'; +import { METADATA_BITSTREAM } from './metadata-bitstream.resource-type'; + +/** + * Class that represents a MetadataBitstream + */ +@typedObject +export class MetadataBitstream extends ListableObject implements HALResource { + static type = METADATA_BITSTREAM; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + /** + * The identifier of this metadata field + */ + @autoserialize + id: string; + + /** + * The name of this bitstream + */ + @autoserialize + name: string; + + /** + * The description of this bitstream + */ + @autoserialize + description: string; + + /** + * The fileSize of this bitstream + */ + @autoserialize + fileSize: number; + + /** + * The checksum of this bitstream + */ + @autoserialize + checksum: string; + + /** + * The fileInfo of this bitstream + */ + @autoserializeAs(FileInfo, 'fileInfo') fileInfo: FileInfo[]; + + /** + * The format of this bitstream + */ + @autoserialize + format: string; + + /** + * The href of this bitstream + */ + @autoserialize + href: string; + + /** + * The canPreview of this bitstream + */ + @autoserialize + canPreview: boolean; + + /** + * The {@link HALLink}s for this MetadataField + */ + @deserialize + _links: { + self: HALLink; + schema: HALLink; + }; + + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } +} +export { FileInfo }; + diff --git a/src/app/core/metadata/metadata-bitstream.resource-type.ts b/src/app/core/metadata/metadata-bitstream.resource-type.ts new file mode 100644 index 00000000000..6214c846169 --- /dev/null +++ b/src/app/core/metadata/metadata-bitstream.resource-type.ts @@ -0,0 +1,9 @@ +import { ResourceType } from '../shared/resource-type'; + +/** + * The resource type for MetadataBitstream + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +export const METADATA_BITSTREAM = new ResourceType('metadatabitstream'); diff --git a/src/app/core/metadata/metadata-value.model.ts b/src/app/core/metadata/metadata-value.model.ts new file mode 100644 index 00000000000..1d674094a01 --- /dev/null +++ b/src/app/core/metadata/metadata-value.model.ts @@ -0,0 +1,101 @@ +import { + autoserialize, + deserialize, +} from 'cerialize'; +import { Observable } from 'rxjs'; + +import { ListableObject } from '../../shared/object-collection/shared/listable-object.model'; +import { + link, + typedObject, +} from '../cache/builders/build-decorators'; +import { RemoteData } from '../data/remote-data'; +import { GenericConstructor } from '../shared/generic-constructor'; +import { HALLink } from '../shared/hal-link.model'; +import { HALResource } from '../shared/hal-resource.model'; +import { ResourceType } from '../shared/resource-type'; +import { excludeFromEquals } from '../utilities/equals.decorators'; +import { MetadataField } from './metadata-field.model'; +import { METADATA_FIELD } from './metadata-field.resource-type'; +import { METADATA_VALUE } from './metadata-value.resource-type'; + +/** + * Class that represents a metadata value + */ +@typedObject +export class MetadataValue extends ListableObject implements HALResource { + static type = METADATA_VALUE; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + /** + * The identifier of this metadata value + */ + @autoserialize + id: number; + + /** + * The value of this metadata value object + */ + @autoserialize + value: string; + + /** + * The language of this metadata value + */ + @autoserialize + language: string; + + /** + * The authority of this metadata value + */ + @autoserialize + authority: string; + + /** + * The confidence of this metadata value + */ + @autoserialize + confidence: string; + + /** + * The place of this metadata value + */ + @autoserialize + place: string; + + /** + * The {@link HALLink}s for this MetadataValue + */ + @deserialize + _links: { + self: HALLink, + field: HALLink + }; + + /** + * The MetadataField for this MetadataValue + * Will be undefined unless the schema {@link HALLink} has been resolved. + */ + @link(METADATA_FIELD) + field?: Observable>; + + /** + * Method to print this metadata value as a string + */ + toString(): string { + return `Value: ${this.value}`; + } + + /** + * Method that returns as which type of object this object should be rendered + */ + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } +} diff --git a/src/app/core/metadata/metadata-value.resource-type.ts b/src/app/core/metadata/metadata-value.resource-type.ts new file mode 100644 index 00000000000..f13aeb77357 --- /dev/null +++ b/src/app/core/metadata/metadata-value.resource-type.ts @@ -0,0 +1,9 @@ +import { ResourceType } from '../shared/resource-type'; + +/** + * The resource type for the metadata value endpoint + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +export const METADATA_VALUE = new ResourceType('metadatavalue'); diff --git a/src/app/core/provide-core.ts b/src/app/core/provide-core.ts index 0057c0823d7..9719b6d8e46 100644 --- a/src/app/core/provide-core.ts +++ b/src/app/core/provide-core.ts @@ -29,6 +29,8 @@ import { Root } from './data/root.model'; import { DspaceRestService } from './dspace-rest/dspace-rest.service'; import { EPerson } from './eperson/models/eperson.model'; import { Group } from './eperson/models/group.model'; +import { Handle } from './handle/handle.model'; +import { MetadataBitstream } from './metadata/metadata-bitstream.model'; import { MetadataField } from './metadata/metadata-field.model'; import { MetadataSchema } from './metadata/metadata-schema.model'; import { QualityAssuranceEventObject } from './notifications/qa/models/quality-assurance-event.model'; @@ -187,4 +189,6 @@ export const models = SubmissionCoarNotifyConfig, NotifyRequestsStatus, SystemWideAlert, + Handle, + MetadataBitstream, ]; diff --git a/src/app/core/registry/registry.service.spec.ts b/src/app/core/registry/registry.service.spec.ts index 628dad2a7c5..9e7bfab10ce 100644 --- a/src/app/core/registry/registry.service.spec.ts +++ b/src/app/core/registry/registry.service.spec.ts @@ -33,6 +33,7 @@ import { NotificationsServiceStub } from '../../shared/testing/notifications-ser import { StoreMock } from '../../shared/testing/store.mock'; import { createPaginatedList } from '../../shared/testing/utils.test'; import { FindListOptions } from '../data/find-list-options.model'; +import { MetadataBitstreamDataService } from '../data/metadata-bitstream-data.service'; import { MetadataFieldDataService } from '../data/metadata-field-data.service'; import { MetadataSchemaDataService } from '../data/metadata-schema-data.service'; import { RemoteData } from '../data/remote-data'; @@ -164,6 +165,7 @@ describe('RegistryService', () => { { provide: NotificationsService, useValue: new NotificationsServiceStub() }, { provide: MetadataSchemaDataService, useValue: metadataSchemaService }, { provide: MetadataFieldDataService, useValue: metadataFieldService }, + { provide: MetadataBitstreamDataService, useValue: jasmine.createSpyObj('metadataBitstreamDataService', ['searchByHandleParams']) }, RegistryService, ], }); diff --git a/src/app/core/registry/registry.service.ts b/src/app/core/registry/registry.service.ts index d4a272570bf..103b6429f7f 100644 --- a/src/app/core/registry/registry.service.ts +++ b/src/app/core/registry/registry.service.ts @@ -38,10 +38,12 @@ import { NotificationsService } from '../../shared/notifications/notifications.s import { FollowLinkConfig } from '../../shared/utils/follow-link-config.model'; import { RequestParam } from '../cache/models/request-param.model'; import { FindListOptions } from '../data/find-list-options.model'; +import { MetadataBitstreamDataService } from '../data/metadata-bitstream-data.service'; import { MetadataFieldDataService } from '../data/metadata-field-data.service'; import { MetadataSchemaDataService } from '../data/metadata-schema-data.service'; import { PaginatedList } from '../data/paginated-list.model'; import { RemoteData } from '../data/remote-data'; +import { MetadataBitstream } from '../metadata/metadata-bitstream.model'; import { MetadataField } from '../metadata/metadata-field.model'; import { MetadataSchema } from '../metadata/metadata-schema.model'; import { NoContent } from '../shared/NoContent.model'; @@ -63,10 +65,20 @@ export class RegistryService { private notificationsService: NotificationsService, private translateService: TranslateService, private metadataSchemaService: MetadataSchemaDataService, - private metadataFieldService: MetadataFieldDataService) { + private metadataFieldService: MetadataFieldDataService, + private metadataBitstreamDataService: MetadataBitstreamDataService) { } + /** + * CLARIN: retrieve the file-preview metadata (bitstream tree) for an item handle. + * Delegates to MetadataBitstreamDataService; consumed by the clarin-files-section/preview cluster. + */ + public getMetadataBitstream(handle: string, fileGrpType: string, options: FindListOptions = {}, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig[]): Observable> { + return this.metadataBitstreamDataService.searchByHandleParams(handle, fileGrpType, options, + useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow); + } + /** * Retrieves all metadata schemas * @param options The options used to retrieve the schemas diff --git a/src/app/core/shared/bitstream-checksum.model.ts b/src/app/core/shared/bitstream-checksum.model.ts new file mode 100644 index 00000000000..b799325926a --- /dev/null +++ b/src/app/core/shared/bitstream-checksum.model.ts @@ -0,0 +1,67 @@ +import { + autoserialize, + deserialize, +} from 'cerialize'; + +import { typedObject } from '../cache/builders/build-decorators'; +import { TypedObject } from '../cache/typed-object.model'; +import { excludeFromEquals } from '../utilities/equals.decorators'; +import { BITSTREAM_CHECKSUM } from './bitstream-checksum.resource'; +import { HALLink } from './hal-link.model'; +import { ResourceType } from './resource-type'; + + +/** + * Model class containing the checksums of a bitstream (local, S3, DB) + */ +@typedObject +export class BitstreamChecksum extends TypedObject { + /** + * The `bitstreamchecksum` object type. + */ + static type = BITSTREAM_CHECKSUM; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + /** + * The identifier of this BitstreamChecksum object + */ + @autoserialize + id: string; + + /** + * The checksum of the active store (local/S3) + */ + @autoserialize + activeStore: CheckSum; + + /** + * The checksum from the database + */ + @autoserialize + databaseChecksum: CheckSum; + + /** + * The checksum of the synchronized store (S3, local) + */ + @autoserialize + synchronizedStore: CheckSum; + + @deserialize + _links: { + self: HALLink + }; +} + +/** + * Model class containing a checksum value and algorithm + */ +export interface CheckSum { + checkSumAlgorithm: string; + value: string; +} diff --git a/src/app/core/shared/bitstream-checksum.resource.ts b/src/app/core/shared/bitstream-checksum.resource.ts new file mode 100644 index 00000000000..8404c0e7ca6 --- /dev/null +++ b/src/app/core/shared/bitstream-checksum.resource.ts @@ -0,0 +1,9 @@ +import { ResourceType } from './resource-type'; + +/** + * The resource type for BitstreamChecksum + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +export const BITSTREAM_CHECKSUM = new ResourceType('bitstreamchecksum'); diff --git a/src/app/core/shared/clarin/bitstream-authorization.model.ts b/src/app/core/shared/clarin/bitstream-authorization.model.ts new file mode 100644 index 00000000000..f470329dfdc --- /dev/null +++ b/src/app/core/shared/clarin/bitstream-authorization.model.ts @@ -0,0 +1,52 @@ +import { + autoserialize, + deserialize, +} from 'cerialize'; + +import { typedObject } from '../../cache/builders/build-decorators'; +import { excludeFromEquals } from '../../utilities/equals.decorators'; +import { HALLink } from '../hal-link.model'; +import { HALResource } from '../hal-resource.model'; +import { ResourceType } from '../resource-type'; +import { BITSTREAM_AUTHRN } from './bitstream-authorization.resource-type'; + +/** + * Class which is user do wrap Authorization response data for endpoint `/api/authrn` + */ +@typedObject +export class AuthrnBitstream implements HALResource { + /** + * The `authrn` object type. + */ + static type = BITSTREAM_AUTHRN; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + /** + * The identifier of this Clarin License + */ + @autoserialize + id: number; + + /** + * The name of this Clarin License object + */ + @autoserialize + errorName: string; + + @autoserialize + responseStatusCode: string; + + /** + * The {@link HALLink}s for this Clarin License + */ + @deserialize + _links: { + self: HALLink + }; +} diff --git a/src/app/core/shared/clarin/bitstream-authorization.resource-type.ts b/src/app/core/shared/clarin/bitstream-authorization.resource-type.ts new file mode 100644 index 00000000000..17d03cf8545 --- /dev/null +++ b/src/app/core/shared/clarin/bitstream-authorization.resource-type.ts @@ -0,0 +1,9 @@ +/** + * The resource type for the Clarin License endpoint + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +import { ResourceType } from '../resource-type'; + +export const BITSTREAM_AUTHRN = new ResourceType('authrn'); diff --git a/src/app/core/shared/clarin/clarin-featured-service-link.model.ts b/src/app/core/shared/clarin/clarin-featured-service-link.model.ts new file mode 100644 index 00000000000..19080f014c9 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-featured-service-link.model.ts @@ -0,0 +1,14 @@ +/** + * The class represents FeaturedServiceLink in the ref box (Item View) + */ +export class ClarinFeaturedServiceLink { + /** + * The language e.g. `Arabic` + */ + key: string; + + /** + * URL link for redirecting to the featured service page + */ + value: string; +} diff --git a/src/app/core/shared/clarin/clarin-featured-service.model.ts b/src/app/core/shared/clarin/clarin-featured-service.model.ts new file mode 100644 index 00000000000..2d3d301a6e9 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-featured-service.model.ts @@ -0,0 +1,8 @@ +import { ClarinFeaturedServiceLink } from './clarin-featured-service-link.model'; + +export class ClarinFeaturedService { + name: string; + url: string; + description: string; + featuredServiceLinks: ClarinFeaturedServiceLink[]; +} diff --git a/src/app/core/shared/clarin/clarin-license-confirmation-serializer.ts b/src/app/core/shared/clarin/clarin-license-confirmation-serializer.ts new file mode 100644 index 00000000000..eac8f6b4565 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-license-confirmation-serializer.ts @@ -0,0 +1,25 @@ +import { CLARIN_LICENSE_CONFIRMATION } from './clarin-license.resource-type'; + +/** + * The Clarin License REST/API returns license.confirmation as number and this serializer converts it to the + * appropriate string message and vice versa. + */ +export const ClarinLicenseConfirmationSerializer = { + + Serialize(confirmationMessage: any): number { + switch (confirmationMessage) { + case CLARIN_LICENSE_CONFIRMATION[1]: + return 1; + case CLARIN_LICENSE_CONFIRMATION[2]: + return 2; + case CLARIN_LICENSE_CONFIRMATION[3]: + return 3; + default: + return 0; + } + }, + + Deserialize(confirmationId: any): string { + return CLARIN_LICENSE_CONFIRMATION[confirmationId]; + }, +}; diff --git a/src/app/core/shared/clarin/clarin-license-label-extended-serializer.ts b/src/app/core/shared/clarin/clarin-license-label-extended-serializer.ts new file mode 100644 index 00000000000..b9128dc4d03 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-license-label-extended-serializer.ts @@ -0,0 +1,10 @@ +/** + * The Clarin License REST/API accepts the licenseLabel.extended as boolean value but it is a string value + * in the `define-license-label-form`. This serializer converts the string value to the appropriate boolean. + */ +export const ClarinLicenseLabelExtendedSerializer = { + + Serialize(extended: any): boolean { + return extended === 'Yes'; + }, +}; diff --git a/src/app/core/shared/clarin/clarin-license-label.model.ts b/src/app/core/shared/clarin/clarin-license-label.model.ts new file mode 100644 index 00000000000..75234e68841 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-license-label.model.ts @@ -0,0 +1,78 @@ +import { + autoserialize, + autoserializeAs, + deserialize, +} from 'cerialize'; + +import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model'; +import { typedObject } from '../../cache/builders/build-decorators'; +import { excludeFromEquals } from '../../utilities/equals.decorators'; +import { GenericConstructor } from '../generic-constructor'; +import { HALLink } from '../hal-link.model'; +import { HALResource } from '../hal-resource.model'; +import { ResourceType } from '../resource-type'; +import { CLARIN_LICENSE_LABEL } from './clarin-license-label.resource-type'; +import { ClarinLicenseLabelExtendedSerializer } from './clarin-license-label-extended-serializer'; + +/** + * Class that represents a Clarin License Label + */ +@typedObject +export class ClarinLicenseLabel extends ListableObject implements HALResource { + /** + * The `clarinlicenselabel` object type. + */ + static type = CLARIN_LICENSE_LABEL; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + /** + * The identifier of the Clarin License Label + */ + @autoserialize + id: number; + + /** + * The label of the Clarin License Label. It is a shortcut value, it could be max 5 characters long. + */ + @autoserialize + label: string; + + /** + * The title of the Clarin License Label. + */ + @autoserialize + title: string; + + /** + * The extended value of the Clarin License Label. + */ + @autoserializeAs(ClarinLicenseLabelExtendedSerializer) + extended: boolean; + + /** + * The icon of the Clarin License Label. It is converted to the byte array. + */ + @autoserialize + icon: any; + + /** + * The {@link HALLink}s for this Clarin License Label + */ + @deserialize + _links: { + self: HALLink + }; + + /** + * Method that returns as which type of object this object should be rendered + */ + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } +} diff --git a/src/app/core/shared/clarin/clarin-license-label.resource-type.ts b/src/app/core/shared/clarin/clarin-license-label.resource-type.ts new file mode 100644 index 00000000000..d522f1b4f78 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-license-label.resource-type.ts @@ -0,0 +1,9 @@ +/** + * The resource type for the Clarin License Label endpoint + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +import { ResourceType } from '../resource-type'; + +export const CLARIN_LICENSE_LABEL = new ResourceType('clarinlicenselabel'); diff --git a/src/app/core/shared/clarin/clarin-license-required-info-serializer.ts b/src/app/core/shared/clarin/clarin-license-required-info-serializer.ts new file mode 100644 index 00000000000..a13dd3df65c --- /dev/null +++ b/src/app/core/shared/clarin/clarin-license-required-info-serializer.ts @@ -0,0 +1,55 @@ +import { isEmpty } from '../../../shared/empty.util'; +import { + CLARIN_LICENSE_REQUIRED_INFO, + ClarinLicenseRequiredInfo, +} from './clarin-license.resource-type'; + +/** + * The Clarin License REST/API returns license.confirmation as number and this serializer converts it to the + * appropriate string message and vice versa. + */ +export const ClarinLicenseRequiredInfoSerializer = { + + Serialize(requiredInfoArray: ClarinLicenseRequiredInfo[]): string { + if (isEmpty(requiredInfoArray)) { + return ''; + } + + // sometimes the requiredInfoArray is string + if (typeof requiredInfoArray === 'string') { + return requiredInfoArray; + } + + let requiredInfoString = ''; + requiredInfoArray.forEach(requiredInfo => { + requiredInfoString += requiredInfo.name + ','; + }); + + // remove `,` from end of the string + requiredInfoString = requiredInfoString.substring(0, requiredInfoString.length - 1); + return requiredInfoString; + }, + + Deserialize(requiredInfoString: string): ClarinLicenseRequiredInfo[] { + const requiredInfoArray = requiredInfoString.split(','); + if (isEmpty(requiredInfoArray)) { + return []; + } + + const clarinLicenseRequiredInfo = []; + requiredInfoArray.forEach(requiredInfo => { + if (isEmpty(requiredInfo)) { + return; + } + requiredInfo = requiredInfo.trim(); + clarinLicenseRequiredInfo.push( + Object.assign(new ClarinLicenseRequiredInfo(), { + id: clarinLicenseRequiredInfo.length, + value: CLARIN_LICENSE_REQUIRED_INFO[requiredInfo], + name: requiredInfo, + }), + ); + }); + return clarinLicenseRequiredInfo; + }, +}; diff --git a/src/app/core/shared/clarin/clarin-license-resource-mapping.model.ts b/src/app/core/shared/clarin/clarin-license-resource-mapping.model.ts new file mode 100644 index 00000000000..c77ec06a61a --- /dev/null +++ b/src/app/core/shared/clarin/clarin-license-resource-mapping.model.ts @@ -0,0 +1,55 @@ +import { + autoserialize, + deserialize, +} from 'cerialize'; +import { Observable } from 'rxjs'; + +import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model'; +import { + link, + typedObject, +} from '../../cache/builders/build-decorators'; +import { RemoteData } from '../../data/remote-data'; +import { excludeFromEquals } from '../../utilities/equals.decorators'; +import { GenericConstructor } from '../generic-constructor'; +import { HALLink } from '../hal-link.model'; +import { HALResource } from '../hal-resource.model'; +import { ResourceType } from '../resource-type'; +import { ClarinLicense } from './clarin-license.model'; +import { CLARIN_LICENSE } from './clarin-license.resource-type'; +import { CLARIN_LICENSE_RESOURCE_MAPPING } from './clarin-license-resource-mapping.resource-type'; + +/** + * Class which wraps the Clarin License Resource Mapping object for communicating with BE. + */ +@typedObject +export class ClarinLicenseResourceMapping extends ListableObject implements HALResource { + + static type = CLARIN_LICENSE_RESOURCE_MAPPING; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + @autoserialize + bitstreamID: string; + + /** + * The {@link HALLink}s for this Clarin License + */ + @deserialize + _links: { + clarinLicense: HALLink, + self: HALLink + }; + + @link(CLARIN_LICENSE) + clarinLicense?: Observable>; + + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } +} diff --git a/src/app/core/shared/clarin/clarin-license-resource-mapping.resource-type.ts b/src/app/core/shared/clarin/clarin-license-resource-mapping.resource-type.ts new file mode 100644 index 00000000000..47597eac8f3 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-license-resource-mapping.resource-type.ts @@ -0,0 +1,9 @@ +/** + * The resource type for ClarinLicenseResourceMapping + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +import { ResourceType } from '../resource-type'; + +export const CLARIN_LICENSE_RESOURCE_MAPPING = new ResourceType('clarinlicenseresourcemapping'); diff --git a/src/app/core/shared/clarin/clarin-license.model.ts b/src/app/core/shared/clarin/clarin-license.model.ts new file mode 100644 index 00000000000..b90d15477e3 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-license.model.ts @@ -0,0 +1,101 @@ +import { + autoserialize, + autoserializeAs, + deserialize, +} from 'cerialize'; + +import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model'; +import { typedObject } from '../../cache/builders/build-decorators'; +import { excludeFromEquals } from '../../utilities/equals.decorators'; +import { GenericConstructor } from '../generic-constructor'; +import { HALLink } from '../hal-link.model'; +import { HALResource } from '../hal-resource.model'; +import { ResourceType } from '../resource-type'; +import { CLARIN_LICENSE } from './clarin-license.resource-type'; +import { ClarinLicenseConfirmationSerializer } from './clarin-license-confirmation-serializer'; +import { ClarinLicenseLabel } from './clarin-license-label.model'; +import { ClarinLicenseRequiredInfoSerializer } from './clarin-license-required-info-serializer'; + +/** + * Class that represents a Clarin License + */ +@typedObject +export class ClarinLicense extends ListableObject implements HALResource { + /** + * The `clarinlicense` object type. + */ + static type = CLARIN_LICENSE; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + /** + * The identifier of this Clarin License + */ + @autoserialize + id: number; + + /** + * The name of this Clarin License object + */ + @autoserialize + name: string; + + /** + * The definition of this Clarin License object + */ + @autoserialize + definition: string; + + /** + * The confirmation of this Clarin License object. Number value is converted to the appropriate message by the + * `ClarinLicenseConfirmationSerializer`. + */ + @autoserializeAs(ClarinLicenseConfirmationSerializer) + confirmation: number; + + /** + * The requiredInfo of this Clarin License object + */ + @autoserializeAs(ClarinLicenseRequiredInfoSerializer) + requiredInfo: any; + + /** + * The non extended clarinLicenseLabel of this Clarin License object. Clarin License could have only one + * non extended clarinLicenseLabel. + */ + @autoserialize + clarinLicenseLabel: ClarinLicenseLabel; + + /** + * The extended clarinLicenseLabel of this Clarin License object. Clarin License could have multiple + * extended clarinLicenseLabel. + */ + @autoserialize + extendedClarinLicenseLabels: ClarinLicenseLabel[]; + + /** + * The number value of how many bitstreams are used by this Clarin License. + */ + @autoserialize + bitstreams: number; + + /** + * The {@link HALLink}s for this Clarin License + */ + @deserialize + _links: { + self: HALLink + }; + + /** + * Method that returns as which type of object this object should be rendered + */ + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } +} diff --git a/src/app/core/shared/clarin/clarin-license.resource-type.ts b/src/app/core/shared/clarin/clarin-license.resource-type.ts new file mode 100644 index 00000000000..83ee51aeea2 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-license.resource-type.ts @@ -0,0 +1,96 @@ +/** + * The resource type for the Clarin License endpoint + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +import { ResourceType } from '../resource-type'; + +export const CLARIN_LICENSE = new ResourceType('clarinlicense'); + +/** + * Confirmation possible values. + */ +export const CLARIN_LICENSE_CONFIRMATION = ['Not required', 'Ask only once', 'Ask always', 'Allow anonymous']; + +/** + * Wrap required info to the object for better maintaining in the clarin license table. + */ +export class ClarinLicenseRequiredInfo { + id: number; + value: string; + name: string; +} + +/** + * Required info possible values. + */ +export const CLARIN_LICENSE_REQUIRED_INFO = { + SEND_TOKEN: 'The user will receive an email with download instructions.', + NAME: 'User Name', + DOB: 'Date of birth', + ADDRESS: 'Address', + COUNTRY: 'Country', + EXTRA_EMAIL: 'Ask user for another email address', + ORGANIZATION: 'Ask user for organization (optional)', + REQUIRED_ORGANIZATION: 'Ask user for organization (mandatory)', + INTENDED_USE: 'Ask user for his intentions with the item', + ACA_ORG_NAME_AND_SEAT: 'Ask for the name and seat (address) of user\'s academic institution', +}; + +/** + * Create list of required info objects filled by possible values. + */ +export const CLARIN_LICENSE_FORM_REQUIRED_OPTIONS = [ + Object.assign(new ClarinLicenseRequiredInfo(), { + id: 0, + value: CLARIN_LICENSE_REQUIRED_INFO.SEND_TOKEN, + name: 'SEND_TOKEN', + }), + Object.assign(new ClarinLicenseRequiredInfo(), { + id: 1, + value: CLARIN_LICENSE_REQUIRED_INFO.NAME, + name: 'NAME', + }), + Object.assign(new ClarinLicenseRequiredInfo(), { + id: 2, + value: CLARIN_LICENSE_REQUIRED_INFO.DOB, + name: 'DOB', + }), + Object.assign(new ClarinLicenseRequiredInfo(), { + id: 3, + value: CLARIN_LICENSE_REQUIRED_INFO.ADDRESS, + name: 'ADDRESS', + }), + Object.assign(new ClarinLicenseRequiredInfo(), { + id: 4, + value: CLARIN_LICENSE_REQUIRED_INFO.COUNTRY, + name: 'COUNTRY', + }), + Object.assign(new ClarinLicenseRequiredInfo(), { + id: 5, + value: CLARIN_LICENSE_REQUIRED_INFO.EXTRA_EMAIL, + name: 'EXTRA_EMAIL', + }), + Object.assign(new ClarinLicenseRequiredInfo(), { + id: 6, + value: CLARIN_LICENSE_REQUIRED_INFO.ORGANIZATION, + name: 'ORGANIZATION', + }), + Object.assign(new ClarinLicenseRequiredInfo(), { + id: 7, + value: CLARIN_LICENSE_REQUIRED_INFO.REQUIRED_ORGANIZATION, + name: 'REQUIRED_ORGANIZATION', + }), + Object.assign(new ClarinLicenseRequiredInfo(), { + id: 8, + value: CLARIN_LICENSE_REQUIRED_INFO.INTENDED_USE, + name: 'INTENDED_USE', + }), + Object.assign(new ClarinLicenseRequiredInfo(), { + id: 9, + value: CLARIN_LICENSE_REQUIRED_INFO.ACA_ORG_NAME_AND_SEAT, + name: 'ACA_ORG_NAME_AND_SEAT', + }), +]; + diff --git a/src/app/core/shared/clarin/clarin-user-metadata.model.ts b/src/app/core/shared/clarin/clarin-user-metadata.model.ts new file mode 100644 index 00000000000..e325bb23a7d --- /dev/null +++ b/src/app/core/shared/clarin/clarin-user-metadata.model.ts @@ -0,0 +1,46 @@ +import { + autoserialize, + deserialize, +} from 'cerialize'; + +import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model'; +import { typedObject } from '../../cache/builders/build-decorators'; +import { excludeFromEquals } from '../../utilities/equals.decorators'; +import { GenericConstructor } from '../generic-constructor'; +import { HALLink } from '../hal-link.model'; +import { HALResource } from '../hal-resource.model'; +import { ResourceType } from '../resource-type'; +import { CLARIN_USER_METADATA } from './clarin-user-metadata.resource-type'; + +/** + * Class which represents the ClarinUserMetadata object. + */ +@typedObject +export class ClarinUserMetadata extends ListableObject implements HALResource { + static type = CLARIN_USER_METADATA; + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + @autoserialize + metadataKey: string; + + @autoserialize + metadataValue: string; + + /** + * The {@link HALLink}s for this Clarin License + */ + @deserialize + _links: { + self: HALLink + }; + + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } + +} diff --git a/src/app/core/shared/clarin/clarin-user-metadata.resource-type.ts b/src/app/core/shared/clarin/clarin-user-metadata.resource-type.ts new file mode 100644 index 00000000000..723e3240655 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-user-metadata.resource-type.ts @@ -0,0 +1,10 @@ +/** + * The resource type for ClarinUserMetadata + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +import { ResourceType } from '../resource-type'; + +export const CLARIN_USER_METADATA = new ResourceType('clarinusermetadata'); +export const CLARIN_USER_METADATA_MANAGE = 'manage'; diff --git a/src/app/core/shared/clarin/clarin-user-registration.model.ts b/src/app/core/shared/clarin/clarin-user-registration.model.ts new file mode 100644 index 00000000000..bd70f22f16f --- /dev/null +++ b/src/app/core/shared/clarin/clarin-user-registration.model.ts @@ -0,0 +1,75 @@ +import { + autoserialize, + deserialize, +} from 'cerialize'; +import { Observable } from 'rxjs'; + +import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model'; +import { + link, + typedObject, +} from '../../cache/builders/build-decorators'; +import { PaginatedList } from '../../data/paginated-list.model'; +import { RemoteData } from '../../data/remote-data'; +import { excludeFromEquals } from '../../utilities/equals.decorators'; +import { GenericConstructor } from '../generic-constructor'; +import { HALLink } from '../hal-link.model'; +import { HALResource } from '../hal-resource.model'; +import { ResourceType } from '../resource-type'; +import { ClarinLicense } from './clarin-license.model'; +import { CLARIN_LICENSE } from './clarin-license.resource-type'; +import { ClarinUserMetadata } from './clarin-user-metadata.model'; +import { CLARIN_USER_METADATA } from './clarin-user-metadata.resource-type'; +import { CLARIN_USER_REGISTRATION } from './clarin-user-registration.resource-type'; + +/** + * Class which represents ClarinUserRegistration object. + */ +@typedObject +export class ClarinUserRegistration extends ListableObject implements HALResource { + + static type = CLARIN_USER_REGISTRATION; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + @autoserialize + id: number; + + @autoserialize + ePersonID: string; + + @autoserialize + email: string; + + @autoserialize + organization: string; + + @autoserialize + confirmation: boolean; + + /** + * The {@link HALLink}s for this Clarin License + */ + @deserialize + _links: { + clarinLicenses: HALLink, + userMetadata: HALLink, + self: HALLink + }; + + @link(CLARIN_LICENSE) + clarinLicenses?: Observable>>; + + @link(CLARIN_USER_METADATA, true) + userMetadata?: Observable>>; + + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } + +} diff --git a/src/app/core/shared/clarin/clarin-user-registration.resource-type.ts b/src/app/core/shared/clarin/clarin-user-registration.resource-type.ts new file mode 100644 index 00000000000..bd2d624d572 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-user-registration.resource-type.ts @@ -0,0 +1,9 @@ +/** + * The resource type for ClarinUserRegistration. + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +import { ResourceType } from '../resource-type'; + +export const CLARIN_USER_REGISTRATION = new ResourceType('clarinuserregistration'); diff --git a/src/app/core/shared/clarin/clarin-verification-token.model.ts b/src/app/core/shared/clarin/clarin-verification-token.model.ts new file mode 100644 index 00000000000..a0acc691cde --- /dev/null +++ b/src/app/core/shared/clarin/clarin-verification-token.model.ts @@ -0,0 +1,74 @@ +import { + autoserialize, + deserialize, +} from 'cerialize'; + +import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model'; +import { typedObject } from '../../cache/builders/build-decorators'; +import { excludeFromEquals } from '../../utilities/equals.decorators'; +import { GenericConstructor } from '../generic-constructor'; +import { HALLink } from '../hal-link.model'; +import { HALResource } from '../hal-resource.model'; +import { ResourceType } from '../resource-type'; +import { CLARIN_VERIFICATION_TOKEN } from './clarin-verification-token.resource-type'; + +/** + * Class that represents a ClarinVerificationToken. A ClarinVerificationTokenRest is mapped to this object. + */ +@typedObject +export class ClarinVerificationToken extends ListableObject implements HALResource { + static type = CLARIN_VERIFICATION_TOKEN; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + /** + * The identifier of this ClarinVerificationToken + */ + @autoserialize + id: string; + + /** + * The netid of the user which is trying to login. + */ + @autoserialize + ePersonNetID: string; + + /** + * The email of the user which is trying to login. + * The user must fill in the email in the auth-failed.component + */ + @autoserialize + email: string; + + /** + * The Shibboleth headers which are passed from the IdP. + */ + @autoserialize + shibHeaders: string; + + /** + * Generated verification token for registration and login. + */ + @autoserialize + token: string; + + /** + * The {@link HALLink}s for this ClarinVerificationToken + */ + @deserialize + _links: { + self: HALLink + }; + + /** + * Method that returns as which type of object this object should be rendered + */ + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } +} diff --git a/src/app/core/shared/clarin/clarin-verification-token.resource-type.ts b/src/app/core/shared/clarin/clarin-verification-token.resource-type.ts new file mode 100644 index 00000000000..5488f11a957 --- /dev/null +++ b/src/app/core/shared/clarin/clarin-verification-token.resource-type.ts @@ -0,0 +1,9 @@ +/** + * The resource type for the ClarinVerificationToken endpoint + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +import { ResourceType } from '../resource-type'; + +export const CLARIN_VERIFICATION_TOKEN = new ResourceType('clarinverificationtoken'); diff --git a/src/app/core/shared/clarin/clrua.model.ts b/src/app/core/shared/clarin/clrua.model.ts new file mode 100644 index 00000000000..9480e45aced --- /dev/null +++ b/src/app/core/shared/clarin/clrua.model.ts @@ -0,0 +1,69 @@ +import { + autoserialize, + deserialize, +} from 'cerialize'; +import { Observable } from 'rxjs'; + +import { ListableObject } from '../../../shared/object-collection/shared/listable-object.model'; +import { + link, + typedObject, +} from '../../cache/builders/build-decorators'; +import { PaginatedList } from '../../data/paginated-list.model'; +import { RemoteData } from '../../data/remote-data'; +import { excludeFromEquals } from '../../utilities/equals.decorators'; +import { GenericConstructor } from '../generic-constructor'; +import { HALLink } from '../hal-link.model'; +import { HALResource } from '../hal-resource.model'; +import { ResourceType } from '../resource-type'; +import { ClarinLicenseResourceMapping } from './clarin-license-resource-mapping.model'; +import { CLARIN_LICENSE_RESOURCE_MAPPING } from './clarin-license-resource-mapping.resource-type'; +import { ClarinUserMetadata } from './clarin-user-metadata.model'; +import { CLARIN_USER_METADATA } from './clarin-user-metadata.resource-type'; +import { ClarinUserRegistration } from './clarin-user-registration.model'; +import { CLARIN_USER_REGISTRATION } from './clarin-user-registration.resource-type'; +import { CLARIN_LICENSE_RESOURCE_USER_ALLOWANCE } from './clrua.resource-type'; + +/** + * CLRUA = ClarinLicenseResourceUserAllowance + * Class which represents CLRUA object. + */ +@typedObject +export class ClruaModel extends ListableObject implements HALResource { + + static type = CLARIN_LICENSE_RESOURCE_USER_ALLOWANCE; + + /** + * The object type + */ + @excludeFromEquals + @autoserialize + type: ResourceType; + + @autoserialize + token: string; + + /** + * The {@link HALLink}s for this Clarin License + */ + @deserialize + _links: { + userRegistration: HALLink, + userMetadata: HALLink, + resourceMapping: HALLink, + self: HALLink + }; + + @link(CLARIN_USER_REGISTRATION) + userRegistration?: Observable>; + + @link(CLARIN_USER_METADATA, true) + userMetadata?: Observable>>; + + @link(CLARIN_LICENSE_RESOURCE_MAPPING) + resourceMapping?: Observable>; + + getRenderTypes(): (string | GenericConstructor)[] { + return [this.constructor as GenericConstructor]; + } +} diff --git a/src/app/core/shared/clarin/clrua.resource-type.ts b/src/app/core/shared/clarin/clrua.resource-type.ts new file mode 100644 index 00000000000..c9648bc1066 --- /dev/null +++ b/src/app/core/shared/clarin/clrua.resource-type.ts @@ -0,0 +1,10 @@ +/** + * The resource type for ClarinLicenseResourceUserAllowance + * + * + * Needs to be in a separate file to prevent circular + * dependencies in webpack. + */ +import { ResourceType } from '../resource-type'; + +export const CLARIN_LICENSE_RESOURCE_USER_ALLOWANCE = new ResourceType('clarinlruallowance'); diff --git a/src/app/core/shared/clarin/constants.ts b/src/app/core/shared/clarin/constants.ts new file mode 100644 index 00000000000..77dc29602e6 --- /dev/null +++ b/src/app/core/shared/clarin/constants.ts @@ -0,0 +1,12 @@ +// Licenses +export const MISSING_LICENSE_AGREEMENT_EXCEPTION = 'MissingLicenseAgreementException'; +export const DOWNLOAD_TOKEN_EXPIRED_EXCEPTION = 'DownloadTokenExpiredException'; +export const AUTHORIZATION_DENIED_EXCEPTION = 'Authorization denied'; + +// Authorization +export const HTTP_STATUS_UNAUTHORIZED = 401; +export const USER_WITHOUT_EMAIL_EXCEPTION = 'UserWithoutEmailException'; +export const MISSING_HEADERS_FROM_IDP_EXCEPTION = 'MissingHeadersFromIpd'; + +// Metadata field names +export const AUTHOR_METADATA_FIELDS = ['dc.contributor.author', 'dc.creator', 'dc.contributor.other']; diff --git a/src/app/core/shared/clarin/matomo-report-subscription.model.ts b/src/app/core/shared/clarin/matomo-report-subscription.model.ts new file mode 100644 index 00000000000..2d6d44550fe --- /dev/null +++ b/src/app/core/shared/clarin/matomo-report-subscription.model.ts @@ -0,0 +1,34 @@ +import { + autoserialize, + deserialize, +} from 'cerialize'; + +import { typedObject } from '../../cache/builders/build-decorators'; +import { excludeFromEquals } from '../../utilities/equals.decorators'; +import { HALLink } from '../hal-link.model'; +import { HALResource } from '../hal-resource.model'; +import { ResourceType } from '../resource-type'; +import { MATOMO_REPORT_SUBSCRIPTION } from './matomo-report-subscription.resource-type'; + +@typedObject +export class MatomoReportSubscription implements HALResource { + static type = MATOMO_REPORT_SUBSCRIPTION; + + @excludeFromEquals + @autoserialize + type: ResourceType; + + @autoserialize + id: number; + + @autoserialize + epersonId: string; + + @autoserialize + itemId: string; + + @deserialize + _links: { + self: HALLink; + }; +} diff --git a/src/app/core/shared/clarin/matomo-report-subscription.resource-type.ts b/src/app/core/shared/clarin/matomo-report-subscription.resource-type.ts new file mode 100644 index 00000000000..ad1ea2e1496 --- /dev/null +++ b/src/app/core/shared/clarin/matomo-report-subscription.resource-type.ts @@ -0,0 +1,3 @@ +import { ResourceType } from '../resource-type'; + +export const MATOMO_REPORT_SUBSCRIPTION = new ResourceType('matomoreportsubscription'); diff --git a/src/app/core/shared/collection.model.ts b/src/app/core/shared/collection.model.ts index b929e54ccb4..e0cf33743cb 100644 --- a/src/app/core/shared/collection.model.ts +++ b/src/app/core/shared/collection.model.ts @@ -1,5 +1,6 @@ import { autoserialize, + autoserializeAs, deserialize, inheritSerialization, } from 'cerialize'; @@ -87,9 +88,17 @@ export class Collection extends DSpaceObject implements ChildHALResource, Handle * A string representing the unique handle of this Collection */ get handle(): string { - return this.firstMetadataValue('dc.identifier.uri'); + // fall back to the REST handle field - older (CLARIN 7.x) data does not carry + // dc.identifier.uri metadata on collection objects + return this.firstMetadataValue('dc.identifier.uri') ?? this.handleField; } + /** + * The handle exposed by the REST API as a plain field + */ + @autoserializeAs('handle') + protected handleField: string; + /** * The introductory text of this Collection * Corresponds to the metadata field dc.description diff --git a/src/app/core/shared/community.model.ts b/src/app/core/shared/community.model.ts index 31b00398ffb..25a6c5dfb39 100644 --- a/src/app/core/shared/community.model.ts +++ b/src/app/core/shared/community.model.ts @@ -1,5 +1,6 @@ import { autoserialize, + autoserializeAs, deserialize, inheritSerialization, } from 'cerialize'; @@ -76,9 +77,17 @@ export class Community extends DSpaceObject implements ChildHALResource, HandleO * A string representing the unique handle of this Community */ get handle(): string { - return this.firstMetadataValue('dc.identifier.uri'); + // fall back to the REST handle field - older (CLARIN 7.x) data does not carry + // dc.identifier.uri metadata on community objects + return this.firstMetadataValue('dc.identifier.uri') ?? this.handleField; } + /** + * The handle exposed by the REST API as a plain field + */ + @autoserializeAs('handle') + protected handleField: string; + /** * The introductory text of this Community * Corresponds to the metadata field dc.description diff --git a/src/app/core/shared/hal-endpoint.service.spec.ts b/src/app/core/shared/hal-endpoint.service.spec.ts index e2677c2f1ad..e33d512f382 100644 --- a/src/app/core/shared/hal-endpoint.service.spec.ts +++ b/src/app/core/shared/hal-endpoint.service.spec.ts @@ -324,14 +324,16 @@ describe('HALEndpointService', () => { }); }); - it(`should emit undefined when the response doesn't have a payload`, () => { + it(`should emit undefined when the response doesn't have a payload, after retrying`, () => { testScheduler.run(({ cold, expectObservable }) => { (rdbService.buildFromHref as jasmine.Spy).and.returnValue(cold('a', { a: remoteDataMocks.Error, })); - const expected = '(a|)'; + // a payload-less response is transiently retried 3 times (200ms apart) before giving up + // (see HALEndpointService.MAX_ENDPOINT_MAP_RETRIES / ENDPOINT_MAP_RETRY_DELAY_MS) + const expected = '600ms (a|)'; const values = { - g: undefined, + a: undefined, }; expectObservable((service as any).getEndpointMapAt(href)).toBe(expected, values); }); diff --git a/src/app/core/shared/hal-endpoint.service.ts b/src/app/core/shared/hal-endpoint.service.ts index 0e54c8870ca..060240e099f 100644 --- a/src/app/core/shared/hal-endpoint.service.ts +++ b/src/app/core/shared/hal-endpoint.service.ts @@ -1,5 +1,9 @@ import { Injectable } from '@angular/core'; -import { Observable } from 'rxjs'; +import { + Observable, + of, + timer, +} from 'rxjs'; import { distinctUntilChanged, filter, @@ -27,6 +31,17 @@ import { getFirstCompletedRemoteData } from './operators'; @Injectable({ providedIn: 'root' }) export class HALEndpointService { + /** + * How many times to retry resolving a HAL endpoint map that transiently completed without a + * payload (e.g. a root-endpoint request issued before the SSR HTTP layer was ready). + */ + private static readonly MAX_ENDPOINT_MAP_RETRIES = 3; + + /** + * Delay (ms) between endpoint-map resolution retries. + */ + private static readonly ENDPOINT_MAP_RETRY_DELAY_MS = 200; + constructor( private requestService: RequestService, private rdbService: RemoteDataBuildService, @@ -41,10 +56,12 @@ export class HALEndpointService { return this.getEndpointMapAt(this.getRootHref()); } - private getEndpointMapAt(href): Observable { + private getEndpointMapAt(href, attempt = 0): Observable { const request = new EndpointMapRequest(this.requestService.generateRequestId(), href); - this.requestService.send(request, true); + // On the first attempt reuse a cached response if present; on a retry force a fresh, uncached + // request so we bypass a previously cached transient error (see the retry branch below). + this.requestService.send(request, attempt === 0); return this.rdbService.buildFromHref(href).pipe( // Re-request stale responses @@ -57,12 +74,21 @@ export class HALEndpointService { // completed RemoteData filter((rd: RemoteData) => !rd.isStale), getFirstCompletedRemoteData(), - map((response: RemoteData) => { + switchMap((response: RemoteData) => { if (hasValue(response.payload)) { - return response.payload._links; + return of(response.payload._links); + } else if (attempt < HALEndpointService.MAX_ENDPOINT_MAP_RETRIES) { + // The HAL root endpoint request can transiently fail when it is issued before the + // (server-side render) HTTP layer is fully initialised - e.g. an early site/authorization + // lookup on the home or login page. Left unhandled, that first failure is cached and + // poisons every later root-link lookup in the same render, turning the page into a 500. + // Retry with a fresh, uncached request after a short delay so the render recovers. + return timer(HALEndpointService.ENDPOINT_MAP_RETRY_DELAY_MS).pipe( + switchMap(() => this.getEndpointMapAt(href, attempt + 1)), + ); } else { - console.warn(`No _links section found at ${href}`); - return undefined; + console.warn(`No _links section found at ${href} (status: ${response.statusCode}, error: ${response.errorMessage})`); + return of(undefined); } }), ); diff --git a/src/app/core/url-serializer/bitstream-url-serializer.ts b/src/app/core/url-serializer/bitstream-url-serializer.ts new file mode 100644 index 00000000000..d3cd96472fb --- /dev/null +++ b/src/app/core/url-serializer/bitstream-url-serializer.ts @@ -0,0 +1,37 @@ +import { Injectable } from '@angular/core'; +import { + DefaultUrlSerializer, + UrlTree, +} from '@angular/router'; + +import { encodeRFC3986URIComponent } from '../../shared/clarin-shared-util'; + +/** + * This class intercepts the parsing of URLs to ensure that the filename in the URL is properly encoded. + * But it only does this for URLs that start with '/bitstream/'. + */ +@Injectable({ providedIn: 'root' }) +export class BitstreamUrlSerializer extends DefaultUrlSerializer { + FILENAME_INDEX = 5; + // Intercept parsing of every URL + parse(url: string): UrlTree { + if (url.startsWith('/bitstream/')) { + // Separate the path from the query string + const [path, query] = url.split('?'); + + // Split the path to isolate the filename + const parts = path.split('/'); + if (parts.length > this.FILENAME_INDEX) { + const filename = parts.slice(this.FILENAME_INDEX).join('/'); + const encodedFilename = encodeRFC3986URIComponent(filename); + + // Reconstruct the path with the encoded filename + const newPath = [...parts.slice(0, this.FILENAME_INDEX), encodedFilename].join('/'); + + // Reattach query string if present + url = query ? `${newPath}?${query}` : newPath; + } + } + return super.parse(url); + } +} diff --git a/src/app/epic-handle/epic-handle-edit/epic-handle-edit.component.html b/src/app/epic-handle/epic-handle-edit/epic-handle-edit.component.html new file mode 100644 index 00000000000..94d4391bfe2 --- /dev/null +++ b/src/app/epic-handle/epic-handle-edit/epic-handle-edit.component.html @@ -0,0 +1,48 @@ +
+
+
+ +

{{ 'epic-handle-table.edit-handle.description' | translate }}

+
+
+ +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+
diff --git a/src/app/epic-handle/epic-handle-edit/epic-handle-edit.component.scss b/src/app/epic-handle/epic-handle-edit/epic-handle-edit.component.scss new file mode 100644 index 00000000000..e69de29bb2d diff --git a/src/app/epic-handle/epic-handle-edit/epic-handle-edit.component.ts b/src/app/epic-handle/epic-handle-edit/epic-handle-edit.component.ts new file mode 100644 index 00000000000..0c6990ea71d --- /dev/null +++ b/src/app/epic-handle/epic-handle-edit/epic-handle-edit.component.ts @@ -0,0 +1,112 @@ +import { + Component, + OnInit, +} from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { + ActivatedRoute, + Router, +} from '@angular/router'; +import { + TranslateModule, + TranslateService, +} from '@ngx-translate/core'; +import { EpicHandleDataService } from 'src/app/core/data/epic-handle-data.service'; +import { getFirstCompletedRemoteData } from 'src/app/core/shared/operators'; +import { isNull } from 'src/app/shared/empty.util'; +import { NotificationsService } from 'src/app/shared/notifications/notifications.service'; + +import { BtnDisabledDirective } from '../../shared/btn-disabled.directive'; +import { getEpicHandleTableModulePath } from '../epic-handle-routing-paths'; + +@Component({ + imports: [ + BtnDisabledDirective, + FormsModule, + TranslateModule, + ], + selector: 'ds-epic-handle-edit', + templateUrl: './epic-handle-edit.component.html', + styleUrls: ['./epic-handle-edit.component.scss'], +}) +export class EpicHandleEditComponent implements OnInit { + handleId: string; + prefix: string; + suffix: string; + url: string; + newUrl: string; + isLoading = false; + currentPage: number; + constructor(private notificationService: NotificationsService, + private route: ActivatedRoute, private router: Router, + private translateService: TranslateService, + private epicHandleService: EpicHandleDataService, + ) { } + ngOnInit(): void { + this.handleId = this.route.snapshot.queryParams.id; + this.url = this.route.snapshot.queryParams.url; + + this.currentPage = this.route.snapshot.queryParams.currentPage; + if (!this.handleId) { + this.notificationService.error('', this.translateService.instant('epic-handle-table.edit-handle.notify.error.no-handle')); + this.redirectBack(); + return; + } + + const parts = this.handleId.split('/'); + if (parts.length !== 2) { + this.notificationService.error('', this.translateService.instant('epic-handle-table.edit-handle.notify.error.invalid-handle')); + this.redirectBack(); + return; + } + + this.prefix = parts[0]; + this.suffix = parts[1]; + this.newUrl = this.url; + } + + onClickSubmit(value: { url: string }) { + if (!value.url || value.url.trim() === '') { + this.notificationService.error( + this.translateService.instant('epic-handle-table.edit-handle.notify.error.url-required'), + this.translateService.instant('epic-handle-table.edit-handle.notify.error'), + ); + return; + } + + this.isLoading = true; + + this.epicHandleService.update(this.prefix, this.suffix, value.url.trim()).pipe(getFirstCompletedRemoteData()) + .subscribe((handleResponse) => { + this.isLoading = false; + if (isNull(handleResponse)) { + this.notificationService.error('', this.translateService.instant('epic-handle-table.edit-handle.notify.error')); + return; + } + + if (handleResponse.hasSucceeded) { + this.notificationService.success('', this.translateService.instant('epic-handle-table.edit-handle.notify.successful')); + this.redirectBack(); + } else if (handleResponse.hasFailed) { + const errorMsg = handleResponse.errorMessage || + this.translateService.instant('epic-handle-table.edit-handle.notify.error'); + this.notificationService.error('', errorMsg); + } + }, (error: unknown) => { + this.isLoading = false; + this.notificationService.error( + '', + this.translateService.instant('epic-handle-table.edit-handle.notify.error'), + ); + }); + } + + redirectBack() { + const queryParams = this.prefix ? { prefix: this.prefix } : {}; + this.router.navigate([getEpicHandleTableModulePath()], { queryParams }); + } + + onCancel() { + this.redirectBack(); + } +} diff --git a/src/app/epic-handle/epic-handle-new/epic-handle-new.component.html b/src/app/epic-handle/epic-handle-new/epic-handle-new.component.html new file mode 100644 index 00000000000..d73c7f0e3db --- /dev/null +++ b/src/app/epic-handle/epic-handle-new/epic-handle-new.component.html @@ -0,0 +1,59 @@ +
+
+
+ +

{{ 'epic-handle-table.new-handle.description' | translate: {prefix: prefix} }}

+
+
+ +
+
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+ +
+ + +
+
+
diff --git a/src/app/epic-handle/epic-handle-new/epic-handle-new.component.scss b/src/app/epic-handle/epic-handle-new/epic-handle-new.component.scss new file mode 100644 index 00000000000..e69de29bb2d diff --git a/src/app/epic-handle/epic-handle-new/epic-handle-new.component.ts b/src/app/epic-handle/epic-handle-new/epic-handle-new.component.ts new file mode 100644 index 00000000000..ce752fa68e0 --- /dev/null +++ b/src/app/epic-handle/epic-handle-new/epic-handle-new.component.ts @@ -0,0 +1,152 @@ +import { + Component, + OnInit, +} from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { + ActivatedRoute, + Router, +} from '@angular/router'; +import { + TranslateModule, + TranslateService, +} from '@ngx-translate/core'; +import { EpicHandleDataService } from 'src/app/core/data/epic-handle-data.service'; +import { RemoteData } from 'src/app/core/data/remote-data'; +import { EpicHandle } from 'src/app/core/epicHandle/models/epic-handle.model'; +import { getFirstCompletedRemoteData } from 'src/app/core/shared/operators'; +import { isNull } from 'src/app/shared/empty.util'; +import { NotificationsService } from 'src/app/shared/notifications/notifications.service'; + +import { BtnDisabledDirective } from '../../shared/btn-disabled.directive'; +import { getEpicHandleTableModulePath } from '../epic-handle-routing-paths'; + +@Component({ + imports: [ + BtnDisabledDirective, + FormsModule, + TranslateModule, + ], + selector: 'ds-epic-handle-new', + templateUrl: './epic-handle-new.component.html', + styleUrls: ['./epic-handle-new.component.scss'], +}) +export class EpicHandleNewComponent implements OnInit { + url: string; + suffix: string; + subPrefix: string; + subSuffix: string; + prefix: string; + isLoading = false; + currentPage: number; + + constructor(private notificationService: NotificationsService, + private route: ActivatedRoute, + private router: Router, + private translateService: TranslateService, + private epicHandleService: EpicHandleDataService, + ) { } + ngOnInit(): void { + const params = this.route.snapshot.queryParams || {}; + this.currentPage = params.currentPage; + this.prefix = params.prefix; + if (!this.prefix) { + this.router.navigate(['/epic-handle-table/prefix']); + return; + } + } + + onClickSubmit(value: any) { + if (!value.url || value.url.trim() === '') { + this.notificationService.error( + this.translateService.instant('epic-handle-table.new-handle.notify.error.url-required'), + this.translateService.instant('epic-handle-table.new-handle.notify.error'), + ); + return; + } + + this.isLoading = true; + + if (value.suffix) { + this.epicHandleService.update(this.prefix, value.suffix, value.url.trim()).pipe(getFirstCompletedRemoteData()) + .subscribe((handleResponse) => { + this.isLoading = false; + if (isNull(handleResponse)) { + this.notificationService.error('', this.translateService.instant('epic-handle-table.edit-handle.notify.error')); + return; + } + + if (handleResponse.hasSucceeded) { + this.notificationService.success('', this.translateService.instant('epic-handle-table.edit-handle.notify.successful')); + this.redirectBack(); + } else if (handleResponse.hasFailed) { + const errorMsg = handleResponse.errorMessage || + this.translateService.instant('epic-handle-table.edit-handle.notify.error'); + this.notificationService.error('', errorMsg); + } + }, (error: unknown) => { + this.isLoading = false; + this.notificationService.error( + '', + this.translateService.instant('epic-handle-table.edit-handle.notify.error'), + ); + }); + } else { + this.epicHandleService.create( + this.prefix, + value.url.trim(), + value.subPrefix?.trim(), + value.subSuffix?.trim(), + ).pipe(getFirstCompletedRemoteData()) + .subscribe((handleResponse: RemoteData) => { + this.isLoading = false; + if (isNull(handleResponse)) { + this.notificationService.error( + '', this.translateService.instant('epic-handle-table.new-handle.notify.error'), + ); + return; + } + + if (handleResponse.hasSucceeded) { + this.notificationService.success('', this.translateService.instant('epic-handle-table.new-handle.notify.successful')); + this.redirectBack(); + } else if (handleResponse.hasFailed) { + const errorMsg = handleResponse.errorMessage || this.translateService.instant('epic-handle-table.new-handle.notify.error'); + this.notificationService.error('', errorMsg); + } + }, (error: unknown) => { + this.isLoading = false; + this.notificationService.error('', this.translateService.instant('epic-handle-table.new-handle.notify.error')); + }); + } + } + + redirectBack() { + const queryParams = this.prefix ? { prefix: this.prefix } : {}; + this.router.navigate([getEpicHandleTableModulePath()], { queryParams }); + } + + onCancel() { + this.redirectBack(); + } + + get hasSuffix(): boolean { + return !!this.suffix?.trim(); + } + + get hasSubPrefix(): boolean { + return !!this.subPrefix?.trim(); + } + + get hasSubSuffix(): boolean { + return !!this.subSuffix?.trim(); + } + + get isSuffixDisabled(): boolean { + return this.isLoading || this.hasSubPrefix || this.hasSubSuffix; + } + + get isSubValuesDisabled(): boolean { + return this.isLoading || this.hasSuffix; + } +} diff --git a/src/app/epic-handle/epic-handle-prefix/epic-handle-prefix.component.html b/src/app/epic-handle/epic-handle-prefix/epic-handle-prefix.component.html new file mode 100644 index 00000000000..20c9f20c250 --- /dev/null +++ b/src/app/epic-handle/epic-handle-prefix/epic-handle-prefix.component.html @@ -0,0 +1,33 @@ +
+
+
+ +
+
+ +
+
+
+ + + + +
+ @if (hasError('prefix', 'required')) { +
+ {{ 'epic-prefix-handle-page.form.error.required' | translate }} +
+ } + @if (hasError('prefix', 'pattern')) { +
+ {{ 'epic-prefix-handle-page.form.error.pattern' | translate }} +
+ } +
+
+
diff --git a/src/app/epic-handle/epic-handle-prefix/epic-handle-prefix.component.scss b/src/app/epic-handle/epic-handle-prefix/epic-handle-prefix.component.scss new file mode 100644 index 00000000000..e69de29bb2d diff --git a/src/app/epic-handle/epic-handle-prefix/epic-handle-prefix.component.ts b/src/app/epic-handle/epic-handle-prefix/epic-handle-prefix.component.ts new file mode 100644 index 00000000000..bdb7b45d802 --- /dev/null +++ b/src/app/epic-handle/epic-handle-prefix/epic-handle-prefix.component.ts @@ -0,0 +1,51 @@ +import { Component } from '@angular/core'; +import { + ReactiveFormsModule, + UntypedFormBuilder, + Validators, +} from '@angular/forms'; +import { Router } from '@angular/router'; +import { TranslateModule } from '@ngx-translate/core'; + +import { EpicHandleDataService } from '../../core/data/epic-handle-data.service'; + +@Component({ + imports: [ + ReactiveFormsModule, + TranslateModule, + ], + selector: 'ds-epic-handle-prefix', + templateUrl: './epic-handle-prefix.component.html', + styleUrls: ['./epic-handle-prefix.component.scss'], +}) +export class EpicHandlePrefixComponent { + // The prefix form + prefixForm; + + constructor(private formBuilder: UntypedFormBuilder, private router: Router, private epicHandleDataService: EpicHandleDataService) { + this.prefixForm = this.formBuilder.group(({ + prefix: ['', [Validators.required, Validators.pattern('^[a-zA-Z0-9]+$')]], + })); + } + + navigateToEpicHandleList(data) { + if (!data?.prefix) { + return; + } + + const trimmedPrefix = (data.prefix || '').trim(); + const isValidTrimmed = /^[a-zA-Z0-9]+$/.test(trimmedPrefix); + + if (isValidTrimmed) { + this.router.navigate(['/epic-handle-table'], { queryParams: { prefix: trimmedPrefix } }); + } + } + + /** + * Check if the prefix field has an error + */ + hasError(field: string, error: string): boolean { + const control = this.prefixForm.get(field); + return control && control.hasError(error) && (control.dirty || control.touched); + } +} diff --git a/src/app/epic-handle/epic-handle-routes.ts b/src/app/epic-handle/epic-handle-routes.ts new file mode 100644 index 00000000000..783b97df36c --- /dev/null +++ b/src/app/epic-handle/epic-handle-routes.ts @@ -0,0 +1,42 @@ +import { Route } from '@angular/router'; + +import { i18nBreadcrumbResolver } from '../core/breadcrumbs/i18n-breadcrumb.resolver'; +import { EpicHandleComponent } from './epic-handle.component'; +import { EpicHandleEditComponent } from './epic-handle-edit/epic-handle-edit.component'; +import { EpicHandleNewComponent } from './epic-handle-new/epic-handle-new.component'; +import { EpicHandlePrefixComponent } from './epic-handle-prefix/epic-handle-prefix.component'; +import { + EPIC_HANDLE_TABLE_EDIT_HANDLE_PATH, + EPIC_HANDLE_TABLE_NEW_HANDLE_PATH, +} from './epic-handle-routing-paths'; + +/** + * Routes for the EPIC PID handle management feature (table + prefix + new/edit). + * Ported from the 7.x EpicHandleRoutingModule to the v9 standalone routes pattern. + */ +export const ROUTES: Route[] = [ + { + path: 'prefix', + resolve: { breadcrumb: i18nBreadcrumbResolver }, + data: { breadcrumbKey: 'epic-handle-table' }, + component: EpicHandlePrefixComponent, + }, + { + path: EPIC_HANDLE_TABLE_NEW_HANDLE_PATH, + resolve: { breadcrumb: i18nBreadcrumbResolver }, + data: { breadcrumbKey: 'epic-handle-table.new-handle' }, + component: EpicHandleNewComponent, + }, + { + path: EPIC_HANDLE_TABLE_EDIT_HANDLE_PATH, + resolve: { breadcrumb: i18nBreadcrumbResolver }, + data: { breadcrumbKey: 'epic-handle-table.edit-handle' }, + component: EpicHandleEditComponent, + }, + { + path: '', + resolve: { breadcrumb: i18nBreadcrumbResolver }, + data: { breadcrumbKey: 'epic-handle-table' }, + component: EpicHandleComponent, + }, +]; diff --git a/src/app/epic-handle/epic-handle-routing-paths.ts b/src/app/epic-handle/epic-handle-routing-paths.ts new file mode 100644 index 00000000000..49a50a97091 --- /dev/null +++ b/src/app/epic-handle/epic-handle-routing-paths.ts @@ -0,0 +1,10 @@ +/** + * The routing paths + */ +export const EPIC_HANDLE_TABLE_NEW_HANDLE_PATH = 'new-epic-handle'; +export const EPIC_HANDLE_TABLE_EDIT_HANDLE_PATH = 'edit-epic-handle'; + +export const EPIC_HANDLE_TABLE_MODULE_PATH = 'epic-handle-table'; +export function getEpicHandleTableModulePath() { + return `/${EPIC_HANDLE_TABLE_MODULE_PATH}`; +} diff --git a/src/app/epic-handle/epic-handle-table/epic-handle-table.component.html b/src/app/epic-handle/epic-handle-table/epic-handle-table.component.html new file mode 100644 index 00000000000..9df2264bf17 --- /dev/null +++ b/src/app/epic-handle/epic-handle-table/epic-handle-table.component.html @@ -0,0 +1,127 @@ +
+
+
+ {{ 'epic-handle-table.title' | translate }} - {{ prefix }} + +
+
+ +
+ + + + +
+ +
+
+ + + + + + + + + + + + @for (handle of handleData?.payload?.page; track handle) { + + + + + + } + + @if (!isLoading && (!handleData?.payload?.page || handleData?.payload?.page.length === 0)) { + + + + } + +
{{ 'epic-handle-table.table.handle' | translate }}{{ 'epic-handle-table.table.url' | translate }}
+ + + {{ handle.id }} + + @if (handle.url) { + + {{ handle.url }} + + + } + @if (!handle.url) { + + {{ 'epic-handle-table.table.no-url' | translate }} + + } +
+ +

{{ 'epic-handle-table.table.no-results' | translate }}

+
+ + @if (isLoading) { + + } +
+ +
+
+ +
+
+ +
+
+ +
+
+ + @if (handleData?.payload?.pageInfo?.totalElements > 0) { +
+ {{ 'epic-handle-table.table.showing' | translate: { + count: handleData.payload.page.length, + total: handleData.payload?.pageInfo?.totalElements + } }} +
+ } +
+
+ +
+ + + @if (pidQuery && !isPidInputValid()) { +
+ {{ 'epic-handle-table.pid.prefix-suffix-required' | translate }} +
+ } +
+
+
+
diff --git a/src/app/epic-handle/epic-handle-table/epic-handle-table.component.scss b/src/app/epic-handle/epic-handle-table/epic-handle-table.component.scss new file mode 100644 index 00000000000..e69de29bb2d diff --git a/src/app/epic-handle/epic-handle-table/epic-handle-table.component.ts b/src/app/epic-handle/epic-handle-table/epic-handle-table.component.ts new file mode 100644 index 00000000000..0cd32a5fa81 --- /dev/null +++ b/src/app/epic-handle/epic-handle-table/epic-handle-table.component.ts @@ -0,0 +1,381 @@ +import { CommonModule } from '@angular/common'; +import { + ChangeDetectorRef, + Component, + OnDestroy, + OnInit, +} from '@angular/core'; +import { FormsModule } from '@angular/forms'; +import { + ActivatedRoute, + Router, +} from '@angular/router'; +import { + TranslateModule, + TranslateService, +} from '@ngx-translate/core'; +import { + BehaviorSubject, + combineLatest, + Subscription, +} from 'rxjs'; +import { + scan, + switchMap, + take, +} from 'rxjs/operators'; +import { + defaultPagination, + defaultSortConfiguration, +} from 'src/app/clarin-licenses/clarin-license-table-pagination'; +import { SortOptions } from 'src/app/core/cache/models/sort-options.model'; +import { EpicHandleDataService } from 'src/app/core/data/epic-handle-data.service'; +import { PaginationService } from 'src/app/core/pagination/pagination.service'; +import { NotificationsService } from 'src/app/shared/notifications/notifications.service'; +import { PaginationComponentOptions } from 'src/app/shared/pagination/pagination-component-options.model'; + +import { BtnDisabledDirective } from '../../shared/btn-disabled.directive'; +import { + hasValue, + isEmpty, +} from '../../shared/empty.util'; +import { ThemedLoadingComponent } from '../../shared/loading/themed-loading.component'; +import { PaginationComponent } from '../../shared/pagination/pagination.component'; +import { VarDirective } from '../../shared/utils/var.directive'; +import { + EPIC_HANDLE_TABLE_EDIT_HANDLE_PATH, + EPIC_HANDLE_TABLE_NEW_HANDLE_PATH, + getEpicHandleTableModulePath, +} from '../epic-handle-routing-paths'; + +@Component({ + imports: [ + BtnDisabledDirective, + CommonModule, + FormsModule, + PaginationComponent, + ThemedLoadingComponent, + TranslateModule, + VarDirective, + ], + selector: 'ds-epic-handle-table', + templateUrl: './epic-handle-table.component.html', + styleUrls: ['./epic-handle-table.component.scss'], +}) +export class EpicHandleTableComponent implements OnInit, OnDestroy { + constructor(private epicHandleDataService: EpicHandleDataService, + public router: Router, + private cdr: ChangeDetectorRef, + private translateService: TranslateService, + private notificationsService: NotificationsService, + private route: ActivatedRoute, + private paginationService: PaginationService) { + } + + handlesRD$: BehaviorSubject = new BehaviorSubject(null); + pageSize = 10; + options: PaginationComponentOptions; + sortConfiguration: SortOptions; + searchQuery = ''; + pidQuery = ''; + isLoading = false; + handleRoute: string; + newHandleRoute = EPIC_HANDLE_TABLE_NEW_HANDLE_PATH; + editHandlePath = EPIC_HANDLE_TABLE_EDIT_HANDLE_PATH; + selectedHandle = null; + prefix = ''; + totalElements: number = null; + private subs: Subscription[] = []; + + ngOnInit(): void { + // get the prefix from query params and initialize inside the subscription so we only + // proceed once we have the prefix available + this.subs.push( + this.route.queryParams.pipe(take(1)).subscribe(params => { + this.prefix = params.prefix; + if (!this.prefix) { + this.router.navigate(['/epic-handle-table/prefix']); + return; + } + + this.handleRoute = getEpicHandleTableModulePath(); + this.initializePaginationOptions(); + this.initializeSortingOptions(); + this.getAllHandles(); + }), + ); + + } + + getAllHandles() { + this.isLoading = true; + // load the current pagination and sorting options + const currentPagination$ = this.getCurrentPagination(); + const currentSort$ = this.getCurrentSort(); + const searchTerm$ = new BehaviorSubject(this.searchQuery); + + const getAllSub = combineLatest([currentPagination$, currentSort$, searchTerm$]).pipe( + scan((prevState, [currentPagination, currentSort, searchTerm]) => { + // If search term has changed, reset to page 1; otherwise, keep current page + const currentPage = prevState.searchTerm !== searchTerm ? 1 : currentPagination.currentPage; + return { currentPage, currentPagination, currentSort, searchTerm }; + }, { searchTerm: '', currentPage: 1, currentPagination: this.getCurrentPagination(), + currentSort: this.getCurrentSort() }), + switchMap(({ currentPage, currentPagination, currentSort, searchTerm }) => { + return this.epicHandleDataService.findAll({ + currentPage: currentPage, + elementsPerPage: currentPagination.pageSize, + sort: { field: currentSort.field, direction: currentSort.direction }, + }, this.prefix, searchTerm?.trim() !== '' ? searchTerm?.trim() : undefined, this.totalElements, + ); + }), + ).pipe(take(1)).subscribe((response) => { + this.handlesRD$.next(response); + this.isLoading = false; + if (response?.payload?.pageInfo?.totalElements !== undefined) { + this.totalElements = response.payload.pageInfo?.totalElements; + } + this.cdr.detectChanges(); + }, (error: unknown) => { + this.isLoading = false; + if ((error as any)?.error?.status){ + this.notificationsService.error(null, this.translateService.instant((error as any)?.error?.message)); + } else { + this.notificationsService.error(null, this.translateService.instant('error')); + } + this.cdr.detectChanges(); + }); + + this.subs.push(getAllSub); + } + + clearSearch() { + this.searchQuery = ''; + this.totalElements = null; + this.getAllHandles(); + } + + private initializeSortingOptions() { + this.sortConfiguration = defaultSortConfiguration; + } + + private initializePaginationOptions() { + this.options = Object.assign({}, defaultPagination, { + id: 'epic-handle-pagination', + pageSize: this.pageSize, + currentPage: 1, + }); + } + + + redirectToNewHandle() { + this.router.navigate([this.handleRoute, this.newHandleRoute], + { queryParams: { currentPage: this.options.currentPage, prefix: this.prefix } }, + ); + } + redirectToEditHandle() { + + if (isEmpty(this.selectedHandle)) { + return; + } + + const editSub = this.handlesRD$.pipe( + take(1), + ).subscribe(handlesRD => { + const handles = handlesRD?.payload?.page || []; + const handle = handles.find(h => h.id === this.selectedHandle); + + if (handle) { + this.switchSelectedHandle(this.selectedHandle); + this.router.navigate([this.handleRoute, this.editHandlePath], + { + queryParams: { + id: handle.id, + url: handle.url, + prefix: this.prefix, + }, + }, + ); + } + }); + + this.subs.push(editSub); + } + + deleteHandle() { + if (isEmpty(this.selectedHandle)) { + return; + } + + this.isLoading = true; + + const deleteSub = this.epicHandleDataService.deleteByHandleId(this.selectedHandle) + .pipe(take(1)) + .subscribe( + (response) => { + if (response?.hasSucceeded || response?.statusCode === 204) { + this.notificationsService.success( + null, + this.translateService.instant('epic-handle-table.delete-handle.notify.successful'), + ); + this.switchSelectedHandle(this.selectedHandle); + this.totalElements = null; + this.getAllHandles(); + } else { + this.isLoading = false; + this.notificationsService.error( + null, + this.translateService.instant('epic-handle-table.delete-handle.notify.error'), + ); + } + }, + (error: unknown) => { + this.isLoading = false; + const errorMessage = (error as any)?.message || + this.translateService.instant('epic-handle-table.delete-handle.notify.error'); + this.notificationsService.error(null, errorMessage); + }, + ); + + this.subs.push(deleteSub); + } + + onPageChange() { + this.getAllHandles(); + } + + switchSelectedHandle(handleId) { + if (this.selectedHandle === handleId) { + this.selectedHandle = null; + } else { + this.selectedHandle = handleId; + } + } + + searchHandles() { + this.totalElements = null; + this.getAllHandles(); + } + + + changePrefix() { + this.router.navigate(['/epic-handle-table/prefix']); + } + + + goToPID() { + const raw = (this.pidQuery || '').trim(); + if (!raw) { + return; + } + + if (!this.isPidInputValid()) { + this.notificationsService.error(null, this.translateService.instant('epic-handle-table.pid.invalid')); + return; + } + + const pidSub = this.handlesRD$.pipe( + take(1), + ).subscribe(handlesRD => { + const handles = handlesRD?.payload?.page || []; + + let handle = null; + if (raw.includes('/')) { + handle = handles.find(h => h.id === raw); + } else { + handle = handles.find(h => { + const parts = h.id.split('/'); + return parts[1] === raw; + }); + } + + if (handle) { + this.switchSelectedHandle(handle.id); + this.router.navigate([this.handleRoute, this.editHandlePath], + { + queryParams: { + id: handle.id, + url: handle.url, + prefix: this.prefix, + }, + }, + ); + } else { + const suffix = raw.includes('/') ? raw.split('/')[1] : raw; + this.isLoading = true; + const findSub = this.epicHandleDataService.findByPrefixAndSuffix(this.prefix, suffix).pipe(take(1)).subscribe(handleResponse => { + this.isLoading = false; + this.cdr.detectChanges(); + if (handleResponse) { + const fetchedHandle = handleResponse; + this.switchSelectedHandle(fetchedHandle.id); + this.router.navigate([this.handleRoute, this.editHandlePath], + { + queryParams: { + id: fetchedHandle.id, + url: fetchedHandle.url, + prefix: this.prefix, + }, + }, + ); + } else { + this.notificationsService.error(null, this.translateService.instant('epic-handle-table.pid.notfound')); + } + }, (error: unknown) => { + this.isLoading = false; + this.cdr.detectChanges(); + if ((error as any)?.error?.status){ + this.notificationsService.error(null, this.translateService.instant((error as any)?.error?.message)); + } else { + this.notificationsService.error(null, this.translateService.instant('error')); + } + }); + + this.subs.push(findSub); + } + }); + this.subs.push(pidSub); + } + + /** + * Validate the PID input. + * Accepts full id "prefix/suffix". + */ + isPidInputValid(): boolean { + const val = (this.pidQuery || '').trim(); + if (!val) { + return false; + } + if (val.includes('/')) { + const parts = val.split('/'); + return parts.length === 2 && parts[0].length > 0 && parts[1].length > 0; + } + if (val === this.prefix) { + return false; + } + return true; + } + + /** + * Get the current pagination options. + */ + private getCurrentPagination() { + return this.paginationService.getCurrentPagination(this.options.id, defaultPagination); + } + + /** + * Get the current sorting options. + */ + private getCurrentSort() { + return this.paginationService.getCurrentSort(this.options.id, defaultSortConfiguration); + } + + ngOnDestroy(): void { + this.handlesRD$.complete(); + this.subs.forEach(sub => { + if (hasValue(sub)) { + sub.unsubscribe(); + } + }); + } +} diff --git a/src/app/epic-handle/epic-handle.component.html b/src/app/epic-handle/epic-handle.component.html new file mode 100644 index 00000000000..3e42fb68afe --- /dev/null +++ b/src/app/epic-handle/epic-handle.component.html @@ -0,0 +1,8 @@ +
+
+
+ +
+
+ +
diff --git a/src/app/epic-handle/epic-handle.component.scss b/src/app/epic-handle/epic-handle.component.scss new file mode 100644 index 00000000000..e69de29bb2d diff --git a/src/app/epic-handle/epic-handle.component.ts b/src/app/epic-handle/epic-handle.component.ts new file mode 100644 index 00000000000..c614a51ffd3 --- /dev/null +++ b/src/app/epic-handle/epic-handle.component.ts @@ -0,0 +1,16 @@ +import { Component } from '@angular/core'; +import { TranslateModule } from '@ngx-translate/core'; + +import { EpicHandleTableComponent } from './epic-handle-table/epic-handle-table.component'; + +@Component({ + imports: [ + EpicHandleTableComponent, + TranslateModule, + ], + selector: 'ds-epic-handle', + templateUrl: './epic-handle.component.html', + styleUrls: ['./epic-handle.component.scss'], +}) +export class EpicHandleComponent { +} diff --git a/src/app/footer/footer.component.html b/src/app/footer/footer.component.html index 297a300d95b..8ede514c4e9 100644 --- a/src/app/footer/footer.component.html +++ b/src/app/footer/footer.component.html @@ -1,103 +1,94 @@ - - - \ No newline at end of file + diff --git a/src/app/footer/footer.component.scss b/src/app/footer/footer.component.scss index 9381d7378f9..de8a0ed942a 100644 --- a/src/app/footer/footer.component.scss +++ b/src/app/footer/footer.component.scss @@ -22,26 +22,6 @@ } .bottom-footer { - .notify-enabled { - position: relative; - margin-top: 4px; - - .coar-notify-support-route { - padding: 0 calc(var(--bs-spacer) / 2); - color: inherit; - } - - .n-coar { - height: var(--ds-footer-n-coar-height); - margin-bottom: 8.5px; - } - - @media screen and (min-width: map-get($grid-breakpoints, md)) { - position: absolute; - bottom: 4px; - right: 0; - } - } ul { li { display: inline-flex; @@ -71,12 +51,749 @@ } } } + } +} - .btn { - box-shadow: none; - } + +@charset "UTF-8"; +.lindat-common2.lindat-common-header { + background-color: var(--navbar-background-color, red); +} +.lindat-common2.lindat-common-footer { + background-color: var(--footer-background-color); + //z-index: var(--ds-footer-z-index); +} +.lindat-common2 { + font-size: medium; + display: flex; + justify-content: center; + /* this can't hang on :root */ + --navbar-color: #ffffff; + --navbar-background-color: #39688b; + --footer-color: #fffc; + --footer-background-color: #07426eff; + --partners-color: #9cb3c5; + /* styling for light theme; maybe this can get set from outside? + --navbar-color: #000000; + --navbar-background-color: #f0f0f0; + --footer-color: #408080; + --footer-background-color: #f0f0f0; + --partners-color: #408080; + */ + /* XXX svg? */ + /* XXX fade? */ + /* roboto-slab-regular - latin_latin-ext */ + /* source-code-pro-regular - latin_latin-ext */ + /* source-sans-pro-regular - latin_latin-ext */ + /* source-sans-pro-300 - latin_latin-ext */ +} +@media print { + .lindat-common2 *, + .lindat-common2 *::before, + .lindat-common2 *::after { + text-shadow: none !important; + box-shadow: none !important; + } + .lindat-common2 a:not(.lindat-btn) { + text-decoration: underline; + } + .lindat-common2 img { + page-break-inside: avoid; } + @page { + size: a3; + } + .lindat-common2 .lindat-navbar { + display: none; + } + .lindat-common2 .lindat-badge { + border: 1px solid #000; + } +} +.lindat-common2 *, +.lindat-common2 *::before, +.lindat-common2 *::after { + box-sizing: border-box; +} +.lindat-common2 nav, +.lindat-common2 footer { + /* this is orginally from body */ + margin: 0; + font-family: "Source Sans Pro", -apple-system, system-ui, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif; + font-size: 1em; + font-weight: 400; + line-height: 1.5; + color: #212529; + text-align: left; + background-color: #fff; +} +.lindat-common2 footer, +.lindat-common2 header, +.lindat-common2 nav { + display: block; +} +.lindat-common2 h4 { + margin-top: 0; + margin-bottom: 0.85em; +} +.lindat-common2 ul { + margin-top: 0; + margin-bottom: 1em; +} +.lindat-common2 ul ul { + margin-bottom: 0; +} +.lindat-common2 a { + color: #007bff; + text-decoration: none; + background-color: transparent; +} +.lindat-common2 a:hover { + color: #0056b3; + text-decoration: underline; +} +.lindat-common2 img { + vertical-align: middle; + border-style: none; +} +.lindat-common2 button { + border-radius: 0; +} +.lindat-common2 button:focus { + outline: 1px dotted; + outline: 5px auto -webkit-focus-ring-color; +} +.lindat-common2 button { + margin: 0; + font-family: inherit; + font-size: inherit; + line-height: inherit; +} +.lindat-common2 button { + overflow: visible; +} +.lindat-common2 button { + text-transform: none; +} +.lindat-common2 button, +.lindat-common2 [type=button] { + -webkit-appearance: button; +} +.lindat-common2 button:not(:disabled), +.lindat-common2 [type=button]:not(:disabled) { + cursor: pointer; +} +.lindat-common2 button::-moz-focus-inner, +.lindat-common2 [type=button]::-moz-focus-inner, +.lindat-common2 [type=reset]::-moz-focus-inner, +.lindat-common2 [type=submit]::-moz-focus-inner { + padding: 0; + border-style: none; +} +.lindat-common2 [hidden] { + display: none !important; +} +.lindat-common2 h4 { + margin-bottom: 0.85em; + font-weight: 500; + line-height: 1.2; +} +.lindat-common2 h4, +.lindat-common2 .lindat-h4 { + font-size: 1.5em; +} +.lindat-common2 .lindat-collapse:not(.lindat-show) { + display: none; +} +.lindat-common2 .lindat-collapsing { + position: relative; + height: 0; + overflow: hidden; + transition: height 0.35s ease; +} +@media (prefers-reduced-motion: reduce) { + .lindat-common2 .lindat-collapsing { + transition: none; + } +} +.lindat-common2 .lindat-dropdown { + position: relative; +} +.lindat-common2 .lindat-dropdown-toggle { + white-space: nowrap; +} +.lindat-common2 .lindat-dropdown-toggle::after { + display: inline-block; + margin-left: 0.255em; + vertical-align: 0.255em; + content: ""; + border-top: 0.3em solid; + border-right: 0.3em solid transparent; + border-bottom: 0; + border-left: 0.3em solid transparent; +} +.lindat-common2 .lindat-dropdown-toggle:empty::after { + margin-left: 0; +} +.lindat-common2 .lindat-dropdown-menu { + position: absolute; + top: 100%; + left: 0; + z-index: 1000; + display: none; + float: left; + min-width: 10em; + padding: 0.5rem 0; + margin: 0.125rem 0 0; + font-size: 1em; + color: #212529; + text-align: left; + list-style: none; + background-color: #fff; + background-clip: padding-box; + border: 1px solid rgba(0, 0, 0, 0.15); +} +.lindat-common2 .lindat-dropdown-item { + display: block; + width: 100%; + padding: 0.25rem 1.5em; + clear: both; + font-weight: 400; + color: #212529; + text-align: inherit; + white-space: nowrap; + background-color: transparent; + border: 0; +} +.lindat-common2 .lindat-dropdown-item:hover, +.lindat-common2 .lindat-dropdown-item:focus { + color: #16181b; + text-decoration: none; + background-color: #f8f9fa; +} +.lindat-common2 .lindat-dropdown-item.lindat-active, +.lindat-common2 .lindat-dropdown-item:active { + color: #fff; + text-decoration: none; + background-color: #007bff; +} +.lindat-common2 .lindat-dropdown-item.lindat-disabled, +.lindat-common2 .lindat-dropdown-item:disabled { + color: #6c757d; + pointer-events: none; + background-color: transparent; +} +.lindat-common2 .lindat-dropdown-menu.lindat-show { + display: block; +} +.lindat-common2 .lindat-nav { + display: flex; + flex-wrap: wrap; + padding-left: 0; + margin-bottom: 0; + list-style: none; +} +.lindat-common2 .lindat-nav-link { + display: block; + padding: 0.5rem 1em; +} +.lindat-common2 .lindat-nav-link:hover, +.lindat-common2 .lindat-nav-link:focus { + text-decoration: none; +} +.lindat-common2 .lindat-nav-link.lindat-disabled { + color: #6c757d; + pointer-events: none; + cursor: default; +} +.lindat-common2 .lindat-navbar { + position: relative; + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + padding: 0.85rem 1.7em; +} +.lindat-common2 .lindat-navbar-brand { + display: inline-block; + padding-top: 0.3125em; + padding-bottom: 0.3125em; + margin-right: 1.7em; + font-size: 1.25em; + line-height: inherit; + white-space: nowrap; +} +.lindat-common2 .lindat-navbar-brand:hover, +.lindat-common2 .lindat-navbar-brand:focus { + text-decoration: none; +} +.lindat-common2 .lindat-navbar-nav { + display: flex; + flex-direction: column; + padding-left: 0; + margin-bottom: 0; + list-style: none; +} +.lindat-common2 .lindat-navbar-nav .lindat-nav-link { + padding-right: 0; + padding-left: 0; +} +.lindat-common2 .lindat-navbar-nav .lindat-dropdown-menu { + position: static; + float: none; +} +.lindat-common2 .lindat-navbar-collapse { + flex-basis: 100%; + flex-grow: 1; + align-items: center; +} +.lindat-common2 .lindat-navbar-toggler { + padding: 0.25rem 0.75em; + font-size: 1.25em; + line-height: 1; + background-color: transparent; + border: 1px solid transparent; +} +.lindat-common2 .lindat-navbar-toggler:hover, +.lindat-common2 .lindat-navbar-toggler:focus { + text-decoration: none; +} +.lindat-common2 .lindat-navbar-toggler-icon { + display: inline-block; + width: 1.5em; + height: 1.5em; + vertical-align: middle; + content: ""; + background: no-repeat center center; + background-size: 100% 100%; +} +@media (min-width: 992px) { + .lindat-common2 .lindat-navbar-expand-lg { + flex-flow: row nowrap; + justify-content: flex-start; + } + .lindat-common2 .lindat-navbar-expand-lg .lindat-navbar-nav { + flex-direction: row; + } + .lindat-common2 .lindat-navbar-expand-lg .lindat-navbar-nav .lindat-dropdown-menu { + position: absolute; + } + .lindat-common2 .lindat-navbar-expand-lg .lindat-navbar-nav .lindat-nav-link { + padding-right: 0.5em; + padding-left: 0.5em; + } + .lindat-common2 .lindat-navbar-expand-lg .lindat-navbar-collapse { + display: flex !important; + flex-basis: auto; + } + .lindat-common2 .lindat-navbar-expand-lg .lindat-navbar-toggler { + display: none; + } +} +@media (min-width: 1250px) { + .lindat-common2 #margin-filler { + min-width: 5em; + } +} +.lindat-common2 .lindat-navbar-dark .lindat-navbar-brand { + color: #fff; +} +.lindat-common2 .lindat-navbar-dark .lindat-navbar-brand:hover, +.lindat-common2 .lindat-navbar-dark .lindat-navbar-brand:focus { + color: #fff; +} +.lindat-common2 .lindat-navbar-dark .lindat-navbar-nav .lindat-nav-link { + color: rgba(255, 255, 255, 0.5); +} +.lindat-common2 .lindat-navbar-dark .lindat-navbar-nav .lindat-nav-link:hover, +.lindat-common2 .lindat-navbar-dark .lindat-navbar-nav .lindat-nav-link:focus { + color: rgba(255, 255, 255, 0.75); +} +.lindat-common2 .lindat-navbar-dark .lindat-navbar-nav .lindat-nav-link.lindat-disabled { + color: rgba(255, 255, 255, 0.25); +} +.lindat-common2 .lindat-navbar-dark .lindat-navbar-nav .lindat-show > .lindat-nav-link, +.lindat-common2 .lindat-navbar-dark .lindat-navbar-nav .lindat-active > .lindat-nav-link, +.lindat-common2 .lindat-navbar-dark .lindat-navbar-nav .lindat-nav-link.lindat-show, +.lindat-common2 .lindat-navbar-dark .lindat-navbar-nav .lindat-nav-link.lindat-active { + color: #fff; +} +.lindat-common2 .lindat-navbar-dark .lindat-navbar-toggler { + color: rgba(255, 255, 255, 0.5); + border-color: rgba(255, 255, 255, 0.1); +} +.lindat-common2 .lindat-navbar-dark .lindat-navbar-toggler-icon { + background-image: url("data:image/svg+xml,%3csvg viewBox='0 0 30 30' xmlns='http://www.w3.org/2000/svg'%3e%3cpath stroke='rgba(255, 255, 255, 0.5)' stroke-width='2' stroke-linecap='round' stroke-miterlimit='10' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e"); +} +.lindat-common2 .lindat-d-flex { + display: flex !important; +} +.lindat-common2 .lindat-justify-content-between { + justify-content: space-between !important; +} +.lindat-common2 .lindat-align-items-center { + align-items: center !important; +} +.lindat-common2 .lindat-mr-auto, +.lindat-common2 .lindat-mx-auto { + margin-right: auto !important; +} +@font-face { + font-family: "Roboto Slab"; + font-style: normal; + font-weight: 400; + src: url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/roboto-slab-v7-latin_latin-ext-regular.eot"); + /* IE9 Compat Modes */ + src: local("Roboto Slab Regular"), local("RobotoSlab-Regular"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/roboto-slab-v7-latin_latin-ext-regular.eot?#iefix") format("embedded-opentype"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/roboto-slab-v7-latin_latin-ext-regular.woff2") format("woff2"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/roboto-slab-v7-latin_latin-ext-regular.woff") format("woff"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/roboto-slab-v7-latin_latin-ext-regular.ttf") format("truetype"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/roboto-slab-v7-latin_latin-ext-regular.svg#RobotoSlab") format("svg"); + /* Legacy iOS */ +} +@font-face { + font-family: "Source Code Pro"; + font-style: normal; + font-weight: 400; + src: url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-code-pro-v8-latin_latin-ext-regular.eot"); + /* IE9 Compat Modes */ + src: local("Source Code Pro"), local("SourceCodePro-Regular"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-code-pro-v8-latin_latin-ext-regular.eot?#iefix") format("embedded-opentype"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-code-pro-v8-latin_latin-ext-regular.woff2") format("woff2"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-code-pro-v8-latin_latin-ext-regular.woff") format("woff"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-code-pro-v8-latin_latin-ext-regular.ttf") format("truetype"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-code-pro-v8-latin_latin-ext-regular.svg#SourceCodePro") format("svg"); + /* Legacy iOS */ +} +@font-face { + font-family: "Source Sans Pro"; + font-style: normal; + font-weight: 400; + src: url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-regular.eot"); + /* IE9 Compat Modes */ + src: local("Source Sans Pro Regular"), local("SourceSansPro-Regular"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-regular.eot?#iefix") format("embedded-opentype"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-regular.woff2") format("woff2"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-regular.woff") format("woff"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-regular.ttf") format("truetype"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-regular.svg#SourceSansPro") format("svg"); + /* Legacy iOS */ +} +@font-face { + font-family: "Source Sans Pro"; + font-style: normal; + font-weight: 300; + src: url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-300.eot"); + /* IE9 Compat Modes */ + src: local("Source Sans Pro Light"), local("SourceSansPro-Light"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-300.eot?#iefix") format("embedded-opentype"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-300.woff2") format("woff2"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-300.woff") format("woff"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-300.ttf") format("truetype"), url("https://lindat.cz/themes/custom/clariah_theme/assets/fonts/source-sans-pro-v11-latin_latin-ext-300.svg#SourceSansPro") format("svg"); + /* Legacy iOS */ +} +.lindat-common2 .lindat-navbar { + padding-left: calc(3.2vw - 1px); +} +.lindat-common2 .lindat-navbar-nav .lindat-nav-link { + font-size: 1.125em; + font-weight: 300; + letter-spacing: 0.4px; +} +.lindat-common2 .lindat-nav-link-dariah img { + height: 22px; + position: relative; + top: -3px; +} +.lindat-common2 .lindat-nav-link-clarin img { + height: 37px; + margin-top: -5px; + margin-bottom: -4px; +} +.lindat-common2 .lindat-navbar { + background-color: var(--navbar-background-color, red); +} +.lindat-common2 .lindat-navbar .lindat-navbar-brand { + padding-top: 0.28em; + padding-bottom: 0.28em; + color: var(--navbar-color) !important; +} +.lindat-common2 .lindat-navbar .lindat-navbar-brand:focus, +.lindat-common2 .lindat-navbar .lindat-navbar-brand:hover { + color: var(--navbar-color) !important; +} +.lindat-common2 .lindat-navbar .lindat-navbar-nav .lindat-nav-link { + color: var(--navbar-color) !important; + border-radius: 0.25em; + margin: 0 0.25em; +} +.lindat-common2 .lindat-navbar .lindat-navbar-nav .lindat-nav-link:not(.lindat-disabled):focus, +.lindat-common2 .lindat-navbar .lindat-navbar-nav .lindat-nav-link:not(.lindat-disabled):hover { + color: var(--navbar-color) !important; +} +.lindat-common2 .lindat-navbar .lindat-navbar-nav .lindat-nav-item.lindat-active .lindat-nav-link, +.lindat-common2 .lindat-navbar .lindat-navbar-nav .lindat-nav-item.lindat-active .lindat-nav-link:focus, +.lindat-common2 .lindat-navbar .lindat-navbar-nav .lindat-nav-item.lindat-active .lindat-nav-link:hover, +.lindat-common2 .lindat-navbar .lindat-navbar-nav .lindat-nav-item.lindat-show .lindat-nav-link, +.lindat-common2 .lindat-navbar .lindat-navbar-nav .lindat-nav-item.lindat-show .lindat-nav-link:focus, +.lindat-common2 .lindat-navbar .lindat-navbar-nav .lindat-nav-item.lindat-show .lindat-nav-link:hover { + color: var(--navbar-color) !important; + background-color: var(--navbar-background-color); +} +.lindat-common2 .lindat-navbar .lindat-navbar-toggle { + border-color: var(--navbar-background-color); +} +.lindat-common2 .lindat-navbar .lindat-navbar-toggle:focus, +.lindat-common2 .lindat-navbar .lindat-navbar-toggle:hover { + background-color: var(--navbar-background-color); +} +.lindat-common2 .lindat-navbar .lindat-navbar-toggle .lindat-navbar-toggler-icon { + color: var(--navbar-color) !important; +} +.lindat-common2 .lindat-navbar .lindat-navbar-collapse, +.lindat-common2 .lindat-navbar .lindat-navbar-form { + border-color: var(--navbar-color) !important; +} +.lindat-common2 .lindat-navbar .lindat-navbar-link { + color: var(--navbar-color) !important; +} +.lindat-common2 .lindat-navbar .lindat-navbar-link:hover { + color: var(--navbar-color) !important; +} +@media (max-width: 991px) { + .lindat-common2 .lindat-navbar-expend-lg .lindat-navbar-nav .lindat-show .lindat-dropdown-menu .lindat-dropdown-item { + color: var(--navbar-color) !important; + } + .lindat-common2 .lindat-navbar-expend-lg .lindat-navbar-nav .lindat-show .lindat-dropdown-menu .lindat-dropdown-item:focus, + .lindat-common2 .lindat-navbar-expend-lg .lindat-navbar-nav .lindat-show .lindat-dropdown-menu .lindat-dropdown-item:hover { + color: var(--navbar-color) !important; + } + .lindat-common2 .lindat-navbar-expend-lg .lindat-navbar-nav .lindat-show .lindat-dropdown-menu .lindat-dropdown-item.lindat-active { + color: var(--navbar-color) !important; + background-color: var(--navbar-background-color); + } + .lindat-common2 .lindat-nav-link-language { + display: none; + } +} +@media (max-width: 767px) { + .lindat-common2 .lindat-nav-link-language, + .lindat-common2 .lindat-nav-link-dariah, + .lindat-common2 .lindat-nav-link-clarin { + display: initial; + } +} +.lindat-common2 footer { + display: grid; + color: var(--footer-color); + grid-column-gap: 0.5em; + grid-row-gap: 0.1em; + grid-template-rows: 1fr auto auto auto auto auto; + grid-template-columns: 1fr 2fr 1fr; + paddingXX: 1.8em 3.2vw; + background-color: var(--footer-background-color); + padding: 0 1.9vw 0.6em 1.9vw; + justify-items: center; +} +.lindat-common2 footer i { + font-style: normal; +} +@media (min-width: 992px) { + .lindat-common2 #about-lindat { + grid-column: 1/2; + grid-row: 1/2; + } + .lindat-common2 #about-partners { + grid-row: 1/3; + } + .lindat-common2 #badges-b { + grid-column: 3/4; + } + .lindat-common2 #ack-msmt, + .lindat-common2 #ack-ufal, + .lindat-common2 #ack-freepik { + grid-column: 1/4; + } +} +.lindat-common2 #about-partners, +.lindat-common2 #about-lindat, +.lindat-common2 #about-website, +.lindat-common2 #badges-a, +.lindat-common2 #badges-b { + margin-bottom: 2em; +} +.lindat-common2 #ack-msmt { + border-top: 1.5px solid #9cb3c5b3; + padding: 3.5em 0; +} +.lindat-common2 #about-partners > ul { + -webkit-column-count: 2; + column-count: 2; + -webkit-column-gap: 40px; + /* Chrome, Safari, Opera */ + /* Firefox */ + column-gap: 40px; +} +.lindat-common2 #about-partners > ul li { + -webkit-column-break-inside: avoid; + page-break-inside: avoid; + break-inside: avoid; +} +.lindat-common2 footer i { + font-size: 9pt; +} +@media (max-width: 991px) { + .lindat-common2 footer { + grid-template-columns: 1fr 1fr; + } + .lindat-common2 #about-partners { + grid-row: 1/2; + justify-self: start; + grid-column: 1/3; + } + .lindat-common2 #about-partners > ul { + -webkit-column-count: 2; + column-count: 2; + -webkit-column-gap: 40px; + /* Chrome, Safari, Opera */ + /* Firefox */ + column-gap: 40px; + } + .lindat-common2 #about-partners > ul li { + -webkit-column-break-inside: avoid; + page-break-inside: avoid; + break-inside: avoid; + } + .lindat-common2 footer i { + font-size: 9pt; + } + .lindat-common2 #ack-msmt, + .lindat-common2 #ack-ufal, + .lindat-common2 #ack-freepik { + grid-column: 1/3; + } +} +@media (max-width: 576px) { + .lindat-common2 footer { + grid-template-columns: 1fr; + } + .lindat-common2 #about-partners { + grid-row: 1/2; + justify-self: start; + grid-column: 1/2; + } + .lindat-common2 #about-partners > ul { + -webkit-column-count: 1; + column-count: 1; + } + .lindat-common2 #about-lindat, + .lindat-common2 #about-website { + justify-self: start; + } + .lindat-common2 footer i { + font-size: inherit; + } + .lindat-common2 #ack-msmt, + .lindat-common2 #ack-ufal, + .lindat-common2 #ack-freepik { + grid-column: 1/2; + } +} +.lindat-common2 #badges-a { + zoom: 0.83; +} +.lindat-common2 #badges-a img[src*=centre] { + height: 1.9em; +} +.lindat-common2 #badges-a img[src*=dsa2017] { + height: 2.6em; +} +.lindat-common2 #badges-a img[src*=core] { + height: 2.9em; +} +.lindat-common2 #badges-b img[alt="Home Page"] { + height: 3em; +} +.lindat-common2 #badges-b img[alt="Link to Profile"] { + height: 2.8em; +} +.lindat-common2 #badges-a img, +.lindat-common2 #badges-b img { + margin: 0 0.4em; +} +.lindat-common2 #badges-b { + font-size: 10pt; +} +.lindat-common2 footer h4 { + font-size: 14pt; + line-height: 64pt; + margin: 0; +} +.lindat-common2 footer a, +.lindat-common2 footer a:hover, +.lindat-common2 footer a:active { + color: var(--footer-color); +} +.lindat-common2 footer h4 a, +.lindat-common2 footer h4 a:hover, +.lindat-common2 footer h4 a:active { + text-decoration: underline; +} +.lindat-common2 footer #about-partners h4 { + margin-left: 33%; +} +.lindat-common2 footer #about-partners > ul > li { + font-size: 10pt; + color: var(--partners-color); + margin-bottom: 0.9em; +} +.lindat-common2 footer #about-partners ul li.lindat-alone { + font-size: 12pt; + color: var(--footer-color); + margin-bottom: initial; +} +.lindat-common2 footer ul, +.lindat-common2 ul.lindat-dashed { + list-style-type: none; + font-size: 12pt; + padding: 0; + margin: 0; +} +.lindat-common2 footer #about-partners > ul { + margin-left: 1em; +} +.lindat-common2 #about-lindat li, +.lindat-common2 #about-website li, +.lindat-common2 footer > div > ul li.lindat-alone, +.lindat-common2 footer > div > ul ul, +.lindat-common2 ul.lindat-dashed li { + margin-left: -0.65em; +} +.lindat-common2 #about-lindat li:before, +.lindat-common2 #about-website li:before, +.lindat-common2 footer ul li.lindat-alone:before, +.lindat-common2 footer ul ul li:before, +.lindat-common2 ul.lindat-dashed li:before { + content: "\2013 "; +} +.lindat-common2 #ack-msmt, +.lindat-common2 #ack-ufal, +.lindat-common2 #ack-freepik { + text-align: center; +} +.lindat-common2 #ack-msmt { + font-family: "Source Code Pro"; + font-size: 8pt; + color: var(--partners-color); +} +.lindat-common2 #ack-ufal, +.lindat-common2 #ack-freepik { + font-size: 8pt; + color: #7b8d9c; +} +.lindat-common2 #ack-ufal a, +.lindat-common2 #ack-freepik a, +.lindat-common2 #ack-ufal a:hover, +.lindat-common2 #ack-freepik a:hover, +.lindat-common2 #ack-ufal a:visited, +.lindat-common2 #ack-freepik a:visited { + text-decoration: none; + color: #7b8d9c; + letter-spacing: 0.01em; } +// spacer between link groups in the lindat-common footer columns (an
  • instead of the original +//
    , because a