Compare commits
6 Commits
293c59060c
...
v0.1.3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0f985d52a9 | ||
|
|
cdee37e341 | ||
|
|
58c0f972e2 | ||
|
|
0ad09e5b67 | ||
|
|
7a896c8c56 | ||
|
|
745913ca5b |
4
.gitignore
vendored
4
.gitignore
vendored
@@ -13,3 +13,7 @@ backend-java/.gradle/
|
|||||||
|
|
||||||
# K8s secrets (never commit)
|
# K8s secrets (never commit)
|
||||||
k8s/secrets.yaml
|
k8s/secrets.yaml
|
||||||
|
|
||||||
|
# OS / misc
|
||||||
|
.DS_Store
|
||||||
|
backend/cookies.txt
|
||||||
|
|||||||
4
backend-java/.dockerignore
Normal file
4
backend-java/.dockerignore
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
build/
|
||||||
|
.gradle/
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
@@ -1,16 +1,29 @@
|
|||||||
package com.tasteby.config;
|
package com.tasteby.config;
|
||||||
|
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.beans.factory.annotation.Value;
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.boot.context.event.ApplicationReadyEvent;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
|
||||||
|
import javax.sql.DataSource;
|
||||||
import jakarta.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
|
|
||||||
@Configuration
|
@Configuration
|
||||||
public class DataSourceConfig {
|
public class DataSourceConfig {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(DataSourceConfig.class);
|
||||||
|
|
||||||
@Value("${app.oracle.wallet-path:}")
|
@Value("${app.oracle.wallet-path:}")
|
||||||
private String walletPath;
|
private String walletPath;
|
||||||
|
|
||||||
|
private final DataSource dataSource;
|
||||||
|
|
||||||
|
public DataSourceConfig(DataSource dataSource) {
|
||||||
|
this.dataSource = dataSource;
|
||||||
|
}
|
||||||
|
|
||||||
@PostConstruct
|
@PostConstruct
|
||||||
public void configureWallet() {
|
public void configureWallet() {
|
||||||
if (walletPath != null && !walletPath.isBlank()) {
|
if (walletPath != null && !walletPath.isBlank()) {
|
||||||
@@ -18,4 +31,23 @@ public class DataSourceConfig {
|
|||||||
System.setProperty("oracle.net.wallet_location", walletPath);
|
System.setProperty("oracle.net.wallet_location", walletPath);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@EventListener(ApplicationReadyEvent.class)
|
||||||
|
public void runMigrations() {
|
||||||
|
migrate("ALTER TABLE restaurants ADD (tabling_url VARCHAR2(500))");
|
||||||
|
migrate("ALTER TABLE restaurants ADD (catchtable_url VARCHAR2(500))");
|
||||||
|
}
|
||||||
|
|
||||||
|
private void migrate(String sql) {
|
||||||
|
try (var conn = dataSource.getConnection(); var stmt = conn.createStatement()) {
|
||||||
|
stmt.execute(sql);
|
||||||
|
log.info("[MIGRATE] {}", sql);
|
||||||
|
} catch (Exception e) {
|
||||||
|
if (e.getMessage() != null && e.getMessage().contains("ORA-01430")) {
|
||||||
|
log.debug("[MIGRATE] already done: {}", sql);
|
||||||
|
} else {
|
||||||
|
log.warn("[MIGRATE] failed: {} - {}", sql, e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import com.tasteby.domain.Channel;
|
|||||||
import com.tasteby.security.AuthUtil;
|
import com.tasteby.security.AuthUtil;
|
||||||
import com.tasteby.service.CacheService;
|
import com.tasteby.service.CacheService;
|
||||||
import com.tasteby.service.ChannelService;
|
import com.tasteby.service.ChannelService;
|
||||||
|
import com.tasteby.service.YouTubeService;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
@@ -18,11 +19,14 @@ import java.util.Map;
|
|||||||
public class ChannelController {
|
public class ChannelController {
|
||||||
|
|
||||||
private final ChannelService channelService;
|
private final ChannelService channelService;
|
||||||
|
private final YouTubeService youtubeService;
|
||||||
private final CacheService cache;
|
private final CacheService cache;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
public ChannelController(ChannelService channelService, CacheService cache, ObjectMapper objectMapper) {
|
public ChannelController(ChannelService channelService, YouTubeService youtubeService,
|
||||||
|
CacheService cache, ObjectMapper objectMapper) {
|
||||||
this.channelService = channelService;
|
this.channelService = channelService;
|
||||||
|
this.youtubeService = youtubeService;
|
||||||
this.cache = cache;
|
this.cache = cache;
|
||||||
this.objectMapper = objectMapper;
|
this.objectMapper = objectMapper;
|
||||||
}
|
}
|
||||||
@@ -60,6 +64,18 @@ public class ChannelController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PostMapping("/{channelId}/scan")
|
||||||
|
public Map<String, Object> scan(@PathVariable String channelId,
|
||||||
|
@RequestParam(defaultValue = "false") boolean full) {
|
||||||
|
AuthUtil.requireAdmin();
|
||||||
|
var result = youtubeService.scanChannel(channelId, full);
|
||||||
|
if (result == null) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Channel not found");
|
||||||
|
}
|
||||||
|
cache.flush();
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
@DeleteMapping("/{channelId}")
|
@DeleteMapping("/{channelId}")
|
||||||
public Map<String, Object> delete(@PathVariable String channelId) {
|
public Map<String, Object> delete(@PathVariable String channelId) {
|
||||||
AuthUtil.requireAdmin();
|
AuthUtil.requireAdmin();
|
||||||
|
|||||||
@@ -2,27 +2,44 @@ package com.tasteby.controller;
|
|||||||
|
|
||||||
import com.fasterxml.jackson.core.type.TypeReference;
|
import com.fasterxml.jackson.core.type.TypeReference;
|
||||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import com.microsoft.playwright.*;
|
||||||
import com.tasteby.domain.Restaurant;
|
import com.tasteby.domain.Restaurant;
|
||||||
import com.tasteby.security.AuthUtil;
|
import com.tasteby.security.AuthUtil;
|
||||||
import com.tasteby.service.CacheService;
|
import com.tasteby.service.CacheService;
|
||||||
|
import com.tasteby.service.GeocodingService;
|
||||||
import com.tasteby.service.RestaurantService;
|
import com.tasteby.service.RestaurantService;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
import org.springframework.http.HttpStatus;
|
import org.springframework.http.HttpStatus;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
import org.springframework.web.server.ResponseStatusException;
|
import org.springframework.web.server.ResponseStatusException;
|
||||||
|
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
||||||
|
|
||||||
|
import java.net.URLEncoder;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ExecutorService;
|
||||||
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/api/restaurants")
|
@RequestMapping("/api/restaurants")
|
||||||
public class RestaurantController {
|
public class RestaurantController {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(RestaurantController.class);
|
||||||
|
|
||||||
private final RestaurantService restaurantService;
|
private final RestaurantService restaurantService;
|
||||||
|
private final GeocodingService geocodingService;
|
||||||
private final CacheService cache;
|
private final CacheService cache;
|
||||||
private final ObjectMapper objectMapper;
|
private final ObjectMapper objectMapper;
|
||||||
|
private final ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor();
|
||||||
|
|
||||||
public RestaurantController(RestaurantService restaurantService, CacheService cache, ObjectMapper objectMapper) {
|
public RestaurantController(RestaurantService restaurantService, GeocodingService geocodingService, CacheService cache, ObjectMapper objectMapper) {
|
||||||
this.restaurantService = restaurantService;
|
this.restaurantService = restaurantService;
|
||||||
|
this.geocodingService = geocodingService;
|
||||||
this.cache = cache;
|
this.cache = cache;
|
||||||
this.objectMapper = objectMapper;
|
this.objectMapper = objectMapper;
|
||||||
}
|
}
|
||||||
@@ -68,11 +85,43 @@ public class RestaurantController {
|
|||||||
AuthUtil.requireAdmin();
|
AuthUtil.requireAdmin();
|
||||||
var r = restaurantService.findById(id);
|
var r = restaurantService.findById(id);
|
||||||
if (r == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Restaurant not found");
|
if (r == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Restaurant not found");
|
||||||
|
|
||||||
|
// Re-geocode if name or address changed
|
||||||
|
String newName = (String) body.get("name");
|
||||||
|
String newAddress = (String) body.get("address");
|
||||||
|
boolean nameChanged = newName != null && !newName.equals(r.getName());
|
||||||
|
boolean addressChanged = newAddress != null && !newAddress.equals(r.getAddress());
|
||||||
|
if (nameChanged || addressChanged) {
|
||||||
|
String geoName = newName != null ? newName : r.getName();
|
||||||
|
String geoAddr = newAddress != null ? newAddress : r.getAddress();
|
||||||
|
var geo = geocodingService.geocodeRestaurant(geoName, geoAddr);
|
||||||
|
if (geo != null) {
|
||||||
|
body.put("latitude", geo.get("latitude"));
|
||||||
|
body.put("longitude", geo.get("longitude"));
|
||||||
|
body.put("google_place_id", geo.get("google_place_id"));
|
||||||
|
if (geo.containsKey("formatted_address")) {
|
||||||
|
body.put("address", geo.get("formatted_address"));
|
||||||
|
}
|
||||||
|
if (geo.containsKey("rating")) body.put("rating", geo.get("rating"));
|
||||||
|
if (geo.containsKey("rating_count")) body.put("rating_count", geo.get("rating_count"));
|
||||||
|
if (geo.containsKey("phone")) body.put("phone", geo.get("phone"));
|
||||||
|
if (geo.containsKey("business_status")) body.put("business_status", geo.get("business_status"));
|
||||||
|
|
||||||
|
// formatted_address에서 region 파싱 (예: "대한민국 서울특별시 강남구 ..." → "한국|서울|강남구")
|
||||||
|
String addr = (String) geo.get("formatted_address");
|
||||||
|
if (addr != null) {
|
||||||
|
body.put("region", GeocodingService.parseRegionFromAddress(addr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
restaurantService.update(id, body);
|
restaurantService.update(id, body);
|
||||||
cache.flush();
|
cache.flush();
|
||||||
return Map.of("ok", true);
|
var updated = restaurantService.findById(id);
|
||||||
|
return Map.of("ok", true, "restaurant", updated);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@DeleteMapping("/{id}")
|
@DeleteMapping("/{id}")
|
||||||
public Map<String, Object> delete(@PathVariable String id) {
|
public Map<String, Object> delete(@PathVariable String id) {
|
||||||
AuthUtil.requireAdmin();
|
AuthUtil.requireAdmin();
|
||||||
@@ -83,6 +132,232 @@ public class RestaurantController {
|
|||||||
return Map.of("ok", true);
|
return Map.of("ok", true);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 단건 테이블링 URL 검색 */
|
||||||
|
@GetMapping("/{id}/tabling-search")
|
||||||
|
public List<Map<String, Object>> tablingSearch(@PathVariable String id) {
|
||||||
|
AuthUtil.requireAdmin();
|
||||||
|
var r = restaurantService.findById(id);
|
||||||
|
if (r == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||||
|
|
||||||
|
try (Playwright pw = Playwright.create()) {
|
||||||
|
try (Browser browser = launchBrowser(pw)) {
|
||||||
|
BrowserContext ctx = newContext(browser);
|
||||||
|
Page page = newPage(ctx);
|
||||||
|
return searchTabling(page, r.getName());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[TABLING] Search failed for '{}': {}", r.getName(), e.getMessage());
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "Search failed: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 테이블링 미연결 식당 목록 */
|
||||||
|
@GetMapping("/tabling-pending")
|
||||||
|
public Map<String, Object> tablingPending() {
|
||||||
|
AuthUtil.requireAdmin();
|
||||||
|
var list = restaurantService.findWithoutTabling();
|
||||||
|
var summary = list.stream()
|
||||||
|
.map(r -> Map.of("id", (Object) r.getId(), "name", (Object) r.getName()))
|
||||||
|
.toList();
|
||||||
|
return Map.of("count", list.size(), "restaurants", summary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 벌크 테이블링 검색 (SSE) */
|
||||||
|
@PostMapping("/bulk-tabling")
|
||||||
|
public SseEmitter bulkTabling() {
|
||||||
|
AuthUtil.requireAdmin();
|
||||||
|
SseEmitter emitter = new SseEmitter(600_000L);
|
||||||
|
|
||||||
|
executor.execute(() -> {
|
||||||
|
try {
|
||||||
|
var restaurants = restaurantService.findWithoutTabling();
|
||||||
|
int total = restaurants.size();
|
||||||
|
emit(emitter, Map.of("type", "start", "total", total));
|
||||||
|
|
||||||
|
if (total == 0) {
|
||||||
|
emit(emitter, Map.of("type", "complete", "total", 0, "linked", 0, "notFound", 0));
|
||||||
|
emitter.complete();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int linked = 0;
|
||||||
|
int notFound = 0;
|
||||||
|
|
||||||
|
try (Playwright pw = Playwright.create()) {
|
||||||
|
try (Browser browser = launchBrowser(pw)) {
|
||||||
|
BrowserContext ctx = newContext(browser);
|
||||||
|
Page page = newPage(ctx);
|
||||||
|
|
||||||
|
for (int i = 0; i < total; i++) {
|
||||||
|
var r = restaurants.get(i);
|
||||||
|
emit(emitter, Map.of("type", "processing", "current", i + 1,
|
||||||
|
"total", total, "name", r.getName()));
|
||||||
|
|
||||||
|
try {
|
||||||
|
var results = searchTabling(page, r.getName());
|
||||||
|
if (!results.isEmpty()) {
|
||||||
|
String url = String.valueOf(results.get(0).get("url"));
|
||||||
|
String title = String.valueOf(results.get(0).get("title"));
|
||||||
|
restaurantService.update(r.getId(), Map.of("tabling_url", url));
|
||||||
|
linked++;
|
||||||
|
emit(emitter, Map.of("type", "done", "current", i + 1,
|
||||||
|
"name", r.getName(), "url", url, "title", title));
|
||||||
|
} else {
|
||||||
|
restaurantService.update(r.getId(), Map.of("tabling_url", "NONE"));
|
||||||
|
notFound++;
|
||||||
|
emit(emitter, Map.of("type", "notfound", "current", i + 1,
|
||||||
|
"name", r.getName()));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
notFound++;
|
||||||
|
emit(emitter, Map.of("type", "error", "current", i + 1,
|
||||||
|
"name", r.getName(), "message", e.getMessage()));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Google 봇 판정 방지 랜덤 딜레이 (5~15초)
|
||||||
|
int delay = ThreadLocalRandom.current().nextInt(5000, 15001);
|
||||||
|
log.info("[TABLING] Waiting {}ms before next search...", delay);
|
||||||
|
page.waitForTimeout(delay);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cache.flush();
|
||||||
|
emit(emitter, Map.of("type", "complete", "total", total, "linked", linked, "notFound", notFound));
|
||||||
|
emitter.complete();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[TABLING] Bulk search error", e);
|
||||||
|
emitter.completeWithError(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return emitter;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 테이블링 URL 저장 */
|
||||||
|
@PutMapping("/{id}/tabling-url")
|
||||||
|
public Map<String, Object> setTablingUrl(@PathVariable String id, @RequestBody Map<String, String> body) {
|
||||||
|
AuthUtil.requireAdmin();
|
||||||
|
var r = restaurantService.findById(id);
|
||||||
|
if (r == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||||
|
String url = body.get("tabling_url");
|
||||||
|
restaurantService.update(id, Map.of("tabling_url", url != null ? url : ""));
|
||||||
|
cache.flush();
|
||||||
|
return Map.of("ok", true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 단건 캐치테이블 URL 검색 */
|
||||||
|
@GetMapping("/{id}/catchtable-search")
|
||||||
|
public List<Map<String, Object>> catchtableSearch(@PathVariable String id) {
|
||||||
|
AuthUtil.requireAdmin();
|
||||||
|
var r = restaurantService.findById(id);
|
||||||
|
if (r == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||||
|
try (Playwright pw = Playwright.create()) {
|
||||||
|
try (Browser browser = launchBrowser(pw)) {
|
||||||
|
BrowserContext ctx = newContext(browser);
|
||||||
|
Page page = newPage(ctx);
|
||||||
|
return searchCatchtable(page, r.getName());
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[CATCHTABLE] Search failed for '{}': {}", r.getName(), e.getMessage());
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_GATEWAY, "Search failed: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 캐치테이블 미연결 식당 목록 */
|
||||||
|
@GetMapping("/catchtable-pending")
|
||||||
|
public Map<String, Object> catchtablePending() {
|
||||||
|
AuthUtil.requireAdmin();
|
||||||
|
var list = restaurantService.findWithoutCatchtable();
|
||||||
|
var summary = list.stream()
|
||||||
|
.map(r -> Map.of("id", (Object) r.getId(), "name", (Object) r.getName()))
|
||||||
|
.toList();
|
||||||
|
return Map.of("count", list.size(), "restaurants", summary);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 벌크 캐치테이블 검색 (SSE) */
|
||||||
|
@PostMapping("/bulk-catchtable")
|
||||||
|
public SseEmitter bulkCatchtable() {
|
||||||
|
AuthUtil.requireAdmin();
|
||||||
|
SseEmitter emitter = new SseEmitter(600_000L);
|
||||||
|
|
||||||
|
executor.execute(() -> {
|
||||||
|
try {
|
||||||
|
var restaurants = restaurantService.findWithoutCatchtable();
|
||||||
|
int total = restaurants.size();
|
||||||
|
emit(emitter, Map.of("type", "start", "total", total));
|
||||||
|
|
||||||
|
if (total == 0) {
|
||||||
|
emit(emitter, Map.of("type", "complete", "total", 0, "linked", 0, "notFound", 0));
|
||||||
|
emitter.complete();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int linked = 0;
|
||||||
|
int notFound = 0;
|
||||||
|
|
||||||
|
try (Playwright pw = Playwright.create()) {
|
||||||
|
try (Browser browser = launchBrowser(pw)) {
|
||||||
|
BrowserContext ctx = newContext(browser);
|
||||||
|
Page page = newPage(ctx);
|
||||||
|
|
||||||
|
for (int i = 0; i < total; i++) {
|
||||||
|
var r = restaurants.get(i);
|
||||||
|
emit(emitter, Map.of("type", "processing", "current", i + 1,
|
||||||
|
"total", total, "name", r.getName()));
|
||||||
|
|
||||||
|
try {
|
||||||
|
var results = searchCatchtable(page, r.getName());
|
||||||
|
if (!results.isEmpty()) {
|
||||||
|
String url = String.valueOf(results.get(0).get("url"));
|
||||||
|
String title = String.valueOf(results.get(0).get("title"));
|
||||||
|
restaurantService.update(r.getId(), Map.of("catchtable_url", url));
|
||||||
|
linked++;
|
||||||
|
emit(emitter, Map.of("type", "done", "current", i + 1,
|
||||||
|
"name", r.getName(), "url", url, "title", title));
|
||||||
|
} else {
|
||||||
|
restaurantService.update(r.getId(), Map.of("catchtable_url", "NONE"));
|
||||||
|
notFound++;
|
||||||
|
emit(emitter, Map.of("type", "notfound", "current", i + 1,
|
||||||
|
"name", r.getName()));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
notFound++;
|
||||||
|
emit(emitter, Map.of("type", "error", "current", i + 1,
|
||||||
|
"name", r.getName(), "message", e.getMessage()));
|
||||||
|
}
|
||||||
|
|
||||||
|
int delay = ThreadLocalRandom.current().nextInt(5000, 15001);
|
||||||
|
log.info("[CATCHTABLE] Waiting {}ms before next search...", delay);
|
||||||
|
page.waitForTimeout(delay);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
cache.flush();
|
||||||
|
emit(emitter, Map.of("type", "complete", "total", total, "linked", linked, "notFound", notFound));
|
||||||
|
emitter.complete();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[CATCHTABLE] Bulk search error", e);
|
||||||
|
emitter.completeWithError(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return emitter;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 캐치테이블 URL 저장 */
|
||||||
|
@PutMapping("/{id}/catchtable-url")
|
||||||
|
public Map<String, Object> setCatchtableUrl(@PathVariable String id, @RequestBody Map<String, String> body) {
|
||||||
|
AuthUtil.requireAdmin();
|
||||||
|
var r = restaurantService.findById(id);
|
||||||
|
if (r == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND);
|
||||||
|
String url = body.get("catchtable_url");
|
||||||
|
restaurantService.update(id, Map.of("catchtable_url", url != null ? url : ""));
|
||||||
|
cache.flush();
|
||||||
|
return Map.of("ok", true);
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/{id}/videos")
|
@GetMapping("/{id}/videos")
|
||||||
public List<Map<String, Object>> videos(@PathVariable String id) {
|
public List<Map<String, Object>> videos(@PathVariable String id) {
|
||||||
String key = cache.makeKey("restaurant_videos", id);
|
String key = cache.makeKey("restaurant_videos", id);
|
||||||
@@ -98,4 +373,127 @@ public class RestaurantController {
|
|||||||
cache.set(key, result);
|
cache.set(key, result);
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Playwright helpers ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
private Browser launchBrowser(Playwright pw) {
|
||||||
|
return pw.chromium().launch(new BrowserType.LaunchOptions()
|
||||||
|
.setHeadless(false)
|
||||||
|
.setArgs(List.of("--disable-blink-features=AutomationControlled")));
|
||||||
|
}
|
||||||
|
|
||||||
|
private BrowserContext newContext(Browser browser) {
|
||||||
|
return browser.newContext(new Browser.NewContextOptions()
|
||||||
|
.setLocale("ko-KR").setViewportSize(1280, 900));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Page newPage(BrowserContext ctx) {
|
||||||
|
Page page = ctx.newPage();
|
||||||
|
page.addInitScript("Object.defineProperty(navigator, 'webdriver', {get: () => false})");
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private List<Map<String, Object>> searchTabling(Page page, String restaurantName) {
|
||||||
|
String query = "site:tabling.co.kr " + restaurantName;
|
||||||
|
log.info("[TABLING] Searching: {}", query);
|
||||||
|
|
||||||
|
String searchUrl = "https://www.google.com/search?q=" +
|
||||||
|
URLEncoder.encode(query, StandardCharsets.UTF_8);
|
||||||
|
page.navigate(searchUrl);
|
||||||
|
page.waitForTimeout(3000);
|
||||||
|
|
||||||
|
Object linksObj = page.evaluate("""
|
||||||
|
() => {
|
||||||
|
const results = [];
|
||||||
|
const links = document.querySelectorAll('a[href]');
|
||||||
|
for (const a of links) {
|
||||||
|
const href = a.href;
|
||||||
|
if (href.includes('tabling.co.kr/restaurant/') || href.includes('tabling.co.kr/place/')) {
|
||||||
|
const title = a.closest('[data-header-feature]')?.querySelector('h3')?.textContent
|
||||||
|
|| a.querySelector('h3')?.textContent
|
||||||
|
|| a.textContent?.trim()?.substring(0, 80)
|
||||||
|
|| '';
|
||||||
|
results.push({ title, url: href });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const seen = new Set();
|
||||||
|
return results.filter(r => {
|
||||||
|
if (seen.has(r.url)) return false;
|
||||||
|
seen.add(r.url);
|
||||||
|
return true;
|
||||||
|
}).slice(0, 5);
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
|
||||||
|
List<Map<String, Object>> results = new ArrayList<>();
|
||||||
|
if (linksObj instanceof List<?> list) {
|
||||||
|
for (var item : list) {
|
||||||
|
if (item instanceof Map<?, ?> map) {
|
||||||
|
results.add(Map.of(
|
||||||
|
"title", String.valueOf(map.get("title")),
|
||||||
|
"url", String.valueOf(map.get("url"))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.info("[TABLING] Found {} results for '{}'", results.size(), restaurantName);
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private List<Map<String, Object>> searchCatchtable(Page page, String restaurantName) {
|
||||||
|
String query = "site:app.catchtable.co.kr " + restaurantName;
|
||||||
|
log.info("[CATCHTABLE] Searching: {}", query);
|
||||||
|
|
||||||
|
String searchUrl = "https://www.google.com/search?q=" +
|
||||||
|
URLEncoder.encode(query, StandardCharsets.UTF_8);
|
||||||
|
page.navigate(searchUrl);
|
||||||
|
page.waitForTimeout(3000);
|
||||||
|
|
||||||
|
Object linksObj = page.evaluate("""
|
||||||
|
() => {
|
||||||
|
const results = [];
|
||||||
|
const links = document.querySelectorAll('a[href]');
|
||||||
|
for (const a of links) {
|
||||||
|
const href = a.href;
|
||||||
|
if (href.includes('catchtable.co.kr/') && (href.includes('/dining/') || href.includes('/shop/'))) {
|
||||||
|
const title = a.closest('[data-header-feature]')?.querySelector('h3')?.textContent
|
||||||
|
|| a.querySelector('h3')?.textContent
|
||||||
|
|| a.textContent?.trim()?.substring(0, 80)
|
||||||
|
|| '';
|
||||||
|
results.push({ title, url: href });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const seen = new Set();
|
||||||
|
return results.filter(r => {
|
||||||
|
if (seen.has(r.url)) return false;
|
||||||
|
seen.add(r.url);
|
||||||
|
return true;
|
||||||
|
}).slice(0, 5);
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
|
||||||
|
List<Map<String, Object>> results = new ArrayList<>();
|
||||||
|
if (linksObj instanceof List<?> list) {
|
||||||
|
for (var item : list) {
|
||||||
|
if (item instanceof Map<?, ?> map) {
|
||||||
|
results.add(Map.of(
|
||||||
|
"title", String.valueOf(map.get("title")),
|
||||||
|
"url", String.valueOf(map.get("url"))
|
||||||
|
));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
log.info("[CATCHTABLE] Found {} results for '{}'", results.size(), restaurantName);
|
||||||
|
return results;
|
||||||
|
}
|
||||||
|
|
||||||
|
private void emit(SseEmitter emitter, Map<String, Object> data) {
|
||||||
|
try {
|
||||||
|
emitter.send(SseEmitter.event().data(objectMapper.writeValueAsString(data)));
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.debug("SSE emit error: {}", e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -103,6 +103,24 @@ public class VideoController {
|
|||||||
return Map.of("ok", true, "length", result.text().length(), "source", result.source());
|
return Map.of("ok", true, "length", result.text().length(), "source", result.source());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 클라이언트(브라우저)에서 가져온 트랜스크립트를 저장 */
|
||||||
|
@PostMapping("/{id}/upload-transcript")
|
||||||
|
public Map<String, Object> uploadTranscript(@PathVariable String id,
|
||||||
|
@RequestBody Map<String, String> body) {
|
||||||
|
AuthUtil.requireAdmin();
|
||||||
|
var video = videoService.findDetail(id);
|
||||||
|
if (video == null) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "Video not found");
|
||||||
|
|
||||||
|
String text = body.get("text");
|
||||||
|
if (text == null || text.isBlank()) {
|
||||||
|
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "text is required");
|
||||||
|
}
|
||||||
|
|
||||||
|
videoService.updateTranscript(id, text);
|
||||||
|
String source = body.getOrDefault("source", "browser");
|
||||||
|
return Map.of("ok", true, "length", text.length(), "source", source);
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/extract/prompt")
|
@GetMapping("/extract/prompt")
|
||||||
public Map<String, Object> getExtractPrompt() {
|
public Map<String, Object> getExtractPrompt() {
|
||||||
return Map.of("prompt", extractorService.getPrompt());
|
return Map.of("prompt", extractorService.getPrompt());
|
||||||
@@ -234,6 +252,34 @@ public class VideoController {
|
|||||||
if (body.containsKey(key)) restFields.put(key, body.get(key));
|
if (body.containsKey(key)) restFields.put(key, body.get(key));
|
||||||
}
|
}
|
||||||
if (!restFields.isEmpty()) {
|
if (!restFields.isEmpty()) {
|
||||||
|
// Re-geocode if name or address changed
|
||||||
|
var existing = restaurantService.findById(restaurantId);
|
||||||
|
String newName = (String) restFields.get("name");
|
||||||
|
String newAddr = (String) restFields.get("address");
|
||||||
|
boolean nameChanged = newName != null && existing != null && !newName.equals(existing.getName());
|
||||||
|
boolean addrChanged = newAddr != null && existing != null && !newAddr.equals(existing.getAddress());
|
||||||
|
if (nameChanged || addrChanged) {
|
||||||
|
String geoName = newName != null ? newName : existing.getName();
|
||||||
|
String geoAddr = newAddr != null ? newAddr : existing.getAddress();
|
||||||
|
var geo = geocodingService.geocodeRestaurant(geoName, geoAddr);
|
||||||
|
if (geo != null) {
|
||||||
|
restFields.put("latitude", geo.get("latitude"));
|
||||||
|
restFields.put("longitude", geo.get("longitude"));
|
||||||
|
restFields.put("google_place_id", geo.get("google_place_id"));
|
||||||
|
if (geo.containsKey("formatted_address")) {
|
||||||
|
restFields.put("address", geo.get("formatted_address"));
|
||||||
|
}
|
||||||
|
if (geo.containsKey("rating")) restFields.put("rating", geo.get("rating"));
|
||||||
|
if (geo.containsKey("rating_count")) restFields.put("rating_count", geo.get("rating_count"));
|
||||||
|
if (geo.containsKey("phone")) restFields.put("phone", geo.get("phone"));
|
||||||
|
if (geo.containsKey("business_status")) restFields.put("business_status", geo.get("business_status"));
|
||||||
|
// Parse region from address
|
||||||
|
String addr = (String) geo.get("formatted_address");
|
||||||
|
if (addr != null) {
|
||||||
|
restFields.put("region", GeocodingService.parseRegionFromAddress(addr));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
restaurantService.update(restaurantId, restFields);
|
restaurantService.update(restaurantId, restFields);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
|
|||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.concurrent.ExecutorService;
|
import java.util.concurrent.ExecutorService;
|
||||||
import java.util.concurrent.Executors;
|
import java.util.concurrent.Executors;
|
||||||
|
import java.util.concurrent.ThreadLocalRandom;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SSE streaming endpoints for bulk operations.
|
* SSE streaming endpoints for bulk operations.
|
||||||
@@ -26,6 +27,7 @@ public class VideoSseController {
|
|||||||
private final VideoService videoService;
|
private final VideoService videoService;
|
||||||
private final RestaurantService restaurantService;
|
private final RestaurantService restaurantService;
|
||||||
private final PipelineService pipelineService;
|
private final PipelineService pipelineService;
|
||||||
|
private final YouTubeService youTubeService;
|
||||||
private final OciGenAiService genAi;
|
private final OciGenAiService genAi;
|
||||||
private final CacheService cache;
|
private final CacheService cache;
|
||||||
private final ObjectMapper mapper;
|
private final ObjectMapper mapper;
|
||||||
@@ -34,27 +36,120 @@ public class VideoSseController {
|
|||||||
public VideoSseController(VideoService videoService,
|
public VideoSseController(VideoService videoService,
|
||||||
RestaurantService restaurantService,
|
RestaurantService restaurantService,
|
||||||
PipelineService pipelineService,
|
PipelineService pipelineService,
|
||||||
|
YouTubeService youTubeService,
|
||||||
OciGenAiService genAi,
|
OciGenAiService genAi,
|
||||||
CacheService cache,
|
CacheService cache,
|
||||||
ObjectMapper mapper) {
|
ObjectMapper mapper) {
|
||||||
this.videoService = videoService;
|
this.videoService = videoService;
|
||||||
this.restaurantService = restaurantService;
|
this.restaurantService = restaurantService;
|
||||||
this.pipelineService = pipelineService;
|
this.pipelineService = pipelineService;
|
||||||
|
this.youTubeService = youTubeService;
|
||||||
this.genAi = genAi;
|
this.genAi = genAi;
|
||||||
this.cache = cache;
|
this.cache = cache;
|
||||||
this.mapper = mapper;
|
this.mapper = mapper;
|
||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/bulk-transcript")
|
@PostMapping("/bulk-transcript")
|
||||||
public SseEmitter bulkTranscript() {
|
public SseEmitter bulkTranscript(@RequestBody(required = false) Map<String, Object> body) {
|
||||||
AuthUtil.requireAdmin();
|
AuthUtil.requireAdmin();
|
||||||
SseEmitter emitter = new SseEmitter(600_000L); // 10 min timeout
|
SseEmitter emitter = new SseEmitter(1_800_000L); // 30 min timeout
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
List<String> selectedIds = body != null && body.containsKey("ids")
|
||||||
|
? ((List<?>) body.get("ids")).stream().map(Object::toString).toList()
|
||||||
|
: null;
|
||||||
|
|
||||||
executor.execute(() -> {
|
executor.execute(() -> {
|
||||||
try {
|
try {
|
||||||
// TODO: Implement when transcript extraction is available in Java
|
var videos = selectedIds != null && !selectedIds.isEmpty()
|
||||||
emit(emitter, Map.of("type", "start", "total", 0));
|
? videoService.findVideosByIds(selectedIds)
|
||||||
emit(emitter, Map.of("type", "complete", "total", 0, "success", 0));
|
: videoService.findVideosWithoutTranscript();
|
||||||
|
int total = videos.size();
|
||||||
|
emit(emitter, Map.of("type", "start", "total", total));
|
||||||
|
|
||||||
|
if (total == 0) {
|
||||||
|
emit(emitter, Map.of("type", "complete", "total", 0, "success", 0, "failed", 0));
|
||||||
|
emitter.complete();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
int success = 0;
|
||||||
|
int failed = 0;
|
||||||
|
|
||||||
|
// Pass 1: 브라우저 우선 (봇 탐지 회피)
|
||||||
|
var apiNeeded = new ArrayList<Integer>();
|
||||||
|
try (var session = youTubeService.createBrowserSession()) {
|
||||||
|
for (int i = 0; i < total; i++) {
|
||||||
|
var v = videos.get(i);
|
||||||
|
String videoId = (String) v.get("video_id");
|
||||||
|
String title = (String) v.get("title");
|
||||||
|
String id = (String) v.get("id");
|
||||||
|
|
||||||
|
emit(emitter, Map.of("type", "processing", "index", i, "title", title, "method", "browser"));
|
||||||
|
|
||||||
|
try {
|
||||||
|
var result = youTubeService.getTranscriptWithPage(session.page(), videoId);
|
||||||
|
if (result != null) {
|
||||||
|
videoService.updateTranscript(id, result.text());
|
||||||
|
success++;
|
||||||
|
emit(emitter, Map.of("type", "done", "index", i,
|
||||||
|
"title", title, "source", result.source(),
|
||||||
|
"length", result.text().length()));
|
||||||
|
} else {
|
||||||
|
apiNeeded.add(i);
|
||||||
|
emit(emitter, Map.of("type", "skip", "index", i,
|
||||||
|
"title", title, "message", "브라우저 실패, API로 재시도 예정"));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
apiNeeded.add(i);
|
||||||
|
log.warn("[BULK-TRANSCRIPT] Browser failed for {}: {}", videoId, e.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 봇 판정 방지 랜덤 딜레이 (3~8초)
|
||||||
|
if (i < total - 1) {
|
||||||
|
int delay = ThreadLocalRandom.current().nextInt(3000, 8001);
|
||||||
|
log.info("[BULK-TRANSCRIPT] Waiting {}ms before next...", delay);
|
||||||
|
session.page().waitForTimeout(delay);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pass 2: 브라우저 실패분만 API로 재시도
|
||||||
|
if (!apiNeeded.isEmpty()) {
|
||||||
|
emit(emitter, Map.of("type", "api_pass", "count", apiNeeded.size()));
|
||||||
|
for (int i : apiNeeded) {
|
||||||
|
var v = videos.get(i);
|
||||||
|
String videoId = (String) v.get("video_id");
|
||||||
|
String title = (String) v.get("title");
|
||||||
|
String id = (String) v.get("id");
|
||||||
|
|
||||||
|
emit(emitter, Map.of("type", "processing", "index", i, "title", title, "method", "api"));
|
||||||
|
|
||||||
|
try {
|
||||||
|
var result = youTubeService.getTranscriptApi(videoId, "auto");
|
||||||
|
if (result != null) {
|
||||||
|
videoService.updateTranscript(id, result.text());
|
||||||
|
success++;
|
||||||
|
emit(emitter, Map.of("type", "done", "index", i,
|
||||||
|
"title", title, "source", result.source(),
|
||||||
|
"length", result.text().length()));
|
||||||
|
} else {
|
||||||
|
failed++;
|
||||||
|
videoService.updateStatus(id, "no_transcript");
|
||||||
|
emit(emitter, Map.of("type", "error", "index", i,
|
||||||
|
"title", title, "message", "자막을 찾을 수 없음"));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
failed++;
|
||||||
|
videoService.updateStatus(id, "no_transcript");
|
||||||
|
log.error("[BULK-TRANSCRIPT] API error for {}: {}", videoId, e.getMessage());
|
||||||
|
emit(emitter, Map.of("type", "error", "index", i,
|
||||||
|
"title", title, "message", e.getMessage()));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
emit(emitter, Map.of("type", "complete", "total", total, "success", success, "failed", failed));
|
||||||
emitter.complete();
|
emitter.complete();
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Bulk transcript error", e);
|
log.error("Bulk transcript error", e);
|
||||||
@@ -65,13 +160,20 @@ public class VideoSseController {
|
|||||||
}
|
}
|
||||||
|
|
||||||
@PostMapping("/bulk-extract")
|
@PostMapping("/bulk-extract")
|
||||||
public SseEmitter bulkExtract() {
|
public SseEmitter bulkExtract(@RequestBody(required = false) Map<String, Object> body) {
|
||||||
AuthUtil.requireAdmin();
|
AuthUtil.requireAdmin();
|
||||||
SseEmitter emitter = new SseEmitter(600_000L);
|
SseEmitter emitter = new SseEmitter(600_000L);
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
List<String> selectedIds = body != null && body.containsKey("ids")
|
||||||
|
? ((List<?>) body.get("ids")).stream().map(Object::toString).toList()
|
||||||
|
: null;
|
||||||
|
|
||||||
executor.execute(() -> {
|
executor.execute(() -> {
|
||||||
try {
|
try {
|
||||||
var rows = videoService.findVideosForBulkExtract();
|
var rows = selectedIds != null && !selectedIds.isEmpty()
|
||||||
|
? videoService.findVideosForExtractByIds(selectedIds)
|
||||||
|
: videoService.findVideosForBulkExtract();
|
||||||
|
|
||||||
int total = rows.size();
|
int total = rows.size();
|
||||||
int totalRestaurants = 0;
|
int totalRestaurants = 0;
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ public class Restaurant {
|
|||||||
private String phone;
|
private String phone;
|
||||||
private String website;
|
private String website;
|
||||||
private String googlePlaceId;
|
private String googlePlaceId;
|
||||||
|
private String tablingUrl;
|
||||||
|
private String catchtableUrl;
|
||||||
private String businessStatus;
|
private String businessStatus;
|
||||||
private Double rating;
|
private Double rating;
|
||||||
private Integer ratingCount;
|
private Integer ratingCount;
|
||||||
|
|||||||
@@ -55,6 +55,10 @@ public interface RestaurantMapper {
|
|||||||
|
|
||||||
void updateFoodsMentioned(@Param("id") String id, @Param("foods") String foods);
|
void updateFoodsMentioned(@Param("id") String id, @Param("foods") String foods);
|
||||||
|
|
||||||
|
List<Restaurant> findWithoutTabling();
|
||||||
|
|
||||||
|
List<Restaurant> findWithoutCatchtable();
|
||||||
|
|
||||||
List<Map<String, Object>> findForRemapCuisine();
|
List<Map<String, Object>> findForRemapCuisine();
|
||||||
|
|
||||||
List<Map<String, Object>> findForRemapFoods();
|
List<Map<String, Object>> findForRemapFoods();
|
||||||
|
|||||||
@@ -68,6 +68,10 @@ public interface VideoMapper {
|
|||||||
|
|
||||||
List<Map<String, Object>> findVideosWithoutTranscript();
|
List<Map<String, Object>> findVideosWithoutTranscript();
|
||||||
|
|
||||||
|
List<Map<String, Object>> findVideosByIds(@Param("ids") List<String> ids);
|
||||||
|
|
||||||
|
List<Map<String, Object>> findVideosForExtractByIds(@Param("ids") List<String> ids);
|
||||||
|
|
||||||
void updateVideoRestaurantFields(@Param("videoId") String videoId,
|
void updateVideoRestaurantFields(@Param("videoId") String videoId,
|
||||||
@Param("restaurantId") String restaurantId,
|
@Param("restaurantId") String restaurantId,
|
||||||
@Param("foodsJson") String foodsJson,
|
@Param("foodsJson") String foodsJson,
|
||||||
|
|||||||
@@ -131,6 +131,34 @@ public class GeocodingService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse Korean address into region format "나라|시/도|구/군".
|
||||||
|
* Example: "대한민국 서울특별시 강남구 역삼동 123" → "한국|서울|강남구"
|
||||||
|
*/
|
||||||
|
public static String parseRegionFromAddress(String address) {
|
||||||
|
if (address == null || address.isBlank()) return null;
|
||||||
|
String[] parts = address.split("\\s+");
|
||||||
|
String country = "";
|
||||||
|
String city = "";
|
||||||
|
String district = "";
|
||||||
|
|
||||||
|
for (String p : parts) {
|
||||||
|
if (p.equals("대한민국") || p.equals("South Korea")) {
|
||||||
|
country = "한국";
|
||||||
|
} else if (p.endsWith("특별시") || p.endsWith("광역시") || p.endsWith("특별자치시")) {
|
||||||
|
city = p.replace("특별시", "").replace("광역시", "").replace("특별자치시", "");
|
||||||
|
} else if (p.endsWith("도") && !p.endsWith("동") && p.length() <= 5) {
|
||||||
|
city = p;
|
||||||
|
} else if (p.endsWith("구") || p.endsWith("군") || (p.endsWith("시") && !city.isEmpty())) {
|
||||||
|
if (district.isEmpty()) district = p;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (country.isEmpty() && !city.isEmpty()) country = "한국";
|
||||||
|
if (country.isEmpty()) return null;
|
||||||
|
return country + "|" + city + "|" + district;
|
||||||
|
}
|
||||||
|
|
||||||
private Map<String, Object> geocode(String query) {
|
private Map<String, Object> geocode(String query) {
|
||||||
try {
|
try {
|
||||||
String response = webClient.get()
|
String response = webClient.get()
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import org.springframework.beans.factory.annotation.Value;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
import jakarta.annotation.PostConstruct;
|
import jakarta.annotation.PostConstruct;
|
||||||
|
import jakarta.annotation.PreDestroy;
|
||||||
import java.util.ArrayList;
|
import java.util.ArrayList;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -45,6 +46,8 @@ public class OciGenAiService {
|
|||||||
|
|
||||||
private final ObjectMapper mapper;
|
private final ObjectMapper mapper;
|
||||||
private ConfigFileAuthenticationDetailsProvider authProvider;
|
private ConfigFileAuthenticationDetailsProvider authProvider;
|
||||||
|
private GenerativeAiInferenceClient chatClient;
|
||||||
|
private GenerativeAiInferenceClient embedClient;
|
||||||
|
|
||||||
public OciGenAiService(ObjectMapper mapper) {
|
public OciGenAiService(ObjectMapper mapper) {
|
||||||
this.mapper = mapper;
|
this.mapper = mapper;
|
||||||
@@ -55,45 +58,50 @@ public class OciGenAiService {
|
|||||||
try {
|
try {
|
||||||
ConfigFileReader.ConfigFile configFile = ConfigFileReader.parseDefault();
|
ConfigFileReader.ConfigFile configFile = ConfigFileReader.parseDefault();
|
||||||
authProvider = new ConfigFileAuthenticationDetailsProvider(configFile);
|
authProvider = new ConfigFileAuthenticationDetailsProvider(configFile);
|
||||||
log.info("OCI GenAI auth configured");
|
chatClient = GenerativeAiInferenceClient.builder()
|
||||||
|
.endpoint(chatEndpoint).build(authProvider);
|
||||||
|
embedClient = GenerativeAiInferenceClient.builder()
|
||||||
|
.endpoint(embedEndpoint).build(authProvider);
|
||||||
|
log.info("OCI GenAI auth configured (clients initialized)");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.warn("OCI config not found, GenAI features disabled: {}", e.getMessage());
|
log.warn("OCI config not found, GenAI features disabled: {}", e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@PreDestroy
|
||||||
|
public void destroy() {
|
||||||
|
if (chatClient != null) chatClient.close();
|
||||||
|
if (embedClient != null) embedClient.close();
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Call OCI GenAI LLM (Chat).
|
* Call OCI GenAI LLM (Chat).
|
||||||
*/
|
*/
|
||||||
public String chat(String prompt, int maxTokens) {
|
public String chat(String prompt, int maxTokens) {
|
||||||
if (authProvider == null) throw new IllegalStateException("OCI GenAI not configured");
|
if (chatClient == null) throw new IllegalStateException("OCI GenAI not configured");
|
||||||
|
|
||||||
try (var client = GenerativeAiInferenceClient.builder()
|
var textContent = TextContent.builder().text(prompt).build();
|
||||||
.endpoint(chatEndpoint)
|
var userMessage = UserMessage.builder().content(List.of(textContent)).build();
|
||||||
.build(authProvider)) {
|
|
||||||
|
|
||||||
var textContent = TextContent.builder().text(prompt).build();
|
var chatRequest = GenericChatRequest.builder()
|
||||||
var userMessage = UserMessage.builder().content(List.of(textContent)).build();
|
.messages(List.of(userMessage))
|
||||||
|
.maxTokens(maxTokens)
|
||||||
|
.temperature(0.0)
|
||||||
|
.build();
|
||||||
|
|
||||||
var chatRequest = GenericChatRequest.builder()
|
var chatDetails = ChatDetails.builder()
|
||||||
.messages(List.of(userMessage))
|
.compartmentId(compartmentId)
|
||||||
.maxTokens(maxTokens)
|
.servingMode(OnDemandServingMode.builder().modelId(chatModelId).build())
|
||||||
.temperature(0.0)
|
.chatRequest(chatRequest)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
var chatDetails = ChatDetails.builder()
|
ChatResponse response = chatClient.chat(
|
||||||
.compartmentId(compartmentId)
|
ChatRequest.builder().chatDetails(chatDetails).build());
|
||||||
.servingMode(OnDemandServingMode.builder().modelId(chatModelId).build())
|
|
||||||
.chatRequest(chatRequest)
|
|
||||||
.build();
|
|
||||||
|
|
||||||
ChatResponse response = client.chat(
|
var chatResult = (GenericChatResponse) response.getChatResult().getChatResponse();
|
||||||
ChatRequest.builder().chatDetails(chatDetails).build());
|
var choice = chatResult.getChoices().get(0);
|
||||||
|
var content = ((TextContent) choice.getMessage().getContent().get(0)).getText();
|
||||||
var chatResult = (GenericChatResponse) response.getChatResult().getChatResponse();
|
return content.trim();
|
||||||
var choice = chatResult.getChoices().get(0);
|
|
||||||
var content = ((TextContent) choice.getMessage().getContent().get(0)).getText();
|
|
||||||
return content.trim();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -111,25 +119,22 @@ public class OciGenAiService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
private List<List<Double>> embedBatch(List<String> texts) {
|
private List<List<Double>> embedBatch(List<String> texts) {
|
||||||
try (var client = GenerativeAiInferenceClient.builder()
|
if (embedClient == null) throw new IllegalStateException("OCI GenAI not configured");
|
||||||
.endpoint(embedEndpoint)
|
|
||||||
.build(authProvider)) {
|
|
||||||
|
|
||||||
var embedDetails = EmbedTextDetails.builder()
|
var embedDetails = EmbedTextDetails.builder()
|
||||||
.inputs(texts)
|
.inputs(texts)
|
||||||
.servingMode(OnDemandServingMode.builder().modelId(embedModelId).build())
|
.servingMode(OnDemandServingMode.builder().modelId(embedModelId).build())
|
||||||
.compartmentId(compartmentId)
|
.compartmentId(compartmentId)
|
||||||
.inputType(EmbedTextDetails.InputType.SearchDocument)
|
.inputType(EmbedTextDetails.InputType.SearchDocument)
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
EmbedTextResponse response = client.embedText(
|
EmbedTextResponse response = embedClient.embedText(
|
||||||
EmbedTextRequest.builder().embedTextDetails(embedDetails).build());
|
EmbedTextRequest.builder().embedTextDetails(embedDetails).build());
|
||||||
|
|
||||||
return response.getEmbedTextResult().getEmbeddings()
|
return response.getEmbedTextResult().getEmbeddings()
|
||||||
.stream()
|
.stream()
|
||||||
.map(emb -> emb.stream().map(Number::doubleValue).toList())
|
.map(emb -> emb.stream().map(Number::doubleValue).toList())
|
||||||
.toList();
|
.toList();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -26,6 +26,14 @@ public class RestaurantService {
|
|||||||
return restaurants;
|
return restaurants;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<Restaurant> findWithoutTabling() {
|
||||||
|
return mapper.findWithoutTabling();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Restaurant> findWithoutCatchtable() {
|
||||||
|
return mapper.findWithoutCatchtable();
|
||||||
|
}
|
||||||
|
|
||||||
public Restaurant findById(String id) {
|
public Restaurant findById(String id) {
|
||||||
Restaurant restaurant = mapper.findById(id);
|
Restaurant restaurant = mapper.findById(id);
|
||||||
if (restaurant == null) return null;
|
if (restaurant == null) return null;
|
||||||
|
|||||||
@@ -111,6 +111,22 @@ public class VideoService {
|
|||||||
return rows.stream().map(JsonUtil::lowerKeys).toList();
|
return rows.stream().map(JsonUtil::lowerKeys).toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public List<Map<String, Object>> findVideosByIds(List<String> ids) {
|
||||||
|
var rows = mapper.findVideosByIds(ids);
|
||||||
|
return rows.stream().map(JsonUtil::lowerKeys).toList();
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<Map<String, Object>> findVideosForExtractByIds(List<String> ids) {
|
||||||
|
var rows = mapper.findVideosForExtractByIds(ids);
|
||||||
|
return rows.stream().map(row -> {
|
||||||
|
var r = JsonUtil.lowerKeys(row);
|
||||||
|
Object transcript = r.get("transcript_text");
|
||||||
|
r.put("transcript", JsonUtil.readClob(transcript));
|
||||||
|
r.remove("transcript_text");
|
||||||
|
return r;
|
||||||
|
}).toList();
|
||||||
|
}
|
||||||
|
|
||||||
public void updateVideoRestaurantFields(String videoId, String restaurantId,
|
public void updateVideoRestaurantFields(String videoId, String restaurantId,
|
||||||
String foodsJson, String evaluation, String guestsJson) {
|
String foodsJson, String evaluation, String guestsJson) {
|
||||||
mapper.updateVideoRestaurantFields(videoId, restaurantId, foodsJson, evaluation, guestsJson);
|
mapper.updateVideoRestaurantFields(videoId, restaurantId, foodsJson, evaluation, guestsJson);
|
||||||
|
|||||||
@@ -50,10 +50,77 @@ public class YouTubeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Fetch videos from a YouTube channel, page by page.
|
* Fetch videos from a YouTube channel using the uploads playlist (UC→UU).
|
||||||
* Returns all pages merged into one list.
|
* This returns ALL videos unlike the Search API which caps results.
|
||||||
|
* Falls back to Search API if playlist approach fails.
|
||||||
*/
|
*/
|
||||||
public List<Map<String, Object>> fetchChannelVideos(String channelId, String publishedAfter, boolean excludeShorts) {
|
public List<Map<String, Object>> fetchChannelVideos(String channelId, String publishedAfter, boolean excludeShorts) {
|
||||||
|
// Convert channel ID UC... → uploads playlist UU...
|
||||||
|
String uploadsPlaylistId = "UU" + channelId.substring(2);
|
||||||
|
List<Map<String, Object>> allVideos = new ArrayList<>();
|
||||||
|
String nextPage = null;
|
||||||
|
|
||||||
|
try {
|
||||||
|
do {
|
||||||
|
String pageToken = nextPage;
|
||||||
|
String response = webClient.get()
|
||||||
|
.uri(uriBuilder -> {
|
||||||
|
var b = uriBuilder.path("/playlistItems")
|
||||||
|
.queryParam("key", apiKey)
|
||||||
|
.queryParam("playlistId", uploadsPlaylistId)
|
||||||
|
.queryParam("part", "snippet")
|
||||||
|
.queryParam("maxResults", 50);
|
||||||
|
if (pageToken != null) b.queryParam("pageToken", pageToken);
|
||||||
|
return b.build();
|
||||||
|
})
|
||||||
|
.retrieve()
|
||||||
|
.bodyToMono(String.class)
|
||||||
|
.block(Duration.ofSeconds(30));
|
||||||
|
|
||||||
|
JsonNode data = mapper.readTree(response);
|
||||||
|
List<Map<String, Object>> pageVideos = new ArrayList<>();
|
||||||
|
|
||||||
|
for (JsonNode item : data.path("items")) {
|
||||||
|
JsonNode snippet = item.path("snippet");
|
||||||
|
String vid = snippet.path("resourceId").path("videoId").asText();
|
||||||
|
String publishedAt = snippet.path("publishedAt").asText();
|
||||||
|
|
||||||
|
// publishedAfter 필터: 이미 스캔한 영상 이후만
|
||||||
|
if (publishedAfter != null && publishedAt.compareTo(publishedAfter) <= 0) {
|
||||||
|
// 업로드 재생목록은 최신순이므로 이전 날짜 만나면 중단
|
||||||
|
nextPage = null;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
pageVideos.add(Map.of(
|
||||||
|
"video_id", vid,
|
||||||
|
"title", snippet.path("title").asText(),
|
||||||
|
"published_at", publishedAt,
|
||||||
|
"url", "https://www.youtube.com/watch?v=" + vid
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (excludeShorts && !pageVideos.isEmpty()) {
|
||||||
|
pageVideos = filterShorts(pageVideos);
|
||||||
|
}
|
||||||
|
allVideos.addAll(pageVideos);
|
||||||
|
|
||||||
|
if (nextPage != null || data.has("nextPageToken")) {
|
||||||
|
nextPage = data.has("nextPageToken") ? data.path("nextPageToken").asText() : null;
|
||||||
|
}
|
||||||
|
} while (nextPage != null);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("PlaylistItems API failed for {}, falling back to Search API", channelId, e);
|
||||||
|
return fetchChannelVideosViaSearch(channelId, publishedAfter, excludeShorts);
|
||||||
|
}
|
||||||
|
|
||||||
|
return allVideos;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fallback: fetch via Search API (may not return all videos).
|
||||||
|
*/
|
||||||
|
private List<Map<String, Object>> fetchChannelVideosViaSearch(String channelId, String publishedAfter, boolean excludeShorts) {
|
||||||
List<Map<String, Object>> allVideos = new ArrayList<>();
|
List<Map<String, Object>> allVideos = new ArrayList<>();
|
||||||
String nextPage = null;
|
String nextPage = null;
|
||||||
|
|
||||||
@@ -98,7 +165,7 @@ public class YouTubeService {
|
|||||||
|
|
||||||
nextPage = data.has("nextPageToken") ? data.path("nextPageToken").asText() : null;
|
nextPage = data.has("nextPageToken") ? data.path("nextPageToken").asText() : null;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("Failed to parse YouTube API response", e);
|
log.error("Failed to parse YouTube Search API response", e);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
} while (nextPage != null);
|
} while (nextPage != null);
|
||||||
@@ -108,33 +175,39 @@ public class YouTubeService {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Filter out YouTube Shorts (<=60s duration).
|
* Filter out YouTube Shorts (<=60s duration).
|
||||||
|
* YouTube /videos API accepts max 50 IDs per request, so we batch.
|
||||||
*/
|
*/
|
||||||
private List<Map<String, Object>> filterShorts(List<Map<String, Object>> videos) {
|
private List<Map<String, Object>> filterShorts(List<Map<String, Object>> videos) {
|
||||||
String ids = String.join(",", videos.stream().map(v -> (String) v.get("video_id")).toList());
|
Map<String, Integer> durations = new HashMap<>();
|
||||||
String response = webClient.get()
|
List<String> allIds = videos.stream().map(v -> (String) v.get("video_id")).toList();
|
||||||
.uri(uriBuilder -> uriBuilder.path("/videos")
|
|
||||||
.queryParam("key", apiKey)
|
|
||||||
.queryParam("id", ids)
|
|
||||||
.queryParam("part", "contentDetails")
|
|
||||||
.build())
|
|
||||||
.retrieve()
|
|
||||||
.bodyToMono(String.class)
|
|
||||||
.block(Duration.ofSeconds(30));
|
|
||||||
|
|
||||||
try {
|
for (int i = 0; i < allIds.size(); i += 50) {
|
||||||
JsonNode data = mapper.readTree(response);
|
List<String> batch = allIds.subList(i, Math.min(i + 50, allIds.size()));
|
||||||
Map<String, Integer> durations = new HashMap<>();
|
String ids = String.join(",", batch);
|
||||||
for (JsonNode item : data.path("items")) {
|
try {
|
||||||
String duration = item.path("contentDetails").path("duration").asText();
|
String response = webClient.get()
|
||||||
durations.put(item.path("id").asText(), parseDuration(duration));
|
.uri(uriBuilder -> uriBuilder.path("/videos")
|
||||||
|
.queryParam("key", apiKey)
|
||||||
|
.queryParam("id", ids)
|
||||||
|
.queryParam("part", "contentDetails")
|
||||||
|
.build())
|
||||||
|
.retrieve()
|
||||||
|
.bodyToMono(String.class)
|
||||||
|
.block(Duration.ofSeconds(30));
|
||||||
|
|
||||||
|
JsonNode data = mapper.readTree(response);
|
||||||
|
for (JsonNode item : data.path("items")) {
|
||||||
|
String duration = item.path("contentDetails").path("duration").asText();
|
||||||
|
durations.put(item.path("id").asText(), parseDuration(duration));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("Failed to fetch video durations for batch starting at {}", i, e);
|
||||||
}
|
}
|
||||||
return videos.stream()
|
|
||||||
.filter(v -> durations.getOrDefault(v.get("video_id"), 0) > 60)
|
|
||||||
.toList();
|
|
||||||
} catch (Exception e) {
|
|
||||||
log.warn("Failed to filter shorts", e);
|
|
||||||
return videos;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return videos.stream()
|
||||||
|
.filter(v -> durations.getOrDefault(v.get("video_id"), 61) > 60)
|
||||||
|
.toList();
|
||||||
}
|
}
|
||||||
|
|
||||||
private int parseDuration(String dur) {
|
private int parseDuration(String dur) {
|
||||||
@@ -208,16 +281,16 @@ public class YouTubeService {
|
|||||||
public TranscriptResult getTranscript(String videoId, String mode) {
|
public TranscriptResult getTranscript(String videoId, String mode) {
|
||||||
if (mode == null) mode = "auto";
|
if (mode == null) mode = "auto";
|
||||||
|
|
||||||
// 1) Fast path: youtube-transcript-api
|
// 1) Playwright headed browser (봇 판정 회피)
|
||||||
TranscriptResult apiResult = getTranscriptApi(videoId, mode);
|
TranscriptResult browserResult = getTranscriptBrowser(videoId);
|
||||||
if (apiResult != null) return apiResult;
|
if (browserResult != null) return browserResult;
|
||||||
|
|
||||||
// 2) Fallback: Playwright browser
|
// 2) Fallback: youtube-transcript-api
|
||||||
log.warn("API failed for {}, trying Playwright browser", videoId);
|
log.warn("Browser failed for {}, trying API", videoId);
|
||||||
return getTranscriptBrowser(videoId);
|
return getTranscriptApi(videoId, mode);
|
||||||
}
|
}
|
||||||
|
|
||||||
private TranscriptResult getTranscriptApi(String videoId, String mode) {
|
public TranscriptResult getTranscriptApi(String videoId, String mode) {
|
||||||
TranscriptList transcriptList;
|
TranscriptList transcriptList;
|
||||||
try {
|
try {
|
||||||
transcriptList = transcriptApi.listTranscripts(videoId);
|
transcriptList = transcriptApi.listTranscripts(videoId);
|
||||||
@@ -262,163 +335,195 @@ public class YouTubeService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Playwright browser fallback ───────────────────────────────────────────
|
// ─── Playwright browser ───────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch transcript using an existing Playwright Page (for bulk reuse).
|
||||||
|
*/
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
public TranscriptResult getTranscriptWithPage(Page page, String videoId) {
|
||||||
|
return fetchTranscriptFromPage(page, videoId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a Playwright browser + context + page for transcript fetching.
|
||||||
|
* Caller must close the returned resources (Playwright, Browser).
|
||||||
|
*/
|
||||||
|
public record BrowserSession(Playwright playwright, Browser browser, Page page) implements AutoCloseable {
|
||||||
|
@Override
|
||||||
|
public void close() {
|
||||||
|
try { browser.close(); } catch (Exception ignored) {}
|
||||||
|
try { playwright.close(); } catch (Exception ignored) {}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public BrowserSession createBrowserSession() {
|
||||||
|
Playwright pw = Playwright.create();
|
||||||
|
Browser browser = pw.chromium().launch(new BrowserType.LaunchOptions()
|
||||||
|
.setHeadless(false)
|
||||||
|
.setArgs(List.of("--disable-blink-features=AutomationControlled")));
|
||||||
|
BrowserContext ctx = browser.newContext(new Browser.NewContextOptions()
|
||||||
|
.setLocale("ko-KR")
|
||||||
|
.setViewportSize(1280, 900));
|
||||||
|
loadCookies(ctx);
|
||||||
|
Page page = ctx.newPage();
|
||||||
|
page.addInitScript("Object.defineProperty(navigator, 'webdriver', {get: () => false})");
|
||||||
|
return new BrowserSession(pw, browser, page);
|
||||||
|
}
|
||||||
|
|
||||||
@SuppressWarnings("unchecked")
|
@SuppressWarnings("unchecked")
|
||||||
private TranscriptResult getTranscriptBrowser(String videoId) {
|
private TranscriptResult getTranscriptBrowser(String videoId) {
|
||||||
try (Playwright pw = Playwright.create()) {
|
try (BrowserSession session = createBrowserSession()) {
|
||||||
BrowserType.LaunchOptions launchOpts = new BrowserType.LaunchOptions()
|
return fetchTranscriptFromPage(session.page(), videoId);
|
||||||
.setHeadless(false)
|
|
||||||
.setArgs(List.of("--disable-blink-features=AutomationControlled"));
|
|
||||||
|
|
||||||
try (Browser browser = pw.chromium().launch(launchOpts)) {
|
|
||||||
Browser.NewContextOptions ctxOpts = new Browser.NewContextOptions()
|
|
||||||
.setLocale("ko-KR")
|
|
||||||
.setViewportSize(1280, 900);
|
|
||||||
|
|
||||||
BrowserContext ctx = browser.newContext(ctxOpts);
|
|
||||||
|
|
||||||
// Load YouTube cookies if available
|
|
||||||
loadCookies(ctx);
|
|
||||||
|
|
||||||
Page page = ctx.newPage();
|
|
||||||
|
|
||||||
// Hide webdriver flag to reduce bot detection
|
|
||||||
page.addInitScript("Object.defineProperty(navigator, 'webdriver', {get: () => false})");
|
|
||||||
|
|
||||||
log.info("[TRANSCRIPT] Opening YouTube page for {}", videoId);
|
|
||||||
page.navigate("https://www.youtube.com/watch?v=" + videoId,
|
|
||||||
new Page.NavigateOptions().setWaitUntil(WaitUntilState.DOMCONTENTLOADED).setTimeout(30000));
|
|
||||||
page.waitForTimeout(5000);
|
|
||||||
|
|
||||||
// Skip ads if present
|
|
||||||
skipAds(page);
|
|
||||||
|
|
||||||
page.waitForTimeout(2000);
|
|
||||||
log.info("[TRANSCRIPT] Page loaded, looking for transcript button");
|
|
||||||
|
|
||||||
// Click "더보기" (expand description)
|
|
||||||
page.evaluate("""
|
|
||||||
() => {
|
|
||||||
const moreBtn = document.querySelector('tp-yt-paper-button#expand');
|
|
||||||
if (moreBtn) moreBtn.click();
|
|
||||||
}
|
|
||||||
""");
|
|
||||||
page.waitForTimeout(2000);
|
|
||||||
|
|
||||||
// Click transcript button
|
|
||||||
Object clicked = page.evaluate("""
|
|
||||||
() => {
|
|
||||||
// Method 1: aria-label
|
|
||||||
for (const label of ['스크립트 표시', 'Show transcript']) {
|
|
||||||
const btns = document.querySelectorAll(`button[aria-label="${label}"]`);
|
|
||||||
for (const b of btns) { b.click(); return 'aria-label: ' + label; }
|
|
||||||
}
|
|
||||||
// Method 2: text content
|
|
||||||
const allBtns = document.querySelectorAll('button');
|
|
||||||
for (const b of allBtns) {
|
|
||||||
const text = b.textContent.trim();
|
|
||||||
if (text === '스크립트 표시' || text === 'Show transcript') {
|
|
||||||
b.click();
|
|
||||||
return 'text: ' + text;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
// Method 3: engagement panel buttons
|
|
||||||
const engBtns = document.querySelectorAll('ytd-button-renderer button, ytd-button-renderer a');
|
|
||||||
for (const b of engBtns) {
|
|
||||||
const text = b.textContent.trim().toLowerCase();
|
|
||||||
if (text.includes('transcript') || text.includes('스크립트')) {
|
|
||||||
b.click();
|
|
||||||
return 'engagement: ' + text;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
""");
|
|
||||||
log.info("[TRANSCRIPT] Clicked transcript button: {}", clicked);
|
|
||||||
|
|
||||||
if (Boolean.FALSE.equals(clicked)) {
|
|
||||||
Object btnLabels = page.evaluate("""
|
|
||||||
() => {
|
|
||||||
const btns = document.querySelectorAll('button[aria-label]');
|
|
||||||
return Array.from(btns).map(b => b.getAttribute('aria-label')).slice(0, 30);
|
|
||||||
}
|
|
||||||
""");
|
|
||||||
log.warn("[TRANSCRIPT] Transcript button not found. Available buttons: {}", btnLabels);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Wait for transcript segments to appear (max ~40s)
|
|
||||||
page.waitForTimeout(3000);
|
|
||||||
for (int attempt = 0; attempt < 12; attempt++) {
|
|
||||||
page.waitForTimeout(3000);
|
|
||||||
Object count = page.evaluate(
|
|
||||||
"() => document.querySelectorAll('ytd-transcript-segment-renderer').length");
|
|
||||||
int segCount = count instanceof Number n ? n.intValue() : 0;
|
|
||||||
log.info("[TRANSCRIPT] Wait {}s: {} segments", (attempt + 1) * 3 + 3, segCount);
|
|
||||||
if (segCount > 0) break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Select Korean if available
|
|
||||||
selectKorean(page);
|
|
||||||
|
|
||||||
// Scroll transcript panel and collect segments
|
|
||||||
Object segmentsObj = page.evaluate("""
|
|
||||||
async () => {
|
|
||||||
const container = document.querySelector(
|
|
||||||
'ytd-transcript-segment-list-renderer #segments-container, ' +
|
|
||||||
'ytd-transcript-renderer #body'
|
|
||||||
);
|
|
||||||
if (!container) {
|
|
||||||
const segs = document.querySelectorAll('ytd-transcript-segment-renderer');
|
|
||||||
return Array.from(segs).map(s => {
|
|
||||||
const txt = s.querySelector('.segment-text, yt-formatted-string.segment-text');
|
|
||||||
return txt ? txt.textContent.trim() : '';
|
|
||||||
}).filter(t => t);
|
|
||||||
}
|
|
||||||
|
|
||||||
let prevCount = 0;
|
|
||||||
for (let i = 0; i < 50; i++) {
|
|
||||||
container.scrollTop = container.scrollHeight;
|
|
||||||
await new Promise(r => setTimeout(r, 300));
|
|
||||||
const segs = document.querySelectorAll('ytd-transcript-segment-renderer');
|
|
||||||
if (segs.length === prevCount && i > 3) break;
|
|
||||||
prevCount = segs.length;
|
|
||||||
}
|
|
||||||
|
|
||||||
const segs = document.querySelectorAll('ytd-transcript-segment-renderer');
|
|
||||||
return Array.from(segs).map(s => {
|
|
||||||
const txt = s.querySelector('.segment-text, yt-formatted-string.segment-text');
|
|
||||||
return txt ? txt.textContent.trim() : '';
|
|
||||||
}).filter(t => t);
|
|
||||||
}
|
|
||||||
""");
|
|
||||||
|
|
||||||
if (segmentsObj instanceof List<?> segments && !segments.isEmpty()) {
|
|
||||||
String text = segments.stream()
|
|
||||||
.map(Object::toString)
|
|
||||||
.collect(Collectors.joining(" "));
|
|
||||||
log.info("[TRANSCRIPT] Browser success: {} chars from {} segments", text.length(), segments.size());
|
|
||||||
return new TranscriptResult(text, "browser");
|
|
||||||
}
|
|
||||||
|
|
||||||
log.warn("[TRANSCRIPT] No segments found via browser for {}", videoId);
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("[TRANSCRIPT] Playwright failed for {}: {}", videoId, e.getMessage());
|
log.error("[TRANSCRIPT] Playwright failed for {}: {}", videoId, e.getMessage());
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
private TranscriptResult fetchTranscriptFromPage(Page page, String videoId) {
|
||||||
|
try {
|
||||||
|
log.info("[TRANSCRIPT] Opening YouTube page for {}", videoId);
|
||||||
|
page.navigate("https://www.youtube.com/watch?v=" + videoId,
|
||||||
|
new Page.NavigateOptions().setWaitUntil(WaitUntilState.DOMCONTENTLOADED).setTimeout(30000));
|
||||||
|
page.waitForTimeout(3000);
|
||||||
|
|
||||||
|
skipAds(page);
|
||||||
|
|
||||||
|
page.waitForTimeout(1000);
|
||||||
|
log.info("[TRANSCRIPT] Page loaded, looking for transcript button");
|
||||||
|
|
||||||
|
// Click "더보기" (expand description)
|
||||||
|
page.evaluate("""
|
||||||
|
() => {
|
||||||
|
const moreBtn = document.querySelector('tp-yt-paper-button#expand');
|
||||||
|
if (moreBtn) moreBtn.click();
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
page.waitForTimeout(2000);
|
||||||
|
|
||||||
|
// Click transcript button
|
||||||
|
Object clicked = page.evaluate("""
|
||||||
|
() => {
|
||||||
|
// Method 1: aria-label
|
||||||
|
for (const label of ['스크립트 표시', 'Show transcript']) {
|
||||||
|
const btns = document.querySelectorAll(`button[aria-label="${label}"]`);
|
||||||
|
for (const b of btns) { b.click(); return 'aria-label: ' + label; }
|
||||||
|
}
|
||||||
|
// Method 2: text content
|
||||||
|
const allBtns = document.querySelectorAll('button');
|
||||||
|
for (const b of allBtns) {
|
||||||
|
const text = b.textContent.trim();
|
||||||
|
if (text === '스크립트 표시' || text === 'Show transcript') {
|
||||||
|
b.click();
|
||||||
|
return 'text: ' + text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Method 3: engagement panel buttons
|
||||||
|
const engBtns = document.querySelectorAll('ytd-button-renderer button, ytd-button-renderer a');
|
||||||
|
for (const b of engBtns) {
|
||||||
|
const text = b.textContent.trim().toLowerCase();
|
||||||
|
if (text.includes('transcript') || text.includes('스크립트')) {
|
||||||
|
b.click();
|
||||||
|
return 'engagement: ' + text;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
log.info("[TRANSCRIPT] Clicked transcript button: {}", clicked);
|
||||||
|
|
||||||
|
if (Boolean.FALSE.equals(clicked)) {
|
||||||
|
Object btnLabels = page.evaluate("""
|
||||||
|
() => {
|
||||||
|
const btns = document.querySelectorAll('button[aria-label]');
|
||||||
|
return Array.from(btns).map(b => b.getAttribute('aria-label')).slice(0, 30);
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
log.warn("[TRANSCRIPT] Transcript button not found. Available buttons: {}", btnLabels);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for transcript segments to appear (max ~15s)
|
||||||
|
page.waitForTimeout(2000);
|
||||||
|
for (int attempt = 0; attempt < 10; attempt++) {
|
||||||
|
page.waitForTimeout(1500);
|
||||||
|
Object count = page.evaluate(
|
||||||
|
"() => document.querySelectorAll('ytd-transcript-segment-renderer').length");
|
||||||
|
int segCount = count instanceof Number n ? n.intValue() : 0;
|
||||||
|
log.info("[TRANSCRIPT] Wait {}s: {} segments", (attempt + 1) * 1.5 + 2, segCount);
|
||||||
|
if (segCount > 0) break;
|
||||||
|
}
|
||||||
|
|
||||||
|
selectKorean(page);
|
||||||
|
|
||||||
|
// Scroll transcript panel and collect segments
|
||||||
|
Object segmentsObj = page.evaluate("""
|
||||||
|
async () => {
|
||||||
|
const container = document.querySelector(
|
||||||
|
'ytd-transcript-segment-list-renderer #segments-container, ' +
|
||||||
|
'ytd-transcript-renderer #body'
|
||||||
|
);
|
||||||
|
if (!container) {
|
||||||
|
const segs = document.querySelectorAll('ytd-transcript-segment-renderer');
|
||||||
|
return Array.from(segs).map(s => {
|
||||||
|
const txt = s.querySelector('.segment-text, yt-formatted-string.segment-text');
|
||||||
|
return txt ? txt.textContent.trim() : '';
|
||||||
|
}).filter(t => t);
|
||||||
|
}
|
||||||
|
|
||||||
|
let prevCount = 0;
|
||||||
|
for (let i = 0; i < 50; i++) {
|
||||||
|
container.scrollTop = container.scrollHeight;
|
||||||
|
await new Promise(r => setTimeout(r, 300));
|
||||||
|
const segs = document.querySelectorAll('ytd-transcript-segment-renderer');
|
||||||
|
if (segs.length === prevCount && i > 3) break;
|
||||||
|
prevCount = segs.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
const segs = document.querySelectorAll('ytd-transcript-segment-renderer');
|
||||||
|
return Array.from(segs).map(s => {
|
||||||
|
const txt = s.querySelector('.segment-text, yt-formatted-string.segment-text');
|
||||||
|
return txt ? txt.textContent.trim() : '';
|
||||||
|
}).filter(t => t);
|
||||||
|
}
|
||||||
|
""");
|
||||||
|
|
||||||
|
if (segmentsObj instanceof List<?> segments && !segments.isEmpty()) {
|
||||||
|
String text = segments.stream()
|
||||||
|
.map(Object::toString)
|
||||||
|
.collect(Collectors.joining(" "));
|
||||||
|
log.info("[TRANSCRIPT] Browser success: {} chars from {} segments", text.length(), segments.size());
|
||||||
|
return new TranscriptResult(text, "browser");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.warn("[TRANSCRIPT] No segments found via browser for {}", videoId);
|
||||||
|
return null;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("[TRANSCRIPT] Page fetch failed for {}: {}", videoId, e.getMessage());
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void skipAds(Page page) {
|
private void skipAds(Page page) {
|
||||||
for (int i = 0; i < 12; i++) {
|
for (int i = 0; i < 30; i++) {
|
||||||
Object adStatus = page.evaluate("""
|
Object adStatus = page.evaluate("""
|
||||||
() => {
|
() => {
|
||||||
const skipBtn = document.querySelector('.ytp-skip-ad-button, .ytp-ad-skip-button, .ytp-ad-skip-button-modern, button.ytp-ad-skip-button-modern');
|
const skipBtn = document.querySelector('.ytp-skip-ad-button, .ytp-ad-skip-button, .ytp-ad-skip-button-modern, button.ytp-ad-skip-button-modern');
|
||||||
if (skipBtn) { skipBtn.click(); return 'skipped'; }
|
if (skipBtn) { skipBtn.click(); return 'skipped'; }
|
||||||
const adOverlay = document.querySelector('.ytp-ad-player-overlay, .ad-showing');
|
const adOverlay = document.querySelector('.ytp-ad-player-overlay, .ad-showing');
|
||||||
if (adOverlay) return 'playing';
|
if (adOverlay) {
|
||||||
|
// 광고 중: 뮤트 + 끝으로 이동 시도
|
||||||
|
const video = document.querySelector('video');
|
||||||
|
if (video) {
|
||||||
|
video.muted = true;
|
||||||
|
if (video.duration && isFinite(video.duration)) {
|
||||||
|
video.currentTime = video.duration;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 'playing';
|
||||||
|
}
|
||||||
const adBadge = document.querySelector('.ytp-ad-text');
|
const adBadge = document.querySelector('.ytp-ad-text');
|
||||||
if (adBadge && adBadge.textContent) return 'badge';
|
if (adBadge && adBadge.textContent) return 'badge';
|
||||||
return 'none';
|
return 'none';
|
||||||
@@ -428,10 +533,10 @@ public class YouTubeService {
|
|||||||
if ("none".equals(status)) break;
|
if ("none".equals(status)) break;
|
||||||
log.info("[TRANSCRIPT] Ad detected: {}, waiting...", status);
|
log.info("[TRANSCRIPT] Ad detected: {}, waiting...", status);
|
||||||
if ("skipped".equals(status)) {
|
if ("skipped".equals(status)) {
|
||||||
page.waitForTimeout(2000);
|
page.waitForTimeout(1000);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
page.waitForTimeout(5000);
|
page.waitForTimeout(1000);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ app:
|
|||||||
expiration-days: 7
|
expiration-days: 7
|
||||||
|
|
||||||
cors:
|
cors:
|
||||||
allowed-origins: http://localhost:3000,http://localhost:3001,https://www.tasteby.net,https://tasteby.net
|
allowed-origins: http://localhost:3000,http://localhost:3001,https://www.tasteby.net,https://tasteby.net,https://dev.tasteby.net
|
||||||
|
|
||||||
oracle:
|
oracle:
|
||||||
wallet-path: ${ORACLE_WALLET:}
|
wallet-path: ${ORACLE_WALLET:}
|
||||||
|
|||||||
@@ -16,6 +16,8 @@
|
|||||||
<result property="phone" column="phone"/>
|
<result property="phone" column="phone"/>
|
||||||
<result property="website" column="website"/>
|
<result property="website" column="website"/>
|
||||||
<result property="googlePlaceId" column="google_place_id"/>
|
<result property="googlePlaceId" column="google_place_id"/>
|
||||||
|
<result property="tablingUrl" column="tabling_url"/>
|
||||||
|
<result property="catchtableUrl" column="catchtable_url"/>
|
||||||
<result property="businessStatus" column="business_status"/>
|
<result property="businessStatus" column="business_status"/>
|
||||||
<result property="rating" column="rating"/>
|
<result property="rating" column="rating"/>
|
||||||
<result property="ratingCount" column="rating_count"/>
|
<result property="ratingCount" column="rating_count"/>
|
||||||
@@ -26,7 +28,7 @@
|
|||||||
|
|
||||||
<select id="findAll" resultMap="restaurantMap">
|
<select id="findAll" resultMap="restaurantMap">
|
||||||
SELECT DISTINCT r.id, r.name, r.address, r.region, r.latitude, r.longitude,
|
SELECT DISTINCT r.id, r.name, r.address, r.region, r.latitude, r.longitude,
|
||||||
r.cuisine_type, r.price_range, r.google_place_id,
|
r.cuisine_type, r.price_range, r.google_place_id, r.tabling_url, r.catchtable_url,
|
||||||
r.business_status, r.rating, r.rating_count, r.updated_at
|
r.business_status, r.rating, r.rating_count, r.updated_at
|
||||||
FROM restaurants r
|
FROM restaurants r
|
||||||
<if test="channel != null and channel != ''">
|
<if test="channel != null and channel != ''">
|
||||||
@@ -54,7 +56,7 @@
|
|||||||
<select id="findById" resultMap="restaurantMap">
|
<select id="findById" resultMap="restaurantMap">
|
||||||
SELECT r.id, r.name, r.address, r.region, r.latitude, r.longitude,
|
SELECT r.id, r.name, r.address, r.region, r.latitude, r.longitude,
|
||||||
r.cuisine_type, r.price_range, r.phone, r.website, r.google_place_id,
|
r.cuisine_type, r.price_range, r.phone, r.website, r.google_place_id,
|
||||||
r.business_status, r.rating, r.rating_count
|
r.tabling_url, r.catchtable_url, r.business_status, r.rating, r.rating_count
|
||||||
FROM restaurants r
|
FROM restaurants r
|
||||||
WHERE r.id = #{id}
|
WHERE r.id = #{id}
|
||||||
</select>
|
</select>
|
||||||
@@ -129,12 +131,30 @@
|
|||||||
<if test="fields.containsKey('website')">
|
<if test="fields.containsKey('website')">
|
||||||
website = #{fields.website},
|
website = #{fields.website},
|
||||||
</if>
|
</if>
|
||||||
|
<if test="fields.containsKey('tabling_url')">
|
||||||
|
tabling_url = #{fields.tabling_url},
|
||||||
|
</if>
|
||||||
|
<if test="fields.containsKey('catchtable_url')">
|
||||||
|
catchtable_url = #{fields.catchtable_url},
|
||||||
|
</if>
|
||||||
<if test="fields.containsKey('latitude')">
|
<if test="fields.containsKey('latitude')">
|
||||||
latitude = #{fields.latitude},
|
latitude = #{fields.latitude},
|
||||||
</if>
|
</if>
|
||||||
<if test="fields.containsKey('longitude')">
|
<if test="fields.containsKey('longitude')">
|
||||||
longitude = #{fields.longitude},
|
longitude = #{fields.longitude},
|
||||||
</if>
|
</if>
|
||||||
|
<if test="fields.containsKey('google_place_id')">
|
||||||
|
google_place_id = #{fields.google_place_id},
|
||||||
|
</if>
|
||||||
|
<if test="fields.containsKey('business_status')">
|
||||||
|
business_status = #{fields.business_status},
|
||||||
|
</if>
|
||||||
|
<if test="fields.containsKey('rating')">
|
||||||
|
rating = #{fields.rating},
|
||||||
|
</if>
|
||||||
|
<if test="fields.containsKey('rating_count')">
|
||||||
|
rating_count = #{fields.rating_count},
|
||||||
|
</if>
|
||||||
updated_at = SYSTIMESTAMP,
|
updated_at = SYSTIMESTAMP,
|
||||||
</trim>
|
</trim>
|
||||||
WHERE id = #{id}
|
WHERE id = #{id}
|
||||||
@@ -201,6 +221,24 @@
|
|||||||
</foreach>
|
</foreach>
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<select id="findWithoutTabling" resultMap="restaurantMap">
|
||||||
|
SELECT r.id, r.name, r.address, r.region
|
||||||
|
FROM restaurants r
|
||||||
|
WHERE r.tabling_url IS NULL
|
||||||
|
AND r.latitude IS NOT NULL
|
||||||
|
AND EXISTS (SELECT 1 FROM video_restaurants vr WHERE vr.restaurant_id = r.id)
|
||||||
|
ORDER BY r.name
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="findWithoutCatchtable" resultMap="restaurantMap">
|
||||||
|
SELECT r.id, r.name, r.address, r.region
|
||||||
|
FROM restaurants r
|
||||||
|
WHERE r.catchtable_url IS NULL
|
||||||
|
AND r.latitude IS NOT NULL
|
||||||
|
AND EXISTS (SELECT 1 FROM video_restaurants vr WHERE vr.restaurant_id = r.id)
|
||||||
|
ORDER BY r.name
|
||||||
|
</select>
|
||||||
|
|
||||||
<!-- ===== Remap operations ===== -->
|
<!-- ===== Remap operations ===== -->
|
||||||
|
|
||||||
<update id="updateCuisineType">
|
<update id="updateCuisineType">
|
||||||
|
|||||||
@@ -11,7 +11,11 @@
|
|||||||
<result property="longitude" column="longitude"/>
|
<result property="longitude" column="longitude"/>
|
||||||
<result property="cuisineType" column="cuisine_type"/>
|
<result property="cuisineType" column="cuisine_type"/>
|
||||||
<result property="priceRange" column="price_range"/>
|
<result property="priceRange" column="price_range"/>
|
||||||
|
<result property="phone" column="phone"/>
|
||||||
|
<result property="website" column="website"/>
|
||||||
<result property="googlePlaceId" column="google_place_id"/>
|
<result property="googlePlaceId" column="google_place_id"/>
|
||||||
|
<result property="tablingUrl" column="tabling_url"/>
|
||||||
|
<result property="catchtableUrl" column="catchtable_url"/>
|
||||||
<result property="businessStatus" column="business_status"/>
|
<result property="businessStatus" column="business_status"/>
|
||||||
<result property="rating" column="rating"/>
|
<result property="rating" column="rating"/>
|
||||||
<result property="ratingCount" column="rating_count"/>
|
<result property="ratingCount" column="rating_count"/>
|
||||||
@@ -19,7 +23,8 @@
|
|||||||
|
|
||||||
<select id="keywordSearch" resultMap="restaurantMap">
|
<select id="keywordSearch" resultMap="restaurantMap">
|
||||||
SELECT DISTINCT r.id, r.name, r.address, r.region, r.latitude, r.longitude,
|
SELECT DISTINCT r.id, r.name, r.address, r.region, r.latitude, r.longitude,
|
||||||
r.cuisine_type, r.price_range, r.google_place_id,
|
r.cuisine_type, r.price_range, r.phone, r.website, r.google_place_id,
|
||||||
|
r.tabling_url, r.catchtable_url,
|
||||||
r.business_status, r.rating, r.rating_count
|
r.business_status, r.rating, r.rating_count
|
||||||
FROM restaurants r
|
FROM restaurants r
|
||||||
JOIN video_restaurants vr ON vr.restaurant_id = r.id
|
JOIN video_restaurants vr ON vr.restaurant_id = r.id
|
||||||
|
|||||||
@@ -186,7 +186,8 @@
|
|||||||
|
|
||||||
<insert id="insertVideo">
|
<insert id="insertVideo">
|
||||||
INSERT INTO videos (id, channel_id, video_id, title, url, published_at)
|
INSERT INTO videos (id, channel_id, video_id, title, url, published_at)
|
||||||
VALUES (#{id}, #{channelId}, #{videoId}, #{title}, #{url}, #{publishedAt})
|
VALUES (#{id}, #{channelId}, #{videoId}, #{title}, #{url},
|
||||||
|
TO_TIMESTAMP(#{publishedAt}, 'YYYY-MM-DD"T"HH24:MI:SS"Z"'))
|
||||||
</insert>
|
</insert>
|
||||||
|
|
||||||
<select id="getExistingVideoIds" resultType="string">
|
<select id="getExistingVideoIds" resultType="string">
|
||||||
@@ -194,7 +195,7 @@
|
|||||||
</select>
|
</select>
|
||||||
|
|
||||||
<select id="getLatestVideoDate" resultType="string">
|
<select id="getLatestVideoDate" resultType="string">
|
||||||
SELECT TO_CHAR(MAX(published_at), 'YYYY-MM-DD"T"HH24:MI:SS"Z"')
|
SELECT TO_CHAR(MAX(published_at), 'YYYY-MM-DD"T"HH24:MI:SS"Z"') AS latest_date
|
||||||
FROM videos WHERE channel_id = #{channelId}
|
FROM videos WHERE channel_id = #{channelId}
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
@@ -220,10 +221,30 @@
|
|||||||
SELECT id, video_id, title, url
|
SELECT id, video_id, title, url
|
||||||
FROM videos
|
FROM videos
|
||||||
WHERE (transcript_text IS NULL OR dbms_lob.getlength(transcript_text) = 0)
|
WHERE (transcript_text IS NULL OR dbms_lob.getlength(transcript_text) = 0)
|
||||||
AND status != 'skip'
|
AND status NOT IN ('skip', 'no_transcript')
|
||||||
ORDER BY created_at
|
ORDER BY created_at
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
|
<select id="findVideosByIds" resultType="map">
|
||||||
|
SELECT id, video_id, title, url
|
||||||
|
FROM videos
|
||||||
|
WHERE id IN
|
||||||
|
<foreach item="id" collection="ids" open="(" separator="," close=")">
|
||||||
|
#{id}
|
||||||
|
</foreach>
|
||||||
|
ORDER BY created_at
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<select id="findVideosForExtractByIds" resultType="map">
|
||||||
|
SELECT v.id, v.video_id, v.title, v.url, v.transcript_text
|
||||||
|
FROM videos v
|
||||||
|
WHERE v.id IN
|
||||||
|
<foreach item="id" collection="ids" open="(" separator="," close=")">
|
||||||
|
#{id}
|
||||||
|
</foreach>
|
||||||
|
ORDER BY v.published_at DESC
|
||||||
|
</select>
|
||||||
|
|
||||||
<update id="updateVideoRestaurantFields">
|
<update id="updateVideoRestaurantFields">
|
||||||
UPDATE video_restaurants
|
UPDATE video_restaurants
|
||||||
SET foods_mentioned = #{foodsJson,jdbcType=CLOB},
|
SET foods_mentioned = #{foodsJson,jdbcType=CLOB},
|
||||||
|
|||||||
@@ -5,5 +5,6 @@
|
|||||||
<setting name="mapUnderscoreToCamelCase" value="true"/>
|
<setting name="mapUnderscoreToCamelCase" value="true"/>
|
||||||
<setting name="callSettersOnNulls" value="true"/>
|
<setting name="callSettersOnNulls" value="true"/>
|
||||||
<setting name="returnInstanceForEmptyRow" value="true"/>
|
<setting name="returnInstanceForEmptyRow" value="true"/>
|
||||||
|
<setting name="jdbcTypeForNull" value="VARCHAR"/>
|
||||||
</settings>
|
</settings>
|
||||||
</configuration>
|
</configuration>
|
||||||
|
|||||||
61
build_spec.yaml
Normal file
61
build_spec.yaml
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
version: 0.1
|
||||||
|
component: build
|
||||||
|
timeoutInSeconds: 1800
|
||||||
|
runAs: root
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
env:
|
||||||
|
variables:
|
||||||
|
REGISTRY: "icn.ocir.io/idyhsdamac8c/tasteby"
|
||||||
|
exportedVariables:
|
||||||
|
- IMAGE_TAG
|
||||||
|
- BACKEND_IMAGE
|
||||||
|
- FRONTEND_IMAGE
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- type: Command
|
||||||
|
name: "Setup buildx for ARM64"
|
||||||
|
command: |
|
||||||
|
docker run --rm --privileged multiarch/qemu-user-static --reset -p yes
|
||||||
|
docker buildx create --name armbuilder --use
|
||||||
|
docker buildx inspect --bootstrap
|
||||||
|
|
||||||
|
- type: Command
|
||||||
|
name: "Set image tag"
|
||||||
|
command: |
|
||||||
|
IMAGE_TAG="${OCI_BUILD_RUN_ID:0:8}-$(date +%Y%m%d%H%M)"
|
||||||
|
BACKEND_IMAGE="${REGISTRY}/backend:${IMAGE_TAG}"
|
||||||
|
FRONTEND_IMAGE="${REGISTRY}/frontend:${IMAGE_TAG}"
|
||||||
|
echo "IMAGE_TAG=${IMAGE_TAG}"
|
||||||
|
echo "BACKEND_IMAGE=${BACKEND_IMAGE}"
|
||||||
|
echo "FRONTEND_IMAGE=${FRONTEND_IMAGE}"
|
||||||
|
|
||||||
|
- type: Command
|
||||||
|
name: "Build backend image"
|
||||||
|
command: |
|
||||||
|
cd backend-java
|
||||||
|
docker buildx build --platform linux/arm64 \
|
||||||
|
-t "${BACKEND_IMAGE}" \
|
||||||
|
-t "${REGISTRY}/backend:latest" \
|
||||||
|
--load \
|
||||||
|
.
|
||||||
|
|
||||||
|
- type: Command
|
||||||
|
name: "Build frontend image"
|
||||||
|
command: |
|
||||||
|
cd frontend
|
||||||
|
docker buildx build --platform linux/arm64 \
|
||||||
|
--build-arg NEXT_PUBLIC_GOOGLE_MAPS_API_KEY="${NEXT_PUBLIC_GOOGLE_MAPS_API_KEY}" \
|
||||||
|
--build-arg NEXT_PUBLIC_GOOGLE_CLIENT_ID="${NEXT_PUBLIC_GOOGLE_CLIENT_ID}" \
|
||||||
|
-t "${FRONTEND_IMAGE}" \
|
||||||
|
-t "${REGISTRY}/frontend:latest" \
|
||||||
|
--load \
|
||||||
|
.
|
||||||
|
|
||||||
|
outputArtifacts:
|
||||||
|
- name: backend-image
|
||||||
|
type: DOCKER_IMAGE
|
||||||
|
location: ${BACKEND_IMAGE}
|
||||||
|
- name: frontend-image
|
||||||
|
type: DOCKER_IMAGE
|
||||||
|
location: ${FRONTEND_IMAGE}
|
||||||
405
docs/cicd-architecture.md
Normal file
405
docs/cicd-architecture.md
Normal file
@@ -0,0 +1,405 @@
|
|||||||
|
# Tasteby CI/CD 파이프라인 & 전체 아키텍처
|
||||||
|
|
||||||
|
## 전체 시스템 아키텍처
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────────────────┐
|
||||||
|
│ Internet │
|
||||||
|
│ www.tasteby.net │
|
||||||
|
└──────────────────────────────┬──────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
┌─────────▼──────────┐
|
||||||
|
│ Namecheap DNS │
|
||||||
|
│ A → LB External IP │
|
||||||
|
└─────────┬──────────┘
|
||||||
|
│
|
||||||
|
┌──────────────────────────────▼──────────────────────────────────────────┐
|
||||||
|
│ OCI Load Balancer (NLB) │
|
||||||
|
│ (Nginx Ingress Controller가 자동 생성) │
|
||||||
|
└──────────────────────────────┬──────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
┌──────────────────────────────▼──────────────────────────────────────────┐
|
||||||
|
│ OKE Cluster (tasteby-cluster) │
|
||||||
|
│ ap-seoul-1 │ ARM64 × 2 노드 (2CPU/8GB 각) │
|
||||||
|
│ │
|
||||||
|
│ ┌─────────────────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ Nginx Ingress Controller (ingress-nginx) │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ TLS termination (Let's Encrypt via cert-manager) │ │
|
||||||
|
│ │ tasteby.net → www.tasteby.net 리다이렉트 │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ /api/* ──→ backend Service :8000 │ │
|
||||||
|
│ │ /* ──→ frontend Service :3001 │ │
|
||||||
|
│ └─────────────────────────────────────────────────────────────────┘ │
|
||||||
|
│ │
|
||||||
|
│ ┌─── namespace: tasteby ─────────────────────────────────────────────┐ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ ┌──────────────────┐ ┌──────────────────┐ ┌────────────────┐ │ │
|
||||||
|
│ │ │ backend (×1) │ │ frontend (×1) │ │ redis (×1) │ │ │
|
||||||
|
│ │ │ Spring Boot 3 │ │ Next.js 15 │ │ Redis 7 │ │ │
|
||||||
|
│ │ │ Java 21 │ │ standalone mode │ │ alpine │ │ │
|
||||||
|
│ │ │ :8000 │ │ :3001 │ │ :6379 │ │ │
|
||||||
|
│ │ │ │ │ │ │ │ │ │
|
||||||
|
│ │ │ ┌─ Volumes ─────┐│ └──────────────────┘ └────────────────┘ │ │
|
||||||
|
│ │ │ │ oracle-wallet ││ │ │
|
||||||
|
│ │ │ │ oci-config ││ │ │
|
||||||
|
│ │ │ └───────────────┘│ │ │
|
||||||
|
│ │ └──────────────────┘ │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ ┌─── ConfigMap / Secrets ──────────────────────────────────────┐ │ │
|
||||||
|
│ │ │ tasteby-config : REDIS_HOST, OCI endpoints, 등 │ │ │
|
||||||
|
│ │ │ tasteby-secrets : DB credentials, API keys, JWT │ │ │
|
||||||
|
│ │ │ oracle-wallet : cwallet.sso, tnsnames.ora, keystore.jks │ │ │
|
||||||
|
│ │ │ oci-config : OCI API config + PEM key │ │ │
|
||||||
|
│ │ │ ocir-secret : OCIR 이미지 Pull 인증 │ │ │
|
||||||
|
│ │ └──────────────────────────────────────────────────────────────┘ │ │
|
||||||
|
│ └─────────────────────────────────────────────────────────────────────┘ │
|
||||||
|
│ │
|
||||||
|
│ ┌─── namespace: cert-manager ──┐ ┌─── namespace: ingress-nginx ──┐ │
|
||||||
|
│ │ cert-manager (×3 pods) │ │ ingress-nginx-controller │ │
|
||||||
|
│ │ ClusterIssuer: letsencrypt │ │ (NLB 자동 생성) │ │
|
||||||
|
│ └──────────────────────────────┘ └────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
┌─────────▼──────────┐
|
||||||
|
│ Oracle ADB 23ai │
|
||||||
|
│ (mTLS via Wallet) │
|
||||||
|
└────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
## 외부 서비스 연동
|
||||||
|
|
||||||
|
```
|
||||||
|
backend (Spring Boot)
|
||||||
|
├─→ Oracle ADB 23ai : JDBC + mTLS (Wallet)
|
||||||
|
├─→ OCI GenAI (Chat) : 식당 정보 추출, 음식 태그, 평가 생성
|
||||||
|
├─→ OCI GenAI (Embed) : 벡터 임베딩 (Cohere embed-v4)
|
||||||
|
├─→ Google Maps Places API : 식당 검색, 좌표 조회
|
||||||
|
├─→ YouTube Data API v3 : 채널/영상 정보 조회
|
||||||
|
└─→ Redis : 캐시 (API 응답, 검색 결과)
|
||||||
|
|
||||||
|
frontend (Next.js)
|
||||||
|
├─→ Google Maps JavaScript API : 지도 렌더링
|
||||||
|
└─→ Google OAuth 2.0 : 사용자 인증
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## CI/CD 파이프라인
|
||||||
|
|
||||||
|
### 파이프라인 개요
|
||||||
|
|
||||||
|
```
|
||||||
|
┌──────────┐ ┌──────────────────┐ ┌──────────────────────┐ ┌─────────┐
|
||||||
|
│ 개발자 │────→│ OCI Code Repo │────→│ OCI DevOps Build │────→│ OKE │
|
||||||
|
│ git push │ │ (tasteby) │ │ Pipeline │ │ 배포 │
|
||||||
|
└──────────┘ └──────────────────┘ └──────────────────────┘ └─────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 상세 흐름
|
||||||
|
|
||||||
|
```
|
||||||
|
1. 코드 푸시
|
||||||
|
┌──────────────┐
|
||||||
|
│ git push oci │ ← OCI Code Repository remote
|
||||||
|
└──────┬───────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
2. 빌드 파이프라인 (OCI DevOps Build Pipeline)
|
||||||
|
┌───────────────────────────────────────────────────────────┐
|
||||||
|
│ │
|
||||||
|
│ Stage 1: Managed Build │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ build_spec.yaml 실행 │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ 1) IMAGE_TAG 생성 (BuildRunID + timestamp) │ │
|
||||||
|
│ │ 2) docker build --platform linux/arm64 │ │
|
||||||
|
│ │ - backend-java/Dockerfile → backend image │ │
|
||||||
|
│ │ - frontend/Dockerfile → frontend image │ │
|
||||||
|
│ │ 3) Output: BACKEND_IMAGE, FRONTEND_IMAGE │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
│ │ │
|
||||||
|
│ ▼ │
|
||||||
|
│ Stage 2: Deliver Artifacts │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ Docker images → OCIR 푸시 │ │
|
||||||
|
│ │ │ │
|
||||||
|
│ │ icn.ocir.io/idyhsdamac8c/tasteby/backend:TAG │ │
|
||||||
|
│ │ icn.ocir.io/idyhsdamac8c/tasteby/frontend:TAG │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
└───────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
3. 배포 (수동 또는 deploy.sh)
|
||||||
|
┌───────────────────────────────────────────────────────────┐
|
||||||
|
│ kubectl set image deployment/backend backend=IMAGE:TAG │
|
||||||
|
│ kubectl set image deployment/frontend frontend=IMAGE:TAG │
|
||||||
|
│ kubectl rollout status ... │
|
||||||
|
│ │
|
||||||
|
│ git tag -a "vX.Y.Z" -m "Deploy: ..." │
|
||||||
|
│ git push origin "vX.Y.Z" │
|
||||||
|
└───────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### Git Remote 구성
|
||||||
|
|
||||||
|
```
|
||||||
|
origin → Gitea (gittea.cloud-handson.com) ← 소스 코드 관리
|
||||||
|
oci → OCI Code Repository ← CI/CD 트리거용
|
||||||
|
```
|
||||||
|
|
||||||
|
두 리모트에 모두 push하여 소스와 빌드를 동기화합니다.
|
||||||
|
|
||||||
|
### OCI IAM 권한 설정 (빌드/배포용)
|
||||||
|
|
||||||
|
OCI DevOps Build Pipeline이 코드 레포, OCIR, 시크릿 등에 접근하려면 **Dynamic Group**과 **IAM Policy**가 필요합니다.
|
||||||
|
|
||||||
|
#### Dynamic Group
|
||||||
|
|
||||||
|
| 이름 | 설명 |
|
||||||
|
|------|------|
|
||||||
|
| `tasteby-build-pipeline` | DevOps 빌드/배포 파이프라인 리소스 |
|
||||||
|
|
||||||
|
**Matching Rule:**
|
||||||
|
```
|
||||||
|
ANY {
|
||||||
|
resource.type = 'devopsbuildpipeline',
|
||||||
|
resource.type = 'devopsrepository',
|
||||||
|
resource.type = 'devopsdeploypipeline',
|
||||||
|
resource.type = 'devopsconnection'
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### IAM Policy
|
||||||
|
|
||||||
|
| 이름 | 설명 |
|
||||||
|
|------|------|
|
||||||
|
| `tasteby-devops-policy` | DevOps 파이프라인 리소스 접근 권한 |
|
||||||
|
|
||||||
|
**Policy Statements:**
|
||||||
|
```
|
||||||
|
Allow dynamic-group tasteby-build-pipeline to manage devops-family in tenancy
|
||||||
|
Allow dynamic-group tasteby-build-pipeline to manage repos in tenancy
|
||||||
|
Allow dynamic-group tasteby-build-pipeline to read secret-family in tenancy
|
||||||
|
Allow dynamic-group tasteby-build-pipeline to manage generic-artifacts in tenancy
|
||||||
|
Allow dynamic-group tasteby-build-pipeline to use ons-topics in tenancy
|
||||||
|
```
|
||||||
|
|
||||||
|
> **참고**: IAM 정책은 적용 후 전파에 최대 수 분이 걸릴 수 있습니다.
|
||||||
|
> 빌드 실행 시 `RelatedResourceNotAuthorizedOrNotFound` 오류가 나면 정책 전파를 기다린 후 재시도하세요.
|
||||||
|
|
||||||
|
#### OCI Code Repository 인증 (HTTPS)
|
||||||
|
|
||||||
|
```
|
||||||
|
Username: <tenancy-name>/oracleidentitycloudservice/<oci-username>
|
||||||
|
Password: OCI Auth Token (User Settings에서 생성)
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Git remote 추가 예시
|
||||||
|
git remote add oci https://devops.scmservice.ap-seoul-1.oci.oraclecloud.com/namespaces/<namespace>/projects/tasteby/repositories/tasteby
|
||||||
|
```
|
||||||
|
|
||||||
|
### build_spec.yaml 구조
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
# OCI DevOps Build Pipeline 설정
|
||||||
|
version: 0.1
|
||||||
|
component: build
|
||||||
|
shell: bash
|
||||||
|
|
||||||
|
env:
|
||||||
|
variables:
|
||||||
|
REGISTRY: "icn.ocir.io/idyhsdamac8c/tasteby"
|
||||||
|
exportedVariables:
|
||||||
|
- IMAGE_TAG # 다음 stage에서 사용
|
||||||
|
- BACKEND_IMAGE
|
||||||
|
- FRONTEND_IMAGE
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- Set image tag # BuildRunID + timestamp 조합
|
||||||
|
- Build backend image # backend-java/Dockerfile, ARM64
|
||||||
|
- Build frontend image # frontend/Dockerfile, ARM64
|
||||||
|
|
||||||
|
outputArtifacts:
|
||||||
|
- backend-image (DOCKER_IMAGE)
|
||||||
|
- frontend-image (DOCKER_IMAGE)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 로컬 배포 (deploy.sh)
|
||||||
|
|
||||||
|
OCI DevOps 없이 로컬에서 직접 배포할 때 사용합니다.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 전체 배포
|
||||||
|
./deploy.sh "초기 배포"
|
||||||
|
|
||||||
|
# 백엔드만
|
||||||
|
./deploy.sh --backend-only "API 버그 수정"
|
||||||
|
|
||||||
|
# 프론트엔드만
|
||||||
|
./deploy.sh --frontend-only "UI 개선"
|
||||||
|
|
||||||
|
# 드라이런
|
||||||
|
./deploy.sh --dry-run "테스트"
|
||||||
|
```
|
||||||
|
|
||||||
|
**deploy.sh 동작:**
|
||||||
|
1. 최신 git tag에서 다음 버전 계산 (v0.1.X → v0.1.X+1)
|
||||||
|
2. Docker build (ARM64) + OCIR push
|
||||||
|
3. `kubectl set image` → rollout 대기
|
||||||
|
4. git tag 생성 + push
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Docker 이미지 빌드
|
||||||
|
|
||||||
|
### Backend (Spring Boot)
|
||||||
|
|
||||||
|
```
|
||||||
|
eclipse-temurin:21-jdk (build)
|
||||||
|
└─ gradlew bootJar
|
||||||
|
└─ app.jar
|
||||||
|
|
||||||
|
eclipse-temurin:21-jre (runtime)
|
||||||
|
└─ java -XX:MaxRAMPercentage=75.0 -jar app.jar
|
||||||
|
└─ EXPOSE 8000
|
||||||
|
```
|
||||||
|
|
||||||
|
### Frontend (Next.js)
|
||||||
|
|
||||||
|
```
|
||||||
|
node:22-alpine (build)
|
||||||
|
└─ npm ci + npm run build
|
||||||
|
└─ NEXT_PUBLIC_* 빌드 시 주입 (build args)
|
||||||
|
|
||||||
|
node:22-alpine (runtime)
|
||||||
|
└─ .next/standalone + .next/static + public/
|
||||||
|
└─ node server.js
|
||||||
|
└─ EXPOSE 3001
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## K8s 리소스 구성
|
||||||
|
|
||||||
|
### 파일 구조
|
||||||
|
|
||||||
|
```
|
||||||
|
k8s/
|
||||||
|
├── namespace.yaml # tasteby namespace
|
||||||
|
├── configmap.yaml # 비밀이 아닌 설정
|
||||||
|
├── secrets.yaml.template # 시크릿 템플릿 (실제 파일은 .gitignore)
|
||||||
|
├── redis-deployment.yaml # Redis 7 + Service
|
||||||
|
├── backend-deployment.yaml # Spring Boot + Service
|
||||||
|
├── frontend-deployment.yaml # Next.js + Service
|
||||||
|
├── ingress.yaml # Nginx Ingress + TLS
|
||||||
|
└── cert-manager/
|
||||||
|
└── cluster-issuer.yaml # Let's Encrypt ClusterIssuer
|
||||||
|
```
|
||||||
|
|
||||||
|
### 리소스 할당
|
||||||
|
|
||||||
|
| Pod | replicas | CPU req/lim | Memory req/lim |
|
||||||
|
|-----|----------|-------------|----------------|
|
||||||
|
| backend | 1 | 500m / 1 | 768Mi / 1536Mi |
|
||||||
|
| frontend | 1 | 200m / 500m | 256Mi / 512Mi |
|
||||||
|
| redis | 1 | 100m / 200m | 128Mi / 256Mi |
|
||||||
|
| ingress-controller | 1 | 100m / 200m | 128Mi / 256Mi |
|
||||||
|
| cert-manager (×3) | 1 each | 50m / 100m | 64Mi / 128Mi |
|
||||||
|
| **합계** | | **~1.2 CPU** | **~1.6GB** |
|
||||||
|
|
||||||
|
클러스터: ARM64 × 2 노드 (4 CPU / 16GB 총) → 여유 충분
|
||||||
|
|
||||||
|
### 네트워크 흐름
|
||||||
|
|
||||||
|
```
|
||||||
|
Client → NLB:443 → Ingress Controller → /api/* → backend:8000
|
||||||
|
→ /* → frontend:3001
|
||||||
|
|
||||||
|
backend → redis:6379 (K8s Service DNS, 클러스터 내부)
|
||||||
|
backend → Oracle ADB (mTLS, Wallet Volume Mount)
|
||||||
|
backend → OCI GenAI (OCI SDK, oci-config Volume Mount)
|
||||||
|
backend → Google APIs (API Key, 환경변수)
|
||||||
|
```
|
||||||
|
|
||||||
|
### Volume Mounts (backend)
|
||||||
|
|
||||||
|
```
|
||||||
|
/etc/oracle/wallet/ ← Secret: oracle-wallet
|
||||||
|
├── cwallet.sso
|
||||||
|
├── tnsnames.ora
|
||||||
|
├── sqlnet.ora
|
||||||
|
├── keystore.jks
|
||||||
|
├── truststore.jks
|
||||||
|
└── ojdbc.properties
|
||||||
|
|
||||||
|
/root/.oci/ ← Secret: oci-config
|
||||||
|
├── config
|
||||||
|
└── oci_api_key.pem
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 환경 분리
|
||||||
|
|
||||||
|
```
|
||||||
|
┌────────────────────────────┬──────────────────────────────────────┐
|
||||||
|
│ 개발 (Local) │ 운영 (OKE) │
|
||||||
|
├────────────────────────────┼──────────────────────────────────────┤
|
||||||
|
│ backend/.env │ ConfigMap + Secret │
|
||||||
|
│ frontend/.env.local │ Dockerfile build args │
|
||||||
|
│ ~/.oci/config │ Secret: oci-config → /root/.oci/ │
|
||||||
|
│ 로컬 Wallet 디렉토리 │ Secret: oracle-wallet → /etc/oracle/ │
|
||||||
|
│ Redis: 192.168.0.147:6379 │ Redis: redis:6379 (K8s DNS) │
|
||||||
|
│ PM2로 프로세스 관리 │ K8s Deployment로 관리 │
|
||||||
|
│ nginx + certbot (SSL) │ Ingress + cert-manager (SSL) │
|
||||||
|
└────────────────────────────┴──────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
**변수명이 동일**하므로 코드 변경 없이 환경만 교체 가능합니다.
|
||||||
|
자세한 환경변수 목록은 [environment-guide.md](./environment-guide.md) 참고.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## OCI 리소스 정보
|
||||||
|
|
||||||
|
| 항목 | 값 |
|
||||||
|
|------|-----|
|
||||||
|
| 리전 | ap-seoul-1 (Seoul) |
|
||||||
|
| OCI 프로필 | JOUNGMINKOAWS |
|
||||||
|
| OKE 클러스터 | tasteby-cluster |
|
||||||
|
| OCIR Registry | icn.ocir.io/idyhsdamac8c/tasteby |
|
||||||
|
| DevOps 프로젝트 | tasteby |
|
||||||
|
| Code Repository | tasteby (OCI DevOps SCM) |
|
||||||
|
| 도메인 | www.tasteby.net (Namecheap) |
|
||||||
|
| SSL | Let's Encrypt (cert-manager HTTP-01) |
|
||||||
|
| 노드 | ARM64 × 2대 (2 CPU / 8GB 각) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 배포 버전 관리
|
||||||
|
|
||||||
|
- 태그 형식: `v0.1.X` (patch 자동 증가)
|
||||||
|
- deploy.sh가 자동으로 git tag 생성 + push
|
||||||
|
- 태그 메시지에 배포 대상(backend/frontend)과 이미지 태그 포함
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 태그 목록 확인
|
||||||
|
git tag -l 'v*' --sort=-v:refname
|
||||||
|
|
||||||
|
# 특정 태그 상세 확인
|
||||||
|
git tag -n20 v0.1.5
|
||||||
|
|
||||||
|
# 롤백
|
||||||
|
kubectl rollout undo deployment/backend -n tasteby
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 관련 문서
|
||||||
|
|
||||||
|
- [OKE 배포 가이드](./oke-deployment-guide.md) — 인프라 설치 및 배포 절차
|
||||||
|
- [환경 관리 가이드](./environment-guide.md) — 환경변수 및 시크릿 관리
|
||||||
239
docs/troubleshooting.md
Normal file
239
docs/troubleshooting.md
Normal file
@@ -0,0 +1,239 @@
|
|||||||
|
# Tasteby 배포 트러블슈팅 기록
|
||||||
|
|
||||||
|
## 1. OCI DevOps Build Pipeline - 코드 접근 권한 오류
|
||||||
|
|
||||||
|
**오류:**
|
||||||
|
```
|
||||||
|
Unable to fetch build_spec file build_spec.yaml due to RelatedResourceNotAuthorizedOrNotFound.
|
||||||
|
Please check if dynamic groups and the corresponding policies are properly configured.
|
||||||
|
```
|
||||||
|
|
||||||
|
**원인:** OCI DevOps Build Pipeline이 Code Repository에 접근할 IAM 권한이 없음
|
||||||
|
|
||||||
|
**해결:**
|
||||||
|
1. Dynamic Group 생성 — 빌드 파이프라인 리소스를 포함하는 매칭 룰:
|
||||||
|
```
|
||||||
|
ANY {
|
||||||
|
resource.type = 'devopsbuildpipeline',
|
||||||
|
resource.type = 'devopsrepository',
|
||||||
|
resource.type = 'devopsdeploypipeline',
|
||||||
|
resource.type = 'devopsconnection'
|
||||||
|
}
|
||||||
|
```
|
||||||
|
2. IAM Policy 생성:
|
||||||
|
```
|
||||||
|
Allow dynamic-group tasteby-build-pipeline to manage devops-family in tenancy
|
||||||
|
Allow dynamic-group tasteby-build-pipeline to manage repos in tenancy
|
||||||
|
Allow dynamic-group tasteby-build-pipeline to read secret-family in tenancy
|
||||||
|
Allow dynamic-group tasteby-build-pipeline to manage generic-artifacts in tenancy
|
||||||
|
Allow dynamic-group tasteby-build-pipeline to use ons-topics in tenancy
|
||||||
|
```
|
||||||
|
3. IAM 정책 전파에 수 분 소요 — 적용 후 바로 빌드하면 동일 오류 발생할 수 있음
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. OCI DevOps Build Pipeline - Logs 미설정
|
||||||
|
|
||||||
|
**오류:**
|
||||||
|
```
|
||||||
|
Logs need to be enabled in order to run the builds.
|
||||||
|
Please enable logs for your project.
|
||||||
|
```
|
||||||
|
|
||||||
|
**원인:** DevOps 프로젝트에 OCI Logging이 설정되지 않음
|
||||||
|
|
||||||
|
**해결:**
|
||||||
|
1. OCI Logging > Log Group 생성 (예: `tasteby-devops-logs`)
|
||||||
|
2. Log Group에 Service Log 생성:
|
||||||
|
- Source: `devops` 서비스
|
||||||
|
- Resource: DevOps 프로젝트 OCID
|
||||||
|
- Category: `all`
|
||||||
|
3. DevOps 프로젝트에 Notification Topic 설정 필요
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. OCI DevOps Build Pipeline - ARM64 이미지 빌드 불가
|
||||||
|
|
||||||
|
**오류:**
|
||||||
|
```
|
||||||
|
Step 'Step_CommandV1_2' failed with exit code: '1' (docker build --platform linux/arm64)
|
||||||
|
Step 'Step_CommandV1_1' failed with exit code: '125' (QEMU 설정 시도)
|
||||||
|
```
|
||||||
|
|
||||||
|
**원인:**
|
||||||
|
- OCI DevOps Managed Build는 x86_64 러너만 제공 (`OL7_X86_64_STANDARD_10`)
|
||||||
|
- ARM64 이미지를 직접 빌드할 수 없음
|
||||||
|
- `--privileged` 모드가 허용되지 않아 QEMU 크로스빌드도 불가
|
||||||
|
|
||||||
|
**해결:**
|
||||||
|
- Colima (macOS 경량 Docker) 설치로 로컬 ARM64 빌드:
|
||||||
|
```bash
|
||||||
|
brew install colima docker
|
||||||
|
colima start --arch aarch64 --cpu 2 --memory 4
|
||||||
|
```
|
||||||
|
- deploy.sh로 로컬 빌드 → OCIR push → K8s 배포
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. OCI Code Repository - HTTPS 인증 실패
|
||||||
|
|
||||||
|
**오류:**
|
||||||
|
```
|
||||||
|
fatal: Authentication failed for 'https://devops.scmservice.ap-seoul-1.oci.oraclecloud.com/...'
|
||||||
|
```
|
||||||
|
|
||||||
|
**원인:** OCI Code Repository HTTPS 인증의 username 형식이 특수함
|
||||||
|
|
||||||
|
**해결:**
|
||||||
|
- IDCS 연동 사용자의 경우 username 형식:
|
||||||
|
```
|
||||||
|
<tenancy-name>/oracleidentitycloudservice/<oci-username>
|
||||||
|
```
|
||||||
|
예시: `joungminkoaws/oracleidentitycloudservice/joungmin.ko.aws@gmail.com`
|
||||||
|
- Password: OCI Auth Token (User Settings > Auth Tokens에서 생성)
|
||||||
|
- `idyhsdamac8c` (namespace)가 아닌 `joungminkoaws` (tenancy name)을 사용해야 함
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Docker 빌드 컨텍스트 과대 (276MB)
|
||||||
|
|
||||||
|
**증상:**
|
||||||
|
```
|
||||||
|
Sending build context to Docker daemon 276.4MB
|
||||||
|
```
|
||||||
|
|
||||||
|
**원인:** `.dockerignore` 파일이 없어 `build/`, `.gradle/`, `node_modules/` 등이 포함됨
|
||||||
|
|
||||||
|
**해결:**
|
||||||
|
- `backend-java/.dockerignore` 생성:
|
||||||
|
```
|
||||||
|
build/
|
||||||
|
.gradle/
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
```
|
||||||
|
- `frontend/.dockerignore` 생성:
|
||||||
|
```
|
||||||
|
node_modules/
|
||||||
|
.next/
|
||||||
|
.env.local
|
||||||
|
```
|
||||||
|
- 결과: 276MB → 336KB (backend), 602KB (frontend)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Redis ImageInspectError (OKE CRI-O)
|
||||||
|
|
||||||
|
**오류:**
|
||||||
|
```
|
||||||
|
Failed to inspect image "": rpc error: code = Unknown desc = short name mode is enforcing,
|
||||||
|
but image name redis:7-alpine returns ambiguous list
|
||||||
|
```
|
||||||
|
|
||||||
|
**원인:** OKE는 CRI-O 컨테이너 런타임을 사용하며, short name (예: `redis:7-alpine`)을 허용하지 않음
|
||||||
|
|
||||||
|
**해결:**
|
||||||
|
- 이미지명에 full registry prefix 추가:
|
||||||
|
```yaml
|
||||||
|
# 변경 전
|
||||||
|
image: redis:7-alpine
|
||||||
|
# 변경 후
|
||||||
|
image: docker.io/library/redis:7-alpine
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. OCIR ImagePullBackOff (K8s)
|
||||||
|
|
||||||
|
**오류:**
|
||||||
|
```
|
||||||
|
Failed to pull image "icn.ocir.io/.../backend:latest": unable to retrieve auth token:
|
||||||
|
invalid username/password: unknown: Unauthorized
|
||||||
|
```
|
||||||
|
|
||||||
|
**원인:** K8s `ocir-secret`의 username 형식이 잘못됨
|
||||||
|
|
||||||
|
**해결:**
|
||||||
|
- IDCS 사용자의 경우 OCIR pull secret 생성 시:
|
||||||
|
```bash
|
||||||
|
kubectl create secret docker-registry ocir-secret \
|
||||||
|
--docker-server=icn.ocir.io \
|
||||||
|
--docker-username='<namespace>/oracleidentitycloudservice/<username>' \
|
||||||
|
--docker-password='<auth-token>' \
|
||||||
|
-n tasteby
|
||||||
|
```
|
||||||
|
- Docker login 시에도 동일한 형식:
|
||||||
|
```bash
|
||||||
|
docker login icn.ocir.io \
|
||||||
|
-u "<namespace>/oracleidentitycloudservice/<username>"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. kubectl 인증 실패
|
||||||
|
|
||||||
|
**오류:**
|
||||||
|
```
|
||||||
|
error: You must be logged in to the server (Unauthorized)
|
||||||
|
```
|
||||||
|
|
||||||
|
**원인:** kubeconfig 생성 시 OCI 프로필이 지정되지 않음
|
||||||
|
|
||||||
|
**해결:**
|
||||||
|
- `~/.kube/config`의 user args에 `--profile JOUNGMINKOAWS` 추가:
|
||||||
|
```yaml
|
||||||
|
users:
|
||||||
|
- name: user-xxx
|
||||||
|
user:
|
||||||
|
exec:
|
||||||
|
args:
|
||||||
|
- ce
|
||||||
|
- cluster
|
||||||
|
- generate-token
|
||||||
|
- --cluster-id
|
||||||
|
- ocid1.cluster.oc1...
|
||||||
|
- --region
|
||||||
|
- ap-seoul-1
|
||||||
|
- --profile # ← 추가
|
||||||
|
- JOUNGMINKOAWS # ← 추가
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. Let's Encrypt 인증서 발급 실패 - Timeout during connect
|
||||||
|
|
||||||
|
**오류:**
|
||||||
|
```
|
||||||
|
acme: authorization error for www.tasteby.net: 400 urn:ietf:params:acme:error:connection:
|
||||||
|
64.110.90.89: Timeout during connect (likely firewall problem)
|
||||||
|
```
|
||||||
|
|
||||||
|
**원인:** OKE VCN의 Security List에서 LB 서브넷으로의 80/443 포트가 열려있지 않음
|
||||||
|
|
||||||
|
**해결:**
|
||||||
|
1. **LB 서브넷 Security List**에 Ingress 규칙 추가:
|
||||||
|
- `0.0.0.0/0` → TCP 80 (HTTP)
|
||||||
|
- `0.0.0.0/0` → TCP 443 (HTTPS)
|
||||||
|
- Egress: `0.0.0.0/0` → All protocols
|
||||||
|
|
||||||
|
2. **노드 서브넷 Security List**에 LB→노드 Ingress 규칙 추가:
|
||||||
|
- `10.0.20.0/24` (LB 서브넷 CIDR) → TCP 30000-32767 (NodePort)
|
||||||
|
- `10.0.20.0/24` → TCP 10256 (Health check)
|
||||||
|
|
||||||
|
3. 인증서 재발급:
|
||||||
|
```bash
|
||||||
|
kubectl delete certificate tasteby-tls -n tasteby
|
||||||
|
kubectl apply -f k8s/ingress.yaml
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. tasteby.net (root domain) DNS 미전파
|
||||||
|
|
||||||
|
**증상:** www.tasteby.net은 되지만 tasteby.net challenge가 `pending` 상태
|
||||||
|
|
||||||
|
**원인:** Namecheap에서 @ (root) A 레코드가 설정되지 않았거나 전파가 안 됨
|
||||||
|
|
||||||
|
**해결:**
|
||||||
|
- Ingress TLS에서 www.tasteby.net만 먼저 설정하여 인증서 발급
|
||||||
|
- root domain DNS 전파 완료 후 TLS hosts에 tasteby.net 추가하고 인증서 재발급
|
||||||
3
frontend/.dockerignore
Normal file
3
frontend/.dockerignore
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
node_modules/
|
||||||
|
.next/
|
||||||
|
.env.local
|
||||||
@@ -393,35 +393,46 @@ function VideosPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const startBulkStream = async (mode: "transcript" | "extract") => {
|
const startBulkStream = async (mode: "transcript" | "extract", ids?: string[]) => {
|
||||||
const isTranscript = mode === "transcript";
|
const isTranscript = mode === "transcript";
|
||||||
const setRunning = isTranscript ? setBulkTranscripting : setBulkExtracting;
|
const setRunning = isTranscript ? setBulkTranscripting : setBulkExtracting;
|
||||||
|
const hasSelection = ids && ids.length > 0;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const pending = isTranscript
|
let count: number;
|
||||||
? await api.getBulkTranscriptPending()
|
if (hasSelection) {
|
||||||
: await api.getBulkExtractPending();
|
count = ids.length;
|
||||||
if (pending.count === 0) {
|
} else {
|
||||||
alert(isTranscript ? "자막 없는 영상이 없습니다" : "추출 대기 중인 영상이 없습니다");
|
const pending = isTranscript
|
||||||
return;
|
? await api.getBulkTranscriptPending()
|
||||||
|
: await api.getBulkExtractPending();
|
||||||
|
if (pending.count === 0) {
|
||||||
|
alert(isTranscript ? "자막 없는 영상이 없습니다" : "추출 대기 중인 영상이 없습니다");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
count = pending.count;
|
||||||
}
|
}
|
||||||
const msg = isTranscript
|
const msg = isTranscript
|
||||||
? `자막 없는 영상 ${pending.count}개의 트랜스크립트를 수집하시겠습니까?\n(영상 당 5~15초 랜덤 딜레이)`
|
? `${hasSelection ? "선택한 " : "자막 없는 "}영상 ${count}개의 트랜스크립트를 수집하시겠습니까?`
|
||||||
: `LLM 추출이 안된 영상 ${pending.count}개를 벌크 처리하시겠습니까?\n(영상 당 3~8초 랜덤 딜레이)`;
|
: `${hasSelection ? "선택한 " : "LLM 추출이 안된 "}영상 ${count}개를 벌크 처리하시겠습니까?`;
|
||||||
if (!confirm(msg)) return;
|
if (!confirm(msg)) return;
|
||||||
|
|
||||||
setRunning(true);
|
setRunning(true);
|
||||||
setBulkProgress({
|
setBulkProgress({
|
||||||
label: isTranscript ? "벌크 자막 수집" : "벌크 LLM 추출",
|
label: isTranscript ? "벌크 자막 수집" : "벌크 LLM 추출",
|
||||||
total: pending.count, current: 0, currentTitle: "", results: [],
|
total: count, current: 0, currentTitle: "", results: [],
|
||||||
});
|
});
|
||||||
|
|
||||||
const apiBase = process.env.NEXT_PUBLIC_API_URL || "";
|
const apiBase = process.env.NEXT_PUBLIC_API_URL || "";
|
||||||
const endpoint = isTranscript ? "/api/videos/bulk-transcript" : "/api/videos/bulk-extract";
|
const endpoint = isTranscript ? "/api/videos/bulk-transcript" : "/api/videos/bulk-extract";
|
||||||
const token = typeof window !== "undefined" ? localStorage.getItem("tasteby_token") : null;
|
const token = typeof window !== "undefined" ? localStorage.getItem("tasteby_token") : null;
|
||||||
const headers: Record<string, string> = {};
|
const headers: Record<string, string> = { "Content-Type": "application/json" };
|
||||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||||
const resp = await fetch(`${apiBase}${endpoint}`, { method: "POST", headers });
|
const resp = await fetch(`${apiBase}${endpoint}`, {
|
||||||
|
method: "POST",
|
||||||
|
headers,
|
||||||
|
body: hasSelection ? JSON.stringify({ ids }) : undefined,
|
||||||
|
});
|
||||||
if (!resp.ok) {
|
if (!resp.ok) {
|
||||||
alert(`벌크 요청 실패: ${resp.status} ${resp.statusText}`);
|
alert(`벌크 요청 실패: ${resp.status} ${resp.statusText}`);
|
||||||
setRunning(false);
|
setRunning(false);
|
||||||
@@ -757,6 +768,20 @@ function VideosPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
)}
|
)}
|
||||||
{isAdmin && selected.size > 0 && (
|
{isAdmin && selected.size > 0 && (
|
||||||
<>
|
<>
|
||||||
|
<button
|
||||||
|
onClick={() => startBulkStream("transcript", Array.from(selected))}
|
||||||
|
disabled={bulkTranscripting || bulkExtracting}
|
||||||
|
className="bg-orange-500 text-white px-4 py-2 rounded text-sm hover:bg-orange-600 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
선택 자막 수집 ({selected.size})
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={() => startBulkStream("extract", Array.from(selected))}
|
||||||
|
disabled={bulkExtracting || bulkTranscripting}
|
||||||
|
className="bg-purple-500 text-white px-4 py-2 rounded text-sm hover:bg-purple-600 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
선택 LLM 추출 ({selected.size})
|
||||||
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={handleBulkSkip}
|
onClick={handleBulkSkip}
|
||||||
className="bg-gray-500 text-white px-4 py-2 rounded text-sm hover:bg-gray-600"
|
className="bg-gray-500 text-white px-4 py-2 rounded text-sm hover:bg-gray-600"
|
||||||
@@ -1495,6 +1520,12 @@ function RestaurantsPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
const [editForm, setEditForm] = useState<Record<string, string>>({});
|
const [editForm, setEditForm] = useState<Record<string, string>>({});
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
const [videos, setVideos] = useState<VideoLink[]>([]);
|
const [videos, setVideos] = useState<VideoLink[]>([]);
|
||||||
|
const [tablingSearching, setTablingSearching] = useState(false);
|
||||||
|
const [bulkTabling, setBulkTabling] = useState(false);
|
||||||
|
const [bulkTablingProgress, setBulkTablingProgress] = useState({ current: 0, total: 0, name: "", linked: 0, notFound: 0 });
|
||||||
|
const [catchtableSearching, setCatchtableSearching] = useState(false);
|
||||||
|
const [bulkCatchtable, setBulkCatchtable] = useState(false);
|
||||||
|
const [bulkCatchtableProgress, setBulkCatchtableProgress] = useState({ current: 0, total: 0, name: "", linked: 0, notFound: 0 });
|
||||||
type RestSortKey = "name" | "region" | "cuisine_type" | "price_range" | "rating" | "business_status";
|
type RestSortKey = "name" | "region" | "cuisine_type" | "price_range" | "rating" | "business_status";
|
||||||
const [sortKey, setSortKey] = useState<RestSortKey>("name");
|
const [sortKey, setSortKey] = useState<RestSortKey>("name");
|
||||||
const [sortAsc, setSortAsc] = useState(true);
|
const [sortAsc, setSortAsc] = useState(true);
|
||||||
@@ -1617,10 +1648,126 @@ function RestaurantsPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
{isAdmin && (<>
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
const pending = await fetch(`/api/restaurants/tabling-pending`, {
|
||||||
|
headers: { Authorization: `Bearer ${localStorage.getItem("tasteby_token")}` },
|
||||||
|
}).then(r => r.json());
|
||||||
|
if (pending.count === 0) { alert("테이블링 미연결 식당이 없습니다"); return; }
|
||||||
|
if (!confirm(`테이블링 미연결 식당 ${pending.count}개를 벌크 검색합니다.\n식당당 5~15초 소요됩니다. 진행할까요?`)) return;
|
||||||
|
setBulkTabling(true);
|
||||||
|
setBulkTablingProgress({ current: 0, total: pending.count, name: "", linked: 0, notFound: 0 });
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/restaurants/bulk-tabling", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Authorization: `Bearer ${localStorage.getItem("tasteby_token")}` },
|
||||||
|
});
|
||||||
|
const reader = res.body!.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buf = "";
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buf += decoder.decode(value, { stream: true });
|
||||||
|
const lines = buf.split("\n");
|
||||||
|
buf = lines.pop() || "";
|
||||||
|
for (const line of lines) {
|
||||||
|
const m = line.match(/^data:(.+)$/);
|
||||||
|
if (!m) continue;
|
||||||
|
const evt = JSON.parse(m[1]);
|
||||||
|
if (evt.type === "processing" || evt.type === "done" || evt.type === "notfound" || evt.type === "error") {
|
||||||
|
setBulkTablingProgress(p => ({
|
||||||
|
...p, current: evt.current, total: evt.total || p.total, name: evt.name,
|
||||||
|
linked: evt.type === "done" ? p.linked + 1 : p.linked,
|
||||||
|
notFound: (evt.type === "notfound" || evt.type === "error") ? p.notFound + 1 : p.notFound,
|
||||||
|
}));
|
||||||
|
} else if (evt.type === "complete") {
|
||||||
|
alert(`완료! 연결: ${evt.linked}개, 미발견: ${evt.notFound}개`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { alert("벌크 테이블링 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||||
|
finally { setBulkTabling(false); load(); }
|
||||||
|
}}
|
||||||
|
disabled={bulkTabling}
|
||||||
|
className="px-3 py-1.5 text-xs bg-orange-500 text-white rounded hover:bg-orange-600 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{bulkTabling ? `테이블링 검색 중 (${bulkTablingProgress.current}/${bulkTablingProgress.total})` : "벌크 테이블링 연결"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
const pending = await fetch(`/api/restaurants/catchtable-pending`, {
|
||||||
|
headers: { Authorization: `Bearer ${localStorage.getItem("tasteby_token")}` },
|
||||||
|
}).then(r => r.json());
|
||||||
|
if (pending.count === 0) { alert("캐치테이블 미연결 식당이 없습니다"); return; }
|
||||||
|
if (!confirm(`캐치테이블 미연결 식당 ${pending.count}개를 벌크 검색합니다.\n식당당 5~15초 소요됩니다. 진행할까요?`)) return;
|
||||||
|
setBulkCatchtable(true);
|
||||||
|
setBulkCatchtableProgress({ current: 0, total: pending.count, name: "", linked: 0, notFound: 0 });
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/restaurants/bulk-catchtable", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { Authorization: `Bearer ${localStorage.getItem("tasteby_token")}` },
|
||||||
|
});
|
||||||
|
const reader = res.body!.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buf = "";
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
buf += decoder.decode(value, { stream: true });
|
||||||
|
const lines = buf.split("\n");
|
||||||
|
buf = lines.pop() || "";
|
||||||
|
for (const line of lines) {
|
||||||
|
const m = line.match(/^data:(.+)$/);
|
||||||
|
if (!m) continue;
|
||||||
|
const evt = JSON.parse(m[1]);
|
||||||
|
if (evt.type === "processing" || evt.type === "done" || evt.type === "notfound" || evt.type === "error") {
|
||||||
|
setBulkCatchtableProgress(p => ({
|
||||||
|
...p, current: evt.current, total: evt.total || p.total, name: evt.name,
|
||||||
|
linked: evt.type === "done" ? p.linked + 1 : p.linked,
|
||||||
|
notFound: (evt.type === "notfound" || evt.type === "error") ? p.notFound + 1 : p.notFound,
|
||||||
|
}));
|
||||||
|
} else if (evt.type === "complete") {
|
||||||
|
alert(`완료! 연결: ${evt.linked}개, 미발견: ${evt.notFound}개`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { alert("벌크 캐치테이블 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||||
|
finally { setBulkCatchtable(false); load(); }
|
||||||
|
}}
|
||||||
|
disabled={bulkCatchtable}
|
||||||
|
className="px-3 py-1.5 text-xs bg-violet-500 text-white rounded hover:bg-violet-600 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{bulkCatchtable ? `캐치테이블 검색 중 (${bulkCatchtableProgress.current}/${bulkCatchtableProgress.total})` : "벌크 캐치테이블 연결"}
|
||||||
|
</button>
|
||||||
|
</>)}
|
||||||
<span className="text-sm text-gray-400 ml-auto">
|
<span className="text-sm text-gray-400 ml-auto">
|
||||||
{nameSearch ? `${sorted.length} / ` : ""}총 {restaurants.length}개 식당
|
{nameSearch ? `${sorted.length} / ` : ""}총 {restaurants.length}개 식당
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
|
{bulkTabling && bulkTablingProgress.name && (
|
||||||
|
<div className="bg-orange-50 rounded p-3 mb-4 text-sm">
|
||||||
|
<div className="flex justify-between mb-1">
|
||||||
|
<span>{bulkTablingProgress.current}/{bulkTablingProgress.total} - {bulkTablingProgress.name}</span>
|
||||||
|
<span className="text-xs text-gray-500">연결: {bulkTablingProgress.linked} / 미발견: {bulkTablingProgress.notFound}</span>
|
||||||
|
</div>
|
||||||
|
<div className="w-full bg-orange-200 rounded-full h-1.5">
|
||||||
|
<div className="bg-orange-500 h-1.5 rounded-full transition-all" style={{ width: `${(bulkTablingProgress.current / bulkTablingProgress.total) * 100}%` }} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{bulkCatchtable && bulkCatchtableProgress.name && (
|
||||||
|
<div className="bg-violet-50 rounded p-3 mb-4 text-sm">
|
||||||
|
<div className="flex justify-between mb-1">
|
||||||
|
<span>{bulkCatchtableProgress.current}/{bulkCatchtableProgress.total} - {bulkCatchtableProgress.name}</span>
|
||||||
|
<span className="text-xs text-gray-500">연결: {bulkCatchtableProgress.linked} / 미발견: {bulkCatchtableProgress.notFound}</span>
|
||||||
|
</div>
|
||||||
|
<div className="w-full bg-violet-200 rounded-full h-1.5">
|
||||||
|
<div className="bg-violet-500 h-1.5 rounded-full transition-all" style={{ width: `${(bulkCatchtableProgress.current / bulkCatchtableProgress.total) * 100}%` }} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="bg-white rounded-lg shadow overflow-auto">
|
<div className="bg-white rounded-lg shadow overflow-auto">
|
||||||
<table className="w-full text-sm">
|
<table className="w-full text-sm">
|
||||||
@@ -1730,6 +1877,109 @@ function RestaurantsPanel({ isAdmin }: { isAdmin: boolean }) {
|
|||||||
</a>
|
</a>
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
{/* 테이블링 연결 */}
|
||||||
|
{isAdmin && (
|
||||||
|
<div className="mt-4 border-t pt-3">
|
||||||
|
<div className="flex items-center gap-2 mb-2">
|
||||||
|
<h4 className="text-xs font-semibold text-gray-500">테이블링</h4>
|
||||||
|
{selected.tabling_url === "NONE" ? (
|
||||||
|
<span className="text-xs text-gray-400">검색완료-없음</span>
|
||||||
|
) : selected.tabling_url ? (
|
||||||
|
<a href={selected.tabling_url} target="_blank" rel="noopener noreferrer"
|
||||||
|
className="text-blue-600 hover:underline text-xs">{selected.tabling_url}</a>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-gray-400">미연결</span>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
setTablingSearching(true);
|
||||||
|
try {
|
||||||
|
const results = await api.searchTabling(selected.id);
|
||||||
|
if (results.length === 0) {
|
||||||
|
alert("테이블링에서 검색 결과가 없습니다");
|
||||||
|
} else {
|
||||||
|
const best = results[0];
|
||||||
|
if (confirm(`"${best.title}"\n${best.url}\n\n이 테이블링 페이지를 연결할까요?`)) {
|
||||||
|
await api.setTablingUrl(selected.id, best.url);
|
||||||
|
setSelected({ ...selected, tabling_url: best.url });
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { alert("검색 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||||
|
finally { setTablingSearching(false); }
|
||||||
|
}}
|
||||||
|
disabled={tablingSearching}
|
||||||
|
className="px-2 py-0.5 text-[11px] bg-orange-500 text-white rounded hover:bg-orange-600 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{tablingSearching ? "검색 중..." : "테이블링 검색"}
|
||||||
|
</button>
|
||||||
|
{selected.tabling_url && (
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
await api.setTablingUrl(selected.id, "");
|
||||||
|
setSelected({ ...selected, tabling_url: null });
|
||||||
|
load();
|
||||||
|
}}
|
||||||
|
className="px-2 py-0.5 text-[11px] text-red-500 border border-red-200 rounded hover:bg-red-50"
|
||||||
|
>
|
||||||
|
연결 해제
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{/* 캐치테이블 연결 */}
|
||||||
|
{isAdmin && (
|
||||||
|
<div className="mt-4 border-t pt-3">
|
||||||
|
<div className="flex items-center gap-2 mb-2">
|
||||||
|
<h4 className="text-xs font-semibold text-gray-500">캐치테이블</h4>
|
||||||
|
{selected.catchtable_url === "NONE" ? (
|
||||||
|
<span className="text-xs text-gray-400">검색완료-없음</span>
|
||||||
|
) : selected.catchtable_url ? (
|
||||||
|
<a href={selected.catchtable_url} target="_blank" rel="noopener noreferrer"
|
||||||
|
className="text-blue-600 hover:underline text-xs">{selected.catchtable_url}</a>
|
||||||
|
) : (
|
||||||
|
<span className="text-xs text-gray-400">미연결</span>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
setCatchtableSearching(true);
|
||||||
|
try {
|
||||||
|
const results = await api.searchCatchtable(selected.id);
|
||||||
|
if (results.length === 0) {
|
||||||
|
alert("캐치테이블에서 검색 결과가 없습니다");
|
||||||
|
} else {
|
||||||
|
const best = results[0];
|
||||||
|
if (confirm(`"${best.title}"\n${best.url}\n\n이 캐치테이블 페이지를 연결할까요?`)) {
|
||||||
|
await api.setCatchtableUrl(selected.id, best.url);
|
||||||
|
setSelected({ ...selected, catchtable_url: best.url });
|
||||||
|
load();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) { alert("검색 실패: " + (e instanceof Error ? e.message : String(e))); }
|
||||||
|
finally { setCatchtableSearching(false); }
|
||||||
|
}}
|
||||||
|
disabled={catchtableSearching}
|
||||||
|
className="px-2 py-0.5 text-[11px] bg-violet-500 text-white rounded hover:bg-violet-600 disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{catchtableSearching ? "검색 중..." : "캐치테이블 검색"}
|
||||||
|
</button>
|
||||||
|
{selected.catchtable_url && (
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
await api.setCatchtableUrl(selected.id, "");
|
||||||
|
setSelected({ ...selected, catchtable_url: null });
|
||||||
|
load();
|
||||||
|
}}
|
||||||
|
className="px-2 py-0.5 text-[11px] text-red-500 border border-red-200 rounded hover:bg-red-50"
|
||||||
|
>
|
||||||
|
연결 해제
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
{videos.length > 0 && (
|
{videos.length > 0 && (
|
||||||
<div className="mt-4 border-t pt-3">
|
<div className="mt-4 border-t pt-3">
|
||||||
<h4 className="text-xs font-semibold text-gray-500 mb-2">연결된 영상 ({videos.length})</h4>
|
<h4 className="text-xs font-semibold text-gray-500 mb-2">연결된 영상 ({videos.length})</h4>
|
||||||
|
|||||||
@@ -42,3 +42,8 @@ html, body, #__next {
|
|||||||
.gm-style .gm-style-iw-d {
|
.gm-style .gm-style-iw-d {
|
||||||
overflow: auto !important;
|
overflow: auto !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* Safe area for iOS bottom nav */
|
||||||
|
.safe-area-bottom {
|
||||||
|
padding-bottom: env(safe-area-inset-bottom, 0px);
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||||
import { GoogleLogin } from "@react-oauth/google";
|
import { GoogleLogin } from "@react-oauth/google";
|
||||||
|
import LoginMenu from "@/components/LoginMenu";
|
||||||
import { api } from "@/lib/api";
|
import { api } from "@/lib/api";
|
||||||
import type { Restaurant, Channel, Review } from "@/lib/api";
|
import type { Restaurant, Channel, Review } from "@/lib/api";
|
||||||
import { useAuth } from "@/lib/auth-context";
|
import { useAuth } from "@/lib/auth-context";
|
||||||
@@ -140,6 +141,7 @@ export default function Home() {
|
|||||||
const [cuisineFilter, setCuisineFilter] = useState("");
|
const [cuisineFilter, setCuisineFilter] = useState("");
|
||||||
const [priceFilter, setPriceFilter] = useState("");
|
const [priceFilter, setPriceFilter] = useState("");
|
||||||
const [viewMode, setViewMode] = useState<"map" | "list">("list");
|
const [viewMode, setViewMode] = useState<"map" | "list">("list");
|
||||||
|
const [mobileTab, setMobileTab] = useState<"home" | "list" | "nearby" | "favorites" | "profile">("home");
|
||||||
const [showMobileFilters, setShowMobileFilters] = useState(false);
|
const [showMobileFilters, setShowMobileFilters] = useState(false);
|
||||||
const [mapBounds, setMapBounds] = useState<MapBounds | null>(null);
|
const [mapBounds, setMapBounds] = useState<MapBounds | null>(null);
|
||||||
const [boundsFilterOn, setBoundsFilterOn] = useState(false);
|
const [boundsFilterOn, setBoundsFilterOn] = useState(false);
|
||||||
@@ -151,6 +153,9 @@ export default function Home() {
|
|||||||
const [showMyReviews, setShowMyReviews] = useState(false);
|
const [showMyReviews, setShowMyReviews] = useState(false);
|
||||||
const [myReviews, setMyReviews] = useState<(Review & { restaurant_id: string; restaurant_name: string | null })[]>([]);
|
const [myReviews, setMyReviews] = useState<(Review & { restaurant_id: string; restaurant_name: string | null })[]>([]);
|
||||||
const [visits, setVisits] = useState<{ today: number; total: number } | null>(null);
|
const [visits, setVisits] = useState<{ today: number; total: number } | null>(null);
|
||||||
|
const [userLoc, setUserLoc] = useState<{ lat: number; lng: number }>({ lat: 37.498, lng: 127.0276 });
|
||||||
|
const [isSearchResult, setIsSearchResult] = useState(false);
|
||||||
|
const [resetCount, setResetCount] = useState(0);
|
||||||
const geoApplied = useRef(false);
|
const geoApplied = useRef(false);
|
||||||
|
|
||||||
const regionTree = useMemo(() => buildRegionTree(restaurants), [restaurants]);
|
const regionTree = useMemo(() => buildRegionTree(restaurants), [restaurants]);
|
||||||
@@ -169,6 +174,15 @@ export default function Home() {
|
|||||||
}, [regionTree, countryFilter, cityFilter]);
|
}, [regionTree, countryFilter, cityFilter]);
|
||||||
|
|
||||||
const filteredRestaurants = useMemo(() => {
|
const filteredRestaurants = useMemo(() => {
|
||||||
|
const dist = (r: Restaurant) =>
|
||||||
|
(r.latitude - userLoc.lat) ** 2 + (r.longitude - userLoc.lng) ** 2;
|
||||||
|
if (isSearchResult) {
|
||||||
|
return [...restaurants].sort((a, b) => {
|
||||||
|
const da = dist(a), db = dist(b);
|
||||||
|
if (da !== db) return da - db;
|
||||||
|
return (b.rating || 0) - (a.rating || 0);
|
||||||
|
});
|
||||||
|
}
|
||||||
return restaurants.filter((r) => {
|
return restaurants.filter((r) => {
|
||||||
if (channelFilter && !(r.channels || []).includes(channelFilter)) return false;
|
if (channelFilter && !(r.channels || []).includes(channelFilter)) return false;
|
||||||
if (cuisineFilter && !matchCuisineFilter(r.cuisine_type, cuisineFilter)) return false;
|
if (cuisineFilter && !matchCuisineFilter(r.cuisine_type, cuisineFilter)) return false;
|
||||||
@@ -184,12 +198,23 @@ export default function Home() {
|
|||||||
if (r.longitude < mapBounds.west || r.longitude > mapBounds.east) return false;
|
if (r.longitude < mapBounds.west || r.longitude > mapBounds.east) return false;
|
||||||
}
|
}
|
||||||
return true;
|
return true;
|
||||||
|
}).sort((a, b) => {
|
||||||
|
const da = dist(a), db = dist(b);
|
||||||
|
if (da !== db) return da - db;
|
||||||
|
return (b.rating || 0) - (a.rating || 0);
|
||||||
});
|
});
|
||||||
}, [restaurants, channelFilter, cuisineFilter, priceFilter, countryFilter, cityFilter, districtFilter, boundsFilterOn, mapBounds]);
|
}, [restaurants, isSearchResult, channelFilter, cuisineFilter, priceFilter, countryFilter, cityFilter, districtFilter, boundsFilterOn, mapBounds, userLoc]);
|
||||||
|
|
||||||
// Set desktop default to map mode on mount
|
// Set desktop default to map mode on mount + get user location
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (window.innerWidth >= 768) setViewMode("map");
|
if (window.innerWidth >= 768) setViewMode("map");
|
||||||
|
if (navigator.geolocation) {
|
||||||
|
navigator.geolocation.getCurrentPosition(
|
||||||
|
(pos) => setUserLoc({ lat: pos.coords.latitude, lng: pos.coords.longitude }),
|
||||||
|
() => {},
|
||||||
|
{ timeout: 5000 },
|
||||||
|
);
|
||||||
|
}
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
// Load channels + record visit on mount
|
// Load channels + record visit on mount
|
||||||
@@ -201,6 +226,7 @@ export default function Home() {
|
|||||||
// Load restaurants on mount and when channel filter changes
|
// Load restaurants on mount and when channel filter changes
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
|
setIsSearchResult(false);
|
||||||
api
|
api
|
||||||
.getRestaurants({ limit: 500, channel: channelFilter || undefined })
|
.getRestaurants({ limit: 500, channel: channelFilter || undefined })
|
||||||
.then(setRestaurants)
|
.then(setRestaurants)
|
||||||
@@ -220,12 +246,9 @@ export default function Home() {
|
|||||||
if (match) {
|
if (match) {
|
||||||
setCountryFilter(match.country);
|
setCountryFilter(match.country);
|
||||||
setCityFilter(match.city);
|
setCityFilter(match.city);
|
||||||
const matched = restaurants.filter((r) => {
|
|
||||||
const p = parseRegion(r.region);
|
|
||||||
return p && p.country === match.country && p.city === match.city;
|
|
||||||
});
|
|
||||||
setRegionFlyTo(computeFlyTo(matched));
|
|
||||||
}
|
}
|
||||||
|
const mobile = window.innerWidth < 768;
|
||||||
|
setRegionFlyTo({ lat: pos.coords.latitude, lng: pos.coords.longitude, zoom: mobile ? 13 : 16 });
|
||||||
},
|
},
|
||||||
() => { /* user denied or error — do nothing */ },
|
() => { /* user denied or error — do nothing */ },
|
||||||
{ timeout: 5000 },
|
{ timeout: 5000 },
|
||||||
@@ -240,6 +263,18 @@ export default function Home() {
|
|||||||
setRestaurants(results);
|
setRestaurants(results);
|
||||||
setSelected(null);
|
setSelected(null);
|
||||||
setShowDetail(false);
|
setShowDetail(false);
|
||||||
|
setIsSearchResult(true);
|
||||||
|
// 검색 시 필터 초기화
|
||||||
|
setChannelFilter("");
|
||||||
|
setCuisineFilter("");
|
||||||
|
setPriceFilter("");
|
||||||
|
setCountryFilter("");
|
||||||
|
setCityFilter("");
|
||||||
|
setDistrictFilter("");
|
||||||
|
setBoundsFilterOn(false);
|
||||||
|
// 검색 결과에 맞게 지도 이동
|
||||||
|
const flyTo = computeFlyTo(results);
|
||||||
|
if (flyTo) setRegionFlyTo(flyTo);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
console.error("Search failed:", e);
|
console.error("Search failed:", e);
|
||||||
} finally {
|
} finally {
|
||||||
@@ -262,6 +297,21 @@ export default function Home() {
|
|||||||
setMapBounds(bounds);
|
setMapBounds(bounds);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const handleMyLocation = useCallback(() => {
|
||||||
|
if (navigator.geolocation) {
|
||||||
|
navigator.geolocation.getCurrentPosition(
|
||||||
|
(pos) => {
|
||||||
|
setUserLoc({ lat: pos.coords.latitude, lng: pos.coords.longitude });
|
||||||
|
setRegionFlyTo({ lat: pos.coords.latitude, lng: pos.coords.longitude, zoom: 16 });
|
||||||
|
},
|
||||||
|
() => setRegionFlyTo({ lat: 37.498, lng: 127.0276, zoom: 16 }),
|
||||||
|
{ timeout: 5000 },
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
setRegionFlyTo({ lat: 37.498, lng: 127.0276, zoom: 16 });
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
const handleCountryChange = useCallback((country: string) => {
|
const handleCountryChange = useCallback((country: string) => {
|
||||||
setCountryFilter(country);
|
setCountryFilter(country);
|
||||||
setCityFilter("");
|
setCityFilter("");
|
||||||
@@ -322,6 +372,8 @@ export default function Home() {
|
|||||||
setBoundsFilterOn(false);
|
setBoundsFilterOn(false);
|
||||||
setShowFavorites(false);
|
setShowFavorites(false);
|
||||||
setShowMyReviews(false);
|
setShowMyReviews(false);
|
||||||
|
setIsSearchResult(false);
|
||||||
|
setResetCount((c) => c + 1);
|
||||||
api
|
api
|
||||||
.getRestaurants({ limit: 500 })
|
.getRestaurants({ limit: 500 })
|
||||||
.then((data) => {
|
.then((data) => {
|
||||||
@@ -333,6 +385,75 @@ export default function Home() {
|
|||||||
.finally(() => setLoading(false));
|
.finally(() => setLoading(false));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const handleMobileTab = useCallback(async (tab: "home" | "list" | "nearby" | "favorites" | "profile") => {
|
||||||
|
// 홈 탭 재클릭 = 리셋
|
||||||
|
if (tab === "home" && mobileTab === "home") {
|
||||||
|
handleReset();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setMobileTab(tab);
|
||||||
|
setShowDetail(false);
|
||||||
|
setShowMobileFilters(false);
|
||||||
|
setSelected(null);
|
||||||
|
|
||||||
|
if (tab === "nearby") {
|
||||||
|
setBoundsFilterOn(true);
|
||||||
|
if (navigator.geolocation) {
|
||||||
|
navigator.geolocation.getCurrentPosition(
|
||||||
|
(pos) => setRegionFlyTo({ lat: pos.coords.latitude, lng: pos.coords.longitude, zoom: 13 }),
|
||||||
|
() => setRegionFlyTo({ lat: 37.498, lng: 127.0276, zoom: 13 }),
|
||||||
|
{ timeout: 5000 },
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
setRegionFlyTo({ lat: 37.498, lng: 127.0276, zoom: 13 });
|
||||||
|
}
|
||||||
|
// 내주변에서 돌아올 때를 위해 favorites/reviews 해제
|
||||||
|
if (showFavorites || showMyReviews) {
|
||||||
|
setShowFavorites(false);
|
||||||
|
setShowMyReviews(false);
|
||||||
|
setMyReviews([]);
|
||||||
|
api.getRestaurants({ limit: 500, channel: channelFilter || undefined }).then(setRestaurants);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setBoundsFilterOn(false);
|
||||||
|
|
||||||
|
if (tab === "favorites") {
|
||||||
|
if (!user) return;
|
||||||
|
setShowMyReviews(false);
|
||||||
|
setMyReviews([]);
|
||||||
|
try {
|
||||||
|
const favs = await api.getMyFavorites();
|
||||||
|
setRestaurants(favs);
|
||||||
|
setShowFavorites(true);
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
} else if (tab === "profile") {
|
||||||
|
if (!user) return;
|
||||||
|
setShowFavorites(false);
|
||||||
|
try {
|
||||||
|
const reviews = await api.getMyReviews();
|
||||||
|
setMyReviews(reviews);
|
||||||
|
setShowMyReviews(true);
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
// 프로필에서는 식당 목록을 원래대로 복원
|
||||||
|
if (showFavorites) {
|
||||||
|
api.getRestaurants({ limit: 500, channel: channelFilter || undefined }).then(setRestaurants);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 홈 / 식당 목록 - 항상 전체 식당 목록으로 복원
|
||||||
|
const needReload = showFavorites || showMyReviews;
|
||||||
|
setShowFavorites(false);
|
||||||
|
setShowMyReviews(false);
|
||||||
|
setMyReviews([]);
|
||||||
|
if (needReload) {
|
||||||
|
const data = await api.getRestaurants({ limit: 500, channel: channelFilter || undefined });
|
||||||
|
setRestaurants(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}, [user, showFavorites, showMyReviews, channelFilter, mobileTab, handleReset]);
|
||||||
|
|
||||||
const handleToggleFavorites = async () => {
|
const handleToggleFavorites = async () => {
|
||||||
if (showFavorites) {
|
if (showFavorites) {
|
||||||
setShowFavorites(false);
|
setShowFavorites(false);
|
||||||
@@ -434,8 +555,15 @@ export default function Home() {
|
|||||||
{/* Row 1: Search + dropdown filters */}
|
{/* Row 1: Search + dropdown filters */}
|
||||||
<div className="flex items-center gap-3">
|
<div className="flex items-center gap-3">
|
||||||
<div className="w-96 shrink-0">
|
<div className="w-96 shrink-0">
|
||||||
<SearchBar onSearch={handleSearch} isLoading={loading} />
|
<SearchBar key={resetCount} onSearch={handleSearch} isLoading={loading} />
|
||||||
</div>
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={handleReset}
|
||||||
|
className="p-1.5 text-gray-400 dark:text-gray-500 hover:text-orange-500 dark:hover:text-orange-400 transition-colors"
|
||||||
|
title="초기화"
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" className="w-5 h-5 fill-current"><path d="M17.65 6.35A7.958 7.958 0 0012 4c-4.42 0-7.99 3.58-7.99 8s3.57 8 7.99 8c3.73 0 6.84-2.55 7.73-6h-2.08A5.99 5.99 0 0112 18c-3.31 0-6-2.69-6-6s2.69-6 6-6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg>
|
||||||
|
</button>
|
||||||
<select
|
<select
|
||||||
value={channelFilter}
|
value={channelFilter}
|
||||||
onChange={(e) => {
|
onChange={(e) => {
|
||||||
@@ -445,7 +573,7 @@ export default function Home() {
|
|||||||
}}
|
}}
|
||||||
className="border dark:border-gray-700 rounded-lg px-3 py-1.5 text-sm text-gray-600 dark:text-gray-300 dark:bg-gray-800"
|
className="border dark:border-gray-700 rounded-lg px-3 py-1.5 text-sm text-gray-600 dark:text-gray-300 dark:bg-gray-800"
|
||||||
>
|
>
|
||||||
<option value="">📺 전체 채널</option>
|
<option value="">📺 채널</option>
|
||||||
{channels.map((ch) => (
|
{channels.map((ch) => (
|
||||||
<option key={ch.id} value={ch.channel_name}>
|
<option key={ch.id} value={ch.channel_name}>
|
||||||
📺 {ch.channel_name}
|
📺 {ch.channel_name}
|
||||||
@@ -457,7 +585,7 @@ export default function Home() {
|
|||||||
onChange={(e) => setCuisineFilter(e.target.value)}
|
onChange={(e) => setCuisineFilter(e.target.value)}
|
||||||
className="border dark:border-gray-700 rounded-lg px-3 py-1.5 text-sm text-gray-600 dark:text-gray-300 dark:bg-gray-800"
|
className="border dark:border-gray-700 rounded-lg px-3 py-1.5 text-sm text-gray-600 dark:text-gray-300 dark:bg-gray-800"
|
||||||
>
|
>
|
||||||
<option value="">🍽 전체 장르</option>
|
<option value="">🍽 장르</option>
|
||||||
{CUISINE_TAXONOMY.map((g) => (
|
{CUISINE_TAXONOMY.map((g) => (
|
||||||
<optgroup key={g.category} label={`── ${g.category} ──`}>
|
<optgroup key={g.category} label={`── ${g.category} ──`}>
|
||||||
<option value={g.category}>🍽 {g.category} 전체</option>
|
<option value={g.category}>🍽 {g.category} 전체</option>
|
||||||
@@ -474,7 +602,7 @@ export default function Home() {
|
|||||||
onChange={(e) => setPriceFilter(e.target.value)}
|
onChange={(e) => setPriceFilter(e.target.value)}
|
||||||
className="border dark:border-gray-700 rounded-lg px-3 py-1.5 text-sm text-gray-600 dark:text-gray-300 dark:bg-gray-800"
|
className="border dark:border-gray-700 rounded-lg px-3 py-1.5 text-sm text-gray-600 dark:text-gray-300 dark:bg-gray-800"
|
||||||
>
|
>
|
||||||
<option value="">💰 전체 가격</option>
|
<option value="">💰 가격</option>
|
||||||
{PRICE_GROUPS.map((g) => (
|
{PRICE_GROUPS.map((g) => (
|
||||||
<option key={g.label} value={g.label}>{g.label}</option>
|
<option key={g.label} value={g.label}>{g.label}</option>
|
||||||
))}
|
))}
|
||||||
@@ -487,7 +615,7 @@ export default function Home() {
|
|||||||
onChange={(e) => handleCountryChange(e.target.value)}
|
onChange={(e) => handleCountryChange(e.target.value)}
|
||||||
className="border dark:border-gray-700 rounded-lg px-3 py-1.5 text-sm text-gray-600 dark:text-gray-300 dark:bg-gray-800"
|
className="border dark:border-gray-700 rounded-lg px-3 py-1.5 text-sm text-gray-600 dark:text-gray-300 dark:bg-gray-800"
|
||||||
>
|
>
|
||||||
<option value="">🌍 전체 나라</option>
|
<option value="">🌍 나라</option>
|
||||||
{countries.map((c) => (
|
{countries.map((c) => (
|
||||||
<option key={c} value={c}>🌍 {c}</option>
|
<option key={c} value={c}>🌍 {c}</option>
|
||||||
))}
|
))}
|
||||||
@@ -518,15 +646,29 @@ export default function Home() {
|
|||||||
)}
|
)}
|
||||||
<div className="w-px h-5 bg-gray-200 dark:bg-gray-700" />
|
<div className="w-px h-5 bg-gray-200 dark:bg-gray-700" />
|
||||||
<button
|
<button
|
||||||
onClick={() => setBoundsFilterOn(!boundsFilterOn)}
|
onClick={() => {
|
||||||
|
const next = !boundsFilterOn;
|
||||||
|
setBoundsFilterOn(next);
|
||||||
|
if (next) {
|
||||||
|
if (navigator.geolocation) {
|
||||||
|
navigator.geolocation.getCurrentPosition(
|
||||||
|
(pos) => setRegionFlyTo({ lat: pos.coords.latitude, lng: pos.coords.longitude, zoom: 15 }),
|
||||||
|
() => setRegionFlyTo({ lat: 37.498, lng: 127.0276, zoom: 15 }),
|
||||||
|
{ timeout: 5000 },
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
setRegionFlyTo({ lat: 37.498, lng: 127.0276, zoom: 15 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
className={`px-3 py-1.5 text-sm border rounded-lg transition-colors ${
|
className={`px-3 py-1.5 text-sm border rounded-lg transition-colors ${
|
||||||
boundsFilterOn
|
boundsFilterOn
|
||||||
? "bg-orange-50 dark:bg-orange-900/30 border-orange-300 dark:border-orange-700 text-orange-600 dark:text-orange-400"
|
? "bg-orange-50 dark:bg-orange-900/30 border-orange-300 dark:border-orange-700 text-orange-600 dark:text-orange-400"
|
||||||
: "hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-600 dark:text-gray-400"
|
: "hover:bg-gray-100 dark:hover:bg-gray-800 text-gray-600 dark:text-gray-400"
|
||||||
}`}
|
}`}
|
||||||
title="지도 영역 내 식당만 표시"
|
title="내 위치 주변 식당만 표시"
|
||||||
>
|
>
|
||||||
{boundsFilterOn ? "📍 영역 필터" : "📍 영역"}
|
{boundsFilterOn ? "📍 내위치 ON" : "📍 내위치"}
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button
|
||||||
onClick={() => setViewMode(viewMode === "map" ? "list" : "map")}
|
onClick={() => setViewMode(viewMode === "map" ? "list" : "map")}
|
||||||
@@ -591,74 +733,32 @@ export default function Home() {
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<GoogleLogin
|
<LoginMenu onGoogleSuccess={(credential) => login(credential).catch(console.error)} />
|
||||||
onSuccess={(credentialResponse) => {
|
|
||||||
if (credentialResponse.credential) {
|
|
||||||
login(credentialResponse.credential).catch(console.error);
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
onError={() => console.error("Google login failed")}
|
|
||||||
size="small"
|
|
||||||
/>
|
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* ── Header row 2 (mobile only): search + toolbar ── */}
|
{/* ── Header row 2 (mobile only): search + toolbar ── */}
|
||||||
<div className="md:hidden px-4 pb-3 space-y-2">
|
<div className={`md:hidden px-4 pb-3 space-y-2 ${mobileTab === "favorites" || mobileTab === "profile" ? "hidden" : ""}`}>
|
||||||
{/* Row 1: Search */}
|
{/* Row 1: Search */}
|
||||||
<SearchBar onSearch={handleSearch} isLoading={loading} />
|
<SearchBar key={resetCount} onSearch={handleSearch} isLoading={loading} />
|
||||||
{/* Row 2: Toolbar */}
|
{/* Row 2: Toolbar */}
|
||||||
<div className="flex items-center gap-2">
|
<div className="flex items-center gap-2">
|
||||||
<button
|
|
||||||
onClick={() => setViewMode(viewMode === "map" ? "list" : "map")}
|
|
||||||
className={`px-3 py-1.5 text-xs border rounded-lg transition-colors ${
|
|
||||||
viewMode === "map"
|
|
||||||
? "bg-orange-50 dark:bg-orange-900/30 border-orange-300 dark:border-orange-700 text-orange-600 dark:text-orange-400"
|
|
||||||
: "text-gray-600"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{viewMode === "map" ? "🗺 지도" : "☰ 리스트"}
|
|
||||||
</button>
|
|
||||||
<button
|
<button
|
||||||
onClick={() => setShowMobileFilters(!showMobileFilters)}
|
onClick={() => setShowMobileFilters(!showMobileFilters)}
|
||||||
className={`px-3 py-1.5 text-xs border rounded-lg transition-colors relative ${
|
className={`px-3 py-1.5 text-xs border rounded-lg transition-colors relative ${
|
||||||
showMobileFilters || channelFilter || cuisineFilter || priceFilter || countryFilter || boundsFilterOn
|
showMobileFilters || channelFilter || cuisineFilter || priceFilter || countryFilter
|
||||||
? "bg-orange-50 dark:bg-orange-900/30 border-orange-300 dark:border-orange-700 text-orange-600 dark:text-orange-400"
|
? "bg-orange-50 dark:bg-orange-900/30 border-orange-300 dark:border-orange-700 text-orange-600 dark:text-orange-400"
|
||||||
: "text-gray-600"
|
: "text-gray-600"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{showMobileFilters ? "✕ 닫기" : "🔽 필터"}
|
{showMobileFilters ? "✕ 닫기" : "🔽 필터"}
|
||||||
{!showMobileFilters && (channelFilter || cuisineFilter || priceFilter || countryFilter || boundsFilterOn) && (
|
{!showMobileFilters && (channelFilter || cuisineFilter || priceFilter || countryFilter) && (
|
||||||
<span className="absolute -top-1.5 -right-1.5 w-4 h-4 bg-orange-500 text-white rounded-full text-[9px] flex items-center justify-center">
|
<span className="absolute -top-1.5 -right-1.5 w-4 h-4 bg-orange-500 text-white rounded-full text-[9px] flex items-center justify-center">
|
||||||
{[channelFilter, cuisineFilter, priceFilter, countryFilter, boundsFilterOn].filter(Boolean).length}
|
{[channelFilter, cuisineFilter, priceFilter, countryFilter].filter(Boolean).length}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
</button>
|
</button>
|
||||||
{user && (
|
|
||||||
<>
|
|
||||||
<button
|
|
||||||
onClick={handleToggleFavorites}
|
|
||||||
className={`px-3 py-1.5 text-xs rounded-full border transition-colors ${
|
|
||||||
showFavorites
|
|
||||||
? "bg-rose-50 dark:bg-rose-900/30 border-rose-300 dark:border-rose-700 text-rose-600 dark:text-rose-400"
|
|
||||||
: "border-gray-300 dark:border-gray-700 text-gray-600 dark:text-gray-400"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{showFavorites ? "♥ 찜" : "♡ 찜"}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
onClick={handleToggleMyReviews}
|
|
||||||
className={`px-3 py-1.5 text-xs rounded-full border transition-colors ${
|
|
||||||
showMyReviews
|
|
||||||
? "bg-orange-50 dark:bg-orange-900/30 border-orange-300 dark:border-orange-700 text-orange-600 dark:text-orange-400"
|
|
||||||
: "border-gray-300 dark:border-gray-700 text-gray-600 dark:text-gray-400"
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
{showMyReviews ? "✎ 리뷰" : "✎ 리뷰"}
|
|
||||||
</button>
|
|
||||||
</>
|
|
||||||
)}
|
|
||||||
<span className="text-xs text-gray-400 ml-auto">
|
<span className="text-xs text-gray-400 ml-auto">
|
||||||
{filteredRestaurants.length}개
|
{filteredRestaurants.length}개
|
||||||
</span>
|
</span>
|
||||||
@@ -678,7 +778,7 @@ export default function Home() {
|
|||||||
}}
|
}}
|
||||||
className="border dark:border-gray-700 rounded-lg px-2.5 py-1.5 text-xs text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-800"
|
className="border dark:border-gray-700 rounded-lg px-2.5 py-1.5 text-xs text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-800"
|
||||||
>
|
>
|
||||||
<option value="">📺 전체 채널</option>
|
<option value="">📺 채널</option>
|
||||||
{channels.map((ch) => (
|
{channels.map((ch) => (
|
||||||
<option key={ch.id} value={ch.channel_name}>
|
<option key={ch.id} value={ch.channel_name}>
|
||||||
📺 {ch.channel_name}
|
📺 {ch.channel_name}
|
||||||
@@ -690,7 +790,7 @@ export default function Home() {
|
|||||||
onChange={(e) => setCuisineFilter(e.target.value)}
|
onChange={(e) => setCuisineFilter(e.target.value)}
|
||||||
className="border dark:border-gray-700 rounded-lg px-2.5 py-1.5 text-xs text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-800"
|
className="border dark:border-gray-700 rounded-lg px-2.5 py-1.5 text-xs text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-800"
|
||||||
>
|
>
|
||||||
<option value="">🍽 전체 장르</option>
|
<option value="">🍽 장르</option>
|
||||||
{CUISINE_TAXONOMY.map((g) => (
|
{CUISINE_TAXONOMY.map((g) => (
|
||||||
<optgroup key={g.category} label={`── ${g.category} ──`}>
|
<optgroup key={g.category} label={`── ${g.category} ──`}>
|
||||||
<option value={g.category}>🍽 {g.category} 전체</option>
|
<option value={g.category}>🍽 {g.category} 전체</option>
|
||||||
@@ -707,7 +807,7 @@ export default function Home() {
|
|||||||
onChange={(e) => setPriceFilter(e.target.value)}
|
onChange={(e) => setPriceFilter(e.target.value)}
|
||||||
className="border dark:border-gray-700 rounded-lg px-2.5 py-1.5 text-xs text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-800"
|
className="border dark:border-gray-700 rounded-lg px-2.5 py-1.5 text-xs text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-800"
|
||||||
>
|
>
|
||||||
<option value="">💰 전체 가격</option>
|
<option value="">💰 가격</option>
|
||||||
{PRICE_GROUPS.map((g) => (
|
{PRICE_GROUPS.map((g) => (
|
||||||
<option key={g.label} value={g.label}>💰 {g.label}</option>
|
<option key={g.label} value={g.label}>💰 {g.label}</option>
|
||||||
))}
|
))}
|
||||||
@@ -720,7 +820,7 @@ export default function Home() {
|
|||||||
onChange={(e) => handleCountryChange(e.target.value)}
|
onChange={(e) => handleCountryChange(e.target.value)}
|
||||||
className="border dark:border-gray-700 rounded-lg px-2.5 py-1.5 text-xs text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-800"
|
className="border dark:border-gray-700 rounded-lg px-2.5 py-1.5 text-xs text-gray-600 dark:text-gray-300 bg-white dark:bg-gray-800"
|
||||||
>
|
>
|
||||||
<option value="">🌍 전체 나라</option>
|
<option value="">🌍 나라</option>
|
||||||
{countries.map((c) => (
|
{countries.map((c) => (
|
||||||
<option key={c} value={c}>🌍 {c}</option>
|
<option key={c} value={c}>🌍 {c}</option>
|
||||||
))}
|
))}
|
||||||
@@ -753,14 +853,28 @@ export default function Home() {
|
|||||||
{/* Toggle buttons */}
|
{/* Toggle buttons */}
|
||||||
<div className="flex items-center gap-2 flex-wrap">
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
<button
|
<button
|
||||||
onClick={() => setBoundsFilterOn(!boundsFilterOn)}
|
onClick={() => {
|
||||||
|
const next = !boundsFilterOn;
|
||||||
|
setBoundsFilterOn(next);
|
||||||
|
if (next) {
|
||||||
|
if (navigator.geolocation) {
|
||||||
|
navigator.geolocation.getCurrentPosition(
|
||||||
|
(pos) => setRegionFlyTo({ lat: pos.coords.latitude, lng: pos.coords.longitude, zoom: 15 }),
|
||||||
|
() => setRegionFlyTo({ lat: 37.498, lng: 127.0276, zoom: 15 }),
|
||||||
|
{ timeout: 5000 },
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
setRegionFlyTo({ lat: 37.498, lng: 127.0276, zoom: 15 });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}}
|
||||||
className={`px-2.5 py-1.5 text-xs border rounded-lg transition-colors ${
|
className={`px-2.5 py-1.5 text-xs border rounded-lg transition-colors ${
|
||||||
boundsFilterOn
|
boundsFilterOn
|
||||||
? "bg-orange-50 dark:bg-orange-900/30 border-orange-300 dark:border-orange-700 text-orange-600 dark:text-orange-400"
|
? "bg-orange-50 dark:bg-orange-900/30 border-orange-300 dark:border-orange-700 text-orange-600 dark:text-orange-400"
|
||||||
: "text-gray-600 dark:text-gray-400 bg-white dark:bg-gray-800"
|
: "text-gray-600 dark:text-gray-400 bg-white dark:bg-gray-800"
|
||||||
}`}
|
}`}
|
||||||
>
|
>
|
||||||
{boundsFilterOn ? "📍 영역 ON" : "📍 영역"}
|
{boundsFilterOn ? "📍 내위치 ON" : "📍 내위치"}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -784,6 +898,8 @@ export default function Home() {
|
|||||||
onSelectRestaurant={handleSelectRestaurant}
|
onSelectRestaurant={handleSelectRestaurant}
|
||||||
onBoundsChanged={handleBoundsChanged}
|
onBoundsChanged={handleBoundsChanged}
|
||||||
flyTo={regionFlyTo}
|
flyTo={regionFlyTo}
|
||||||
|
onMyLocation={handleMyLocation}
|
||||||
|
activeChannel={channelFilter || undefined}
|
||||||
/>
|
/>
|
||||||
{visits && (
|
{visits && (
|
||||||
<div className="absolute bottom-1 right-2 bg-white/60 backdrop-blur-sm text-gray-700 text-[10px] px-2.5 py-1 rounded-lg shadow-sm">
|
<div className="absolute bottom-1 right-2 bg-white/60 backdrop-blur-sm text-gray-700 text-[10px] px-2.5 py-1 rounded-lg shadow-sm">
|
||||||
@@ -804,6 +920,8 @@ export default function Home() {
|
|||||||
onSelectRestaurant={handleSelectRestaurant}
|
onSelectRestaurant={handleSelectRestaurant}
|
||||||
onBoundsChanged={handleBoundsChanged}
|
onBoundsChanged={handleBoundsChanged}
|
||||||
flyTo={regionFlyTo}
|
flyTo={regionFlyTo}
|
||||||
|
onMyLocation={handleMyLocation}
|
||||||
|
activeChannel={channelFilter || undefined}
|
||||||
/>
|
/>
|
||||||
{visits && (
|
{visits && (
|
||||||
<div className="absolute bottom-1 right-2 bg-white/60 backdrop-blur-sm text-gray-700 text-[10px] px-2.5 py-1 rounded-lg shadow-sm">
|
<div className="absolute bottom-1 right-2 bg-white/60 backdrop-blur-sm text-gray-700 text-[10px] px-2.5 py-1 rounded-lg shadow-sm">
|
||||||
@@ -816,68 +934,115 @@ export default function Home() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Mobile layout */}
|
{/* Mobile layout */}
|
||||||
<div className="md:hidden flex-1 flex flex-col overflow-hidden">
|
<div className="md:hidden flex-1 flex flex-col overflow-hidden pb-14">
|
||||||
{viewMode === "map" ? (
|
{/* Tab content — takes all remaining space above fixed nav */}
|
||||||
<>
|
{mobileTab === "nearby" ? (
|
||||||
<div className="flex-1 relative">
|
/* 내주변: 지도 + 리스트 분할, 영역필터 ON */
|
||||||
|
<div className="flex-1 flex flex-col overflow-hidden">
|
||||||
|
<div className="h-[45%] relative shrink-0">
|
||||||
<MapView
|
<MapView
|
||||||
restaurants={filteredRestaurants}
|
restaurants={filteredRestaurants}
|
||||||
selected={selected}
|
selected={selected}
|
||||||
onSelectRestaurant={handleSelectRestaurant}
|
onSelectRestaurant={handleSelectRestaurant}
|
||||||
onBoundsChanged={handleBoundsChanged}
|
onBoundsChanged={handleBoundsChanged}
|
||||||
flyTo={regionFlyTo}
|
flyTo={regionFlyTo}
|
||||||
|
onMyLocation={handleMyLocation}
|
||||||
|
activeChannel={channelFilter || undefined}
|
||||||
/>
|
/>
|
||||||
|
<div className="absolute top-2 left-2 bg-white/90 dark:bg-gray-900/90 backdrop-blur-sm rounded-lg px-3 py-1.5 shadow-sm z-10">
|
||||||
|
<span className="text-xs font-medium text-orange-600 dark:text-orange-400">
|
||||||
|
내 주변 {filteredRestaurants.length}개
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
{visits && (
|
{visits && (
|
||||||
<div className="absolute bottom-1 right-2 bg-white/60 backdrop-blur-sm text-gray-700 text-[10px] px-2.5 py-1 rounded-lg shadow-sm z-10">
|
<div className="absolute bottom-1 right-2 bg-white/60 backdrop-blur-sm text-gray-700 text-[10px] px-2.5 py-1 rounded-lg shadow-sm z-10">
|
||||||
오늘 {visits.today} · 전체 {visits.total.toLocaleString()}
|
오늘 {visits.today} · 전체 {visits.total.toLocaleString()}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</>
|
<div className="flex-1 overflow-y-auto">
|
||||||
) : (
|
{mobileListContent}
|
||||||
<>
|
</div>
|
||||||
{/* List area — if selected, show single row; otherwise full list */}
|
</div>
|
||||||
{selected ? (
|
) : mobileTab === "profile" ? (
|
||||||
<div
|
/* 내정보 */
|
||||||
className="shrink-0 bg-white dark:bg-gray-950 border-b dark:border-gray-800 px-3 py-2 flex items-center gap-2 cursor-pointer"
|
<div className="flex-1 overflow-y-auto bg-white dark:bg-gray-950">
|
||||||
onClick={() => { setSelected(null); setShowDetail(false); }}
|
{!user ? (
|
||||||
>
|
<div className="flex flex-col items-center justify-center h-full gap-4 px-6">
|
||||||
<span className="text-base">{getCuisineIcon(selected.cuisine_type)}</span>
|
<p className="text-gray-500 dark:text-gray-400 text-sm">로그인하고 리뷰와 찜 목록을 관리하세요</p>
|
||||||
<span className="font-semibold text-sm truncate flex-1">{selected.name}</span>
|
<GoogleLogin
|
||||||
{selected.rating && (
|
onSuccess={(res) => {
|
||||||
<span className="text-xs text-gray-500"><span className="text-yellow-500">★</span> {selected.rating}</span>
|
if (res.credential) login(res.credential).catch(console.error);
|
||||||
)}
|
}}
|
||||||
{selected.cuisine_type && (
|
onError={() => console.error("Google login failed")}
|
||||||
<span className="text-xs text-gray-400">{selected.cuisine_type}</span>
|
size="large"
|
||||||
)}
|
text="signin_with"
|
||||||
<button
|
/>
|
||||||
onClick={(e) => { e.stopPropagation(); setSelected(null); setShowDetail(false); }}
|
|
||||||
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 text-lg leading-none ml-1"
|
|
||||||
>
|
|
||||||
✕
|
|
||||||
</button>
|
|
||||||
</div>
|
</div>
|
||||||
) : (
|
) : (
|
||||||
<div className="max-h-[360px] bg-white dark:bg-gray-950 overflow-y-auto border-b dark:border-gray-800">
|
<div className="p-4 space-y-4">
|
||||||
{mobileListContent}
|
{/* 프로필 헤더 */}
|
||||||
|
<div className="flex items-center gap-3 pb-4 border-b dark:border-gray-800">
|
||||||
|
{user.avatar_url ? (
|
||||||
|
<img src={user.avatar_url} alt="" className="w-12 h-12 rounded-full border border-gray-200" />
|
||||||
|
) : (
|
||||||
|
<div className="w-12 h-12 rounded-full bg-orange-100 text-orange-700 flex items-center justify-center text-lg font-semibold border border-orange-200">
|
||||||
|
{(user.nickname || user.email || "?").charAt(0).toUpperCase()}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex-1">
|
||||||
|
<p className="font-semibold text-sm dark:text-gray-100">{user.nickname || user.email}</p>
|
||||||
|
{user.nickname && user.email && (
|
||||||
|
<p className="text-xs text-gray-400">{user.email}</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
onClick={logout}
|
||||||
|
className="px-3 py-1.5 text-xs text-gray-500 border border-gray-300 dark:border-gray-700 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-800"
|
||||||
|
>
|
||||||
|
로그아웃
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{/* 내 리뷰 */}
|
||||||
|
<div>
|
||||||
|
<h3 className="font-semibold text-sm mb-2 dark:text-gray-200">내 리뷰</h3>
|
||||||
|
{myReviews.length === 0 ? (
|
||||||
|
<p className="text-sm text-gray-400">작성한 리뷰가 없습니다</p>
|
||||||
|
) : (
|
||||||
|
<MyReviewsList
|
||||||
|
reviews={myReviews}
|
||||||
|
onClose={() => {}}
|
||||||
|
onSelectRestaurant={async (restaurantId) => {
|
||||||
|
try {
|
||||||
|
const r = await api.getRestaurant(restaurantId);
|
||||||
|
handleSelectRestaurant(r);
|
||||||
|
} catch { /* ignore */ }
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{/* Map fills remaining space below the list */}
|
</div>
|
||||||
<div className="flex-1 relative">
|
) : (
|
||||||
<MapView
|
/* 홈 / 식당 목록 / 찜: 리스트 표시 */
|
||||||
restaurants={filteredRestaurants}
|
<div className="flex-1 overflow-y-auto bg-white dark:bg-gray-950">
|
||||||
selected={selected}
|
{mobileTab === "favorites" && !user ? (
|
||||||
onSelectRestaurant={handleSelectRestaurant}
|
<div className="flex flex-col items-center justify-center h-full gap-4 px-6">
|
||||||
onBoundsChanged={handleBoundsChanged}
|
<p className="text-gray-500 dark:text-gray-400 text-sm">로그인하고 찜 목록을 확인하세요</p>
|
||||||
flyTo={regionFlyTo}
|
<GoogleLogin
|
||||||
/>
|
onSuccess={(res) => {
|
||||||
{visits && (
|
if (res.credential) login(res.credential).catch(console.error);
|
||||||
<div className="absolute bottom-1 right-2 bg-white/60 backdrop-blur-sm text-gray-700 text-[10px] px-2.5 py-1 rounded-lg shadow-sm z-10">
|
}}
|
||||||
오늘 {visits.today} · 전체 {visits.total.toLocaleString()}
|
onError={() => console.error("Google login failed")}
|
||||||
</div>
|
size="large"
|
||||||
)}
|
text="signin_with"
|
||||||
</div>
|
/>
|
||||||
</>
|
</div>
|
||||||
|
) : (
|
||||||
|
mobileListContent
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Mobile Bottom Sheet for restaurant detail */}
|
{/* Mobile Bottom Sheet for restaurant detail */}
|
||||||
@@ -888,8 +1053,44 @@ export default function Home() {
|
|||||||
</BottomSheet>
|
</BottomSheet>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Footer */}
|
{/* ── Mobile Bottom Nav (fixed) ── */}
|
||||||
<footer className="shrink-0 border-t dark:border-gray-800 bg-white/60 dark:bg-gray-900/60 backdrop-blur-sm py-2.5 flex items-center justify-center gap-2 text-[11px] text-gray-400 dark:text-gray-500 group">
|
<nav className="md:hidden fixed bottom-0 left-0 right-0 z-40 border-t dark:border-gray-800 bg-white dark:bg-gray-950 safe-area-bottom">
|
||||||
|
<div className="flex items-stretch h-14">
|
||||||
|
{([
|
||||||
|
{ key: "home", label: "홈", icon: (
|
||||||
|
<svg viewBox="0 0 24 24" className="w-5 h-5 fill-current"><path d="M12 3l9 8h-3v9h-5v-6h-2v6H6v-9H3z"/></svg>
|
||||||
|
)},
|
||||||
|
{ key: "list", label: "식당 목록", icon: (
|
||||||
|
<svg viewBox="0 0 24 24" className="w-5 h-5 fill-current"><path d="M3 4h18v2H3zm0 7h18v2H3zm0 7h18v2H3z"/></svg>
|
||||||
|
)},
|
||||||
|
{ key: "nearby", label: "내주변", icon: (
|
||||||
|
<svg viewBox="0 0 24 24" className="w-5 h-5 fill-current"><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z"/></svg>
|
||||||
|
)},
|
||||||
|
{ key: "favorites", label: "찜", icon: (
|
||||||
|
<svg viewBox="0 0 24 24" className="w-5 h-5 fill-current"><path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/></svg>
|
||||||
|
)},
|
||||||
|
{ key: "profile", label: "내정보", icon: (
|
||||||
|
<svg viewBox="0 0 24 24" className="w-5 h-5 fill-current"><path d="M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/></svg>
|
||||||
|
)},
|
||||||
|
] as { key: "home" | "list" | "nearby" | "favorites" | "profile"; label: string; icon: React.ReactNode }[]).map((tab) => (
|
||||||
|
<button
|
||||||
|
key={tab.key}
|
||||||
|
onClick={() => handleMobileTab(tab.key)}
|
||||||
|
className={`flex-1 flex flex-col items-center justify-center gap-0.5 py-2 transition-colors ${
|
||||||
|
mobileTab === tab.key
|
||||||
|
? "text-orange-600 dark:text-orange-400"
|
||||||
|
: "text-gray-400 dark:text-gray-500"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{tab.icon}
|
||||||
|
<span className="text-[10px] font-medium">{tab.label}</span>
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
{/* Desktop Footer */}
|
||||||
|
<footer className="hidden md:flex shrink-0 border-t dark:border-gray-800 bg-white/60 dark:bg-gray-900/60 backdrop-blur-sm py-2.5 items-center justify-center gap-2 text-[11px] text-gray-400 dark:text-gray-500 group">
|
||||||
<div className="relative">
|
<div className="relative">
|
||||||
<img
|
<img
|
||||||
src="/icon.jpg"
|
src="/icon.jpg"
|
||||||
|
|||||||
60
frontend/src/components/LoginMenu.tsx
Normal file
60
frontend/src/components/LoginMenu.tsx
Normal file
@@ -0,0 +1,60 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { createPortal } from "react-dom";
|
||||||
|
import { GoogleLogin } from "@react-oauth/google";
|
||||||
|
|
||||||
|
interface LoginMenuProps {
|
||||||
|
onGoogleSuccess: (credential: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function LoginMenu({ onGoogleSuccess }: LoginMenuProps) {
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button
|
||||||
|
onClick={() => setOpen(true)}
|
||||||
|
className="px-3 py-1.5 text-sm font-medium text-gray-600 dark:text-gray-300 hover:text-orange-600 dark:hover:text-orange-400 border border-gray-300 dark:border-gray-600 hover:border-orange-400 dark:hover:border-orange-500 rounded-lg transition-colors"
|
||||||
|
>
|
||||||
|
로그인
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{open && createPortal(
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 flex items-center justify-center bg-black/40 backdrop-blur-sm"
|
||||||
|
style={{ zIndex: 99999 }}
|
||||||
|
onClick={(e) => { if (e.target === e.currentTarget) setOpen(false); }}
|
||||||
|
>
|
||||||
|
<div className="bg-white dark:bg-gray-900 rounded-2xl shadow-2xl p-6 mx-4 w-full max-w-xs space-y-4">
|
||||||
|
<div className="flex items-center justify-between">
|
||||||
|
<h3 className="text-base font-semibold dark:text-gray-100">로그인</h3>
|
||||||
|
<button
|
||||||
|
onClick={() => setOpen(false)}
|
||||||
|
className="text-gray-400 hover:text-gray-600 dark:hover:text-gray-200 text-lg leading-none"
|
||||||
|
>
|
||||||
|
✕
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-gray-400 dark:text-gray-500">소셜 계정으로 간편 로그인</p>
|
||||||
|
<div className="flex flex-col items-center gap-3">
|
||||||
|
<GoogleLogin
|
||||||
|
onSuccess={(res) => {
|
||||||
|
if (res.credential) {
|
||||||
|
onGoogleSuccess(res.credential);
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onError={() => console.error("Google login failed")}
|
||||||
|
size="large"
|
||||||
|
width="260"
|
||||||
|
text="signin_with"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>,
|
||||||
|
document.body,
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -57,33 +57,14 @@ interface MapViewProps {
|
|||||||
onSelectRestaurant?: (r: Restaurant) => void;
|
onSelectRestaurant?: (r: Restaurant) => void;
|
||||||
onBoundsChanged?: (bounds: MapBounds) => void;
|
onBoundsChanged?: (bounds: MapBounds) => void;
|
||||||
flyTo?: FlyTo | null;
|
flyTo?: FlyTo | null;
|
||||||
|
onMyLocation?: () => void;
|
||||||
|
activeChannel?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
function MapContent({ restaurants, selected, onSelectRestaurant, onBoundsChanged, flyTo }: MapViewProps) {
|
function MapContent({ restaurants, selected, onSelectRestaurant, flyTo, activeChannel }: Omit<MapViewProps, "onMyLocation" | "onBoundsChanged">) {
|
||||||
const map = useMap();
|
const map = useMap();
|
||||||
const [infoTarget, setInfoTarget] = useState<Restaurant | null>(null);
|
const [infoTarget, setInfoTarget] = useState<Restaurant | null>(null);
|
||||||
const channelColors = useMemo(() => getChannelColorMap(restaurants), [restaurants]);
|
const channelColors = useMemo(() => getChannelColorMap(restaurants), [restaurants]);
|
||||||
const boundsTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
|
||||||
|
|
||||||
// Report bounds on idle (debounced)
|
|
||||||
useEffect(() => {
|
|
||||||
if (!map) return;
|
|
||||||
const listener = map.addListener("idle", () => {
|
|
||||||
if (boundsTimerRef.current) clearTimeout(boundsTimerRef.current);
|
|
||||||
boundsTimerRef.current = setTimeout(() => {
|
|
||||||
const b = map.getBounds();
|
|
||||||
if (b && onBoundsChanged) {
|
|
||||||
const ne = b.getNorthEast();
|
|
||||||
const sw = b.getSouthWest();
|
|
||||||
onBoundsChanged({ north: ne.lat(), south: sw.lat(), east: ne.lng(), west: sw.lng() });
|
|
||||||
}
|
|
||||||
}, 300);
|
|
||||||
});
|
|
||||||
return () => {
|
|
||||||
google.maps.event.removeListener(listener);
|
|
||||||
if (boundsTimerRef.current) clearTimeout(boundsTimerRef.current);
|
|
||||||
};
|
|
||||||
}, [map, onBoundsChanged]);
|
|
||||||
|
|
||||||
const handleMarkerClick = useCallback(
|
const handleMarkerClick = useCallback(
|
||||||
(r: Restaurant) => {
|
(r: Restaurant) => {
|
||||||
@@ -113,7 +94,8 @@ function MapContent({ restaurants, selected, onSelectRestaurant, onBoundsChanged
|
|||||||
{restaurants.map((r) => {
|
{restaurants.map((r) => {
|
||||||
const isSelected = selected?.id === r.id;
|
const isSelected = selected?.id === r.id;
|
||||||
const isClosed = r.business_status === "CLOSED_PERMANENTLY";
|
const isClosed = r.business_status === "CLOSED_PERMANENTLY";
|
||||||
const chColor = r.channels?.[0] ? channelColors[r.channels[0]] : CHANNEL_COLORS[0];
|
const chKey = activeChannel && r.channels?.includes(activeChannel) ? activeChannel : r.channels?.[0];
|
||||||
|
const chColor = chKey ? channelColors[chKey] : CHANNEL_COLORS[0];
|
||||||
const c = chColor || CHANNEL_COLORS[0];
|
const c = chColor || CHANNEL_COLORS[0];
|
||||||
return (
|
return (
|
||||||
<AdvancedMarker
|
<AdvancedMarker
|
||||||
@@ -208,29 +190,56 @@ function MapContent({ restaurants, selected, onSelectRestaurant, onBoundsChanged
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function MapView({ restaurants, selected, onSelectRestaurant, onBoundsChanged, flyTo }: MapViewProps) {
|
export default function MapView({ restaurants, selected, onSelectRestaurant, onBoundsChanged, flyTo, onMyLocation, activeChannel }: MapViewProps) {
|
||||||
const channelColors = useMemo(() => getChannelColorMap(restaurants), [restaurants]);
|
const channelColors = useMemo(() => getChannelColorMap(restaurants), [restaurants]);
|
||||||
const channelNames = useMemo(() => Object.keys(channelColors), [channelColors]);
|
const channelNames = useMemo(() => {
|
||||||
|
const names = Object.keys(channelColors);
|
||||||
|
if (activeChannel) return names.filter((n) => n === activeChannel);
|
||||||
|
return names;
|
||||||
|
}, [channelColors, activeChannel]);
|
||||||
|
const boundsTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
|
||||||
|
|
||||||
|
const handleCameraChanged = useCallback((ev: { detail: { bounds: { north: number; south: number; east: number; west: number } } }) => {
|
||||||
|
if (!onBoundsChanged) return;
|
||||||
|
if (boundsTimerRef.current) clearTimeout(boundsTimerRef.current);
|
||||||
|
boundsTimerRef.current = setTimeout(() => {
|
||||||
|
const { north, south, east, west } = ev.detail.bounds;
|
||||||
|
onBoundsChanged({ north, south, east, west });
|
||||||
|
}, 150);
|
||||||
|
}, [onBoundsChanged]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<APIProvider apiKey={API_KEY}>
|
<APIProvider apiKey={API_KEY}>
|
||||||
<Map
|
<Map
|
||||||
defaultCenter={SEOUL_CENTER}
|
defaultCenter={SEOUL_CENTER}
|
||||||
defaultZoom={12}
|
defaultZoom={13}
|
||||||
mapId="tasteby-map"
|
mapId="tasteby-map"
|
||||||
className="h-full w-full"
|
className="h-full w-full"
|
||||||
colorScheme="LIGHT"
|
colorScheme="LIGHT"
|
||||||
mapTypeControl={false}
|
mapTypeControl={false}
|
||||||
|
fullscreenControl={false}
|
||||||
|
onCameraChanged={handleCameraChanged}
|
||||||
>
|
>
|
||||||
<MapContent
|
<MapContent
|
||||||
restaurants={restaurants}
|
restaurants={restaurants}
|
||||||
selected={selected}
|
selected={selected}
|
||||||
onSelectRestaurant={onSelectRestaurant}
|
onSelectRestaurant={onSelectRestaurant}
|
||||||
onBoundsChanged={onBoundsChanged}
|
|
||||||
flyTo={flyTo}
|
flyTo={flyTo}
|
||||||
|
activeChannel={activeChannel}
|
||||||
/>
|
/>
|
||||||
</Map>
|
</Map>
|
||||||
{channelNames.length > 1 && (
|
{onMyLocation && (
|
||||||
|
<button
|
||||||
|
onClick={onMyLocation}
|
||||||
|
className="absolute top-2 right-2 w-9 h-9 bg-white dark:bg-gray-900 rounded-lg shadow-md flex items-center justify-center text-gray-600 dark:text-gray-300 hover:text-orange-500 dark:hover:text-orange-400 transition-colors z-10"
|
||||||
|
title="내 위치"
|
||||||
|
>
|
||||||
|
<svg viewBox="0 0 24 24" className="w-5 h-5 fill-current">
|
||||||
|
<path d="M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm8.94 3A8.994 8.994 0 0013 3.06V1h-2v2.06A8.994 8.994 0 003.06 11H1v2h2.06A8.994 8.994 0 0011 20.94V23h2v-2.06A8.994 8.994 0 0020.94 13H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/>
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
{channelNames.length > 0 && (
|
||||||
<div className="absolute bottom-2 left-2 bg-white/90 dark:bg-gray-900/90 backdrop-blur-sm rounded-lg shadow px-2.5 py-1.5 flex flex-wrap gap-x-3 gap-y-1 text-[11px] z-10">
|
<div className="absolute bottom-2 left-2 bg-white/90 dark:bg-gray-900/90 backdrop-blur-sm rounded-lg shadow px-2.5 py-1.5 flex flex-wrap gap-x-3 gap-y-1 text-[11px] z-10">
|
||||||
{channelNames.map((ch) => (
|
{channelNames.map((ch) => (
|
||||||
<div key={ch} className="flex items-center gap-1">
|
<div key={ch} className="flex items-center gap-1">
|
||||||
|
|||||||
@@ -84,6 +84,7 @@ export default function RestaurantDetail({
|
|||||||
|
|
||||||
{restaurant.rating && (
|
{restaurant.rating && (
|
||||||
<div className="flex items-center gap-2 text-sm">
|
<div className="flex items-center gap-2 text-sm">
|
||||||
|
<span className="text-blue-500 dark:text-blue-400 font-medium text-xs">Google</span>
|
||||||
<span className="text-yellow-500 dark:text-yellow-400">{"★".repeat(Math.round(restaurant.rating))}</span>
|
<span className="text-yellow-500 dark:text-yellow-400">{"★".repeat(Math.round(restaurant.rating))}</span>
|
||||||
<span className="font-medium dark:text-gray-200">{restaurant.rating}</span>
|
<span className="font-medium dark:text-gray-200">{restaurant.rating}</span>
|
||||||
{restaurant.rating_count && (
|
{restaurant.rating_count && (
|
||||||
@@ -122,19 +123,51 @@ export default function RestaurantDetail({
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
{restaurant.google_place_id && (
|
{restaurant.google_place_id && (
|
||||||
<p>
|
<p className="flex gap-3">
|
||||||
<a
|
<a
|
||||||
href={`https://www.google.com/maps/place/?q=place_id:${restaurant.google_place_id}`}
|
href={`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(restaurant.name)}`}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="text-orange-600 dark:text-orange-400 hover:underline text-xs"
|
className="text-orange-600 dark:text-orange-400 hover:underline text-xs"
|
||||||
>
|
>
|
||||||
Google Maps에서 보기
|
Google Maps에서 보기
|
||||||
</a>
|
</a>
|
||||||
|
<a
|
||||||
|
href={`https://map.naver.com/v5/search/${encodeURIComponent(restaurant.name)}`}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="text-green-600 dark:text-green-400 hover:underline text-xs"
|
||||||
|
>
|
||||||
|
네이버 지도에서 보기
|
||||||
|
</a>
|
||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{restaurant.tabling_url && restaurant.tabling_url !== "NONE" && (
|
||||||
|
<a
|
||||||
|
href={restaurant.tabling_url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="flex items-center justify-center gap-2 w-full px-4 py-2.5 bg-rose-500 hover:bg-rose-600 text-white rounded-lg text-sm font-semibold transition-colors"
|
||||||
|
>
|
||||||
|
<span>T</span>
|
||||||
|
<span>테이블링에서 줄서기</span>
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{restaurant.catchtable_url && restaurant.catchtable_url !== "NONE" && (
|
||||||
|
<a
|
||||||
|
href={restaurant.catchtable_url}
|
||||||
|
target="_blank"
|
||||||
|
rel="noopener noreferrer"
|
||||||
|
className="flex items-center justify-center gap-2 w-full px-4 py-2.5 bg-violet-500 hover:bg-violet-600 text-white rounded-lg text-sm font-semibold transition-colors"
|
||||||
|
>
|
||||||
|
<span>C</span>
|
||||||
|
<span>캐치테이블에서 예약하기</span>
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
|
|
||||||
<div>
|
<div>
|
||||||
<h3 className="font-semibold text-sm mb-2 dark:text-gray-200">관련 영상</h3>
|
<h3 className="font-semibold text-sm mb-2 dark:text-gray-200">관련 영상</h3>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
@@ -161,7 +194,8 @@ export default function RestaurantDetail({
|
|||||||
<div key={v.video_id} className="border dark:border-gray-700 rounded-lg p-3">
|
<div key={v.video_id} className="border dark:border-gray-700 rounded-lg p-3">
|
||||||
<div className="flex items-center gap-2 mb-1">
|
<div className="flex items-center gap-2 mb-1">
|
||||||
{v.channel_name && (
|
{v.channel_name && (
|
||||||
<span className="inline-block px-1.5 py-0.5 bg-orange-50 dark:bg-orange-900/30 text-orange-600 dark:text-orange-400 rounded text-[10px] font-medium">
|
<span className="inline-flex items-center gap-1 px-1.5 py-0.5 bg-red-100 dark:bg-red-900/40 text-red-600 dark:text-red-400 rounded text-[10px] font-semibold">
|
||||||
|
<span className="text-[9px]">▶</span>
|
||||||
{v.channel_name}
|
{v.channel_name}
|
||||||
</span>
|
</span>
|
||||||
)}
|
)}
|
||||||
@@ -175,8 +209,11 @@ export default function RestaurantDetail({
|
|||||||
href={v.url}
|
href={v.url}
|
||||||
target="_blank"
|
target="_blank"
|
||||||
rel="noopener noreferrer"
|
rel="noopener noreferrer"
|
||||||
className="block text-sm font-medium text-orange-600 dark:text-orange-400 hover:underline"
|
className="inline-flex items-center gap-1.5 text-sm font-medium text-red-600 dark:text-red-400 hover:underline"
|
||||||
>
|
>
|
||||||
|
<svg viewBox="0 0 24 24" className="w-4 h-4 flex-shrink-0 fill-current" aria-hidden="true">
|
||||||
|
<path d="M23.5 6.2c-.3-1-1-1.8-2-2.1C19.6 3.5 12 3.5 12 3.5s-7.6 0-9.5.6c-1 .3-1.7 1.1-2 2.1C0 8.1 0 12 0 12s0 3.9.5 5.8c.3 1 1 1.8 2 2.1 1.9.6 9.5.6 9.5.6s7.6 0 9.5-.6c1-.3 1.7-1.1 2-2.1.5-1.9.5-5.8.5-5.8s0-3.9-.5-5.8zM9.5 15.5V8.5l6.3 3.5-6.3 3.5z"/>
|
||||||
|
</svg>
|
||||||
{v.title}
|
{v.title}
|
||||||
</a>
|
</a>
|
||||||
{v.foods_mentioned.length > 0 && (
|
{v.foods_mentioned.length > 0 && (
|
||||||
|
|||||||
@@ -34,7 +34,7 @@ export default function SearchBar({ onSearch, isLoading }: SearchBarProps) {
|
|||||||
>
|
>
|
||||||
<option value="hybrid">통합</option>
|
<option value="hybrid">통합</option>
|
||||||
<option value="keyword">키워드</option>
|
<option value="keyword">키워드</option>
|
||||||
<option value="semantic">의미</option>
|
<option value="semantic">유사</option>
|
||||||
</select>
|
</select>
|
||||||
<button
|
<button
|
||||||
type="submit"
|
type="submit"
|
||||||
|
|||||||
@@ -42,6 +42,8 @@ export interface Restaurant {
|
|||||||
cuisine_type: string | null;
|
cuisine_type: string | null;
|
||||||
price_range: string | null;
|
price_range: string | null;
|
||||||
google_place_id: string | null;
|
google_place_id: string | null;
|
||||||
|
tabling_url: string | null;
|
||||||
|
catchtable_url: string | null;
|
||||||
business_status: string | null;
|
business_status: string | null;
|
||||||
rating: number | null;
|
rating: number | null;
|
||||||
rating_count: number | null;
|
rating_count: number | null;
|
||||||
@@ -322,6 +324,32 @@ export const api = {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
searchTabling(restaurantId: string) {
|
||||||
|
return fetchApi<{ title: string; url: string }[]>(
|
||||||
|
`/api/restaurants/${restaurantId}/tabling-search`
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
setTablingUrl(restaurantId: string, tablingUrl: string) {
|
||||||
|
return fetchApi<{ ok: boolean }>(
|
||||||
|
`/api/restaurants/${restaurantId}/tabling-url`,
|
||||||
|
{ method: "PUT", body: JSON.stringify({ tabling_url: tablingUrl }) }
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
searchCatchtable(restaurantId: string) {
|
||||||
|
return fetchApi<{ title: string; url: string }[]>(
|
||||||
|
`/api/restaurants/${restaurantId}/catchtable-search`
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
setCatchtableUrl(restaurantId: string, catchtableUrl: string) {
|
||||||
|
return fetchApi<{ ok: boolean }>(
|
||||||
|
`/api/restaurants/${restaurantId}/catchtable-url`,
|
||||||
|
{ method: "PUT", body: JSON.stringify({ catchtable_url: catchtableUrl }) }
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
deleteChannel(channelId: string) {
|
deleteChannel(channelId: string) {
|
||||||
return fetchApi<{ ok: boolean }>(`/api/channels/${channelId}`, {
|
return fetchApi<{ ok: boolean }>(`/api/channels/${channelId}`, {
|
||||||
method: "DELETE",
|
method: "DELETE",
|
||||||
@@ -381,6 +409,13 @@ export const api = {
|
|||||||
);
|
);
|
||||||
},
|
},
|
||||||
|
|
||||||
|
uploadTranscript(videoDbId: string, text: string, source: string = "browser") {
|
||||||
|
return fetchApi<{ ok: boolean; length: number; source: string }>(
|
||||||
|
`/api/videos/${videoDbId}/upload-transcript`,
|
||||||
|
{ method: "POST", body: JSON.stringify({ text, source }) }
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
triggerProcessing(limit: number = 5) {
|
triggerProcessing(limit: number = 5) {
|
||||||
return fetchApi<{ restaurants_extracted: number }>(
|
return fetchApi<{ restaurants_extracted: number }>(
|
||||||
`/api/videos/process?limit=${limit}`,
|
`/api/videos/process?limit=${limit}`,
|
||||||
|
|||||||
@@ -16,7 +16,6 @@ spec:
|
|||||||
tls:
|
tls:
|
||||||
- hosts:
|
- hosts:
|
||||||
- www.tasteby.net
|
- www.tasteby.net
|
||||||
- tasteby.net
|
|
||||||
secretName: tasteby-tls
|
secretName: tasteby-tls
|
||||||
rules:
|
rules:
|
||||||
- host: www.tasteby.net
|
- host: www.tasteby.net
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ spec:
|
|||||||
spec:
|
spec:
|
||||||
containers:
|
containers:
|
||||||
- name: redis
|
- name: redis
|
||||||
image: redis:7-alpine
|
image: docker.io/library/redis:7-alpine
|
||||||
ports:
|
ports:
|
||||||
- containerPort: 6379
|
- containerPort: 6379
|
||||||
resources:
|
resources:
|
||||||
|
|||||||
41
nginx.conf
41
nginx.conf
@@ -4,6 +4,47 @@ server {
|
|||||||
return 301 https://www.tasteby.net$request_uri;
|
return 301 https://www.tasteby.net$request_uri;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 80;
|
||||||
|
server_name dev.tasteby.net;
|
||||||
|
return 301 https://dev.tasteby.net$request_uri;
|
||||||
|
}
|
||||||
|
|
||||||
|
server {
|
||||||
|
listen 443 ssl http2;
|
||||||
|
server_name dev.tasteby.net;
|
||||||
|
|
||||||
|
ssl_certificate /etc/letsencrypt/live/dev.tasteby.net/fullchain.pem;
|
||||||
|
ssl_certificate_key /etc/letsencrypt/live/dev.tasteby.net/privkey.pem;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
ssl_ciphers HIGH:!aNULL:!MD5;
|
||||||
|
|
||||||
|
# Frontend (Next.js)
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:3001;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_set_header Upgrade $http_upgrade;
|
||||||
|
proxy_set_header Connection "upgrade";
|
||||||
|
}
|
||||||
|
|
||||||
|
# Backend API
|
||||||
|
location /api/ {
|
||||||
|
proxy_pass http://127.0.0.1:8000;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Real-IP $remote_addr;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_set_header X-Forwarded-Proto $scheme;
|
||||||
|
proxy_read_timeout 300;
|
||||||
|
proxy_connect_timeout 75;
|
||||||
|
proxy_send_timeout 300;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
server {
|
server {
|
||||||
listen 443 ssl http2;
|
listen 443 ssl http2;
|
||||||
server_name tasteby.net;
|
server_name tasteby.net;
|
||||||
|
|||||||
Reference in New Issue
Block a user