Skip to content

Commit

Permalink
feat: content 관련 api 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
JONG-KYEONG committed Aug 13, 2024
1 parent 63a0638 commit 3d7a5db
Show file tree
Hide file tree
Showing 45 changed files with 331 additions and 4 deletions.
Binary file modified server/.gradle/8.8/executionHistory/executionHistory.bin
Binary file not shown.
Binary file modified server/.gradle/8.8/executionHistory/executionHistory.lock
Binary file not shown.
Binary file modified server/.gradle/8.8/fileHashes/fileHashes.bin
Binary file not shown.
Binary file modified server/.gradle/8.8/fileHashes/fileHashes.lock
Binary file not shown.
Binary file modified server/.gradle/8.8/fileHashes/resourceHashesCache.bin
Binary file not shown.
Binary file modified server/.gradle/buildOutputCleanup/buildOutputCleanup.lock
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
1 change: 0 additions & 1 deletion server/build/resources/main/application.properties
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,6 @@
#
#tmdb.api.key=${TMDB_API_KEY}


spring.security.oauth2.client.registration.google.client-id=240772131497-d17ho20q4gb42n5s42ncohdh5k9379rc.apps.googleusercontent.com
spring.security.oauth2.client.registration.google.client-secret=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
spring.security.oauth2.client.registration.google.redirect-uri=http://glogglogglog-env.eba-fuksumx7.ap-northeast-2.elasticbeanstalk.com/oauth2/callback/google
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file modified server/build/tmp/compileJava/previous-compilation-data.bin
Binary file not shown.
Original file line number Diff line number Diff line change
@@ -0,0 +1,122 @@
package com.example.hackathon.content.application;

import com.example.hackathon.content.dto.ContentDto;
import com.example.hackathon.content.dto.InterestContentResponse;
import com.example.hackathon.content.dto.ScrapContentResponse;
import com.example.hackathon.content.dto.SimpleContentDto;
import com.example.hackathon.dataset.domain.Data;
import com.example.hackathon.dataset.domain.DataField;
import com.example.hackathon.dataset.domain.DataFieldUser;
import com.example.hackathon.dataset.repository.DataFieldRepository;
import com.example.hackathon.dataset.repository.DataFieldUserRepository;
import com.example.hackathon.dataset.repository.DataRepository;
import com.example.hackathon.exception.BadRequestException;
import com.example.hackathon.user.model.User;
import com.example.hackathon.user.repository.UserRepository;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

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

