Merge remote-tracking branch 'origin/main' into CST-6685

This commit is contained in:
Nikunj Sharma
2022-09-29 19:16:08 +05:30
53 changed files with 5637 additions and 2388 deletions

View File

@@ -76,6 +76,10 @@ export function app() {
*/
const server = express();
// Tell Express to trust X-FORWARDED-* headers from proxies
// See https://expressjs.com/en/guide/behind-proxies.html
server.set('trust proxy', environment.ui.useProxies);
/*
* If production mode is enabled in the environment file:
* - Enable Angular's production mode

View File

@@ -1,5 +1,5 @@
<ds-comcol-role
*ngFor="let comcolRole of getComcolRoles$() | async"
*ngFor="let comcolRole of comcolRoles$ | async"
[dso]="community$ | async"
[comcolRole]="comcolRole"
>

View File

@@ -78,8 +78,9 @@ describe('CommunityRolesComponent', () => {
fixture.detectChanges();
});
it('should display a community admin role component', () => {
it('should display a community admin role component', (done) => {
expect(de.query(By.css('ds-comcol-role .community-admin')))
.toBeTruthy();
done();
});
});

View File

@@ -19,28 +19,14 @@ export class CommunityRolesComponent implements OnInit {
dsoRD$: Observable<RemoteData<Community>>;
/**
* The community to manage, as an observable.
* The different roles for the community, as an observable.
*/
get community$(): Observable<Community> {
return this.dsoRD$.pipe(
getFirstSucceededRemoteData(),
getRemoteDataPayload(),
);
}
comcolRoles$: Observable<HALLink[]>;
/**
* The different roles for the community.
* The community to manage, as an observable.
*/
getComcolRoles$(): Observable<HALLink[]> {
return this.community$.pipe(
map((community) => [
{
name: 'community-admin',
href: community._links.adminGroup.href,
},
]),
);
}
community$: Observable<Community>;
constructor(
protected route: ActivatedRoute,
@@ -52,5 +38,22 @@ export class CommunityRolesComponent implements OnInit {
first(),
map((data) => data.dso),
);
this.community$ = this.dsoRD$.pipe(
getFirstSucceededRemoteData(),
getRemoteDataPayload(),
);
/**
* The different roles for the community.
*/
this.comcolRoles$ = this.community$.pipe(
map((community) => [
{
name: 'community-admin',
href: community._links.adminGroup.href,
},
]),
);
}
}

View File

@@ -13,7 +13,9 @@ export const ObjectCacheActionTypes = {
REMOVE: type('dspace/core/cache/object/REMOVE'),
RESET_TIMESTAMPS: type('dspace/core/cache/object/RESET_TIMESTAMPS'),
ADD_PATCH: type('dspace/core/cache/object/ADD_PATCH'),
APPLY_PATCH: type('dspace/core/cache/object/APPLY_PATCH')
APPLY_PATCH: type('dspace/core/cache/object/APPLY_PATCH'),
ADD_DEPENDENTS: type('dspace/core/cache/object/ADD_DEPENDENTS'),
REMOVE_DEPENDENTS: type('dspace/core/cache/object/REMOVE_DEPENDENTS')
};
/**
@@ -126,13 +128,55 @@ export class ApplyPatchObjectCacheAction implements Action {
}
}
/**
* An NgRx action to add dependent request UUIDs to a cached object
*/
export class AddDependentsObjectCacheAction implements Action {
type = ObjectCacheActionTypes.ADD_DEPENDENTS;
payload: {
href: string;
dependentRequestUUIDs: string[];
};
/**
* Create a new AddDependentsObjectCacheAction
*
* @param href the self link of a cached object
* @param dependentRequestUUIDs the UUID of the request that depends on this object
*/
constructor(href: string, dependentRequestUUIDs: string[]) {
this.payload = {
href,
dependentRequestUUIDs,
};
}
}
/**
* An NgRx action to remove all dependent request UUIDs from a cached object
*/
export class RemoveDependentsObjectCacheAction implements Action {
type = ObjectCacheActionTypes.REMOVE_DEPENDENTS;
payload: string;
/**
* Create a new RemoveDependentsObjectCacheAction
*
* @param href the self link of a cached object for which to remove all dependent request UUIDs
*/
constructor(href: string) {
this.payload = href;
}
}
/**
* A type to encompass all ObjectCacheActions
*/
export type ObjectCacheAction
= AddToObjectCacheAction
| RemoveFromObjectCacheAction
| ResetObjectCacheTimestampsAction
| AddPatchObjectCacheAction
| ApplyPatchObjectCacheAction;
| RemoveFromObjectCacheAction
| ResetObjectCacheTimestampsAction
| AddPatchObjectCacheAction
| ApplyPatchObjectCacheAction
| AddDependentsObjectCacheAction
| RemoveDependentsObjectCacheAction;

View File

@@ -2,11 +2,13 @@ import * as deepFreeze from 'deep-freeze';
import { Operation } from 'fast-json-patch';
import { Item } from '../shared/item.model';
import {
AddDependentsObjectCacheAction,
AddPatchObjectCacheAction,
AddToObjectCacheAction,
ApplyPatchObjectCacheAction,
RemoveDependentsObjectCacheAction,
RemoveFromObjectCacheAction,
ResetObjectCacheTimestampsAction
ResetObjectCacheTimestampsAction,
} from './object-cache.actions';
import { objectCacheReducer } from './object-cache.reducer';
@@ -42,20 +44,22 @@ describe('objectCacheReducer', () => {
timeCompleted: new Date().getTime(),
msToLive: 900000,
requestUUIDs: [requestUUID1],
dependentRequestUUIDs: [],
patches: [],
isDirty: false,
},
[selfLink2]: {
data: {
type: Item.type,
self: requestUUID2,
self: selfLink2,
foo: 'baz',
_links: { self: { href: requestUUID2 } }
_links: { self: { href: selfLink2 } }
},
alternativeLinks: [altLink3, altLink4],
timeCompleted: new Date().getTime(),
msToLive: 900000,
requestUUIDs: [selfLink2],
requestUUIDs: [requestUUID2],
dependentRequestUUIDs: [requestUUID1],
patches: [],
isDirty: false
}
@@ -189,4 +193,20 @@ describe('objectCacheReducer', () => {
expect((newState[selfLink1].data as any).name).toEqual(newName);
});
it('should add dependent requests on ADD_DEPENDENTS', () => {
let newState = objectCacheReducer(testState, new AddDependentsObjectCacheAction(selfLink1, ['new', 'newer', 'newest']));
expect(newState[selfLink1].dependentRequestUUIDs).toEqual(['new', 'newer', 'newest']);
newState = objectCacheReducer(newState, new AddDependentsObjectCacheAction(selfLink2, ['more']));
expect(newState[selfLink2].dependentRequestUUIDs).toEqual([requestUUID1, 'more']);
});
it('should clear dependent requests on REMOVE_DEPENDENTS', () => {
let newState = objectCacheReducer(testState, new RemoveDependentsObjectCacheAction(selfLink1));
expect(newState[selfLink1].dependentRequestUUIDs).toEqual([]);
newState = objectCacheReducer(newState, new RemoveDependentsObjectCacheAction(selfLink2));
expect(newState[selfLink2].dependentRequestUUIDs).toEqual([]);
});
});

View File

