Skip to content

Commit

Permalink
Merge pull request #38 from RitehWebTeam/matching
Browse files Browse the repository at this point in the history
Add matching functionality.
  • Loading branch information
andrezz-b authored Jan 27, 2024
2 parents b3d65ae + 7e42a73 commit 5f8ebb9
Show file tree
Hide file tree
Showing 32 changed files with 816 additions and 157 deletions.
4 changes: 4 additions & 0 deletions .github/workflows/deploy-backend.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,4 +51,8 @@ jobs:
-e CORS_ALLOWED_ORIGINS="${{vars.FRONTEND_URL}}"
-e JWT_SECRET_ACCESS="${{ secrets.JWT_SECRET_ACCESS }}"
-e JWT_SECRET_REFRESH="${{ secrets.JWT_SECRET_REFRESH }}"
-e INFOBIP_API_KEY="${{ secrets.INFOBIP_API_KEY }}"
-e INFOBIP_BASE_URL="${{ secrets.INFOBIP_BASE_URL }}"
-e INFOBIP_SENDER_EMAIL="${{ secrets.INFOBIP_SENDER_EMAIL }}"
-e INFOBIP_PHONE_NUMBER="${{ secrets.INFOBIP_PHONE_NUMBER }}"
--name rimatch-backend-container dominikkovacevic/rimatch
5 changes: 5 additions & 0 deletions backend/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,11 @@
<version>0.12.3</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.infobip</groupId>
<artifactId>infobip-api-java-client</artifactId>
<version>4.0.0</version>
</dependency>

<dependency>
<groupId>org.springframework.security</groupId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.data.mongodb.config.EnableMongoAuditing;



import java.util.Arrays;
import java.util.Collections;