@AllArgsConstructor
@Service
public class ContentService {
private final UserRepository userRepository;
private final DataRepository dataRepository;
private final DataFieldRepository dataFieldRepository;
private final DataFieldUserRepository dataFieldUserRepository;
public InterestContentResponse getInterestContentResponse(Long userId, Integer pagesize){
User user = userRepository.findById(userId)
.orElseThrow(() -> new BadRequestException("유저 토큰 값을 다시 확인해주세요"));
Optional<DataFieldUser> dataFieldUser = dataFieldUserRepository.findByUserId(userId);
if(dataFieldUser.isPresent()){
DataField dataField = dataFieldUser.get().getDataField();
if(dataField.getGenre().equals("") || dataField.getGenre().equals("No genres found")){
Pageable pageable = PageRequest.of(0, pagesize);
List<DataField> dataFields = dataFieldRepository.findDataFieldRandom(pageable);
List<ContentDto> contentDtos = getContentDto(dataFields, user);
return new InterestContentResponse(contentDtos);
}
else{
String[] parts = dataField.getGenre().split(",");
Pageable pageable = PageRequest.of(0, pagesize);
if (parts.length > 0) {
String firstPart = parts[0];
List<DataField> dataFields = dataFieldRepository.findDataFieldByGenre(firstPart, pageable);
List<ContentDto> contentDtos = getContentDto(dataFields, user);
return new InterestContentResponse(contentDtos);
} else {
List<DataField> dataFields = dataFieldRepository.findDataFieldByGenre(dataField.getGenre(), pageable);
List<ContentDto> contentDtos = getContentDto(dataFields, user);
return new InterestContentResponse(contentDtos);
}

}
}
else{
Pageable pageable = PageRequest.of(0, pagesize);
List<DataField> dataFields = dataFieldRepository.findDataFieldRandom(pageable);
List<ContentDto> contentDtos = getContentDto(dataFields, user);
return new InterestContentResponse(contentDtos);
}
}

public ScrapContentResponse getScrapContentResponse(Long userId){
User user = userRepository.findById(userId)
.orElseThrow(() -> new BadRequestException("유저 토큰 값을 다시 확인해주세요"));
List<DataFieldUser> dataFieldUser = dataFieldUserRepository.findListByUserId(userId);
if(dataFieldUser==null){
return new ScrapContentResponse(null);
}
else{
List<SimpleContentDto> simpleContentDtos = getSimpleContentDto(dataFieldUser, user);
return new ScrapContentResponse(simpleContentDtos);
}
}

public List<SimpleContentDto> getSimpleContentDto(List<DataFieldUser> dataFieldUsers, User user){
List<SimpleContentDto> simpleContentDtos = new ArrayList<>();
for(DataFieldUser dataFieldUser : dataFieldUsers){
DataField dataField = dataFieldUser.getDataField();
SimpleContentDto simpleContentDto = SimpleContentDto.builder()
.contentId(dataField.getId())
.contentTitle(dataField.getTitleName())
.contentImage(dataField.getImage())
.isScraped(isScraped(user, dataField))
.build();
simpleContentDtos.add(simpleContentDto);
}
return simpleContentDtos;
}

public List<ContentDto> getContentDto(List<DataField> dataFields, User user){
List<ContentDto> contentDtos = new ArrayList<>();
for(DataField dataField : dataFields){
Data data = dataRepository.findByTitle(dataField.getTitleName())
.orElseThrow(() -> new BadRequestException("작품 정보를 다시 확인해주세요"));
String[] parts = data.getAddress().split(" ");
String result = parts[0] + " " + parts[1];
ContentDto contentDto = ContentDto.builder()
.contentId(dataField.getId())
.contentTitle(dataField.getTitleName())
.contentImage(dataField.getImage())
.isScraped(isScraped(user, dataField))
.address(result)
.build();
contentDtos.add(contentDto);
}
return contentDtos;
}
public Boolean isScraped(User user, DataField dataField){
Optional<DataFieldUser> dataFieldUser = dataFieldUserRepository.findByUserAndDataField(user, dataField);
if (dataFieldUser.isEmpty())
return false;
else
return true;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
package com.example.hackathon.content.controller;

import com.example.hackathon.content.application.ContentService;
import com.example.hackathon.content.dto.InterestContentResponse;
import com.example.hackathon.content.dto.ScrapContentResponse;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@AllArgsConstructor
@RequestMapping("/api/content")
public class ContentController {
private final ContentService contentService;
@GetMapping("/interest")
@Operation(summary = "내가 관심 있어 하는 장르의 작품 리스트 + 간편 주소를 가져옵니다. " ,description = "userId와 가져올 컨텐츠 갯수를 파라미터로 넣어주세요")
public ResponseEntity<InterestContentResponse> getInterestContentResponse(@RequestParam Long userId, @RequestParam Integer pagesize) {
InterestContentResponse interestContentResponse = contentService.getInterestContentResponse(userId, pagesize);
return new ResponseEntity<>(interestContentResponse, HttpStatus.OK);
}

@GetMapping("/scrap")
@Operation(summary = "내가 찜한 작품 리스트를 가져옵니다. " ,description = "userId를 파라미터로 넣어주세요")
public ResponseEntity<ScrapContentResponse> getScrapContentResponse(@RequestParam Long userId) {
ScrapContentResponse scrapContentResponse = contentService.getScrapContentResponse(userId);
return new ResponseEntity<>(scrapContentResponse, HttpStatus.OK);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.hackathon.content.dto;

import lombok.Builder;

@Builder
public record ContentDto(
Long contentId,
String contentTitle,
String contentImage,
Boolean isScraped,
String address
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package com.example.hackathon.content.dto;

import lombok.Builder;

import java.util.List;

@Builder
public record InterestContentResponse(
List<ContentDto> contentDtos
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package com.example.hackathon.content.dto;

import lombok.Builder;

import java.util.List;
@Builder
public record ScrapContentResponse(
List<SimpleContentDto> simpleContentDtos
) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
package com.example.hackathon.content.dto;

import lombok.Builder;

@Builder
public record SimpleContentDto(
Long contentId,
String contentTitle,
String contentImage,
Boolean isScraped
) {
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,6 @@ public class DataField {
private String mediaType;
@Column(name = "image")
private String image;
@Column(name = "genre")
private String genre;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.example.hackathon.dataset.domain;

import com.example.hackathon.user.model.User;
import jakarta.persistence.*;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@Entity
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class DataFieldUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@ManyToOne(fetch = FetchType.LAZY)
private User user;
@ManyToOne(fetch = FetchType.LAZY)
private DataField dataField;
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,18 @@
package com.example.hackathon.dataset.repository;

import com.example.hackathon.dataset.domain.DataField;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface DataFieldRepository extends JpaRepository<DataField, Long> {
@Query("SELECT df FROM DataField df ORDER BY RAND()")
List<DataField> findDataFieldRandom(Pageable pageable);
@Query("SELECT df FROM DataField df WHERE df.genre LIKE %:genre% ORDER BY RAND()")
List<DataField> findDataFieldByGenre(@Param("genre")String genre , Pageable pageable);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.example.hackathon.dataset.repository;

import com.example.hackathon.dataset.domain.DataField;
import com.example.hackathon.dataset.domain.DataFieldUser;
import com.example.hackathon.user.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

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

@Repository
public interface DataFieldUserRepository extends JpaRepository<DataFieldUser, Long> {
@Query("SELECT dfu FROM DataFieldUser dfu WHERE dfu.user.id=:userId ORDER BY RAND() limit 1")
Optional<DataFieldUser> findByUserId(@Param("userId")Long userId);

@Query("SELECT dfu FROM DataFieldUser dfu WHERE dfu.user.id=:userId")
List<DataFieldUser> findListByUserId(@Param("userId")Long userId);

Optional<DataFieldUser>findByUserAndDataField(User user, DataField dataField);
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
package com.example.hackathon.dataset.repository;

import com.example.hackathon.dataset.domain.Data;
import com.example.hackathon.dataset.domain.DataFieldUser;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import java.util.Optional;

public interface DataRepository extends JpaRepository<Data, Long> {
@Query("SELECT d FROM Data d WHERE d.titleName=:title ORDER BY RAND() limit 1")
Optional<Data> findByTitle(@Param("title")String title);
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class TmdbService {
Expand All @@ -26,11 +27,11 @@ public void saveImage(){
List<DataField> dataFields = dataFieldRepository.findAll();
for(DataField dataField : dataFields){
if(dataField.getMediaType().equals("movie")){
dataField.setImage(getMovieImage(dataField.getTitleName()));
dataField.setGenre(getMovieGenres(dataField.getTitleName()));
dataFieldRepository.save(dataField);
}
else{
dataField.setImage(getTvImage(dataField.getTitleName()));
dataField.setGenre(getTvShowGenres(dataField.getTitleName()));
dataFieldRepository.save(dataField);
}
}
Expand Down Expand Up @@ -92,4 +93,67 @@ public String getMovieImage(String query) {
}
return null;
}

// TV 드라마 장르 가져오기
public String getTvShowGenres(String query) {
String searchUrl = UriComponentsBuilder.fromHttpUrl("https://api.themoviedb.org/3/search/tv")
.queryParam("api_key", apiKey)
.queryParam("query", query)
.queryParam("language", "ko-KR")
.toUriString();

Map<String, Object> searchResponse = restTemplate.getForObject(searchUrl, Map.class);

if (searchResponse != null && !((List<?>) searchResponse.get("results")).isEmpty()) {
Map<String, Object> firstResult = ((List<Map<String, Object>>) searchResponse.get("results")).get(0);
String id = String.valueOf(firstResult.get("id"));

String detailsUrl = UriComponentsBuilder.fromHttpUrl("https://api.themoviedb.org/3/tv/" + id)
.queryParam("api_key", apiKey)
.queryParam("language", "ko-KR")
.toUriString();

Map<String, Object> detailsResponse = restTemplate.getForObject(detailsUrl, Map.class);

if (detailsResponse != null && detailsResponse.get("genres") != null) {
List<Map<String, Object>> genres = (List<Map<String, Object>>) detailsResponse.get("genres");
return genres.stream()
.map(genre -> genre.get("name").toString())
.collect(Collectors.joining(", "));
}
}
return "No genres found";
}

// 영화 장르 가져오기
public String getMovieGenres(String query) {
String searchUrl = UriComponentsBuilder.fromHttpUrl("https://api.themoviedb.org/3/search/movie")
.queryParam("api_key", apiKey)
.queryParam("query", query)
.queryParam("language", "ko-KR")
.toUriString();

Map<String, Object> searchResponse = restTemplate.getForObject(searchUrl, Map.class);

if (searchResponse != null && !((List<?>) searchResponse.get("results")).isEmpty()) {
Map<String, Object> firstResult = ((List<Map<String, Object>>) searchResponse.get("results")).get(0);
String id = String.valueOf(firstResult.get("id"));

String detailsUrl = UriComponentsBuilder.fromHttpUrl("https://api.themoviedb.org/3/movie/" + id)
.queryParam("api_key", apiKey)
.queryParam("language", "ko-KR")
.toUriString();

Map<String, Object> detailsResponse = restTemplate.getForObject(detailsUrl, Map.class);

if (detailsResponse != null && detailsResponse.get("genres") != null) {
List<Map<String, Object>> genres = (List<Map<String, Object>>) detailsResponse.get("genres");
return genres.stream()
.map(genre -> genre.get("name").toString())
.collect(Collectors.joining(", "));
}
}
return "No genres found";
}

}
Loading

0 comments on commit 3d7a5db

Please sign in to comment.