22
33import apptive .team5 .global .exception .ExceptionCode ;
44import apptive .team5 .global .exception .ExternalApiConnectException ;
5+ import apptive .team5 .youtube .YoutubeApiKeyProvider ;
56import apptive .team5 .youtube .dto .YoutubeSearchRequest ;
67import apptive .team5 .youtube .dto .YoutubeVideoResponse ;
78import com .google .api .client .http .javanet .NetHttpTransport ;
89import com .google .api .client .json .gson .GsonFactory ;
910import com .google .api .services .youtube .YouTube ;
1011import com .google .api .services .youtube .model .SearchListResponse ;
1112import com .google .api .services .youtube .model .VideoListResponse ;
12- import org .springframework .beans .factory .annotation .Value ;
1313import org .springframework .http .HttpStatus ;
1414import org .springframework .stereotype .Service ;
1515
2121@ Service
2222public class YoutubeService {
2323
24- @ Value ("${youtube.api.key}" )
25- private String apiKey ;
24+ private final YoutubeApiKeyProvider apiKeyProvider ;
2625 private static final GsonFactory gsonFactory = new GsonFactory ();
2726
27+ public YoutubeService (YoutubeApiKeyProvider provider ) {
28+ this .apiKeyProvider = provider ;
29+ }
30+
2831 public List <YoutubeVideoResponse > searchVideo (YoutubeSearchRequest searchRequest ) {
29- YouTube youtube = new YouTube .
30- Builder (
32+
33+ String apiKey = apiKeyProvider .nextKey ();
34+
35+ YouTube youtube = new YouTube .Builder (
3136 new NetHttpTransport (), gsonFactory , request -> {}
3237 ).build ();
3338
@@ -40,25 +45,29 @@ public List<YoutubeVideoResponse> searchVideo(YoutubeSearchRequest searchRequest
4045 .setKey (apiKey )
4146 .execute ();
4247
43- List <String > videoIds = searchResponse .getItems ().stream ()
48+ List <String > videoIds = searchResponse .getItems ()
49+ .stream ()
4450 .map (r -> r .getId ().getVideoId ())
4551 .filter (Objects ::nonNull )
4652 .toList ();
4753
48-
4954 VideoListResponse videoResponse = youtube .videos ()
5055 .list (Collections .singletonList ("snippet,contentDetails,statistics" ))
5156 .setId (Collections .singletonList (String .join ("," , videoIds )))
5257 .setKey (apiKey )
5358 .execute ();
5459
5560 return videoResponse .getItems ()
56- .stream ().map (YoutubeVideoResponse ::new )
61+ .stream ()
62+ .map (YoutubeVideoResponse ::new )
5763 .sorted ()
5864 .toList ();
5965
6066 } catch (IOException e ) {
61- throw new ExternalApiConnectException (ExceptionCode .YOUTUBE_API_EXCEPTION .getDescription (), HttpStatus .INTERNAL_SERVER_ERROR );
67+ throw new ExternalApiConnectException (
68+ ExceptionCode .YOUTUBE_API_EXCEPTION .getDescription (),
69+ HttpStatus .INTERNAL_SERVER_ERROR
70+ );
6271 }
6372 }
6473}
0 commit comments