|
| 1 | +package com.gu.liveactivities |
| 2 | + |
| 3 | +import java.net.http.HttpClient |
| 4 | +import java.time.Duration |
| 5 | +import java.nio.charset.StandardCharsets |
| 6 | +import java.net.URI |
| 7 | +import java.net.http.HttpRequest |
| 8 | +import java.net.http.HttpResponse |
| 9 | +import scala.concurrent.Future |
| 10 | +import scala.concurrent.Promise |
| 11 | + |
| 12 | +import com.turo.pushy.apns.auth.ApnsSigningKey; |
| 13 | +import com.turo.pushy.apns.auth.AuthenticationToken; |
| 14 | +import java.time.Instant |
| 15 | +import java.util.Date |
| 16 | + |
| 17 | +class ChannelApiClient { |
| 18 | + |
| 19 | + private val httpClient: HttpClient = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build() |
| 20 | + |
| 21 | + println("HttpClient is instantiated") |
| 22 | + |
| 23 | + private val charSet = StandardCharsets.UTF_8 |
| 24 | + |
| 25 | + private val mediaType = "application/json; charset=UTF-8" |
| 26 | + |
| 27 | + private val url = "https://api-manage-broadcast.sandbox.push.apple.com:2195/1/apps/<bundleId>/channels" |
| 28 | + |
| 29 | + private val message = "{\"message-storage-policy\": 1, \"push-type\": \"LiveActivity\"}" |
| 30 | + |
| 31 | + private def getAccessToken(): String = { |
| 32 | + return "invalid-token-for-testing" |
| 33 | + } |
| 34 | + |
| 35 | + private def generateToken(): String = { |
| 36 | + val signingKey = ApnsSigningKey.loadFromPkcs8File( |
| 37 | + new java.io.File("src/main/resources/AuthKey_XXXXXXXXXX.p8"), |
| 38 | + "TEAMID", |
| 39 | + "KEYID" |
| 40 | + ) |
| 41 | + val authenticationToken = new AuthenticationToken(signingKey, new Date()) |
| 42 | + return authenticationToken.getAuthorizationHeader().toString() |
| 43 | + } |
| 44 | + |
| 45 | + def createChannel(): Future[String] = { |
| 46 | + println("Creating channel") |
| 47 | + |
| 48 | + val request: HttpRequest = HttpRequest.newBuilder(new URI(url)) |
| 49 | + .version(HttpClient.Version.HTTP_2) |
| 50 | + .header("Authorization", "Bearer " + getAccessToken()) |
| 51 | + .header("Content-Type", mediaType) |
| 52 | + .POST(HttpRequest.BodyPublishers.ofString(message, charSet)) |
| 53 | + .timeout(Duration.ofSeconds(60)) |
| 54 | + .build() |
| 55 | + val p = Promise[String]() |
| 56 | + httpClient.sendAsync(request, HttpResponse.BodyHandlers.ofString()).whenComplete((response, err) => { |
| 57 | + if (response == null) { |
| 58 | + p.failure(err) |
| 59 | + } else { |
| 60 | + println(s"Received response with status code ${response.statusCode()} and body ${response.body()}") |
| 61 | + p.success(response.body()) |
| 62 | + } |
| 63 | + }) |
| 64 | + p.future |
| 65 | + } |
| 66 | +} |
0 commit comments