|
1 | 1 | package io.github.yvasyliev.deezer.factory; |
2 | 2 |
|
| 3 | +import io.github.yvasyliev.deezer.exception.DeezerException; |
3 | 4 | import io.github.yvasyliev.deezer.model.AccessToken; |
| 5 | +import io.github.yvasyliev.deezer.model.Permission; |
4 | 6 | import io.github.yvasyliev.deezer.request.DeezerRequest; |
5 | 7 | import io.github.yvasyliev.deezer.request.SimpleDeezerRequest; |
6 | 8 | import io.github.yvasyliev.deezer.service.OAuthService; |
7 | 9 | import lombok.RequiredArgsConstructor; |
8 | 10 |
|
| 11 | +import java.net.MalformedURLException; |
| 12 | +import java.net.URI; |
| 13 | +import java.net.URL; |
| 14 | +import java.net.URLEncoder; |
| 15 | +import java.nio.charset.StandardCharsets; |
| 16 | +import java.util.Collection; |
| 17 | +import java.util.stream.Collectors; |
| 18 | + |
| 19 | +/** |
| 20 | + * Factory for creating OAuth-related requests. |
| 21 | + */ |
9 | 22 | @RequiredArgsConstructor |
10 | 23 | public class OAuthRequestFactory { |
| 24 | + private static final String LOGIN_URL_TEMPLATE = "%s/oauth/auth.php?app_id=%d&redirect_uri=%s&perms=%s"; |
| 25 | + private final URL authHost; |
11 | 26 | private final OAuthService oAuthService; |
12 | 27 |
|
| 28 | + /** |
| 29 | + * Generates the login URL for the OAuth flow. |
| 30 | + * |
| 31 | + * @param appId the application ID |
| 32 | + * @param redirectUri the URI to redirect to after login |
| 33 | + * @param permissions the permissions to request |
| 34 | + * @return the login URL |
| 35 | + * @throws DeezerException if URL generation fails |
| 36 | + */ |
| 37 | + public URL getLoginUrl(int appId, String redirectUri, Collection<Permission> permissions) |
| 38 | + throws DeezerException { |
| 39 | + try { |
| 40 | + var perms = permissions.stream().map(Permission::getValue).collect(Collectors.joining(",")); |
| 41 | + var loginUrl = LOGIN_URL_TEMPLATE.formatted( |
| 42 | + authHost, |
| 43 | + appId, |
| 44 | + URLEncoder.encode(redirectUri, StandardCharsets.UTF_8), |
| 45 | + URLEncoder.encode(perms, StandardCharsets.UTF_8) |
| 46 | + ); |
| 47 | + |
| 48 | + return URI.create(loginUrl).toURL(); |
| 49 | + } catch (MalformedURLException e) { |
| 50 | + throw new DeezerException("Failed to generate login URL", e); |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + /** |
| 55 | + * Exchanges the authorization code for an access token. |
| 56 | + * |
| 57 | + * @param appId the application ID |
| 58 | + * @param secret the application secret |
| 59 | + * @param code the authorization code received from the login flow |
| 60 | + * @return an access token request |
| 61 | + */ |
13 | 62 | public DeezerRequest<AccessToken> getAccessToken(int appId, String secret, String code) { |
14 | 63 | return new SimpleDeezerRequest<>(() -> oAuthService.getAccessTokenAsync(appId, secret, code)); |
15 | 64 | } |
|
0 commit comments