Merge branch 'master' of Software_Engineering_I/greenvironment-frontend into max_dev

master
Max_ES 5 years ago committed by Gitea
commit 8e218da95f

@ -13,7 +13,7 @@ export class AppComponent implements OnInit {
} }
ngOnInit() { ngOnInit() {
this.data.currentUserInfo.subscribe(user => { this.data.currentUser.subscribe(user => {
if (user.loggedIn !== true) { if (user.loggedIn !== true) {
this.selfservice.checkIfLoggedIn().subscribe(); this.selfservice.checkIfLoggedIn().subscribe();
} }

@ -39,7 +39,7 @@ export class FeedComponent implements OnInit {
} }
ngOnInit() { ngOnInit() {
this.data.currentUserInfo.subscribe(user => { this.data.currentUser.subscribe(user => {
this.user = user; this.user = user;
this.loggedIn = user.loggedIn; this.loggedIn = user.loggedIn;
}); });

@ -26,13 +26,13 @@
</mat-card-content> </mat-card-content>
<mat-card-actions> <mat-card-actions>
<button mat-button (click)="voteUp(post)" matTooltip="vote up" matTooltipShowDelay="500"> <button mat-button (click)="voteUp(post)" matTooltip="vote up" matTooltipShowDelay="500">
<mat-icon aria-hidden="false" color="primary" *ngIf="post.userVote == 'UPVOTE'">keyboard_arrow_up</mat-icon> <mat-icon class="voteButton voted" aria-hidden="false" color="primary" *ngIf="post.userVote == 'UPVOTE'">thumb_up</mat-icon>
<mat-icon aria-hidden="false" *ngIf="!post.userVote || post.userVote == 'DOWNVOTE'">keyboard_arrow_up</mat-icon> <mat-icon class="voteButton" aria-hidden="false" *ngIf="!post.userVote || post.userVote == 'DOWNVOTE'">thumb_up</mat-icon>
</button> </button>
{{post.upvotes}} {{post.upvotes}}
<button mat-button (click)="voteDown(post)" matTooltip="vote down" matTooltipShowDelay="500"> <button mat-button (click)="voteDown(post)" matTooltip="vote down" matTooltipShowDelay="500">
<mat-icon aria-hidden="false" color="primary" *ngIf="post.userVote == 'DOWNVOTE'">keyboard_arrow_down</mat-icon> <mat-icon class="voteButton voted" aria-hidden="false" color="primary" *ngIf="post.userVote == 'DOWNVOTE'">thumb_down</mat-icon>
<mat-icon aria-hidden="false" *ngIf="!post.userVote || post.userVote == 'UPVOTE'">keyboard_arrow_down</mat-icon> <mat-icon class="voteButton" aria-hidden="false" *ngIf="!post.userVote || post.userVote == 'UPVOTE'">thumb_down</mat-icon>
</button> </button>
{{post.downvotes}} {{post.downvotes}}
<div *ngIf="post.activity" class="activity-info"> <div *ngIf="post.activity" class="activity-info">

@ -17,7 +17,7 @@ $mat-card-header-size: 40px !default
.mat-card-content .mat-card-content
overflow: auto overflow: auto
margin: 0 margin: 0 1em
::ng-deep a ::ng-deep a
color: $primary-color color: $primary-color
.mat-card-actions .mat-card-actions
@ -65,3 +65,10 @@ $mat-card-header-size: 40px !default
.span .span
margin-left: 32px margin-left: 32px
.voteButton
scale: 0.8
transition-duration: 0.125s
&.voted
scale: 0.9

@ -12,6 +12,7 @@
<input matInput #time type="time" placeholder="choose a time"> <input matInput #time type="time" placeholder="choose a time">
</mat-form-field> </mat-form-field>
</div> </div>
<mat-error *ngIf="errorOccurred">{{getErrorMessage()}}</mat-error>
<div mat-dialog-actions> <div mat-dialog-actions>
<button mat-button (click)="onNoClick()">Cancel</button> <button mat-button (click)="onNoClick()">Cancel</button>
<button mat-button cdkFocusInitial (click)="createEvent(name.value, date.value, time.value)">Create Event</button> <button mat-button cdkFocusInitial (click)="createEvent(name.value, date.value, time.value)">Create Event</button>

@ -1,5 +1,5 @@
import {Component, OnInit, ViewChild} from '@angular/core'; import {Component, OnInit, ViewChild} from '@angular/core';
import {NavigationEnd, Router} from '@angular/router'; import {Data, NavigationEnd, Router} from '@angular/router';
import {User} from 'src/app/models/user'; import {User} from 'src/app/models/user';
import {MatSort} from '@angular/material/sort'; import {MatSort} from '@angular/material/sort';
import {RequestService} from 'src/app/services/request/request.service'; import {RequestService} from 'src/app/services/request/request.service';
@ -17,6 +17,8 @@ import {DialogGroupFileUploadComponent} from './fileUpload/fileUpload.component'
}) })
export class DialogCreateEventComponent { export class DialogCreateEventComponent {
groupId: string; groupId: string;
private errorMessage: string;
errorOccurred: boolean;
constructor( constructor(
public dialogRef: MatDialogRef<DialogCreateEventComponent>, public dialogRef: MatDialogRef<DialogCreateEventComponent>,
@ -29,15 +31,36 @@ export class DialogCreateEventComponent {
this.dialogRef.close(); this.dialogRef.close();
} }
/**
* Creates a new event
* @param name
* @param date
* @param time
*/
createEvent(name: string, date: string, time: string) { createEvent(name: string, date: string, time: string) {
name = name.trim(); name = name.trim();
this.errorOccurred = false;
if (name && date && time) { if (name && date && time) {
date = date + ' ' + time; date = date + ' ' + time;
this.group.createEvent(name, (new Date(date)).getTime().toString(), this.groupId); this.group.createEvent(name, (new Date(date)).getTime().toString(), this.groupId)
this.dialogRef.close(); .subscribe((response) => {
this.dialogRef.close();
}, (error) => {
if (error.error) {
this.errorMessage = error.error.errors[0].message;
this.errorOccurred = true;
}
});
} }
} }
/**
* Returns the error message
*/
getErrorMessage(): string {
return this.errorMessage;
}
} }
// GROUP COMPONENT // GROUP COMPONENT
@ -61,7 +84,8 @@ export class GroupComponent implements OnInit {
public dialog: MatDialog, public dialog: MatDialog,
private requestService: RequestService, private requestService: RequestService,
private data: DatasharingService, private data: DatasharingService,
private groupService: GroupService) { private groupService: GroupService,
private datasharingService: DatasharingService) {
router.events.forEach((event) => { router.events.forEach((event) => {
// check if url changes // check if url changes
if (event instanceof NavigationEnd) { if (event instanceof NavigationEnd) {
@ -79,7 +103,7 @@ export class GroupComponent implements OnInit {
ngOnInit() { ngOnInit() {
this.loading = true; this.loading = true;
this.id = this.router.url.substr(this.router.url.lastIndexOf('/') + 1); this.id = this.router.url.substr(this.router.url.lastIndexOf('/') + 1);
this.data.currentUserInfo.subscribe(user => { this.data.currentUser.subscribe(user => {
this.self = user; this.self = user;
}); });
this.groupService.getGroupData(this.id).subscribe(); this.groupService.getGroupData(this.id).subscribe();
@ -127,19 +151,22 @@ export class GroupComponent implements OnInit {
public joinGroup(group: Group) { public joinGroup(group: Group) {
group.allowedToJoinGroup = false; group.allowedToJoinGroup = false;
this.requestService.joinGroup(group); this.requestService.joinGroup(group)
.subscribe(() => {
this.datasharingService.addGroupToUser(group);
});
} }
public joinEvent(event: Event) { public joinEvent(event: Event) {
this.groupService.joinEvent(event.id).subscribe(response => { this.groupService.joinEvent(event.id).subscribe(response => {
const pEvent = response.json().data.joinEvent; const pEvent = response.data.joinEvent;
event.joined = pEvent.joined; event.joined = pEvent.joined;
}); });
} }
public leaveEvent(event: Event) { public leaveEvent(event: Event) {
this.groupService.leaveEvent(event.id).subscribe(response => { this.groupService.leaveEvent(event.id).subscribe(response => {
const pEvent = response.json().data.leaveEvent; const pEvent = response.data.leaveEvent;
event.joined = pEvent.joined; event.joined = pEvent.joined;
}); });
} }

@ -1,5 +1,5 @@
<!--on big screen--> <!--on big screen-->
<div id="content" *ngIf="media.isActive('md') || media.isActive('lg')"> <div id="content" *ngIf="!(media.isActive('sm') || media.isActive('xs'))">
<div id="chat"> <div id="chat">
<home-chatmanager [hidden]="!loggedIn"></home-chatmanager> <home-chatmanager [hidden]="!loggedIn"></home-chatmanager>
</div> </div>

@ -15,7 +15,7 @@ export class HomeComponent implements OnInit {
} }
ngOnInit() { ngOnInit() {
this.data.currentUserInfo.subscribe(user => { this.data.currentUser.subscribe(user => {
this.loggedIn = user.loggedIn; this.loggedIn = user.loggedIn;
}); });
} }

@ -51,6 +51,7 @@ export class LoginComponent implements OnInit {
}); });
}, (error: IErrorResponse) => { }, (error: IErrorResponse) => {
if (error.error) { if (error.error) {
console.error(error);
this.loginError(error); this.loginError(error);
} }
}); });

@ -5,10 +5,10 @@ import {RequestService} from '../../services/request/request.service';
import {SettingsService} from '../../services/settings/settings.service'; import {SettingsService} from '../../services/settings/settings.service';
import {environment} from 'src/environments/environment'; import {environment} from 'src/environments/environment';
import {Levellist} from 'src/app/models/levellist'; import {Levellist} from 'src/app/models/levellist';
import {Http} from '@angular/http';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {User} from 'src/app/models/user'; import {User} from 'src/app/models/user';
import {OverlayContainer} from '@angular/cdk/overlay'; import {OverlayContainer} from '@angular/cdk/overlay';
import {LoginService} from '../../services/login/login.service';
@Component({ @Component({
selector: 'app-main-navigation', selector: 'app-main-navigation',
@ -21,9 +21,10 @@ export class MainNavigationComponent implements OnInit {
public overlayContainer: OverlayContainer, public overlayContainer: OverlayContainer,
private data: DatasharingService, private data: DatasharingService,
private settingsService: SettingsService, private settingsService: SettingsService,
private requestservice: RequestService, private requestService: RequestService,
private breakpointObserver: BreakpointObserver, private breakpointObserver: BreakpointObserver,
private http: Http, private router: Router, private loginService: LoginService,
private router: Router,
) { ) {
this.overlay = overlayContainer.getContainerElement(); this.overlay = overlayContainer.getContainerElement();
} }
@ -56,7 +57,11 @@ export class MainNavigationComponent implements OnInit {
@HostBinding('class') componentCssClass; @HostBinding('class') componentCssClass;
ngOnInit() { ngOnInit() {
this.data.currentUserInfo.subscribe(user => { if (this.lighttheme && this.getThemeFromLocalStorage() === 'dark-theme') {
this.toggleTheme();
this.darkModeButtonChecked = true;
}
this.data.currentUser.subscribe(user => {
this.user = user; this.user = user;
this.loggedIn = user.loggedIn; this.loggedIn = user.loggedIn;
this.userId = user.userID; this.userId = user.userID;
@ -70,11 +75,19 @@ export class MainNavigationComponent implements OnInit {
// IF user activated darkmode and logged in after that // IF user activated darkmode and logged in after that
} else if (this.user.loggedIn && !this.user.darkmode && !this.lighttheme) { } else if (this.user.loggedIn && !this.user.darkmode && !this.lighttheme) {
this.settingsService.setDarkModeActive(true); this.settingsService.setDarkModeActive(true);
this.darkModeButtonChecked = true;
} }
this.updateLinks(); this.updateLinks();
}); });
} }
/**
* Returns the saved theme from the local storage
*/
private getThemeFromLocalStorage(): string {
return localStorage.getItem('theme');
}
toggleTheme() { toggleTheme() {
if (this.overlay.classList.contains('dark-theme')) { if (this.overlay.classList.contains('dark-theme')) {
this.overlay.classList.remove('dark-theme'); this.overlay.classList.remove('dark-theme');
@ -108,52 +121,49 @@ export class MainNavigationComponent implements OnInit {
onSetTheme(theme) { onSetTheme(theme) {
this.overlayContainer.getContainerElement().classList.add(theme); this.overlayContainer.getContainerElement().classList.add(theme);
this.componentCssClass = theme; this.componentCssClass = theme;
localStorage.setItem('theme', theme);
} }
/**
* Logs out
*/
logout() { logout() {
const url = environment.graphQLUrl; this.loginService.logout().subscribe(() => {
this.loggedIn = false;
const headers = new Headers(); const user = new User();
headers.set('Content-Type', 'application/json'); user.loggedIn = false;
const body = { this.data.currentUser.next(user);
query: `mutation { this.router.navigate(['login']);
logout
}`
};
this.http.post(url, body).subscribe(response => {
}); });
this.loggedIn = false;
const user = new User();
user.loggedIn = false;
this.data.changeUserInfo(user);
this.router.navigate(['login']);
} }
/**
* Accepts a request
* @param id
*/
acceptRequest(id: number) { acceptRequest(id: number) {
const headers = new Headers(); this.requestService.acceptRequest(id).subscribe(response => {
headers.set('Content-Type', 'application/json'); for (let i = 0; i < this.user.receivedRequests.length; i++) {
this.http.post(environment.graphQLUrl, this.requestservice.buildJsonAcceptRequest(id)) if (this.user.receivedRequests[i].senderUserID === id) {
.subscribe(response => { this.user.receivedRequests.splice(i, 1);
for (let i = 0; i < this.user.receivedRequests.length; i++) { return;
if (this.user.receivedRequests[i].senderUserID === id) {
this.user.receivedRequests.splice(i, 1);
return;
}
} }
}); }
});
} }
/**
* Denys a request
* @param id
*/
denyRequest(id: number) { denyRequest(id: number) {
const headers = new Headers(); this.requestService.denyRequest(id).subscribe(() => {
headers.set('Content-Type', 'application/json'); for (let i = 0; i < this.user.receivedRequests.length; i++) {
this.http.post(environment.graphQLUrl, this.requestservice.buildJsonDenyRequest(id)) if (this.user.receivedRequests[i].senderUserID === id) {
.subscribe(response => { this.user.receivedRequests.splice(i, 1);
for (let i = 0; i < this.user.receivedRequests.length; i++) { return;
if (this.user.receivedRequests[i].senderUserID === id) {
this.user.receivedRequests.splice(i, 1);
return;
}
} }
}); }
});
} }
} }

@ -49,7 +49,7 @@ export class ProfileComponent implements OnInit {
ngOnInit() { ngOnInit() {
this.loading = true; this.loading = true;
this.id = this.router.url.substr(this.router.url.lastIndexOf('/') + 1); this.id = this.router.url.substr(this.router.url.lastIndexOf('/') + 1);
this.data.currentUserInfo.subscribe(user => { this.data.currentUser.subscribe(user => {
this.self = user; this.self = user;
}); });
this.profileService.getUserData(this.id); this.profileService.getUserData(this.id);

@ -27,7 +27,7 @@ export class SearchComponent implements OnInit {
} }
ngOnInit() { ngOnInit() {
this.data.currentUserInfo.subscribe(user => { this.data.currentUser.subscribe(user => {
this.user = user; this.user = user;
}); });
} }

@ -16,7 +16,7 @@ export class FriendsComponent implements OnInit {
} }
ngOnInit() { ngOnInit() {
this.data.currentUserInfo.subscribe(user => { this.data.currentUser.subscribe(user => {
this.user = user; this.user = user;
}); });
} }

@ -54,7 +54,7 @@ export class GroupsComponent implements OnInit {
} }
ngOnInit() { ngOnInit() {
this.data.currentUserInfo.subscribe(user => { this.data.currentUser.subscribe(user => {
this.user = user; this.user = user;
}); });
} }

@ -1,7 +1,8 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import { HttpErrorResponse, HttpHeaders} from '@angular/common/http'; import {HttpClient, HttpHeaders} from '@angular/common/http';
import {delay, mergeMap, retryWhen} from 'rxjs/operators'; import {delay, mergeMap, retry, retryWhen} from 'rxjs/operators';
import {Observable, of, throwError} from 'rxjs'; import {Observable, of, throwError} from 'rxjs';
import {environment} from '../../environments/environment';
const httpTooManyCode = 429; const httpTooManyCode = 429;
const httpHeaderRateRetry = 'Retry-After'; const httpHeaderRateRetry = 'Retry-After';
@ -11,11 +12,33 @@ const httpHeaderRateRetry = 'Retry-After';
}) })
export abstract class BaseService { export abstract class BaseService {
protected headers: HttpHeaders; protected headers: HttpHeaders;
protected constructor() { protected constructor(protected http?: HttpClient) {
this.headers = new HttpHeaders(); this.headers = new HttpHeaders();
this.headers.set('Content-Type', 'application/json'); this.headers.set('Content-Type', 'application/json');
} }
/**
* Does a http post request
* @param url
* @param body
* @param options
* @param retryLimit
*/
protected post<T>(url: string, body: any, options?: any, retryLimit: number = 3): Observable<any | T> {
return this.http.post<T>(url, body, Object.assign({headers: this.headers}, options))
.pipe(this.retryRated(retryLimit));
}
/**
* Does a http post to the graphql url
* @param body
* @param options
* @param retryLimit
*/
protected postGraphql<T>(body: any, options?: any, retryLimit: number = 3): Observable<any | T> {
return this.post<T>(environment.graphQLUrl, body, options, retryLimit);
}
/** /**
* Retries a request according to the rate limit * Retries a request according to the rate limit
* @param maxRetry * @param maxRetry

@ -16,7 +16,7 @@ export class ChatService {
chats: Array<Chat> = []; chats: Array<Chat> = [];
constructor(private http: Http, private data: DatasharingService) { constructor(private http: Http, private data: DatasharingService) {
this.data.currentUserInfo.subscribe(user => { this.data.currentUser.subscribe(user => {
this.ownID = user.userID; this.ownID = user.userID;
}); });
} }

@ -1,37 +1,47 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs'; import {BehaviorSubject} from 'rxjs';
import {User} from '../models/user'; import {User} from '../models/user';
import {FriendInfo} from '../models/friendinfo';
import {Group} from '../models/group';
import {GroupInfo} from '../models/groupinfo';
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class DatasharingService { export class DatasharingService {
private userInfoSource = new BehaviorSubject<User>(new User()); currentUser = new BehaviorSubject<User>(new User());
private chatIDsSource = new BehaviorSubject<number[]>(new Array<number>());
currentUserInfo = this.userInfoSource.asObservable();
currentChatIDs = this.chatIDsSource.asObservable();
constructor() { constructor() {
} }
changeUserInfo(pUserInfo: User) {
this.userInfoSource.next(pUserInfo);
}
addSentRequestUserID(id: number) { addSentRequestUserID(id: number) {
const user: User = this.userInfoSource.getValue(); const user: User = this.currentUser.getValue();
user.sentRequestUserIDs.push(id); user.sentRequestUserIDs.push(id);
this.changeUserInfo(user); this.currentUser.next(user);
}
addGroupToUser(group: GroupInfo) {
const user = this.currentUser.getValue();
user.groups.push(group);
user.groupCount++;
this.currentUser.next(user);
} }
addFriendToUser(friend: FriendInfo) {
const user = this.currentUser.getValue();
user.friends.push(friend);
user.friendCount++;
this.currentUser.next(user);
}
setDarkMode(active: boolean) { setDarkMode(active: boolean) {
const user: User = this.userInfoSource.getValue(); const user: User = this.currentUser.getValue();
user.darkmode = active; user.darkmode = active;
this.changeUserInfo(user); this.currentUser.next(user);
} }
changeChatIDs(pChatIDs: number[]) { changeUserInfo(user: User) {
this.chatIDsSource.next(pChatIDs); this.currentUser.next(user);
} }
} }

@ -1,12 +0,0 @@
import {TestBed} from '@angular/core/testing';
import {DocumentService} from './document.service';
describe('DocumentService', () => {
beforeEach(() => TestBed.configureTestingModule({}));
it('should be created', () => {
const service: DocumentService = TestBed.get(DocumentService);
expect(service).toBeTruthy();
});
});

@ -1,39 +0,0 @@
import {Injectable} from '@angular/core';
import {Socket} from 'ngx-socket-io';
import {Document} from '../models/document';
@Injectable({
providedIn: 'root'
})
export class DocumentService {
currentDocument = this.socket.fromEvent<Document>('document');
documents = this.socket.fromEvent<string[]>('documents');
constructor(private socket: Socket) {
}
getDocument(id: string) {
this.socket.emit('getDoc', id);
}
newDocument() {
this.socket.emit('addDoc', {id: this.docId(), doc: ''});
}
editDocument(document: Document) {
this.socket.emit('editDoc', document);
}
private docId() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 5; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
}

@ -99,8 +99,8 @@ export enum Sort {
}) })
export class FeedService extends BaseService { export class FeedService extends BaseService {
constructor(private http: HttpClient) { constructor(http: HttpClient) {
super(); super(http);
} }
public postsAvailable = new BehaviorSubject<boolean>(true); public postsAvailable = new BehaviorSubject<boolean>(true);
@ -159,7 +159,7 @@ export class FeedService extends BaseService {
* @param body * @param body
*/ */
private createPostRequest(body: { variables: any; query: string }) { private createPostRequest(body: { variables: any; query: string }) {
return this.http.post(environment.graphQLUrl, body, {headers: this.headers}) return this.postGraphql(body, null, 0)
.pipe(tap(response => { .pipe(tap(response => {
if (this.activePostList === Sort.NEW) { if (this.activePostList === Sort.NEW) {
const updatedPosts = this.posts.getValue(); const updatedPosts = this.posts.getValue();
@ -180,7 +180,7 @@ export class FeedService extends BaseService {
} }
}; };
return this.http.post(environment.graphQLUrl, body, {headers: this.headers}).pipe(this.retryRated()); return this.postGraphql(body);
} }
/** /**
@ -194,7 +194,7 @@ export class FeedService extends BaseService {
} }
}; };
return this.http.post(environment.graphQLUrl, body, {headers: this.headers}).pipe(this.retryRated()); return this.postGraphql(body);
} }
/** /**

@ -29,8 +29,8 @@ export class GroupService extends BaseService {
public group: BehaviorSubject<Group> = new BehaviorSubject(new Group()); public group: BehaviorSubject<Group> = new BehaviorSubject(new Group());
constructor(private http: HttpClient) { constructor(http: HttpClient) {
super(); super(http);
} }
/** /**
@ -70,8 +70,7 @@ export class GroupService extends BaseService {
} }
}; };
this.http.post(environment.graphQLUrl, body, {headers: this.headers}) return this.postGraphql(body, null, 0)
.pipe(this.retryRated())
.pipe(tap(response => { .pipe(tap(response => {
const event = new Event(); const event = new Event();
event.assignFromResponse(response.data.createEvent); event.assignFromResponse(response.data.createEvent);
@ -82,8 +81,6 @@ export class GroupService extends BaseService {
} }
public joinEvent(eventId: string) { public joinEvent(eventId: string) {
const headers = new Headers();
headers.set('Content-Type', 'application/json');
const body = { const body = {
query: `mutation($eventId: ID!) { query: `mutation($eventId: ID!) {
joinEvent(eventId: $eventId) { joinEvent(eventId: $eventId) {
@ -93,7 +90,7 @@ export class GroupService extends BaseService {
eventId: eventId eventId: eventId
} }
}; };
return this.http.post(environment.graphQLUrl, body, {headers: this.headers}) return this.postGraphql(body)
.pipe(this.retryRated()); .pipe(this.retryRated());
} }
@ -109,16 +106,13 @@ export class GroupService extends BaseService {
eventId: eventId eventId: eventId
} }
}; };
return this.http.post(environment.graphQLUrl, body, {headers: this.headers}) return this.postGraphql(body);
.pipe(this.retryRated());
} }
public changeProfilePicture(file: any, id: number) { public changeProfilePicture(file: any, id: number) {
const formData: any = new FormData(); const formData: any = new FormData();
formData.append('groupPicture', file); formData.append('groupPicture', file);
formData.append('groupId', id); formData.append('groupId', id);
return this.http.post<IFileUploadResult>(environment.greenvironmentUrl + '/upload', formData) return this.post<IFileUploadResult>(environment.greenvironmentUrl + '/upload', formData);
.pipe(this.retryRated());
} }
} }

@ -43,13 +43,17 @@ const graphqlQuery = `mutation($email: String!, $pwHash: String!) {
} }
}`; }`;
const logoutGqlQuery = `mutation {
logout
}`;
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class LoginService extends BaseService { export class LoginService extends BaseService {
constructor(private http: HttpClient, private datasharingService: DatasharingService) { constructor(http: HttpClient, private datasharingService: DatasharingService) {
super(); super(http);
} }
/** /**
@ -66,17 +70,33 @@ export class LoginService extends BaseService {
}; };
} }
/**
* Builds a logout request
*/
public static buildLogoutBody(): any {
return {
query: logoutGqlQuery
};
}
/** /**
* Performs a login request and returns the data of the logged in user. * Performs a login request and returns the data of the logged in user.
* @param login * @param login
*/ */
public login(login: Login) { public login(login: Login) {
const body = LoginService.buildRequestBody(login); const body = LoginService.buildRequestBody(login);
return this.http.post<ILoginRequestResult>(environment.graphQLUrl, body, {headers: this.headers}) return this.postGraphql<ILoginRequestResult>(body, null, 0)
.pipe(tap(response => { .pipe(tap(response => {
const user = new User(); const user = new User();
user.assignFromResponse(response.data.login); user.assignFromResponse(response.data.login);
this.datasharingService.changeUserInfo(user); this.datasharingService.changeUserInfo(user);
})); }));
} }
/**
* Loggs out
*/
public logout() {
return this.postGraphql(LoginService.buildLogoutBody());
}
} }

@ -51,8 +51,8 @@ const graphqlGetProfileQuery = `query($userId: ID) {
}) })
export class ProfileService extends BaseService { export class ProfileService extends BaseService {
constructor(private http: HttpClient) { constructor(http: HttpClient) {
super(); super(http);
} }
public proflile: Subject<any> = new Subject(); public proflile: Subject<any> = new Subject();
@ -77,8 +77,7 @@ export class ProfileService extends BaseService {
public getUserData(userId: string) { public getUserData(userId: string) {
const headers = new Headers(); const headers = new Headers();
headers.set('Content-Type', 'application/json'); headers.set('Content-Type', 'application/json');
this.http.post(environment.graphQLUrl, ProfileService.buildGetProfileBody(userId)) this.postGraphql(ProfileService.buildGetProfileBody(userId))
.pipe(this.retryRated())
.subscribe(result => { .subscribe(result => {
this.proflile.next(this.getProfileData(result)); this.proflile.next(this.getProfileData(result));
return this.proflile; return this.proflile;

@ -1,18 +1,74 @@
import {Injectable} from '@angular/core'; import {Injectable} from '@angular/core';
import {Headers, Http} from '@angular/http';
import {DatasharingService} from '../datasharing.service'; import {DatasharingService} from '../datasharing.service';
import {Router} from '@angular/router'; import {Router} from '@angular/router';
import {environment} from 'src/environments/environment';
import {User} from 'src/app/models/user'; import {User} from 'src/app/models/user';
import {GroupInfo} from 'src/app/models/groupinfo'; import {GroupInfo} from 'src/app/models/groupinfo';
import {HttpClient} from '@angular/common/http';
import {BaseService} from '../base.service';
const denyRequestGqlQuery = `mutation($id: ID!) {
denyRequest(sender: $id, type: FRIENDREQUEST)
}`;
const acceptRequestGqlQuery = `mutation($id: ID!) {
acceptRequest(sender: $id, type: FRIENDREQUEST)
}`;
const sendRequestGqlQuery = `mutation($id: ID!, $type: RequestType) {
sendRequest(receiver: $id, type: $type) {
id
}
}`;
@Injectable({ @Injectable({
providedIn: 'root' providedIn: 'root'
}) })
export class RequestService { export class RequestService extends BaseService {
constructor(http: HttpClient, private data: DatasharingService, private router: Router) {
super(http);
}
private static buildDenyRequestBody(id: number): any {
return {
query: denyRequestGqlQuery
, variables: {
id
}
};
}
private static buildAcceptRequestBody(id: number): any {
return {
query: acceptRequestGqlQuery
, variables: {
id
}
};
}
constructor(private http: Http, private data: DatasharingService, private router: Router) { private static buildJoinGroupBody(id: number): any {
return {
query: `mutation($id: ID!) {
joinGroup(id: $id) {
id
}
}`
, variables: {
id
}
};
}
private static buildSendRequestBody(id: number, type: String): any {
return {
query: sendRequestGqlQuery
, variables: {
id,
type
}
};
} }
public isAllowedToSendRequest(userID: number, self: User): boolean { public isAllowedToSendRequest(userID: number, self: User): boolean {
@ -55,74 +111,38 @@ export class RequestService {
return true; return true;
} }
/**
* Sends a send request
* @param user
*/
public sendFriendRequest(user: User) { public sendFriendRequest(user: User) {
this.data.addSentRequestUserID(user.userID); this.postGraphql(RequestService.buildSendRequestBody(user.userID, 'FRIENDREQUEST'))
const headers = new Headers(); .subscribe(() => {
headers.set('Content-Type', 'application/json'); this.data.addSentRequestUserID(user.userID);
this.http.post(environment.graphQLUrl, this.buildJsonRequest(user.userID, 'FRIENDREQUEST'))
.subscribe(response => {
}); });
} }
/**
* Joins a group
* @param group
*/
public joinGroup(group: GroupInfo) { public joinGroup(group: GroupInfo) {
const headers = new Headers(); return this.postGraphql(RequestService.buildJoinGroupBody(group.id));
headers.set('Content-Type', 'application/json');
this.http.post(environment.graphQLUrl, this.buildJsonJoinGroup(group.id))
.subscribe(response => {
});
} }
public buildJsonRequest(id_: number, type_: String): any { /**
const body = { * Accepts a request
query: `mutation($id: ID!, $type: RequestType) { * @param id
sendRequest(receiver: $id, type: $type) { */
id public acceptRequest(id: number) {
} return this.postGraphql(RequestService.buildAcceptRequestBody(id));
}`
, variables: {
id: id_,
type: type_
}
};
return body;
} }
public buildJsonJoinGroup(id_: number): any { /**
const body = { * Denys a request
query: `mutation($id: ID!) { * @param id
joinGroup(id: $id) { */
id public denyRequest(id: number) {
} return this.postGraphql(RequestService.buildDenyRequestBody(id));
}`
, variables: {
id: id_
}
};
return body;
} }
public buildJsonAcceptRequest(id_: number): any {
const body = {
query: `mutation($id: ID!) {
acceptRequest(sender: $id, type: FRIENDREQUEST)
}`
, variables: {
id: id_
}
};
return body;
}
public buildJsonDenyRequest(id_: number): any {
const body = {
query: `mutation($id: ID!) {
denyRequest(sender: $id, type: FRIENDREQUEST)
}`
, variables: {
id: id_
}
};
return body;
}
} }

@ -42,8 +42,8 @@ const graphqlQuery = `query($query: String!, $first: Int, $offset: Int) {
providedIn: 'root' providedIn: 'root'
}) })
export class SearchService extends BaseService { export class SearchService extends BaseService {
constructor(private http: HttpClient, private data: DatasharingService, private router: Router) { constructor(http: HttpClient, private data: DatasharingService, private router: Router) {
super(); super(http);
} }
/** /**
@ -102,7 +102,7 @@ export class SearchService extends BaseService {
*/ */
public search(query: string): Observable<ISearchRequestResult> { public search(query: string): Observable<ISearchRequestResult> {
const body = SearchService.buildRequestBody(query); const body = SearchService.buildRequestBody(query);
return this.http.post<ISearchRequestResult>(environment.graphQLUrl, body, {headers: this.headers}) return this.postGraphql<ISearchRequestResult>(body)
.pipe(this.retryRated()); .pipe(this.retryRated());
} }
} }

@ -41,8 +41,8 @@ const getSelfGraphqlQuery = `{
}) })
export class SelfService extends BaseService { export class SelfService extends BaseService {
constructor(private http: HttpClient, private data: DatasharingService) { constructor(http: HttpClient, private data: DatasharingService) {
super(); super(http);
} }
/** /**
@ -62,8 +62,7 @@ export class SelfService extends BaseService {
const headers = new Headers(); const headers = new Headers();
headers.set('Content-Type', 'application/json'); headers.set('Content-Type', 'application/json');
return this.http.post(url, SelfService.buildGetSelfBody(), {headers: this.headers}) return this.postGraphql(SelfService.buildGetSelfBody())
.pipe(this.retryRated())
.pipe(tap(response => { .pipe(tap(response => {
this.updateUserInfo(response); this.updateUserInfo(response);
})); }));
@ -76,7 +75,7 @@ export class SelfService extends BaseService {
public changeProfilePicture(file: any) { public changeProfilePicture(file: any) {
const formData: any = new FormData(); const formData: any = new FormData();
formData.append('profilePicture', file); formData.append('profilePicture', file);
return this.http.post<IFileUploadResult>(environment.greenvironmentUrl + '/upload', formData) return this.post<IFileUploadResult>(environment.greenvironmentUrl + '/upload', formData, null, 0)
.pipe(this.retryRated()); .pipe(this.retryRated());
} }

@ -14,8 +14,8 @@ const graphqlCreateGroupQuery = `mutation($name: String!) {
}) })
export class SocialService extends BaseService { export class SocialService extends BaseService {
constructor(private http: HttpClient) { constructor(http: HttpClient) {
super(); super(http);
} }
/** /**
@ -36,7 +36,6 @@ export class SocialService extends BaseService {
*/ */
createGroup(name: string) { createGroup(name: string) {
const body = SocialService.buildGroupCreateBody(name); const body = SocialService.buildGroupCreateBody(name);
return this.http.post(environment.graphQLUrl, body, {headers: this.headers}) return this.postGraphql(body);
.pipe(this.retryRated());
} }
} }

@ -1,7 +1,7 @@
{ {
"name": "greenvironment", "name": "greenvironment",
"short_name": "greenvironment", "short_name": "greenvironment",
"theme_color": "#1976d2", "theme_color": "#8bc34a",
"background_color": "#fafafa", "background_color": "#fafafa",
"display": "standalone", "display": "standalone",
"scope": "/", "scope": "/",

Loading…
Cancel
Save