@@ -1,12 +1,13 @@
/* eslint-disable max-classes-per-file */
import {
AddDependentsObjectCacheAction,
AddPatchObjectCacheAction,
AddToObjectCacheAction,
ApplyPatchObjectCacheAction,
ObjectCacheAction,
ObjectCacheActionTypes,
ObjectCacheActionTypes, RemoveDependentsObjectCacheAction,
RemoveFromObjectCacheAction,
ResetObjectCacheTimestampsAction
ResetObjectCacheTimestampsAction,
} from './object-cache.actions';
import { hasValue, isNotEmpty } from '../../shared/empty.util';
import { CacheEntry } from './cache-entry';
@@ -69,6 +70,12 @@ export class ObjectCacheEntry implements CacheEntry {
*/
requestUUIDs: string[];
/**
* A list of UUIDs for the requests that depend on this object.
* When this object is invalidated, these requests will be invalidated as well.
*/
dependentRequestUUIDs: string[];
/**
* An array of patches that were made on the client side to this entry, but haven't been sent to the server yet
*/
@@ -134,6 +141,14 @@ export function objectCacheReducer(state = initialState, action: ObjectCacheActi
return applyPatchObjectCache(state, action as ApplyPatchObjectCacheAction);
}
case ObjectCacheActionTypes.ADD_DEPENDENTS: {
return addDependentsObjectCacheState(state, action as AddDependentsObjectCacheAction);
}
case ObjectCacheActionTypes.REMOVE_DEPENDENTS: {
return removeDependentsObjectCacheState(state, action as RemoveDependentsObjectCacheAction);
}
default: {
return state;
}
@@ -159,6 +174,7 @@ function addToObjectCache(state: ObjectCacheState, action: AddToObjectCacheActio
timeCompleted: action.payload.timeCompleted,
msToLive: action.payload.msToLive,
requestUUIDs: [action.payload.requestUUID, ...(existing.requestUUIDs || [])],
dependentRequestUUIDs: existing.dependentRequestUUIDs || [],
isDirty: isNotEmpty(existing.patches),
patches: existing.patches || [],
alternativeLinks: [...(existing.alternativeLinks || []), ...newAltLinks]
@@ -252,3 +268,49 @@ function applyPatchObjectCache(state: ObjectCacheState, action: ApplyPatchObject
}
return newState;
}
/**
* Add a list of dependent request UUIDs to a cached object, used when defining new dependencies
*
* @param state the current state
* @param action an AddDependentsObjectCacheAction
* @return the new state, with the dependent requests of the cached object updated
*/
function addDependentsObjectCacheState(state: ObjectCacheState, action: AddDependentsObjectCacheAction): ObjectCacheState {
const href = action.payload.href;
const newState = Object.assign({}, state);
if (hasValue(newState[href])) {
newState[href] = Object.assign({}, newState[href], {
dependentRequestUUIDs: [
...new Set([
...newState[href]?.dependentRequestUUIDs || [],
...action.payload.dependentRequestUUIDs,
])
]
});
}
return newState;
}
/**
* Remove all dependent request UUIDs from a cached object, used to clear out-of-date depedencies
*
* @param state the current state
* @param action an AddDependentsObjectCacheAction
* @return the new state, with the dependent requests of the cached object updated
*/
function removeDependentsObjectCacheState(state: ObjectCacheState, action: RemoveDependentsObjectCacheAction): ObjectCacheState {
const href = action.payload;
const newState = Object.assign({}, state);
if (hasValue(newState[href])) {
newState[href] = Object.assign({}, newState[href], {
dependentRequestUUIDs: []
});
}
return newState;
}

View File

@@ -11,10 +11,12 @@ import { coreReducers} from '../core.reducers';
import { RestRequestMethod } from '../data/rest-request-method';
import { Item } from '../shared/item.model';
import {
AddDependentsObjectCacheAction,
RemoveDependentsObjectCacheAction,
AddPatchObjectCacheAction,
AddToObjectCacheAction,
ApplyPatchObjectCacheAction,
RemoveFromObjectCacheAction
RemoveFromObjectCacheAction,
} from './object-cache.actions';
import { Patch } from './object-cache.reducer';
import { ObjectCacheService } from './object-cache.service';
@@ -25,6 +27,7 @@ import { storeModuleConfig } from '../../app.reducer';
import { TestColdObservable } from 'jasmine-marbles/src/test-observables';
import { IndexName } from '../index/index-name.model';
import { CoreState } from '../core-state.model';
import { TestScheduler } from 'rxjs/testing';
describe('ObjectCacheService', () => {
let service: ObjectCacheService;
@@ -38,6 +41,7 @@ describe('ObjectCacheService', () => {
let altLink1;
let altLink2;
let requestUUID;
let requestUUID2;
let alternativeLink;
let timestamp;
let timestamp2;
@@ -55,6 +59,7 @@ describe('ObjectCacheService', () => {
altLink1 = 'https://alternative.link/endpoint/1234';
altLink2 = 'https://alternative.link/endpoint/5678';
requestUUID = '4d3a4ce8-a375-4b98-859b-39f0a014d736';
requestUUID2 = 'c0f486c1-c4d3-4a03-b293-ca5b71ff0054';
alternativeLink = 'https://rest.api/endpoint/5e4f8a5-be98-4c51-9fd8-6bfedcbd59b7/item';
timestamp = new Date().getTime();
timestamp2 = new Date().getTime() - 200;
@@ -71,13 +76,17 @@ describe('ObjectCacheService', () => {
data: objectToCache,
timeCompleted: timestamp,
msToLive: msToLive,
alternativeLinks: [altLink1, altLink2]
alternativeLinks: [altLink1, altLink2],
requestUUIDs: [requestUUID],
dependentRequestUUIDs: [],
};
cacheEntry2 = {
data: objectToCache,
timeCompleted: timestamp2,
msToLive: msToLive2,
alternativeLinks: [altLink2]
alternativeLinks: [altLink2],
requestUUIDs: [requestUUID2],
dependentRequestUUIDs: [],
};
invalidCacheEntry = Object.assign({}, cacheEntry, { msToLive: -1 });
operations = [{ op: 'replace', path: '/name', value: 'random string' } as Operation];
@@ -343,4 +352,122 @@ describe('ObjectCacheService', () => {
expect(store.dispatch).toHaveBeenCalledWith(new ApplyPatchObjectCacheAction(selfLink));
});
});
describe('request dependencies', () => {
beforeEach(() => {
const state = Object.assign({}, initialState, {
core: Object.assign({}, initialState.core, {
'cache/object': {
['objectWithoutDependents']: {
dependentRequestUUIDs: [],
},
['objectWithDependents']: {
dependentRequestUUIDs: [requestUUID],
},
[selfLink]: cacheEntry,
},
'index': {
'object/alt-link-to-self-link': {
[anotherLink]: selfLink,
['objectWithoutDependentsAlt']: 'objectWithoutDependents',
['objectWithDependentsAlt']: 'objectWithDependents',
}
}
})
});
mockStore.setState(state);
});
describe('addDependency', () => {
it('should dispatch an ADD_DEPENDENTS action', () => {
service.addDependency(selfLink, 'objectWithoutDependents');
expect(store.dispatch).toHaveBeenCalledOnceWith(new AddDependentsObjectCacheAction('objectWithoutDependents', [requestUUID]));
});
it('should resolve alt links', () => {
service.addDependency(anotherLink, 'objectWithoutDependentsAlt');
expect(store.dispatch).toHaveBeenCalledOnceWith(new AddDependentsObjectCacheAction('objectWithoutDependents', [requestUUID]));
});
it('should not dispatch if either href cannot be resolved to a cached self link', () => {
service.addDependency(selfLink, 'unknown');
service.addDependency('unknown', 'objectWithoutDependents');
service.addDependency('nothing', 'matches');
expect(store.dispatch).not.toHaveBeenCalled();
});
it('should not dispatch if either href is undefined', () => {
service.addDependency(selfLink, undefined);
service.addDependency(undefined, 'objectWithoutDependents');
service.addDependency(undefined, undefined);
expect(store.dispatch).not.toHaveBeenCalled();
});
it('should not dispatch if the dependency exists already', () => {
service.addDependency(selfLink, 'objectWithDependents');
expect(store.dispatch).not.toHaveBeenCalled();
});
it('should work with observable hrefs', () => {
service.addDependency(observableOf(selfLink), observableOf('objectWithoutDependents'));
expect(store.dispatch).toHaveBeenCalledOnceWith(new AddDependentsObjectCacheAction('objectWithoutDependents', [requestUUID]));
});
it('should only dispatch once for the first value of either observable href', () => {
const testScheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
testScheduler.run(({ cold: tsCold, flush }) => {
const href$ = tsCold('--y-n-n', {
y: selfLink,
n: 'NOPE'
});
const dependsOnHref$ = tsCold('-y-n-n', {
y: 'objectWithoutDependents',
n: 'NOPE'
});
service.addDependency(href$, dependsOnHref$);
flush();
expect(store.dispatch).toHaveBeenCalledOnceWith(new AddDependentsObjectCacheAction('objectWithoutDependents', [requestUUID]));
});
});
it('should not dispatch if either of the hrefs emits undefined', () => {
const testScheduler = new TestScheduler((actual, expected) => {
expect(actual).toEqual(expected);
});
testScheduler.run(({ cold: tsCold, flush }) => {
const undefined$ = tsCold('--u');
service.addDependency(selfLink, undefined$);
service.addDependency(undefined$, 'objectWithoutDependents');
service.addDependency(undefined$, undefined$);
flush();
expect(store.dispatch).not.toHaveBeenCalled();
});
});
});
describe('removeDependents', () => {
it('should dispatch a REMOVE_DEPENDENTS action', () => {
service.removeDependents('objectWithDependents');
expect(store.dispatch).toHaveBeenCalledOnceWith(new RemoveDependentsObjectCacheAction('objectWithDependents'));
});
it('should resolve alt links', () => {
service.removeDependents('objectWithDependentsAlt');
expect(store.dispatch).toHaveBeenCalledOnceWith(new RemoveDependentsObjectCacheAction('objectWithDependents'));
});
it('should not dispatch if the href cannot be resolved to a cached self link', () => {
service.removeDependents('unknown');
expect(store.dispatch).not.toHaveBeenCalled();
});
});
});
});

View File

@@ -4,23 +4,15 @@ import { applyPatch, Operation } from 'fast-json-patch';
import { combineLatest as observableCombineLatest, Observable, of as observableOf } from 'rxjs';
import { distinctUntilChanged, filter, map, mergeMap, switchMap, take } from 'rxjs/operators';
import { hasValue, isNotEmpty, isEmpty } from '../../shared/empty.util';
import { hasNoValue, hasValue, isEmpty, isNotEmpty } from '../../shared/empty.util';
import { CoreState } from '../core-state.model';
import { coreSelector } from '../core.selectors';
import { RestRequestMethod } from '../data/rest-request-method';
import {
selfLinkFromAlternativeLinkSelector,
selfLinkFromUuidSelector
} from '../index/index.selectors';
import { selfLinkFromAlternativeLinkSelector, selfLinkFromUuidSelector } from '../index/index.selectors';
import { GenericConstructor } from '../shared/generic-constructor';
import { getClassForType } from './builders/build-decorators';
import { LinkService } from './builders/link.service';
import {
AddPatchObjectCacheAction,
AddToObjectCacheAction,
ApplyPatchObjectCacheAction,
RemoveFromObjectCacheAction
} from './object-cache.actions';
import { AddDependentsObjectCacheAction, AddPatchObjectCacheAction, AddToObjectCacheAction, ApplyPatchObjectCacheAction, RemoveDependentsObjectCacheAction, RemoveFromObjectCacheAction } from './object-cache.actions';
import { ObjectCacheEntry, ObjectCacheState } from './object-cache.reducer';
import { AddToSSBAction } from './server-sync-buffer.actions';
@@ -339,4 +331,97 @@ export class ObjectCacheService {
this.store.dispatch(new ApplyPatchObjectCacheAction(selfLink));
}
/**
* Add a new dependency between two cached objects.
* When {@link dependsOnHref$} is invalidated, {@link href$} will be invalidated as well.
*
* This method should be called _after_ requests have been sent;
* it will only work if both objects are already present in the cache.
*
* If either object is undefined, the dependency will not be added
*
* @param href$ the href of an object to add a dependency to
* @param dependsOnHref$ the href of the new dependency
*/
addDependency(href$: string | Observable<string>, dependsOnHref$: string | Observable<string>) {
if (hasNoValue(href$) || hasNoValue(dependsOnHref$)) {
return;
}
if (typeof href$ === 'string') {
href$ = observableOf(href$);
}
if (typeof dependsOnHref$ === 'string') {
dependsOnHref$ = observableOf(dependsOnHref$);
}
observableCombineLatest([
href$,
dependsOnHref$.pipe(
switchMap(dependsOnHref => this.resolveSelfLink(dependsOnHref))
),
]).pipe(
switchMap(([href, dependsOnSelfLink]: [string, string]) => {
const dependsOnSelfLink$ = observableOf(dependsOnSelfLink);
return observableCombineLatest([
dependsOnSelfLink$,
dependsOnSelfLink$.pipe(
switchMap(selfLink => this.getBySelfLink(selfLink)),
map(oce => oce?.dependentRequestUUIDs || []),
),
this.getByHref(href).pipe(
// only add the latest request to keep dependency index from growing indefinitely
map((entry: ObjectCacheEntry) => entry?.requestUUIDs?.[0]),
)
]);
}),
take(1),
).subscribe(([dependsOnSelfLink, currentDependents, newDependent]: [string, string[], string]) => {
// don't dispatch if either href is invalid or if the new dependency already exists
if (hasValue(dependsOnSelfLink) && hasValue(newDependent) && !currentDependents.includes(newDependent)) {
this.store.dispatch(new AddDependentsObjectCacheAction(dependsOnSelfLink, [newDependent]));
}
});
}
/**
* Clear all dependent requests associated with a cache entry.
*
* @href the href of a cached object
*/
removeDependents(href: string) {
this.resolveSelfLink(href).pipe(
take(1),
).subscribe((selfLink: string) => {
if (hasValue(selfLink)) {
this.store.dispatch(new RemoveDependentsObjectCacheAction(selfLink));
}
});
}
/**
* Resolve the self link of an existing cached object from an arbitrary href
*
* @param href any href
* @return an observable of the self link corresponding to the given href.
* Will emit the given href if it was a self link, another href
* if the given href was an alt link, or undefined if there is no
* cached object for this href.
*/
private resolveSelfLink(href: string): Observable<string> {
return this.getBySelfLink(href).pipe(
switchMap((oce: ObjectCacheEntry) => {
if (isNotEmpty(oce)) {
return [href];
} else {
return this.store.pipe(
select(selfLinkFromAlternativeLinkSelector(href)),
);
}
}),
);
}
}

View File

@@ -10,7 +10,7 @@ import { RemoteDataBuildService } from '../../cache/builders/remote-data-build.s
import { HALEndpointService } from '../../shared/hal-endpoint.service';
import { ObjectCacheService } from '../../cache/object-cache.service';
import { FindListOptions } from '../find-list-options.model';
import { Observable, of as observableOf } from 'rxjs';
import { Observable, of as observableOf, combineLatest as observableCombineLatest } from 'rxjs';
import { getMockRequestService } from '../../../shared/mocks/request.service.mock';
import { HALEndpointServiceStub } from '../../../shared/testing/hal-endpoint-service.stub';
import { getMockRemoteDataBuildService } from '../../../shared/mocks/remote-data-build.service.mock';
@@ -20,6 +20,7 @@ import { RemoteData } from '../remote-data';
import { RequestEntryState } from '../request-entry-state.model';
import { fakeAsync, tick } from '@angular/core/testing';
import { BaseDataService } from './base-data.service';
import { createFailedRemoteDataObject$, createSuccessfulRemoteDataObject$ } from '../../../shared/remote-data.utils';
const endpoint = 'https://rest.api/core';
@@ -65,7 +66,13 @@ describe('BaseDataService', () => {
},
getByHref: () => {
/* empty */
}
},
addDependency: () => {
/* empty */
},
removeDependents: () => {
/* empty */
},
} as any;
selfLink = 'https://rest.api/endpoint/1698f1d3-be98-4c51-9fd8-6bfedcbd59b7';
linksToFollow = [
@@ -558,7 +565,8 @@ describe('BaseDataService', () => {
beforeEach(() => {
getByHrefSpy = spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2', 'request3']
requestUUIDs: ['request1', 'request2', 'request3'],
dependentRequestUUIDs: ['request4', 'request5']
}));
});
@@ -570,6 +578,8 @@ describe('BaseDataService', () => {
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request1');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request2');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request3');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request4');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request5');
done();
});
});
@@ -582,6 +592,8 @@ describe('BaseDataService', () => {
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request1');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request2');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request3');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request4');
expect(requestService.setStaleByUUID).toHaveBeenCalledWith('request5');
}));
it('should return an Observable that only emits true once all requests are stale', () => {
@@ -591,9 +603,13 @@ describe('BaseDataService', () => {
case 'request1':
return cold('--(t|)', BOOLEAN);
case 'request2':
return cold('----(t|)', BOOLEAN);
case 'request3':
return cold('------(t|)', BOOLEAN);
case 'request3':
return cold('---(t|)', BOOLEAN);
case 'request4':
return cold('-(t|)', BOOLEAN);
case 'request5':
return cold('----(t|)', BOOLEAN);
}
});
@@ -607,9 +623,9 @@ describe('BaseDataService', () => {
it('should only fire for the current state of the object (instead of tracking it)', () => {
testScheduler.run(({ cold, flush }) => {
getByHrefSpy.and.returnValue(cold('a---b---c---', {
a: { requestUUIDs: ['request1'] }, // this is the state at the moment we're invalidating the cache
b: { requestUUIDs: ['request2'] }, // we shouldn't keep tracking the state
c: { requestUUIDs: ['request3'] }, // because we may invalidate when we shouldn't
a: { requestUUIDs: ['request1'], dependentRequestUUIDs: [] }, // this is the state at the moment we're invalidating the cache
b: { requestUUIDs: ['request2'], dependentRequestUUIDs: [] }, // we shouldn't keep tracking the state
c: { requestUUIDs: ['request3'], dependentRequestUUIDs: [] }, // because we may invalidate when we shouldn't
}));
service.invalidateByHref('some-href');
@@ -624,4 +640,42 @@ describe('BaseDataService', () => {
});
});
});
describe('addDependency', () => {
let addDependencySpy;
beforeEach(() => {
addDependencySpy = spyOn(objectCache, 'addDependency');
});
it('should call objectCache.addDependency with the object\'s self link', () => {
addDependencySpy.and.callFake((href$: Observable<string>, dependsOn$: Observable<string>) => {
observableCombineLatest([href$, dependsOn$]).subscribe(([href, dependsOn]) => {
expect(href).toBe('object-href');
expect(dependsOn).toBe('dependsOnHref');
});
});
(service as any).addDependency(
createSuccessfulRemoteDataObject$({ _links: { self: { href: 'object-href' } } }),
observableOf('dependsOnHref')
);
expect(addDependencySpy).toHaveBeenCalled();
});
it('should call objectCache.addDependency without an href if request failed', () => {
addDependencySpy.and.callFake((href$: Observable<string>, dependsOn$: Observable<string>) => {
observableCombineLatest([href$, dependsOn$]).subscribe(([href, dependsOn]) => {
expect(href).toBe(undefined);
expect(dependsOn).toBe('dependsOnHref');
});
});
(service as any).addDependency(
createFailedRemoteDataObject$('something went wrong'),
observableOf('dependsOnHref')
);
expect(addDependencySpy).toHaveBeenCalled();
});
});
});

View File

@@ -23,6 +23,7 @@ import { PaginatedList } from '../paginated-list.model';
import { ObjectCacheEntry } from '../../cache/object-cache.reducer';
import { ObjectCacheService } from '../../cache/object-cache.service';
import { HALDataService } from './hal-data-service.interface';
import { getFirstCompletedRemoteData } from '../../shared/operators';
/**
* Common functionality for data services.
@@ -352,19 +353,55 @@ export class BaseDataService<T extends CacheableObject> implements HALDataServic
}
/**
* Invalidate a cached object by its href
* @param href the href to invalidate
* Shorthand method to add a dependency to a cached object
* ```
* const out$ = this.findByHref(...); // or another method that sends a request
* this.addDependency(out$, dependsOnHref);
* ```
* When {@link dependsOnHref$} is invalidated, {@link object$} will be invalidated as well.
*
*
* @param object$ the cached object
* @param dependsOnHref$ the href of the object it should depend on
*/
public invalidateByHref(href: string): Observable<boolean> {
protected addDependency(object$: Observable<RemoteData<T | PaginatedList<T>>>, dependsOnHref$: string | Observable<string>) {
this.objectCache.addDependency(
object$.pipe(
getFirstCompletedRemoteData(),
switchMap((rd: RemoteData<T>) => {
if (rd.hasSucceeded) {
return [rd.payload._links.self.href];
} else {
// undefined href will be skipped in objectCache.addDependency
return [undefined];
}
}),
),
dependsOnHref$
);
}
/**
* Invalidate an existing DSpaceObject by marking all requests it is included in as stale
* @param href The self link of the object to be invalidated
* @return An Observable that will emit `true` once all requests are stale
*/
invalidateByHref(href: string): Observable<boolean> {
const done$ = new AsyncSubject<boolean>();
this.objectCache.getByHref(href).pipe(
take(1),
switchMap((oce: ObjectCacheEntry) => observableFrom(oce.requestUUIDs).pipe(
mergeMap((requestUUID: string) => this.requestService.setStaleByUUID(requestUUID)),
toArray(),
)),
switchMap((oce: ObjectCacheEntry) => {
return observableFrom([
...oce.requestUUIDs,
...oce.dependentRequestUUIDs
]).pipe(
mergeMap((requestUUID: string) => this.requestService.setStaleByUUID(requestUUID)),
toArray(),
);
}),
).subscribe(() => {
this.objectCache.removeDependents(href);
done$.next(true);
done$.complete();
});

View File

@@ -178,7 +178,12 @@ describe('PatchDataImpl', () => {
describe('patch', () => {
const dso = {
uuid: 'dso-uuid'
uuid: 'dso-uuid',
_links: {
self: {
href: 'dso-href',
}
}
};
const operations = [
Object.assign({
@@ -188,14 +193,23 @@ describe('PatchDataImpl', () => {
}) as Operation
];
beforeEach((done) => {
service.patch(dso, operations).subscribe(() => {
done();
});
it('should send a PatchRequest', () => {
service.patch(dso, operations);
expect(requestService.send).toHaveBeenCalledWith(jasmine.any(PatchRequest));
});
it('should send a PatchRequest', () => {
expect(requestService.send).toHaveBeenCalledWith(jasmine.any(PatchRequest));
it('should invalidate the cached object if successfully patched', () => {
spyOn(rdbService, 'buildFromRequestUUIDAndAwait');
spyOn(service, 'invalidateByHref');
service.patch(dso, operations);
expect(rdbService.buildFromRequestUUIDAndAwait).toHaveBeenCalled();
expect((rdbService.buildFromRequestUUIDAndAwait as jasmine.Spy).calls.argsFor(0)[0]).toBe(requestService.generateRequestId());
const callback = (rdbService.buildFromRequestUUIDAndAwait as jasmine.Spy).calls.argsFor(0)[1];
callback();
expect(service.invalidateByHref).toHaveBeenCalledWith('dso-href');
});
});

View File

@@ -101,7 +101,7 @@ export class PatchDataImpl<T extends CacheableObject> extends IdentifiableDataSe
this.requestService.send(request);
});
return this.rdbService.buildFromRequestUUID(requestId);
return this.rdbService.buildFromRequestUUIDAndAwait(requestId, () => this.invalidateByHref(object._links.self.href));
}
/**

View File

@@ -2,7 +2,7 @@ import { AuthorizationDataService } from './authorization-data.service';
import { SiteDataService } from '../site-data.service';
import { Site } from '../../shared/site.model';
import { EPerson } from '../../eperson/models/eperson.model';
import { of as observableOf } from 'rxjs';
import { of as observableOf, combineLatest as observableCombineLatest, Observable } from 'rxjs';
import { FeatureID } from './feature-id';
import { hasValue } from '../../../shared/empty.util';
import { RequestParam } from '../../cache/models/request-param.model';
@@ -12,10 +12,12 @@ import { createPaginatedList } from '../../../shared/testing/utils.test';
import { Feature } from '../../shared/feature.model';
import { FindListOptions } from '../find-list-options.model';
import { testSearchDataImplementation } from '../base/search-data.spec';
import { getMockObjectCacheService } from '../../../shared/mocks/object-cache.service.mock';
describe('AuthorizationDataService', () => {
let service: AuthorizationDataService;
let siteService: SiteDataService;
let objectCache;
let site: Site;
let ePerson: EPerson;
@@ -38,7 +40,8 @@ describe('AuthorizationDataService', () => {
siteService = jasmine.createSpyObj('siteService', {
find: observableOf(site),
});
service = new AuthorizationDataService(requestService, undefined, undefined, undefined, siteService);
objectCache = getMockObjectCacheService();
service = new AuthorizationDataService(requestService, undefined, objectCache, undefined, siteService);
}
beforeEach(() => {
@@ -110,6 +113,43 @@ describe('AuthorizationDataService', () => {
expect(service.searchBy).toHaveBeenCalledWith('object', createExpected(objectUrl, ePersonUuid, FeatureID.LoginOnBehalfOf), true, true);
});
});
describe('dependencies', () => {
let addDependencySpy;
beforeEach(() => {
(service.searchBy as any).and.returnValue(observableOf('searchBy RD$'));
addDependencySpy = spyOn(service as any, 'addDependency');
});
it('should add a dependency on the objectUrl', (done) => {
addDependencySpy.and.callFake((href$: Observable<string>, dependsOn$: Observable<string>) => {
observableCombineLatest([href$, dependsOn$]).subscribe(([href, dependsOn]) => {
expect(href).toBe('searchBy RD$');
expect(dependsOn).toBe('object-href');
});
});
service.searchByObject(FeatureID.AdministratorOf, 'object-href').subscribe(() => {
expect(addDependencySpy).toHaveBeenCalled();
done();
});
});
it('should add a dependency on the Site object if no objectUrl is given', (done) => {
addDependencySpy.and.callFake((object$: Observable<any>, dependsOn$: Observable<string>) => {
observableCombineLatest([object$, dependsOn$]).subscribe(([object, dependsOn]) => {
expect(object).toBe('searchBy RD$');
expect(dependsOn).toBe('test-site-href');
});
});
service.searchByObject(FeatureID.AdministratorOf).subscribe(() => {
expect(addDependencySpy).toHaveBeenCalled();
done();
});
});
});
});
describe('isAuthorized', () => {

View File

@@ -11,10 +11,10 @@ import { followLink, FollowLinkConfig } from '../../../shared/utils/follow-link-
import { RemoteData } from '../remote-data';
import { PaginatedList } from '../paginated-list.model';
import { catchError, map, switchMap } from 'rxjs/operators';
import { hasValue, isNotEmpty } from '../../../shared/empty.util';
import { hasNoValue, hasValue, isNotEmpty } from '../../../shared/empty.util';
import { RequestParam } from '../../cache/models/request-param.model';
import { AuthorizationSearchParams } from './authorization-search-params';
import { addSiteObjectUrlIfEmpty, oneAuthorizationMatchesFeature } from './authorization-utils';
import { oneAuthorizationMatchesFeature } from './authorization-utils';
import { FeatureID } from './feature-id';
import { getFirstCompletedRemoteData } from '../../shared/operators';
import { FindListOptions } from '../find-list-options.model';
@@ -96,12 +96,28 @@ export class AuthorizationDataService extends BaseDataService<Authorization> imp
* {@link HALLink}s should be automatically resolved
*/
searchByObject(featureId?: FeatureID, objectUrl?: string, ePersonUuid?: string, options: FindListOptions = {}, useCachedVersionIfAvailable = true, reRequestOnStale = true, ...linksToFollow: FollowLinkConfig<Authorization>[]): Observable<RemoteData<PaginatedList<Authorization>>> {
return observableOf(new AuthorizationSearchParams(objectUrl, ePersonUuid, featureId)).pipe(
addSiteObjectUrlIfEmpty(this.siteService),
const objectUrl$ = observableOf(objectUrl).pipe(
switchMap((url) => {
if (hasNoValue(url)) {
return this.siteService.find().pipe(
map((site) => site.self)
);
} else {
return observableOf(url);
}
}),
);
const out$ = objectUrl$.pipe(
map((url: string) => new AuthorizationSearchParams(url, ePersonUuid, featureId)),
switchMap((params: AuthorizationSearchParams) => {
return this.searchBy(this.searchByObjectPath, this.createSearchOptions(params.objectUrl, options, params.ePersonUuid, params.featureId), useCachedVersionIfAvailable, reRequestOnStale, ...linksToFollow);
})
);
this.addDependency(out$, objectUrl$);
return out$;
}
/**

View File

@@ -307,7 +307,7 @@ describe('EPersonDataService', () => {
it('should sent a patch request with an uuid, token and new password to the epersons endpoint', () => {
service.patchPasswordWithToken('test-uuid', 'test-token', 'test-password');
const operation = Object.assign({ op: 'add', path: '/password', value: 'test-password' });
const operation = Object.assign({ op: 'add', path: '/password', value: { new_password: 'test-password' } });
const expected = new PatchRequest(requestService.generateRequestId(), epersonsEndpoint + '/test-uuid?token=test-token', [operation]);
expect(requestService.send).toHaveBeenCalledWith(expected);

View File

@@ -3,7 +3,10 @@ import { createSelector, select, Store } from '@ngrx/store';
import { Operation } from 'fast-json-patch';
import { Observable } from 'rxjs';
import { find, map, take } from 'rxjs/operators';
import { EPeopleRegistryCancelEPersonAction, EPeopleRegistryEditEPersonAction } from '../../access-control/epeople-registry/epeople-registry.actions';
import {
EPeopleRegistryCancelEPersonAction,
EPeopleRegistryEditEPersonAction
} from '../../access-control/epeople-registry/epeople-registry.actions';
import { EPeopleRegistryState } from '../../access-control/epeople-registry/epeople-registry.reducers';
import { AppState } from '../../app.reducer';
import { hasNoValue, hasValue } from '../../shared/empty.util';
@@ -318,7 +321,7 @@ export class EPersonDataService extends IdentifiableDataService<EPerson> impleme
patchPasswordWithToken(uuid: string, token: string, password: string): Observable<RemoteData<EPerson>> {
const requestId = this.requestService.generateRequestId();
const operation = Object.assign({ op: 'add', path: '/password', value: password });
const operation = Object.assign({ op: 'add', path: '/password', value: { 'new_password': password } });
const hrefObs = this.halService.getEndpoint(this.linkPath).pipe(
map((endpoint: string) => this.getIDHref(endpoint, uuid)),

View File

@@ -26,10 +26,9 @@ import { EPersonMock, EPersonMock2 } from '../../shared/testing/eperson.mock';
import { createPaginatedList, createRequestEntry$ } from '../../shared/testing/utils.test';
import { CoreState } from '../core-state.model';
import { FindListOptions } from '../data/find-list-options.model';
import { ObjectCacheService } from '../cache/object-cache.service';
import { getMockLinkService } from '../../shared/mocks/link-service.mock';
import { of as observableOf } from 'rxjs';
import { ObjectCacheEntry } from '../cache/object-cache.reducer';
import { getMockObjectCacheService } from '../../shared/mocks/object-cache.service.mock';
describe('GroupDataService', () => {
let service: GroupDataService;
@@ -42,7 +41,7 @@ describe('GroupDataService', () => {
let groups$;
let halService;
let rdbService;
let objectCache: ObjectCacheService;
let objectCache;
function init() {
restEndpointURL = 'https://dspace.4science.it/dspace-spring-rest/api/eperson';
groupsEndpoint = `${restEndpointURL}/groups`;
@@ -50,7 +49,7 @@ describe('GroupDataService', () => {
groups$ = createSuccessfulRemoteDataObject$(createPaginatedList(groups));
rdbService = getMockRemoteDataBuildServiceHrefMap(undefined, { 'https://dspace.4science.it/dspace-spring-rest/api/eperson/groups': groups$ });
halService = new HALEndpointServiceStub(restEndpointURL);
objectCache = new ObjectCacheService(store, getMockLinkService());
objectCache = getMockObjectCacheService();
TestBed.configureTestingModule({
imports: [
CommonModule,
@@ -114,8 +113,9 @@ describe('GroupDataService', () => {
describe('addSubGroupToGroup', () => {
beforeEach(() => {
spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2']
objectCache.getByHref.and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2'],
dependentRequestUUIDs: [],
} as ObjectCacheEntry));
spyOn((service as any).deleteData, 'invalidateByHref');
service.addSubGroupToGroup(GroupMock, GroupMock2).subscribe();
@@ -143,8 +143,9 @@ describe('GroupDataService', () => {
describe('deleteSubGroupFromGroup', () => {
beforeEach(() => {
spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2']
objectCache.getByHref.and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2'],
dependentRequestUUIDs: [],
} as ObjectCacheEntry));
spyOn((service as any).deleteData, 'invalidateByHref');
service.deleteSubGroupFromGroup(GroupMock, GroupMock2).subscribe();
@@ -168,8 +169,9 @@ describe('GroupDataService', () => {
describe('addMemberToGroup', () => {
beforeEach(() => {
spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2']
objectCache.getByHref.and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2'],
dependentRequestUUIDs: [],
} as ObjectCacheEntry));
spyOn((service as any).deleteData, 'invalidateByHref');
service.addMemberToGroup(GroupMock, EPersonMock2).subscribe();
@@ -198,8 +200,9 @@ describe('GroupDataService', () => {
describe('deleteMemberFromGroup', () => {
beforeEach(() => {
spyOn(objectCache, 'getByHref').and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2']
objectCache.getByHref.and.returnValue(observableOf({
requestUUIDs: ['request1', 'request2'],
dependentRequestUUIDs: [],
} as ObjectCacheEntry));
spyOn((service as any).deleteData, 'invalidateByHref');
service.deleteMemberFromGroup(GroupMock, EPersonMock).subscribe();

View File

@@ -2,17 +2,25 @@ import { TestBed } from '@angular/core/testing';
import { BrowserHardRedirectService } from './browser-hard-redirect.service';
describe('BrowserHardRedirectService', () => {
const origin = 'https://test-host.com:4000';
const mockLocation = {
href: undefined,
pathname: '/pathname',
search: '/search',
origin
} as Location;
const service: BrowserHardRedirectService = new BrowserHardRedirectService(mockLocation);
let origin: string;
let mockLocation: Location;
let service: BrowserHardRedirectService;
beforeEach(() => {
origin = 'https://test-host.com:4000';
mockLocation = {
href: undefined,
pathname: '/pathname',
search: '/search',
origin,
replace: (url: string) => {
mockLocation.href = url;
}
} as Location;
spyOn(mockLocation, 'replace');
service = new BrowserHardRedirectService(mockLocation);
TestBed.configureTestingModule({});
});
@@ -28,8 +36,8 @@ describe('BrowserHardRedirectService', () => {
service.redirect(redirect);
});
it('should update the location', () => {
expect(mockLocation.href).toEqual(redirect);
it('should call location.replace with the new url', () => {
expect(mockLocation.replace).toHaveBeenCalledWith(redirect);
});
});

View File

@@ -24,7 +24,7 @@ export class BrowserHardRedirectService extends HardRedirectService {
* @param url
*/
redirect(url: string) {
this.location.href = url;
this.location.replace(url);
}
/**

View File

@@ -10,6 +10,9 @@ import { StatisticsModule } from '../statistics/statistics.module';
import { ThemedHomeNewsComponent } from './home-news/themed-home-news.component';
import { ThemedHomePageComponent } from './themed-home-page.component';
import { RecentItemListComponent } from './recent-item-list/recent-item-list.component';
import { JournalEntitiesModule } from '../entity-groups/journal-entities/journal-entities.module';
import { ResearchEntitiesModule } from '../entity-groups/research-entities/research-entities.module';
const DECLARATIONS = [
HomePageComponent,
ThemedHomePageComponent,
@@ -22,7 +25,9 @@ const DECLARATIONS = [
@NgModule({
imports: [
CommonModule,
SharedModule,
SharedModule.withEntryComponents(),
JournalEntitiesModule.withEntryComponents(),
ResearchEntitiesModule.withEntryComponents(),
HomePageRoutingModule,
StatisticsModule.forRoot()
],

View File

@@ -1,5 +1,5 @@
<ng-container *ngVar="(itemRD$ | async) as itemRD">
<div class="mt-4" *ngIf="itemRD?.hasSucceeded && itemRD?.payload?.page.length > 0" @fadeIn>
<div class="mt-4" [ngClass]="placeholderFontClass" *ngIf="itemRD?.hasSucceeded && itemRD?.payload?.page.length > 0" @fadeIn>
<div class="d-flex flex-row border-bottom mb-4 pb-4 ng-tns-c416-2"></div>
<h2> {{'home.recent-submissions.head' | translate}}</h2>
<div class="my-4" *ngFor="let item of itemRD?.payload?.page">
@@ -12,4 +12,4 @@
<ds-error *ngIf="itemRD?.hasFailed" message="{{'error.recent-submissions' | translate}}"></ds-error>
<ds-loading *ngIf="!itemRD || itemRD.isLoading" message="{{'loading.recent-submissions' | translate}}">
</ds-loading>
</ng-container>
</ng-container>

View File

@@ -10,8 +10,11 @@ import { SearchConfigurationService } from '../../core/shared/search/search-conf
import { PaginatedSearchOptions } from '../../shared/search/models/paginated-search-options.model';
import { PaginationComponentOptions } from '../../shared/pagination/pagination-component-options.model';
import { SortDirection, SortOptions } from '../../core/cache/models/sort-options.model';
import { ViewMode } from 'src/app/core/shared/view-mode.model';
import { of as observableOf } from 'rxjs';
import { APP_CONFIG } from '../../../config/app-config.interface';
import { environment } from '../../../environments/environment';
import { PLATFORM_ID } from '@angular/core';
describe('RecentItemListComponent', () => {
let component: RecentItemListComponent;
let fixture: ComponentFixture<RecentItemListComponent>;
@@ -42,6 +45,8 @@ describe('RecentItemListComponent', () => {
{ provide: SearchService, useValue: searchServiceStub },
{ provide: PaginationService, useValue: paginationService },
{ provide: SearchConfigurationService, useValue: searchConfigServiceStub },
{ provide: APP_CONFIG, useValue: environment },
{ provide: PLATFORM_ID, useValue: 'browser' },
],
})
.compileComponents();

View File

@@ -1,4 +1,4 @@
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ChangeDetectionStrategy, Component, ElementRef, Inject, OnInit, PLATFORM_ID } from '@angular/core';
import { PaginatedSearchOptions } from '../../shared/search/models/paginated-search-options.model';
import { fadeIn, fadeInOut } from '../../shared/animations/fade';
import { RemoteData } from '../../core/data/remote-data';
@@ -11,12 +11,13 @@ import { SortDirection, SortOptions } from '../../core/cache/models/sort-options
import { environment } from '../../../environments/environment';
import { ViewMode } from '../../core/shared/view-mode.model';
import { SearchConfigurationService } from '../../core/shared/search/search-configuration.service';
import {
toDSpaceObjectListRD
} from '../../core/shared/operators';
import {
Observable,
} from 'rxjs';
import { toDSpaceObjectListRD } from '../../core/shared/operators';
import { Observable } from 'rxjs';
import { followLink, FollowLinkConfig } from '../../shared/utils/follow-link-config.model';
import { APP_CONFIG, AppConfig } from '../../../config/app-config.interface';
import { isPlatformBrowser } from '@angular/common';
import { setPlaceHolderAttributes } from '../../shared/utils/object-list-utils';
@Component({
selector: 'ds-recent-item-list',
templateUrl: './recent-item-list.component.html',
@@ -31,14 +32,22 @@ export class RecentItemListComponent implements OnInit {
itemRD$: Observable<RemoteData<PaginatedList<Item>>>;
paginationConfig: PaginationComponentOptions;
sortConfig: SortOptions;
/**
* The view-mode we're currently on
* @type {ViewMode}
*/
viewMode = ViewMode.ListElement;
constructor(private searchService: SearchService,
private _placeholderFontClass: string;
constructor(
private searchService: SearchService,
private paginationService: PaginationService,
public searchConfigurationService: SearchConfigurationService
public searchConfigurationService: SearchConfigurationService,
protected elementRef: ElementRef,
@Inject(APP_CONFIG) private appConfig: AppConfig,
@Inject(PLATFORM_ID) private platformId: Object,
) {
this.paginationConfig = Object.assign(new PaginationComponentOptions(), {
@@ -50,16 +59,29 @@ export class RecentItemListComponent implements OnInit {
this.sortConfig = new SortOptions(environment.homePage.recentSubmissions.sortField, SortDirection.DESC);
}
ngOnInit(): void {
const linksToFollow: FollowLinkConfig<Item>[] = [];
if (this.appConfig.browseBy.showThumbnails) {
linksToFollow.push(followLink('thumbnail'));
}
this.itemRD$ = this.searchService.search(
new PaginatedSearchOptions({
pagination: this.paginationConfig,
sort: this.sortConfig,
}),
).pipe(toDSpaceObjectListRD()) as Observable<RemoteData<PaginatedList<Item>>>;
undefined,
undefined,
undefined,
...linksToFollow,
).pipe(
toDSpaceObjectListRD()
) as Observable<RemoteData<PaginatedList<Item>>>;
}
ngOnDestroy(): void {
this.paginationService.clearPagination(this.paginationConfig.id);
}
onLoadMore(): void {
this.paginationService.updateRouteWithUrl(this.searchConfigurationService.paginationID, ['search'], {
sortField: environment.homePage.recentSubmissions.sortField,
@@ -68,5 +90,17 @@ export class RecentItemListComponent implements OnInit {
});
}
get placeholderFontClass(): string {
if (this._placeholderFontClass === undefined) {
if (isPlatformBrowser(this.platformId)) {
const width = this.elementRef.nativeElement.offsetWidth;
this._placeholderFontClass = setPlaceHolderAttributes(width);
} else {
this._placeholderFontClass = 'hide-placeholder-text';
}
}
return this._placeholderFontClass;
}
}

View File

@@ -12,6 +12,7 @@ import { createPaginatedList } from '../../shared/testing/utils.test';
import { of as observableOf } from 'rxjs';
import { MiradorViewerService } from './mirador-viewer.service';
import { HostWindowService } from '../../shared/host-window.service';
import { BundleDataService } from '../../core/data/bundle-data.service';
function getItem(metadata: MetadataMap) {
@@ -46,6 +47,7 @@ describe('MiradorViewerComponent with search', () => {
declarations: [MiradorViewerComponent],
providers: [
{ provide: BitstreamDataService, useValue: {} },
{ provide: BundleDataService, useValue: {} },
{ provide: HostWindowService, useValue: mockHostWindowService }
],
schemas: [NO_ERRORS_SCHEMA]
@@ -108,6 +110,7 @@ describe('MiradorViewerComponent with multiple images', () => {
declarations: [MiradorViewerComponent],
providers: [
{ provide: BitstreamDataService, useValue: {} },
{ provide: BundleDataService, useValue: {} },
{ provide: HostWindowService, useValue: mockHostWindowService }
],
schemas: [NO_ERRORS_SCHEMA]
@@ -167,6 +170,7 @@ describe('MiradorViewerComponent with a single image', () => {
declarations: [MiradorViewerComponent],
providers: [
{ provide: BitstreamDataService, useValue: {} },
{ provide: BundleDataService, useValue: {} },
{ provide: HostWindowService, useValue: mockHostWindowService }
],
schemas: [NO_ERRORS_SCHEMA]
@@ -225,6 +229,7 @@ describe('MiradorViewerComponent in development mode', () => {
set: {
providers: [
{ provide: MiradorViewerService, useValue: viewerService },
{ provide: BundleDataService, useValue: {} },
{ provide: HostWindowService, useValue: mockHostWindowService }
]
}

View File

@@ -8,6 +8,7 @@ import { map, take } from 'rxjs/operators';
import { isPlatformBrowser } from '@angular/common';
import { MiradorViewerService } from './mirador-viewer.service';
import { HostWindowService, WidthCategory } from '../../shared/host-window.service';
import { BundleDataService } from '../../core/data/bundle-data.service';
@Component({
selector: 'ds-mirador-viewer',
@@ -55,6 +56,7 @@ export class MiradorViewerComponent implements OnInit {
constructor(private sanitizer: DomSanitizer,
private viewerService: MiradorViewerService,
private bitstreamDataService: BitstreamDataService,
private bundleDataService: BundleDataService,
private hostWindowService: HostWindowService,
@Inject(PLATFORM_ID) private platformId: any) {
}
@@ -107,10 +109,10 @@ export class MiradorViewerComponent implements OnInit {
this.notMobile = !(category === WidthCategory.XS || category === WidthCategory.SM);
});
// We need to set the multi property to true if the
// item is searchable or when the ORIGINAL bundle contains more
// than 1 image. (The multi property determines whether the
// Mirador side thumbnail navigation panel is shown.)
// Set the multi property. The default mirador configuration adds a right
// thumbnail navigation panel to the viewer when multi is 'true'.
// Set the multi property to 'true' if the item is searchable.
if (this.searchable) {
this.multi = true;
const observable = of('');
@@ -120,8 +122,12 @@ export class MiradorViewerComponent implements OnInit {
})
);
} else {
// Sets the multi value based on the image count.
this.iframeViewerUrl = this.viewerService.getImageCount(this.object, this.bitstreamDataService).pipe(
// Set the multi property based on the image count in IIIF-eligible bundles.
// Any count greater than 1 sets the value to 'true'.
this.iframeViewerUrl = this.viewerService.getImageCount(
this.object,
this.bitstreamDataService,
this.bundleDataService).pipe(
map(c => {
if (c > 1) {
this.multi = true;

View File

@@ -1,14 +1,18 @@
import { Injectable, isDevMode } from '@angular/core';
import { Observable } from 'rxjs';
import { Item } from '../../core/shared/item.model';
import { getFirstCompletedRemoteData, getFirstSucceededRemoteDataPayload } from '../../core/shared/operators';
import { last, map, switchMap } from 'rxjs/operators';
import {
getFirstCompletedRemoteData,
} from '../../core/shared/operators';
import { filter, last, map, mergeMap, switchMap } from 'rxjs/operators';
import { RemoteData } from '../../core/data/remote-data';
import { PaginatedList } from '../../core/data/paginated-list.model';
import { Bitstream } from '../../core/shared/bitstream.model';
import { BitstreamFormat } from '../../core/shared/bitstream-format.model';
import { BitstreamDataService } from '../../core/data/bitstream-data.service';
import { followLink, FollowLinkConfig } from '../../shared/utils/follow-link-config.model';
import { Bundle } from '../../core/shared/bundle.model';
import { BundleDataService } from '../../core/data/bundle-data.service';
@Injectable()
export class MiradorViewerService {
@@ -26,32 +30,64 @@ export class MiradorViewerService {
}
/**
* Returns observable of the number of images in the ORIGINAL bundle
* Returns observable of the number of images found in eligible IIIF bundles. Checks
* the mimetype of the first 5 bitstreams in each bundle.
* @param item
* @param bitstreamDataService
* @param bundleDataService
* @returns the total image count
*/
getImageCount(item: Item, bitstreamDataService: BitstreamDataService): Observable<number> {
let count = 0;
return bitstreamDataService.findAllByItemAndBundleName(item, 'ORIGINAL', {
currentPage: 1,
elementsPerPage: 10
}, true, true, ...this.LINKS_TO_FOLLOW)
.pipe(
getFirstCompletedRemoteData(),
map((bitstreamsRD: RemoteData<PaginatedList<Bitstream>>) => bitstreamsRD.payload),
map((paginatedList: PaginatedList<Bitstream>) => paginatedList.page),
switchMap((bitstreams: Bitstream[]) => bitstreams),
switchMap((bitstream: Bitstream) => bitstream.format.pipe(
getFirstSucceededRemoteDataPayload(),
map((format: BitstreamFormat) => format)
)),
map((format: BitstreamFormat) => {
if (format.mimetype.includes('image')) {
count++;
}
return count;
}),
last()
getImageCount(item: Item, bitstreamDataService: BitstreamDataService, bundleDataService: BundleDataService):
Observable<number> {
let count = 0;
return bundleDataService.findAllByItem(item).pipe(
getFirstCompletedRemoteData(),
map((bundlesRD: RemoteData<PaginatedList<Bundle>>) => {
return bundlesRD.payload;
}),
map((paginatedList: PaginatedList<Bundle>) => paginatedList.page),
switchMap((bundles: Bundle[]) => bundles),
filter((b: Bundle) => this.isIiifBundle(b.name)),
mergeMap((bundle: Bundle) => {
return bitstreamDataService.findAllByItemAndBundleName(item, bundle.name, {
currentPage: 1,
elementsPerPage: 5
}, true, true, ...this.LINKS_TO_FOLLOW).pipe(
getFirstCompletedRemoteData(),
map((bitstreamsRD: RemoteData<PaginatedList<Bitstream>>) => {
return bitstreamsRD.payload;
}),
map((paginatedList: PaginatedList<Bitstream>) => paginatedList.page),
switchMap((bitstreams: Bitstream[]) => bitstreams),
switchMap((bitstream: Bitstream) => bitstream.format.pipe(
getFirstCompletedRemoteData(),
map((formatRD: RemoteData<BitstreamFormat>) => {
return formatRD.payload;
}),
map((format: BitstreamFormat) => {
if (format.mimetype.includes('image')) {
count++;
}
return count;
}),
)
)
);
}),
last()
);
}
isIiifBundle(bundleName: string): boolean {
return !(
bundleName === 'OtherContent' ||
bundleName === 'LICENSE' ||
bundleName === 'THUMBNAIL' ||
bundleName === 'TEXT' ||
bundleName === 'METADATA' ||
bundleName === 'CC-LICENSE' ||
bundleName === 'BRANDED_PREVIEW'
);
}
}

View File

@@ -8,15 +8,14 @@ import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { AuthService } from '../../core/auth/auth.service';
import { DSpaceObject } from '../../core/shared/dspace-object.model';
import { NotificationsService } from '../../shared/notifications/notifications.service';
import { NotificationOptions } from '../../shared/notifications/models/notification-options.model';
import { UploaderOptions } from '../../shared/uploader/uploader-options.model';
import { HALEndpointService } from '../../core/shared/hal-endpoint.service';
import { NotificationType } from '../../shared/notifications/models/notification-type';
import { hasValue } from '../../shared/empty.util';
import { SearchResult } from '../../shared/search/models/search-result.model';
import { CollectionSelectorComponent } from '../collection-selector/collection-selector.component';
import { UploaderComponent } from '../../shared/uploader/uploader.component';
import { UploaderError } from '../../shared/uploader/uploader-error.model';
import { Router } from '@angular/router';
/**
* This component represents the whole mydspace page header
@@ -56,13 +55,15 @@ export class MyDSpaceNewSubmissionComponent implements OnDestroy, OnInit {
* @param {NotificationsService} notificationsService
* @param {TranslateService} translate
* @param {NgbModal} modalService
* @param {Router} router
*/
constructor(private authService: AuthService,
private changeDetectorRef: ChangeDetectorRef,
private halService: HALEndpointService,
private notificationsService: NotificationsService,
private translate: TranslateService,
private modalService: NgbModal) {
private modalService: NgbModal,
private router: Router) {
}
/**
@@ -87,16 +88,9 @@ export class MyDSpaceNewSubmissionComponent implements OnDestroy, OnInit {
this.uploadEnd.emit(workspaceitems);
if (workspaceitems.length === 1) {
const options = new NotificationOptions();
options.timeOut = 0;
const link = '/workspaceitems/' + workspaceitems[0].id + '/edit';
this.notificationsService.notificationWithAnchor(
NotificationType.Success,
options,
link,
'mydspace.general.text-here',
'mydspace.upload.upload-successful',
'here');
// To avoid confusion and ambiguity, redirect the user on the publication page.
this.router.navigateByUrl(link);
} else if (workspaceitems.length > 1) {
this.notificationsService.success(null, this.translate.get('mydspace.upload.upload-multiple-successful', {qty: workspaceitems.length}));
}

View File

@@ -4,7 +4,7 @@ nav.navbar {
}
/** Mobile menu styling **/
@media screen and (max-width: map-get($grid-breakpoints, md)) {
@media screen and (max-width: map-get($grid-breakpoints, md)-0.02) {
.navbar {
width: 100vw;
background-color: var(--bs-white);
@@ -26,7 +26,7 @@ nav.navbar {
/* TODO remove when https://github.com/twbs/bootstrap/issues/24726 is fixed */
.navbar-expand-md.navbar-container {
@media screen and (max-width: map-get($grid-breakpoints, md)) {
@media screen and (max-width: map-get($grid-breakpoints, md)-0.02) {
> .container {
padding: 0 var(--bs-spacer);
}

View File

@@ -74,6 +74,19 @@ describe('ProfilePageSecurityFormComponent', () => {
expect(component.passwordValue.emit).toHaveBeenCalledWith('new-password');
}));
it('should emit the value on password change with current password for profile-page', fakeAsync(() => {
spyOn(component.passwordValue, 'emit');
spyOn(component.currentPasswordValue, 'emit');
component.FORM_PREFIX = 'profile.security.form.';
component.ngOnInit();
component.formGroup.patchValue({password: 'new-password'});
component.formGroup.patchValue({'current-password': 'current-password'});
tick(300);
expect(component.passwordValue.emit).toHaveBeenCalledWith('new-password');
expect(component.currentPasswordValue.emit).toHaveBeenCalledWith('current-password');
}));
});
});
});

View File

@@ -27,6 +27,10 @@ export class ProfilePageSecurityFormComponent implements OnInit {
* Emits the value of the password
*/
@Output() passwordValue = new EventEmitter<string>();
/**
* Emits the value of the current-password
*/
@Output() currentPasswordValue = new EventEmitter<string>();
/**
* The form's input models
@@ -70,6 +74,14 @@ export class ProfilePageSecurityFormComponent implements OnInit {
}
ngOnInit(): void {
if (this.FORM_PREFIX === 'profile.security.form.') {
this.formModel.unshift(new DynamicInputModel({
id: 'current-password',
name: 'current-password',
inputType: 'password',
required: true
}));
}
if (this.passwordCanBeEmpty) {
this.formGroup = this.formService.createFormGroup(this.formModel,
{ validators: [this.checkPasswordsEqual] });
@@ -94,6 +106,9 @@ export class ProfilePageSecurityFormComponent implements OnInit {
debounceTime(300),
).subscribe((valueChange) => {
this.passwordValue.emit(valueChange.password);
if (this.FORM_PREFIX === 'profile.security.form.') {
this.currentPasswordValue.emit(valueChange['current-password']);
}
}));
}

View File

@@ -24,6 +24,7 @@
[FORM_PREFIX]="'profile.security.form.'"
(isInvalid)="setInvalid($event)"
(passwordValue)="setPasswordValue($event)"
(currentPasswordValue)="setCurrentPasswordValue($event)"
></ds-profile-page-security-form>
</div>
</div>

View File

@@ -180,7 +180,7 @@ describe('ProfilePageComponent', () => {
beforeEach(() => {
component.setPasswordValue('');
component.setCurrentPasswordValue('current-password');
result = component.updateSecurity();
});
@@ -199,6 +199,7 @@ describe('ProfilePageComponent', () => {
beforeEach(() => {
component.setPasswordValue('test');
component.setInvalid(true);
component.setCurrentPasswordValue('current-password');
result = component.updateSecurity();
});
@@ -215,8 +216,11 @@ describe('ProfilePageComponent', () => {
beforeEach(() => {
component.setPasswordValue('testest');
component.setInvalid(false);
component.setCurrentPasswordValue('current-password');
operations = [{ op: 'add', path: '/password', value: 'testest' }];
operations = [
{ 'op': 'add', 'path': '/password', 'value': { 'new_password': 'testest', 'current_password': 'current-password' } }
];
result = component.updateSecurity();
});
@@ -228,6 +232,28 @@ describe('ProfilePageComponent', () => {
expect(epersonService.patch).toHaveBeenCalledWith(user, operations);
});
});
describe('when password is filled in, and is valid but return 403', () => {
let result;
let operations;
it('should return call epersonService.patch', (done) => {
epersonService.patch.and.returnValue(observableOf(Object.assign(new RestResponse(false, 403, 'Error'))));
component.setPasswordValue('testest');
component.setInvalid(false);
component.setCurrentPasswordValue('current-password');
operations = [
{ 'op': 'add', 'path': '/password', 'value': {'new_password': 'testest', 'current_password': 'current-password' }}
];
result = component.updateSecurity();
epersonService.patch(user, operations).subscribe((response) => {
expect(response.statusCode).toEqual(403);
done();
});
expect(epersonService.patch).toHaveBeenCalledWith(user, operations);
expect(result).toEqual(true);
});
});
});
describe('canChangePassword$', () => {

View File

@@ -67,6 +67,10 @@ export class ProfilePageComponent implements OnInit {
* The password filled in, in the security form
*/
private password: string;
/**
* The current-password filled in, in the security form
*/
private currentPassword: string;
/**
* The authenticated user
@@ -138,15 +142,14 @@ export class ProfilePageComponent implements OnInit {
*/
updateSecurity() {
const passEntered = isNotEmpty(this.password);
if (this.invalidSecurity) {
this.notificationsService.error(this.translate.instant(this.PASSWORD_NOTIFICATIONS_PREFIX + 'error.general'));
}
if (!this.invalidSecurity && passEntered) {
const operation = {op: 'add', path: '/password', value: this.password} as Operation;
this.epersonService.patch(this.currentUser, [operation]).pipe(
getFirstCompletedRemoteData()
).subscribe((response: RemoteData<EPerson>) => {
const operations = [
{ 'op': 'add', 'path': '/password', 'value': { 'new_password': this.password, 'current_password': this.currentPassword } }
] as Operation[];
this.epersonService.patch(this.currentUser, operations).pipe(getFirstCompletedRemoteData()).subscribe((response: RemoteData<EPerson>) => {
if (response.hasSucceeded) {
this.notificationsService.success(
this.translate.instant(this.PASSWORD_NOTIFICATIONS_PREFIX + 'success.title'),
@@ -154,7 +157,8 @@ export class ProfilePageComponent implements OnInit {
);
} else {
this.notificationsService.error(
this.translate.instant(this.PASSWORD_NOTIFICATIONS_PREFIX + 'error.title'), response.errorMessage
this.translate.instant(this.PASSWORD_NOTIFICATIONS_PREFIX + 'error.title'),
this.translate.instant(this.PASSWORD_NOTIFICATIONS_PREFIX + 'error.change-failed')
);
}
});
@@ -170,6 +174,14 @@ export class ProfilePageComponent implements OnInit {
this.password = $event;
}
/**
* Set the current-password value based on the value emitted from the security form
* @param $event
*/
setCurrentPasswordValue($event: string) {
this.currentPassword = $event;
}
/**
* Submit of the security form that triggers the updateProfile method
*/

View File

@@ -41,6 +41,11 @@ export class CreateProfileComponent implements OnInit {
userInfoForm: FormGroup;
activeLangs: LangConfig[];
/**
* Prefix for the notification messages of this security form
*/
NOTIFICATIONS_PREFIX = 'register-page.create-profile.submit.';
constructor(
private translateService: TranslateService,
private ePersonDataService: EPersonDataService,
@@ -161,13 +166,12 @@ export class CreateProfileComponent implements OnInit {
getFirstCompletedRemoteData(),
).subscribe((rd: RemoteData<EPerson>) => {
if (rd.hasSucceeded) {
this.notificationsService.success(this.translateService.get('register-page.create-profile.submit.success.head'),
this.translateService.get('register-page.create-profile.submit.success.content'));
this.notificationsService.success(this.translateService.get(this.NOTIFICATIONS_PREFIX + 'success.head'),
this.translateService.get(this.NOTIFICATIONS_PREFIX + 'success.content'));
this.store.dispatch(new AuthenticateAction(this.email, this.password));
this.router.navigate(['/home']);
} else {
this.notificationsService.error(this.translateService.get('register-page.create-profile.submit.error.head'),
this.translateService.get('register-page.create-profile.submit.error.content'));
this.notificationsService.error(this.translateService.get(this.NOTIFICATIONS_PREFIX + 'error.head'), rd.errorMessage);
}
});
}

View File

@@ -13,6 +13,8 @@ export function getMockObjectCacheService(): ObjectCacheService {
'hasByUUID',
'hasByHref',
'getRequestUUIDBySelfLink',
'addDependency',
'removeDependents',
]);
}

View File

@@ -0,0 +1,33 @@
import { Component, Input } from '@angular/core';
import { ThemedComponent } from '../../theme-support/themed.component';
import { SearchSettingsComponent } from './search-settings.component';
import { SortOptions } from '../../../core/cache/models/sort-options.model';
/**
* Themed wrapper for SearchSettingsComponent
*/
@Component({
selector: 'ds-themed-search-settings',
styleUrls: [],
templateUrl: '../../theme-support/themed.component.html',
})
export class ThemedSearchSettingsComponent extends ThemedComponent<SearchSettingsComponent> {
@Input() currentSortOption: SortOptions;
@Input() sortOptionsList: SortOptions[];
protected inAndOutputNames: (keyof SearchSettingsComponent & keyof this)[] = [
'currentSortOption', 'sortOptionsList'];
protected getComponentName(): string {
return 'SearchSettingsComponent';
}
protected importThemedComponent(themeName: string): Promise<any> {
return import(`../../../../themes/${themeName}/app/shared/search/search-settings/search-settings.component`);
}
protected importUnthemedComponent(): Promise<any> {
return import('./search-settings.component');
}
}

View File

@@ -21,7 +21,8 @@
[currentConfiguration]="configuration"
[refreshFilters]="refreshFilters"
[inPlaceSearch]="inPlaceSearch"></ds-search-filters>
<ds-search-settings [currentSortOption]="currentSortOption" [sortOptionsList]="sortOptionsList"></ds-search-settings>
<ds-themed-search-settings [currentSortOption]="currentSortOption"
[sortOptionsList]="sortOptionsList"></ds-themed-search-settings>
</div>
</div>
</div>

View File

@@ -30,6 +30,7 @@ import { SearchResultsComponent } from './search-results/search-results.componen
import { SearchComponent } from './search.component';
import { ThemedSearchComponent } from './themed-search.component';
import { ThemedSearchResultsComponent } from './search-results/themed-search-results.component';
import { ThemedSearchSettingsComponent } from './search-settings/themed-search-settings.component';
const COMPONENTS = [
SearchComponent,
@@ -55,6 +56,7 @@ const COMPONENTS = [
ConfigurationSearchPageComponent,
ThemedConfigurationSearchPageComponent,
ThemedSearchResultsComponent,
ThemedSearchSettingsComponent,
];
const ENTRY_COMPONENTS = [

View File

@@ -127,19 +127,18 @@ describe('ThumbnailComponent', () => {
});
const errorHandler = () => {
let fallbackSpy;
let setSrcSpy;
beforeEach(() => {
fallbackSpy = spyOn(comp, 'showFallback').and.callThrough();
// disconnect error handler to be sure it's only called once
const img = fixture.debugElement.query(By.css('img.thumbnail-content'));
img.nativeNode.onerror = null;
comp.ngOnChanges();
setSrcSpy = spyOn(comp, 'setSrc').and.callThrough();
});
describe('retry with authentication token', () => {
beforeEach(() => {
// disconnect error handler to be sure it's only called once
const img = fixture.debugElement.query(By.css('img.thumbnail-content'));
img.nativeNode.onerror = null;
});
it('should remember that it already retried once', () => {
expect(comp.retriedWithToken).toBeFalse();
comp.errorHandler();
@@ -153,7 +152,7 @@ describe('ThumbnailComponent', () => {
it('should fall back to default', () => {
comp.errorHandler();
expect(fallbackSpy).toHaveBeenCalled();
expect(setSrcSpy).toHaveBeenCalledWith(comp.defaultImage);
});
});
@@ -172,11 +171,9 @@ describe('ThumbnailComponent', () => {
if ((comp.thumbnail as RemoteData<Bitstream>)?.hasFailed) {
// If we failed to retrieve the Bitstream in the first place, fall back to the default
expect(comp.src$.getValue()).toBe(null);
expect(fallbackSpy).toHaveBeenCalled();
expect(setSrcSpy).toHaveBeenCalledWith(comp.defaultImage);
} else {
expect(comp.src$.getValue()).toBe(CONTENT + '?authentication-token=fake');
expect(fallbackSpy).not.toHaveBeenCalled();
expect(setSrcSpy).toHaveBeenCalledWith(CONTENT + '?authentication-token=fake');
}
});
});
@@ -189,8 +186,7 @@ describe('ThumbnailComponent', () => {
it('should fall back to default', () => {
comp.errorHandler();
expect(comp.src$.getValue()).toBe(null);
expect(fallbackSpy).toHaveBeenCalled();
expect(setSrcSpy).toHaveBeenCalledWith(comp.defaultImage);
// We don't need to check authorization if we failed to retrieve the Bitstreamin the first place
if (!(comp.thumbnail as RemoteData<Bitstream>)?.hasFailed) {
@@ -210,7 +206,7 @@ describe('ThumbnailComponent', () => {
comp.errorHandler();
expect(authService.isAuthenticated).not.toHaveBeenCalled();
expect(fileService.retrieveFileDownloadLink).not.toHaveBeenCalled();
expect(fallbackSpy).toHaveBeenCalled();
expect(setSrcSpy).toHaveBeenCalledWith(comp.defaultImage);
});
});
};
@@ -263,21 +259,23 @@ describe('ThumbnailComponent', () => {
comp.thumbnail = thumbnail;
});
it('should display an image', () => {
comp.ngOnChanges();
fixture.detectChanges();
const image: HTMLElement = fixture.debugElement.query(By.css('img')).nativeElement;
expect(image.getAttribute('src')).toBe(thumbnail._links.content.href);
describe('if content can be loaded', () => {
it('should display an image', () => {
comp.ngOnChanges();
fixture.detectChanges();
const image: HTMLElement = fixture.debugElement.query(By.css('img')).nativeElement;
expect(image.getAttribute('src')).toBe(thumbnail._links.content.href);
});
it('should include the alt text', () => {
comp.ngOnChanges();
fixture.detectChanges();
const image: HTMLElement = fixture.debugElement.query(By.css('img')).nativeElement;
expect(image.getAttribute('alt')).toBe('TRANSLATED ' + comp.alt);
});
});
it('should include the alt text', () => {
comp.ngOnChanges();
fixture.detectChanges();
const image: HTMLElement = fixture.debugElement.query(By.css('img')).nativeElement;
expect(image.getAttribute('alt')).toBe('TRANSLATED ' + comp.alt);
});
describe('when there is no thumbnail', () => {
describe('if content can\'t be loaded', () => {
errorHandler();
});
});
@@ -296,36 +294,42 @@ describe('ThumbnailComponent', () => {
};
});
describe('when there is a thumbnail', () => {
describe('if RemoteData succeeded', () => {
beforeEach(() => {
comp.thumbnail = createSuccessfulRemoteDataObject(thumbnail);
});
it('should display an image', () => {
comp.ngOnChanges();
fixture.detectChanges();
const image: HTMLElement = de.query(By.css('img')).nativeElement;
expect(image.getAttribute('src')).toBe(thumbnail._links.content.href);
describe('if content can be loaded', () => {
it('should display an image', () => {
comp.ngOnChanges();
fixture.detectChanges();
const image: HTMLElement = de.query(By.css('img')).nativeElement;
expect(image.getAttribute('src')).toBe(thumbnail._links.content.href);
});
it('should display the alt text', () => {
comp.ngOnChanges();
fixture.detectChanges();
const image: HTMLElement = de.query(By.css('img')).nativeElement;
expect(image.getAttribute('alt')).toBe('TRANSLATED ' + comp.alt);
});
});
it('should display the alt text', () => {
comp.ngOnChanges();
fixture.detectChanges();
const image: HTMLElement = de.query(By.css('img')).nativeElement;
expect(image.getAttribute('alt')).toBe('TRANSLATED ' + comp.alt);
});
describe('but it can\'t be loaded', () => {
describe('if content can\'t be loaded', () => {
errorHandler();
});
});
describe('when there is no thumbnail', () => {
describe('if RemoteData failed', () => {
beforeEach(() => {
comp.thumbnail = createFailedRemoteDataObject();
});
errorHandler();
it('should show the default image', () => {
comp.defaultImage = 'default/image.jpg';
comp.ngOnChanges();
expect(comp.src$.getValue()).toBe('default/image.jpg');
});
});
});
});

View File

@@ -12,7 +12,7 @@ import { FileService } from '../core/shared/file.service';
/**
* This component renders a given Bitstream as a thumbnail.
* One input parameter of type Bitstream is expected.
* If no Bitstream is provided, a HTML placeholder will be rendered instead.
* If no Bitstream is provided, an HTML placeholder will be rendered instead.
*/
@Component({
selector: 'ds-thumbnail',
@@ -75,11 +75,11 @@ export class ThumbnailComponent implements OnChanges {
return;
}
const thumbnail = this.bitstream;
if (hasValue(thumbnail?._links?.content?.href)) {
this.setSrc(thumbnail?._links?.content?.href);
const src = this.contentHref;
if (hasValue(src)) {
this.setSrc(src);
} else {
this.showFallback();
this.setSrc(this.defaultImage);
}
}
@@ -95,22 +95,33 @@ export class ThumbnailComponent implements OnChanges {
}
}
private get contentHref(): string | undefined {
if (this.thumbnail instanceof Bitstream) {
return this.thumbnail?._links?.content?.href;
} else if (this.thumbnail instanceof RemoteData) {
return this.thumbnail?.payload?._links?.content?.href;
}
}
/**
* Handle image download errors.
* If the image can't be loaded, try re-requesting it with an authorization token in case it's a restricted Bitstream
* Otherwise, fall back to the default image or a HTML placeholder
*/
errorHandler() {
if (!this.retriedWithToken && hasValue(this.thumbnail)) {
const src = this.src$.getValue();
const thumbnail = this.bitstream;
const thumbnailSrc = thumbnail?._links?.content?.href;
if (!this.retriedWithToken && hasValue(thumbnailSrc) && src === thumbnailSrc) {
// the thumbnail may have failed to load because it's restricted
// → retry with an authorization token
// only do this once; fall back to the default if it still fails
this.retriedWithToken = true;
const thumbnail = this.bitstream;
this.auth.isAuthenticated().pipe(
switchMap((isLoggedIn) => {
if (isLoggedIn && hasValue(thumbnail)) {
if (isLoggedIn) {
return this.authorizationService.isAuthorized(FeatureID.CanDownload, thumbnail.self);
} else {
return observableOf(false);
@@ -118,7 +129,7 @@ export class ThumbnailComponent implements OnChanges {
}),
switchMap((isAuthorized) => {
if (isAuthorized) {
return this.fileService.retrieveFileDownloadLink(thumbnail._links.content.href);
return this.fileService.retrieveFileDownloadLink(thumbnailSrc);
} else {
return observableOf(null);
}
@@ -130,27 +141,17 @@ export class ThumbnailComponent implements OnChanges {
// Otherwise, fall back to the default image right now
this.setSrc(url);
} else {
this.showFallback();
this.setSrc(this.defaultImage);
}
});
} else {
this.showFallback();
}
}
/**
* To be called when the requested thumbnail could not be found
* - If the current src is not the default image, try that first
* - If this was already the case and the default image could not be found either,
* show an HTML placecholder by setting src to null
*
* Also stops the loading animation.
*/
showFallback() {
if (this.src$.getValue() !== this.defaultImage) {
this.setSrc(this.defaultImage);
} else {
this.setSrc(null);
if (src !== this.defaultImage) {
// we failed to get thumbnail (possibly retried with a token but failed again)
this.setSrc(this.defaultImage);
} else {
// we have failed to retrieve the default image, fall back to the placeholder
this.setSrc(null);
}
}
}

View File

@@ -2764,8 +2764,6 @@
"mydspace.description": "",
"mydspace.general.text-here": "here",
"mydspace.messages.controller-help": "Select this option to send a message to item's submitter.",
"mydspace.messages.description-placeholder": "Insert your message here...",
@@ -2842,8 +2840,6 @@
"mydspace.upload.upload-multiple-successful": "{{qty}} new workspace items created.",
"mydspace.upload.upload-successful": "New workspace item created. Click {{here}} for edit it.",
"mydspace.view-btn": "View",
@@ -3111,12 +3107,16 @@
"profile.security.form.label.passwordrepeat": "Retype to confirm",
"profile.security.form.label.current-password": "Current password",
"profile.security.form.notifications.success.content": "Your changes to the password were saved.",
"profile.security.form.notifications.success.title": "Password saved",
"profile.security.form.notifications.error.title": "Error changing passwords",
"profile.security.form.notifications.error.change-failed": "An error occurred while trying to change the password. Please check if the current password is correct.",
"profile.security.form.notifications.error.not-same": "The provided passwords are not the same.",
"profile.security.form.notifications.error.general": "Please fill required fields of security form.",

View File

@@ -3627,9 +3627,6 @@
// "mydspace.description": "",
"mydspace.description": "",
// "mydspace.general.text-here": "here",
"mydspace.general.text-here": "ici",
// "mydspace.messages.controller-help": "Select this option to send a message to item's submitter.",
"mydspace.messages.controller-help": "Sélectionner cette option pour envoyer un message au déposant.",
@@ -3744,9 +3741,6 @@
// "mydspace.upload.upload-multiple-successful": "{{qty}} new workspace items created.",
"mydspace.upload.upload-multiple-successful": "{{qty}} nouveaux Items créés dans l'espace de travail.",
// "mydspace.upload.upload-successful": "New workspace item created. Click {{here}} for edit it.",
"mydspace.upload.upload-successful": "Nouvel item créé dans l'espace de travail. Cliquer {{here}} pour l'éditer.",
// "mydspace.view-btn": "View",
"mydspace.view-btn": "Afficher",

File diff suppressed because it is too large Load Diff

View File

@@ -10,6 +10,7 @@ describe('Config Util', () => {
expect(appConfig.cache.msToLive.default).toEqual(15 * 60 * 1000); // 15 minute
expect(appConfig.ui.rateLimiter.windowMs).toEqual(1 * 60 * 1000); // 1 minute
expect(appConfig.ui.rateLimiter.max).toEqual(500);
expect(appConfig.ui.useProxies).toEqual(true);
expect(appConfig.submission.autosave.metadata).toEqual([]);
@@ -25,6 +26,8 @@ describe('Config Util', () => {
};
appConfig.ui.rateLimiter = rateLimiter;
appConfig.ui.useProxies = false;
const autoSaveMetadata = [
'dc.author',
'dc.title'
@@ -44,6 +47,7 @@ describe('Config Util', () => {
expect(environment.cache.msToLive.default).toEqual(msToLive);
expect(environment.ui.rateLimiter.windowMs).toEqual(rateLimiter.windowMs);
expect(environment.ui.rateLimiter.max).toEqual(rateLimiter.max);
expect(environment.ui.useProxies).toEqual(false);
expect(environment.submission.autosave.metadata[0]).toEqual(autoSaveMetadata[0]);
expect(environment.submission.autosave.metadata[1]).toEqual(autoSaveMetadata[1]);

View File

@@ -39,7 +39,10 @@ export class DefaultAppConfig implements AppConfig {
rateLimiter: {
windowMs: 1 * 60 * 1000, // 1 minute
max: 500 // limit each IP to 500 requests per windowMs
}
},
// Trust X-FORWARDED-* headers from proxies
useProxies: true,
};
// The REST API server settings

View File

@@ -11,4 +11,6 @@ export class UIServerConfig extends ServerConfig {
max: number;
};
// Trust X-FORWARDED-* headers from proxies
useProxies: boolean;
}

View File

@@ -25,7 +25,8 @@ export const environment: BuildConfig = {
rateLimiter: {
windowMs: 1 * 60 * 1000, // 1 minute
max: 500 // limit each IP to 500 requests per windowMs
}
},
useProxies: true,
},
// The REST API server settings.

View File

@@ -0,0 +1,31 @@
/**
* The contents of this file are subject to the license and copyright
* detailed in the LICENSE_ATMIRE and NOTICE_ATMIRE files at the root of the source
* tree and available online at
*
* https://www.atmire.com/software-license/
*/
import { Component } from '@angular/core';
import {
SearchSettingsComponent as BaseComponent,
} from '../../../../../../app/shared/search/search-settings/search-settings.component';
import { SEARCH_CONFIG_SERVICE } from '../../../../../../app/my-dspace-page/my-dspace-page.component';
import { SearchConfigurationService } from '../../../../../../app/core/shared/search/search-configuration.service';
@Component({
selector: 'ds-search-settings',
// styleUrls: ['./search-settings.component.scss'],
styleUrls: ['../../../../../../app/shared/search/search-settings/search-settings.component.scss'],
// templateUrl: './search-settings.component.html',
templateUrl: '../../../../../../app/shared/search/search-settings/search-settings.component.html',
providers: [
{
provide: SEARCH_CONFIG_SERVICE,
useClass: SearchConfigurationService
}
]
})
export class SearchSettingsComponent extends BaseComponent {}

View File

@@ -99,6 +99,7 @@ import {
import { LoadingComponent } from './app/shared/loading/loading.component';
import { SearchResultsComponent } from './app/shared/search/search-results/search-results.component';
import { AdminSidebarComponent } from './app/admin/admin-sidebar/admin-sidebar.component';
import { SearchSettingsComponent } from './app/shared/search/search-settings/search-settings.component';
import {
CommunityPageSubCommunityListComponent
} from './app/community-page/sub-community-list/community-page-sub-community-list.component';
@@ -152,6 +153,7 @@ const DECLARATIONS = [
LoadingComponent,
SearchResultsComponent,
AdminSidebarComponent,
SearchSettingsComponent
];
@NgModule({

View File

@@ -6,7 +6,7 @@ nav.navbar {
}
/** Mobile menu styling **/
@media screen and (max-width: map-get($grid-breakpoints, md)) {
@media screen and (max-width: map-get($grid-breakpoints, md)-0.02) {
.navbar {
width: 100%;
background-color: var(--bs-white);
@@ -28,7 +28,7 @@ nav.navbar {
/* TODO remove when https://github.com/twbs/bootstrap/issues/24726 is fixed */
.navbar-expand-md.navbar-container {
@media screen and (max-width: map-get($grid-breakpoints, md)) {
@media screen and (max-width: map-get($grid-breakpoints, md)-0.02) {
> .container {
padding: 0 var(--bs-spacer);
a.navbar-brand {