@Configuration
Expand All @@ -25,7 +28,7 @@ FilterRegistrationBean<JwtAuthenticationFilter> jwtFilterRegistrationBean(){
final FilterRegistrationBean<JwtAuthenticationFilter> registrationBean = new FilterRegistrationBean<>();

registrationBean.setFilter(jwtAuthenticationFilter);
registrationBean.setUrlPatterns(Collections.singletonList("/api/users/*"));
registrationBean.setUrlPatterns(Arrays.asList("/api/users/*","/api/match/*"));
registrationBean.setOrder(1);

return registrationBean;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package com.rimatch.rimatchbackend.controller;

import com.infobip.ApiException;
import com.rimatch.rimatchbackend.dto.DisplayUserDto;
import com.rimatch.rimatchbackend.dto.MatchDto;
import com.rimatch.rimatchbackend.lib.InfobipClient;
import com.rimatch.rimatchbackend.model.Match;
import com.rimatch.rimatchbackend.model.User;
import com.rimatch.rimatchbackend.service.MatchService;
import com.rimatch.rimatchbackend.service.UserService;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("api/match")
public class MatchController {

@Autowired
MatchService matchService;

@Autowired
UserService userService;

/*@Autowired
private SendEmailLib sendEmailLib;*/

@Autowired
private InfobipClient infobipClient;

@GetMapping("/potential")
public List<DisplayUserDto> getPotentinalMatch(HttpServletRequest request){
String authToken = request.getHeader("Authorization");
User user = userService.getUserByToken(authToken);
List<DisplayUserDto> list = matchService.findPotentialMatches(user);
return list;
}

@PostMapping("/accept")
public ResponseEntity<Match> accept(HttpServletRequest request, @Valid @RequestBody MatchDto matchDto) throws ApiException {
String authToken = request.getHeader("Authorization");
User user = userService.getUserByToken(authToken);
userService.insertToSeenUserIds(user,matchDto.getUserId());

Optional<User> matchedUser = userService.getUserById(matchDto.getUserId());

Match match = matchService.findMatch(user.getId(),matchedUser.get().getId());

if(match != null){

var recepients = new ArrayList<>(List.of("dominikkovacevic6@gmail.com"));
var string = String.format("Hello %s you just matched with %s %s!",matchedUser.get().getFirstName(),user.getFirstName(),user.getLastName());
infobipClient.sendEmail(recepients,"You got a match!", string);
infobipClient.sendSms(string);
return ResponseEntity.ok(matchService.finishMatch(match,true));
}

return ResponseEntity.ok(matchService.saveMatch(user.getId(),matchDto.getUserId()));
}

@PostMapping("/reject")
public ResponseEntity<?> reject(HttpServletRequest request, @Valid @RequestBody MatchDto matchDto){
String authToken = request.getHeader("Authorization");
User user = userService.getUserByToken(authToken);

userService.insertToSeenUserIds(user,matchDto.getUserId());
Optional<User> matchedUser = userService.getUserById(matchDto.getUserId());
matchedUser.ifPresent(value -> userService.insertToSeenUserIds(value, user.getId()));

Match match = matchService.findMatch(user.getId(),matchedUser.get().getId());

if(match != null){
return ResponseEntity.ok(matchService.finishMatch(match,false));
}

return ResponseEntity.ok("Test");
}

// all matches for user sending the reuqest
@GetMapping("/all")
public ResponseEntity<List<DisplayUserDto>> getAllMatches(HttpServletRequest request){
String authToken = request.getHeader("Authorization");
User user = userService.getUserByToken(authToken);
List<DisplayUserDto> list = matchService.getAllSuccessfulMatchedUsers(user);
return ResponseEntity.ok(list);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import com.rimatch.rimatchbackend.service.UserService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
Expand All @@ -14,6 +15,9 @@

import java.util.HashMap;
import java.util.Map;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;


@RestController
@RequestMapping("api/users")
Expand All @@ -22,17 +26,17 @@ public class UserController {
@Autowired
private UserService userService;

@GetMapping("/potentional")
public ResponseEntity<?> getPotentinalMatch(HttpServletRequest request){
@GetMapping("/potential")
public ResponseEntity<?> getPotentinalMatch(HttpServletRequest request) {
String authToken = request.getHeader("Authorization");
/*
Replace with something that doesn't query a database but ok for now
*/
* Replace with something that doesn't query a database but ok for now
*/
User user = userService.getUserByToken(authToken);
User randomUser = userService.getRandomUser(user.getEmail(),user.getPreferences().getPartnerGender());
var randomUsers = userService.getRandomUser(user.getEmail(), user.getPreferences().getPartnerGender());

if (randomUser != null) {
return new ResponseEntity<>(randomUser, HttpStatus.OK);
if (randomUsers != null) {
return new ResponseEntity<>(randomUsers, HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
package com.rimatch.rimatchbackend.dto;

import com.rimatch.rimatchbackend.model.User;
import lombok.Data;

@Data
public class DisplayUserDto {

private String id;

private String firstName;

private String lastName;

private String description;

private String profileImageUrl;

private String location;

private Character gender;

private int age;

public void initDisplayUser(User user){
this.id = user.getId();
this.firstName = user.getFirstName();
this.lastName = user.getLastName();
this.description = user.getDescription();
this.profileImageUrl = user.getProfileImageUrl();
this.location = user.getLocation();
this.gender = user.getGender();
this.age = user.getAge();
}

}
15 changes: 15 additions & 0 deletions backend/src/main/java/com/rimatch/rimatchbackend/dto/MatchDto.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.rimatch.rimatchbackend.dto;

import jakarta.validation.Valid;
import lombok.Getter;
import lombok.NonNull;

@Getter
public class MatchDto {

@Valid

@NonNull
private String userId;

}
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
import lombok.Data;
import lombok.Getter;

@Getter
@Data
public class RegisterDto {
@NotNull(message = "Email field cannot be null!")
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
package com.rimatch.rimatchbackend.lib;

import com.infobip.*;
import com.infobip.api.EmailApi;
import com.infobip.api.SmsApi;
import com.infobip.model.SmsAdvancedTextualRequest;
import com.infobip.model.SmsDestination;
import com.infobip.model.SmsResponse;
import com.infobip.model.SmsTextualMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

@Component
public class InfobipClient {

@Value("${infobip.api-key}")
private String API_KEY;

@Value("${infobip.base-url}")
private String BASE_URL;

// Sender email address must be verified on the infobip portal for your account
@Value("${infobip.sender-email}")
private String SENDER_EMAIL_ADDRESS;

@Value("${infobip.phone-number}")
private String PHONE_NUMBER;

private String getSenderEmail() {
return String.format("RiMatchApp <%s>", SENDER_EMAIL_ADDRESS);
}

private EmailApi initEmailApi() {
return new EmailApi(initApiClient());
}

private SmsApi initSmsApi(){
return new SmsApi(initApiClient());
}

private ApiClient initApiClient(){
return ApiClient.forApiKey(ApiKey.from(API_KEY)).withBaseUrl(BaseUrl.from(BASE_URL)).build();
}

public void sendSms(String text){

var smsApi = initSmsApi();

SmsTextualMessage smsMessage = new SmsTextualMessage()
.from("InfoSMS")
.addDestinationsItem(new SmsDestination().to(PHONE_NUMBER))
.text(text);

SmsAdvancedTextualRequest smsMessageRequest = new SmsAdvancedTextualRequest()
.messages(List.of(smsMessage));

smsApi.sendSmsMessage(smsMessageRequest)
.executeAsync(new ApiCallback<SmsResponse>() {
@Override
public void onSuccess(SmsResponse result, int responseStatusCode, Map<String, List<String>> responseHeaders) {

}
@Override
public void onFailure(ApiException exception, int responseStatusCode, Map<String, List<String>> responseHeaders) {
}
});
}

public void sendEmail(List<String> recepientEmailAddress, String subject, String text) throws ApiException {
var sendEmailApi = initEmailApi();



try {
var emailResponse = sendEmailApi.sendEmail(recepientEmailAddress)
.from(getSenderEmail())
.subject(subject)
.text(text)
.execute();

System.out.println("Response body: " + emailResponse);

var reportsResponse = sendEmailApi.getEmailDeliveryReports().execute();
System.out.println(reportsResponse.getResults());
} catch (ApiException e) {
System.out.println("HTTP status code: " + e.responseStatusCode());
System.out.println("Response body: " + e.rawResponseBody());
throw e;
}
}
}
27 changes: 27 additions & 0 deletions backend/src/main/java/com/rimatch/rimatchbackend/model/Match.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package com.rimatch.rimatchbackend.model;

import jakarta.validation.constraints.NotBlank;
import lombok.Data;
import lombok.NonNull;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;

@Document(collection = "matches")
@Data
public class Match {

@Id
private String id;

@NonNull
@NotBlank
private String firstUserId;

@NonNull
@NotBlank
private String secondUserId;

private boolean accepted = false;

private boolean finished = false;
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
import lombok.*;

@Data
@Getter
@Setter
public class Preferences {

private int ageGroupMin;
Expand Down
Loading

0 comments on commit 5f8ebb9

Please sign in to comment.