This is the codeAbility Sharing Platform! Learn more about the codeAbility Sharing Platform.

Skip to content
Snippets Groups Projects
Commit 6bb78b6a authored by Michael Breu's avatar Michael Breu :speech_balloon:
Browse files

Intermediate commit

parent b344e03d
Branches
No related merge requests found
Showing
with 354 additions and 120 deletions
......@@ -39,7 +39,7 @@ public class WatchListEntry implements Serializable {
private String exerciseName;
@ManyToOne(optional = false)
// @NotNull
@NotNull
@JsonIgnoreProperties(value = "watchListEntries", allowSetters = true)
private UserWatchList watchlist;
......
package at.ac.uibk.gitsearch.service;
import at.ac.uibk.gitsearch.domain.WatchListEntry;
import at.ac.uibk.gitsearch.repository.UserWatchListRepository;
import at.ac.uibk.gitsearch.repository.WatchListEntryRepository;
import at.ac.uibk.gitsearch.repository.search.WatchListEntrySearchRepository;
import at.ac.uibk.gitsearch.service.dto.WatchListEntryDTO;
......@@ -13,7 +14,9 @@ import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import static org.elasticsearch.index.query.QueryBuilders.*;
......@@ -27,15 +30,20 @@ public class WatchListEntryService {
private final Logger log = LoggerFactory.getLogger(WatchListEntryService.class);
private final WatchListEntryRepository watchListEntryRepository;
private final UserWatchListRepository userWatchListRepository;
private final WatchListEntryMapper watchListEntryMapper;
private final WatchListEntrySearchRepository watchListEntrySearchRepository;
public WatchListEntryService(WatchListEntryRepository watchListEntryRepository, WatchListEntryMapper watchListEntryMapper, WatchListEntrySearchRepository watchListEntrySearchRepository) {
public WatchListEntryService(WatchListEntryRepository watchListEntryRepository,
UserWatchListRepository userWatchListRepository,
WatchListEntryMapper watchListEntryMapper,
WatchListEntrySearchRepository watchListEntrySearchRepository) {
this.watchListEntryRepository = watchListEntryRepository;
this.watchListEntryMapper = watchListEntryMapper;
this.watchListEntrySearchRepository = watchListEntrySearchRepository;
this.userWatchListRepository = userWatchListRepository;
}
/**
......@@ -91,6 +99,15 @@ public class WatchListEntryService {
watchListEntrySearchRepository.deleteById(id);
}
/**
* Delete the watchListEntry by id.
*
* @param id the id of the entity.
*/
public void deleteInWatchlist(Long watchListId, String exerciseId) {
final List<WatchListEntry> entries = watchListEntryRepository.getEntriesbyWatchlistAndExerciseId(watchListId, exerciseId);
entries.forEach(en -> delete(en.getId()));
}
/**
* Search for the watchListEntry corresponding to the query.
*
......@@ -104,4 +121,17 @@ public class WatchListEntryService {
return watchListEntrySearchRepository.search(queryStringQuery(query), pageable)
.map(watchListEntryMapper::toDto);
}
/**
* Search for the watchListEntry for a watchlist.
*
* @param query the query of the search.
* @param pageable the pagination information.
* @return the list of entities.
*/
@Transactional(readOnly = true)
public List<WatchListEntryDTO> getEntriesForWatchlist(Long watchlistId) {
return watchListEntryMapper.toDto(watchListEntryRepository.getEntriesbyWatchlist(watchlistId));
}
}
package at.ac.uibk.gitsearch.web.rest;
import at.ac.uibk.gitsearch.service.UserWatchListService;
import at.ac.uibk.gitsearch.web.rest.errors.BadRequestAlertException;
import at.ac.uibk.gitsearch.service.dto.UserWatchListDTO;
import at.ac.uibk.gitsearch.service.dto.UserWatchListCriteria;
import at.ac.uibk.gitsearch.service.UserWatchListQueryService;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import static org.elasticsearch.index.query.QueryBuilders.*;
import at.ac.uibk.gitsearch.security.jwt.TokenProvider;
import at.ac.uibk.gitsearch.service.UserService;
import at.ac.uibk.gitsearch.service.UserWatchListQueryService;
import at.ac.uibk.gitsearch.service.UserWatchListService;
import at.ac.uibk.gitsearch.service.dto.UserWatchListCriteria;
import at.ac.uibk.gitsearch.service.dto.UserWatchListDTO;
import at.ac.uibk.gitsearch.web.rest.errors.BadRequestAlertException;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
/**
* REST controller for managing {@link at.ac.uibk.gitsearch.domain.UserWatchList}.
......@@ -44,13 +52,19 @@ public class UserWatchListResource {
@Value("${jhipster.clientApp.name}")
private String applicationName;
private final UserService userService;
private final UserWatchListService userWatchListService;
private final UserWatchListQueryService userWatchListQueryService;
public UserWatchListResource(UserWatchListService userWatchListService, UserWatchListQueryService userWatchListQueryService) {
private final TokenProvider tokenProvider;
public UserWatchListResource(UserWatchListService userWatchListService, UserWatchListQueryService userWatchListQueryService, TokenProvider tokenProvider, UserService userService) {
this.userWatchListService = userWatchListService;
this.userWatchListQueryService = userWatchListQueryService;
this.tokenProvider = tokenProvider;
this.userService = userService;
}
/**
......@@ -73,6 +87,36 @@ public class UserWatchListResource {
.body(result);
}
/**
* {@code POST /user-watch-lists} : Create a new userWatchList.
*
* @param userWatchListDTO the userWatchListDTO to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new userWatchListDTO, or with status {@code 400 (Bad Request)} if the userWatchList has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/currentuser-watch-lists")
public ResponseEntity<UserWatchListDTO> createWatchListForCurrentUser(@Valid @RequestBody UserWatchListDTO userWatchListDTO) throws URISyntaxException {
log.debug("REST request to save UserWatchList for current User: {}", userWatchListDTO);
if (userWatchListDTO.getId() != null) {
throw new BadRequestAlertException("A new userWatchList cannot already have an ID", ENTITY_NAME, "idexists");
}
final Optional<User> currentUser = tokenProvider.getCurrentPrincipal();
if(currentUser.isEmpty()) {
log.warn("Cannot create a watchlist {} for unknown user", userWatchListDTO.getName());
}
User springUser = currentUser.get();
final Optional<at.ac.uibk.gitsearch.domain.User> userWithAuthoritiesByLogin = userService.getUserWithAuthoritiesByLogin(springUser.getUsername());
if(userWithAuthoritiesByLogin.isEmpty()) {
log.warn("Cannot create a watchlist {} for unknown user", springUser.getUsername());
}
userWatchListDTO.setUserIdLogin(springUser.getUsername());
userWatchListDTO.setUserIdId(userWithAuthoritiesByLogin.get().getId());
UserWatchListDTO result = userWatchListService.save(userWatchListDTO);
return ResponseEntity.created(new URI("/api/user-watch-lists/" + result.getId()))
.headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, result.getId().toString()))
.body(result);
}
/**
* {@code PUT /user-watch-lists} : Updates an existing userWatchList.
*
......
package at.ac.uibk.gitsearch.web.rest;
import at.ac.uibk.gitsearch.service.WatchListEntryService;
import at.ac.uibk.gitsearch.web.rest.errors.BadRequestAlertException;
import at.ac.uibk.gitsearch.service.dto.WatchListEntryDTO;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Optional;
import java.util.stream.StreamSupport;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import static org.elasticsearch.index.query.QueryBuilders.*;
import at.ac.uibk.gitsearch.security.jwt.TokenProvider;
import at.ac.uibk.gitsearch.service.UserWatchListService;
import at.ac.uibk.gitsearch.service.WatchListEntryService;
import at.ac.uibk.gitsearch.service.dto.UserWatchListDTO;
import at.ac.uibk.gitsearch.service.dto.WatchListEntryDTO;
import at.ac.uibk.gitsearch.web.rest.errors.BadRequestAlertException;
import io.github.jhipster.web.util.HeaderUtil;
import io.github.jhipster.web.util.PaginationUtil;
import io.github.jhipster.web.util.ResponseUtil;
/**
* REST controller for managing {@link at.ac.uibk.gitsearch.domain.WatchListEntry}.
......@@ -42,9 +51,13 @@ public class WatchListEntryResource {
private String applicationName;
private final WatchListEntryService watchListEntryService;
private final UserWatchListService userWatchListService;
private final TokenProvider tokenProvider;
public WatchListEntryResource(WatchListEntryService watchListEntryService) {
public WatchListEntryResource(WatchListEntryService watchListEntryService, UserWatchListService userWatchListService, TokenProvider tokenProvider) {
this.watchListEntryService = watchListEntryService;
this.userWatchListService = userWatchListService;
this.tokenProvider = tokenProvider;
}
/**
......@@ -66,6 +79,44 @@ public class WatchListEntryResource {
.body(result);
}
/**
* {@code POST /watch-list-entries} : Create a new watchListEntry.
*
* @param watchListEntryDTO the watchListEntryDTO to create.
* @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new watchListEntryDTO, or with status {@code 400 (Bad Request)} if the watchListEntry has already an ID.
* @throws URISyntaxException if the Location URI syntax is incorrect.
*/
@PostMapping("/currentuser-watch-list-entries")
public ResponseEntity<WatchListEntryDTO> createWatchListEntryForCurrentUser(@Valid @RequestBody WatchListEntryDTO watchListEntryDTO) throws URISyntaxException {
checkAccessToWatchList(watchListEntryDTO.getWatchlistId(), watchListEntryDTO.getExerciseName());
return createWatchListEntry(watchListEntryDTO);
}
/**
* checks the access to this watchlist.
* @param watchlistId the id of the watchlist
* @param description some description of the request
* @throws BadRequestAlertException if access not allowed
*/
public void checkAccessToWatchList(final Long watchlistId, final String description) throws BadRequestAlertException {
final Optional<User> currentPrincipal = tokenProvider.getCurrentPrincipal();
if(currentPrincipal.isEmpty()) {
log.warn("Cannot find a principal for watchlist {} for exercise {}", watchlistId, description);
throw new BadRequestAlertException("Cannot find a principal", "WatchListEntry", "missingPrincipal");
}
final Optional<UserWatchListDTO> watchListO = userWatchListService.findOne(watchlistId);
if(watchListO.isEmpty()) {
log.warn("Cannot find watchlist for : {} for exercise {}", watchlistId, description);
throw new BadRequestAlertException("Cannot find watchlist", "WatchListEntry", "missingWatchlist");
}
final boolean isAccessible = watchListO.get().getUserIdLogin().equals(currentPrincipal.get().getUsername());
if(!isAccessible) {
log.warn("watchlist {} does not belong to current user", watchListO.get().getName());
throw new BadRequestAlertException("watchlist does not belong to current User", "WatchListEntry", "illegalAccess");
}
}
/**
* {@code PUT /watch-list-entries} : Updates an existing watchListEntry.
*
......@@ -135,11 +186,32 @@ public class WatchListEntryResource {
* @param pageable the pagination information.
* @return the result of the search.
*/
@GetMapping("/_search/watch-list-entries")
public ResponseEntity<List<WatchListEntryDTO>> searchWatchListEntries(@RequestParam String query, Pageable pageable) {
log.debug("REST request to search for a page of WatchListEntries for query {}", query);
Page<WatchListEntryDTO> page = watchListEntryService.search(query, pageable);
HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
@GetMapping("/_search/watch-list-entries")
public ResponseEntity<List<WatchListEntryDTO>> searchWatchListEntries(@RequestParam String query,
Pageable pageable) {
log.debug("REST request to search for a page of WatchListEntries for query {}", query);
Page<WatchListEntryDTO> page = watchListEntryService.search(query, pageable);
HttpHeaders headers = PaginationUtil
.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
return ResponseEntity.ok().headers(headers).body(page.getContent());
}
@GetMapping("/user-watch-lists/{id}/entries")
public ResponseEntity<List<WatchListEntryDTO>> getWatchListEntries(@PathVariable Long id) {
return ResponseEntity.ok().body(watchListEntryService.getEntriesForWatchlist(id));
}
@GetMapping("/currentuser-watch-lists/{id}/entries")
public ResponseEntity<List<WatchListEntryDTO>> getWatchListEntriesIfCurrentUser(@PathVariable Long id) {
checkAccessToWatchList(id, "getWatchlist");
return getWatchListEntries(id);
}
@DeleteMapping("/currentuser-watch-lists/{watchListId}/entries/{exerciseId}")
public ResponseEntity<Void> deleteWatchListEntryIfCurrentUser(
@PathVariable("watchListId") Long watchListId, @PathVariable String exerciseId) {
checkAccessToWatchList(watchListId, "deleteOnWatchlist");
watchListEntryService.deleteInWatchlist(watchListId, exerciseId);
return ResponseEntity.noContent().headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, exerciseId)).build();
}
}
......@@ -12,6 +12,7 @@ type EntityArrayResponseType = HttpResponse<IUserWatchList[]>;
@Injectable({ providedIn: 'root' })
export class UserWatchListService {
public resourceUrl = SERVER_API_URL + 'api/user-watch-lists';
public currentUserResourceUrl = SERVER_API_URL + 'api/currentuser-watch-lists';
public resourceSearchUrl = SERVER_API_URL + 'api/_search/user-watch-lists';
constructor(protected http: HttpClient) {}
......@@ -20,6 +21,10 @@ export class UserWatchListService {
return this.http.post<IUserWatchList>(this.resourceUrl, userWatchList, { observe: 'response' });
}
createForCurrentUser(userWatchList: IUserWatchList): Observable<EntityResponseType> {
return this.http.post<IUserWatchList>(this.currentUserResourceUrl, userWatchList, { observe: 'response' });
}
update(userWatchList: IUserWatchList): Observable<EntityResponseType> {
return this.http.put<IUserWatchList>(this.resourceUrl, userWatchList, { observe: 'response' });
}
......
......@@ -12,6 +12,8 @@ type EntityArrayResponseType = HttpResponse<IWatchListEntry[]>;
@Injectable({ providedIn: 'root' })
export class WatchListEntryService {
public resourceUrl = SERVER_API_URL + 'api/watch-list-entries';
public resourceUrlCurrentUser = SERVER_API_URL + 'api/currentuser-watch-list-entries';
public resourceUrlCurrentUserWL = SERVER_API_URL + 'api/currentuser-watch-lists'
public resourceSearchUrl = SERVER_API_URL + 'api/_search/watch-list-entries';
constructor(protected http: HttpClient) {}
......@@ -20,6 +22,14 @@ export class WatchListEntryService {
return this.http.post<IWatchListEntry>(this.resourceUrl, watchListEntry, { observe: 'response' });
}
createForCurrentUser(watchListEntry: IWatchListEntry): Observable<EntityResponseType> {
return this.http.post<IWatchListEntry>(this.resourceUrlCurrentUser, watchListEntry, { observe: 'response' });
}
deleteForCurrentUser(watchListId: number, exerciseId: string): Observable<HttpResponse<{}>> {
return this.http.delete(this.resourceUrlCurrentUserWL + "/" + watchListId + "/entries/" + exerciseId,
{ observe: 'response' });
}
update(watchListEntry: IWatchListEntry): Observable<EntityResponseType> {
return this.http.put<IWatchListEntry>(this.resourceUrl, watchListEntry, { observe: 'response' });
}
......@@ -41,4 +51,10 @@ export class WatchListEntryService {
const options = createRequestOption(req);
return this.http.get<IWatchListEntry[]>(this.resourceSearchUrl, { params: options, observe: 'response' });
}
getWatchListContent(id: number): Observable<EntityArrayResponseType> {
return this.http.get<IWatchListEntry[]>(this.resourceUrlCurrentUserWL + '/' + id + '/entries', { observe: 'response' });
}
}
......@@ -26,9 +26,8 @@
<div style="float: left;">
<p class="card-text" jhiTranslate="exercise.details.bookmark"></p>
</div>
<ng-template #helpBookmark> {{ 'exercise.comingSoon' | translate}}</ng-template>
<div class="form-check" style="float: right; padding-right: 10px;" [ngbTooltip]="helpBookmark">
<input class="form-check-input" type="checkbox" value="" id="card-defaultCheck1" (clicked)="handleForCurrentWatchlist(exercise)">
<div class="form-check" style="float: right; padding-right: 10px;" >
<input class="form-check-input" type="checkbox" [checked]="isOnCurrentWatchlist(exercise)" id="card-defaultCheck1" (change)="handleForCurrentWatchlist(exercise)">
<label class="form-check-label" for="card-defaultCheck1"></label>
</div>
</div> <!-- card bookmark end-->
......
......@@ -3,47 +3,50 @@ import { Exercise } from 'app/shared/model/exercise.model';
import { SearchService } from 'app/search/service/search-service';
import { Statistics } from 'app/shared/model/statistics.model';
import { WatchlistManager } from 'app/shared/watchlist/watchlist-manager';
import { IUserWatchList } from 'app/shared/model/user-watch-list.model';
@Component({
selector: 'jhi-exercise-card',
templateUrl: './exercise-card.component.html',
styleUrls: ['./exercise-card.component.scss'],
selector: 'jhi-exercise-card',
templateUrl: './exercise-card.component.html',
styleUrls: ['./exercise-card.component.scss'],
})
export class ExerciseCardComponent implements OnInit {
@Input() exercise: Exercise | undefined;
@Input() exercise: Exercise | undefined;
@Output() exerciseSelectionEvent = new EventEmitter<Exercise>();
@Output() exerciseSelectionEvent = new EventEmitter<Exercise>();
constructor(protected searchService: SearchService, private watchlistManager: WatchlistManager) {}
constructor(protected searchService: SearchService, private watchlistManager: WatchlistManager) { }
ngOnInit(): void {}
ngOnInit(): void { }
selectExercise(): void {
if (this.exercise !== undefined) {
this.exercise.views = 0;
this.exercise.downloads = 0;
this.searchService.getStatisticsForExercise(this.exercise.originalResult.project.project_id).subscribe(
(data: Statistics) => {
this.exercise!.views = data.views!;
this.exercise!.downloads = data.downloads!;
},
() => alert('Could not load exercise statistics')
);
selectExercise(): void {
if (this.exercise !== undefined) {
this.exercise.views = 0;
this.exercise.downloads = 0;
this.searchService.getStatisticsForExercise(this.exercise.originalResult.exerciseId).subscribe(
(data: Statistics) => {
this.exercise!.views = data.views!;
this.exercise!.downloads = data.downloads!;
},
() => alert('Could not load exercise statistics')
);
}
this.exerciseSelectionEvent.emit(this.exercise);
}
this.exerciseSelectionEvent.emit(this.exercise);
}
handleForCurrentWatchlist(e: Exercise) {
isOnCurrentWatchlist(e: Exercise): boolean {
return this.watchlistManager.isExerciseOnCurrentWatchlist(e);
}
handleForCurrentWatchlist(e: Exercise) {
this.watchlistManager.handleCheckForCurrentWatchlist(e);
}
/**
* correct missing image urls
*/
correctImageURL(event: Event): void {
if (event.srcElement) {
event.srcElement['src'] = '/content/img/gitLab.png';
/**
* correct missing image urls
*/
correctImageURL(event: Event): void {
if (event.srcElement) {
event.srcElement['src'] = '/content/img/gitLab.png';
}
}
}
}
......@@ -57,11 +57,11 @@ export class ExerciseDetailsComponent implements OnInit, OnDestroy {
}
public download(): void {
this.exportExercise(Number(this.exercise!.originalResult.project.project_id));
this.exportProject(Number(this.exercise!.originalResult.project.project_id));
}
exportExercise(projectId: number) {
return this.searchService.exportExercise(projectId).subscribe(
exportProject(projectId: number) {
return this.searchService.exportProject(projectId).subscribe(
(response: HttpResponse<Blob>) => {
this.jhiAlertService.success('artemisApp.programmingExercise.export.successMessage');
if (response.body) {
......
......@@ -33,8 +33,8 @@ export class SearchService {
* The file will contain all the three repositories as well as the exercise text and further metadata
* @param exerciseId
*/
exportExercise(exerciseId: number): Observable<HttpResponse<Blob>> {
return this.http.post(SERVER_API_URL + `/api/programming-exercises/${exerciseId}/export-programming-exercise`, '', {
exportProject(projectId: number): Observable<HttpResponse<Blob>> {
return this.http.post(SERVER_API_URL + `/api/programming-exercises/${projectId}/export-programming-exercise`, '', {
observe: 'response',
responseType: 'blob',
});
......
......@@ -21,6 +21,7 @@ export enum IExerciseType {
export interface Exercise {
// from metadata (required)
title: string;
license: string;
......
......@@ -3,6 +3,7 @@ import { MetadataFileDTO } from './metadata-file-dto.model';
import { UserProvidedMetadataDTO } from './user-provided-metadata-dto.model';
export interface SearchResultDTO {
exerciseId: string;
project: ProjectDTO;
file: MetadataFileDTO;
metadata: UserProvidedMetadataDTO;
......
......@@ -11,6 +11,7 @@ export class UserWatchList implements IUserWatchList {
constructor(public id?: number, public name?: string, public userIdLogin?: string, public userIdId?: number) {}
}
export class UserWatchListWithContent {
constructor(public userWatchList: UserWatchList, public exerciseIds: Array<IWatchListEntry>) {}
export interface UserWatchListWithContent {
userWatchList: IUserWatchList,
exercises: Array<IWatchListEntry>
}
import { Injectable, OnDestroy, OnInit } from '@angular/core';
import { HttpResponse } from '@angular/common/http';
import { UserWatchListService } from 'app/entities/user-watch-list/user-watch-list.service';
import { IUserWatchList } from 'app/shared/model/user-watch-list.model';
import { WatchListEntryService } from 'app/entities/watch-list-entry/watch-list-entry.service';
import { IUserWatchList, UserWatchListWithContent } from 'app/shared/model/user-watch-list.model';
import { IWatchListEntry } from 'app/shared/model/watch-list-entry.model';
import { AccountService } from 'app/core/auth/account.service';
import { Subscription } from 'rxjs';
import { Account } from 'app/core/user/account.model';
import { Exercise } from 'app/shared/model/exercise.model';
/**
......@@ -15,60 +19,118 @@ import { Account } from 'app/core/user/account.model';
@Injectable({ providedIn: 'root' })
export class WatchlistManager implements OnInit, OnDestroy {
account: Account | null = null;
authSubscription?: Subscription;
account: Account | null = null;
authSubscription?: Subscription;
myWatchLists?: IUserWatchList[];
currentWatchlist? = '';
currentWatchlist?: UserWatchListWithContent;
constructor(
protected watchListService: UserWatchListService,
protected watchListEntryService: WatchListEntryService,
private accountService: AccountService,
) {
this.authSubscription = this.accountService.getAuthenticationState().subscribe(account => {
this.account = account;
if(this.accountService.isAuthenticated()) {
this.watchListService.findMyWatchlists().subscribe((data: HttpResponse<IUserWatchList[]>) => {
if (data.body) {
this.myWatchLists = data.body;
if(this.myWatchLists.length > 0) {
this.currentWatchlist = this.myWatchLists[0].name
} else {
this.currentWatchlist = undefined;
if (this.accountService.isAuthenticated()) {
this.watchListService.findMyWatchlists().subscribe((data: HttpResponse<IUserWatchList[]>) => {
if (data.body) {
this.myWatchLists = data.body;
if (this.myWatchLists.length > 0) {
this.loadCurrentWatchList(this.myWatchLists[0]);
} else {
// if watchlist is empty, define default watchlist :-)
const userWatchlist: IUserWatchList = {
name: "Default Watchlist",
userIdLogin: this.account!.login,
userIdId: 1, // unused, replaced by
};
this.watchListService.createForCurrentUser(userWatchlist).subscribe((wl: HttpResponse<IUserWatchList>) => {
this.myWatchLists = [wl.body!];
this.loadCurrentWatchList(wl.body!)
});
this.currentWatchlist = undefined;
}
}
}
})
})
}
else { this.myWatchLists = undefined; this.currentWatchlist = undefined;}
});
else { this.myWatchLists = undefined; this.currentWatchlist = undefined; }
});
}
public isExerciseOnCurrentWatchlist(e: Exercise): boolean {
if (this.currentWatchlist) {
const elem = this.currentWatchlist.exercises.find(entry => entry.exerciseId === e.originalResult.exerciseId);
return elem !== undefined
}
return false;
}
private loadCurrentWatchList(wl: IUserWatchList) {
this.watchListEntryService.getWatchListContent(wl.id!)
.subscribe((wles: HttpResponse<IWatchListEntry[]>) => {
this.currentWatchlist = {
userWatchList: wl,
exercises: wles.body!
}
})
}
public getMyWatchLists(): IUserWatchList[] | undefined {
return this.myWatchLists;
}
public getCurrentWatchList(): string | undefined {
public getCurrentWatchList(): UserWatchListWithContent | undefined {
return this.currentWatchlist;
}
public setCurrentWatchList(watchListName:string): void {
if(this.myWatchLists) {
this.myWatchLists.forEach(watchList => {
if(watchList.name === watchListName) {
this.currentWatchlist = watchList.name;
public handleCheckForCurrentWatchlist(e: Exercise) {
if (this.currentWatchlist) {
if (!this.isExerciseOnCurrentWatchlist(e)) { // add
const watchListEntry: IWatchListEntry = {
exerciseId: e.originalResult.exerciseId,
exerciseName: e.originalResult.metadata.title,
watchlistId: this.currentWatchlist.userWatchList.id
}
// reload watchlist
this.watchListEntryService.createForCurrentUser(watchListEntry).subscribe(
(/* wle: HttpResponse<IWatchListEntry> */) => {
this.loadCurrentWatchList(this.currentWatchlist!.userWatchList);
})
} else { // delete
this.watchListEntryService.deleteForCurrentUser(this.currentWatchlist.userWatchList.id!, e.originalResult.exerciseId).subscribe(
() => { this.loadCurrentWatchList(this.currentWatchlist!.userWatchList); }
)
}
});
}
}
public setCurrentWatchList(watchListName: string): void {
if (this.myWatchLists) {
this.myWatchLists.forEach(watchList => {
if (watchList.name === watchListName) {
this.loadCurrentWatchList(watchList)
}
});
}
}
ngOnInit(): void {
}
ngOnDestroy(): void {
if (this.authSubscription) {
this.authSubscription.unsubscribe();
ngOnDestroy(): void {
if (this.authSubscription) {
this.authSubscription.unsubscribe();
}
}
}
}
<div *ngIf="getMyWatchLists() && getCurrentWatchList()" ngbDropdown>
<button class="btn btn-outline-primary mr-2" id="dropdownManual" ngbDropdownToggle ngbDropdownAnchor>{{'gitsearchApp.userWatchList.selectedList'|translate}}<br/>{{getCurrentWatchList()?getCurrentWatchList():'undefined'}}</button>
<button class="btn btn-outline-primary mr-2" id="dropdownManual" ngbDropdownToggle ngbDropdownAnchor>{{'gitsearchApp.userWatchList.selectedList'|translate}}<br/>{{getCurrentWatchList()?getCurrentWatchList()!.userWatchList.name:'undefined'}}</button>
<div ngbDropdownMenu aria-labelledby="dropdownManual" >
<button ngbDropdownItem *ngFor="let watchList of getMyWatchLists()" (click)="setCurrentWatchList(watchList.name)">{{watchList.name}}</button>
</div>
......
import { Component } from '@angular/core';
import { WatchlistManager } from 'app/shared/watchlist/watchlist-manager';
import { IUserWatchList } from 'app/shared/model/user-watch-list.model';
import { IUserWatchList, UserWatchListWithContent } from 'app/shared/model/user-watch-list.model';
@Component({
......@@ -20,7 +20,7 @@ export class WatchlistComponent {
return this.watchlistManager.getMyWatchLists();
}
getCurrentWatchList(): string | undefined {
getCurrentWatchList(): UserWatchListWithContent | undefined {
return this.watchlistManager.getCurrentWatchList();
}
......
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment