Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix memory issues #26

Merged
merged 3 commits into from
Aug 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Sources/FCM/FCM.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import JWT
public struct FCM {
let application: Application

let client: HTTPClient
let client: Client

let scope = "https://www.googleapis.com/auth/cloud-platform"
let audience = "https://www.googleapis.com/oauth2/v4/token"
Expand Down Expand Up @@ -38,7 +38,7 @@ public struct FCM {
if !application.http.client.configuration.ignoreUncleanSSLShutdown {
application.http.client.configuration.ignoreUncleanSSLShutdown = true
}
self.client = application.http.client.shared
self.client = application.client
}
}

Expand Down
18 changes: 18 additions & 0 deletions Sources/FCM/FCMError.swift
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import Vapor

public struct GoogleError: Error, Decodable {
public let code: Int
public let message: String
Expand Down Expand Up @@ -39,3 +41,19 @@ public struct FCMError: Error, Decodable {
case `internal` = "INTERNAL"
}
}

extension EventLoopFuture where Value == ClientResponse {
func validate() -> EventLoopFuture<ClientResponse> {
return flatMapThrowing { (response) in
guard 200 ..< 300 ~= response.status.code else {
if let error = try? response.content.decode(GoogleError.self) {
throw error
}
let body = response.body.map(String.init) ?? ""
throw Abort(.internalServerError, reason: "FCM: Unexpected error '\(body)'")
}

return response
}
}
}
42 changes: 14 additions & 28 deletions Sources/FCM/Helpers/FCM+AccessToken.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,22 @@ extension FCM {
fatalError("FCM gAuth can't be nil")
}
if !gAuth.hasExpired, let token = accessToken {
return client.eventLoopGroup.future(token)
return client.eventLoop.future(token)
}
return application.eventLoopGroup.future(()).flatMapThrowing { _ throws -> Data in
var payload: [String: String] = [:]
payload["grant_type"] = "urn:ietf:params:oauth:grant-type:jwt-bearer"
payload["assertion"] = try self.getJWT()
return try JSONEncoder().encode(payload)
}.flatMapThrowing { data -> HTTPClient.Request in
var headers = HTTPHeaders()
headers.add(name: "Content-Type", value: "application/json")
return try HTTPClient.Request(url: self.audience, method: .POST, headers: headers, body: .data(data))
}.flatMap { request in
return self.client.execute(request: request).flatMapThrowing { res throws -> String in
guard let body = res.body, let data = body.getData(at: body.readerIndex, length: body.readableBytes) else {
throw Abort(.notFound, reason: "Data not found")
}
if res.status.code != 200 {
let code = "Code: \(res.status.code)"
let message = "Message: \(String(data: data, encoding: .utf8) ?? "n/a"))"
let reason = "[FCM] Unable to refresh access token. \(code) \(message)"
throw Abort(.internalServerError, reason: reason)
}
struct Result: Codable {
var access_token: String
}
guard let result = try? JSONDecoder().decode(Result.self, from: data) else {
throw Abort(.notFound, reason: "Data not found")
}
return result.access_token

return client.post(URI(string: audience)) { (req) in
try req.content.encode([
"grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer",
"assertion": try self.getJWT(),
])
}
.validate()
.flatMapThrowing { res -> String in
struct Result: Codable {
var access_token: String
}
let result = try res.content.decode(Result.self)
return result.access_token
}
}
}
8 changes: 4 additions & 4 deletions Sources/FCM/Helpers/FCM+BatchSend.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@ extension FCM {
public func batchSend(_ message: FCMMessageDefault, tokens: String...) -> EventLoopFuture<[String]> {
_send(message, tokens: tokens)
}

public func batchSend(_ message: FCMMessageDefault, tokens: String..., on eventLoop: EventLoop) -> EventLoopFuture<[String]> {
_send(message, tokens: tokens).hop(to: eventLoop)
}

public func batchSend(_ message: FCMMessageDefault, tokens: [String]) -> EventLoopFuture<[String]> {
_send(message, tokens: tokens)
}

public func batchSend(_ message: FCMMessageDefault, tokens: [String], on eventLoop: EventLoop) -> EventLoopFuture<[String]> {
_send(message, tokens: tokens).hop(to: eventLoop)
}

private func _send(_ message: FCMMessageDefault, tokens: [String]) -> EventLoopFuture<[String]> {
if message.apns == nil,
let apnsDefaultConfig = apnsDefaultConfig {
Expand Down
54 changes: 21 additions & 33 deletions Sources/FCM/Helpers/FCM+CreateTopic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@ extension FCM {
public func createTopic(_ name: String? = nil, tokens: String...) -> EventLoopFuture<String> {
createTopic(name, tokens: tokens)
}

public func createTopic(_ name: String? = nil, tokens: String..., on eventLoop: EventLoop) -> EventLoopFuture<String> {
createTopic(name, tokens: tokens).hop(to: eventLoop)
}

public func createTopic(_ name: String? = nil, tokens: [String]) -> EventLoopFuture<String> {
_createTopic(name, tokens: tokens)
}

public func createTopic(_ name: String? = nil, tokens: [String], on eventLoop: EventLoop) -> EventLoopFuture<String> {
_createTopic(name, tokens: tokens).hop(to: eventLoop)
}

private func _createTopic(_ name: String? = nil, tokens: [String]) -> EventLoopFuture<String> {
guard let configuration = self.configuration else {
fatalError("FCM not configured. Use app.fcm.configuration = ...")
Expand All @@ -27,39 +27,27 @@ extension FCM {
}
let url = self.iidURL + "batchAdd"
let name = name ?? UUID().uuidString
return getAccessToken().flatMapThrowing { accessToken throws -> HTTPClient.Request in
struct Payload: Codable {
let to: String
let registration_tokens: [String]

init (to: String, registration_tokens: [String]) {
self.to = "/topics/\(to)"
self.registration_tokens = registration_tokens
}
}
let payload = Payload(to: name, registration_tokens: tokens)
let payloadData = try JSONEncoder().encode(payload)
return getAccessToken().flatMap { accessToken -> EventLoopFuture<ClientResponse> in
var headers = HTTPHeaders()
headers.add(name: "Authorization", value: "key=\(serverKey)")
headers.add(name: "Content-Type", value: "application/json")
return try .init(url: url, method: .POST, headers: headers, body: .data(payloadData))
}.flatMap { request in
return self.client.execute(request: request).flatMapThrowing { res in
guard 200 ..< 300 ~= res.status.code else {
if let body = res.body, let googleError = try? JSONDecoder().decode(GoogleError.self, from: body) {
throw googleError
} else {
guard
let bb = res.body,
let bytes = bb.getBytes(at: 0, length: bb.readableBytes),
let reason = String(bytes: bytes, encoding: .utf8) else {
throw Abort(.internalServerError, reason: "FCM: CreateTopic: unable to decode error response")
}
throw Abort(.internalServerError, reason: reason)
headers.add(name: .authorization, value: "key=\(serverKey)")

return self.client.post(URI(string: url), headers: headers) { (req) in
struct Payload: Content {
let to: String
let registration_tokens: [String]

init(to: String, registration_tokens: [String]) {
self.to = "/topics/\(to)"
self.registration_tokens = registration_tokens
}
}
return name
let payload = Payload(to: name, registration_tokens: tokens)
try req.content.encode(payload)
}
}
.validate()
.map { _ in
return name
}
}
}
51 changes: 19 additions & 32 deletions Sources/FCM/Helpers/FCM+DeleteTopic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@ extension FCM {
public func deleteTopic(_ name: String, tokens: String...) -> EventLoopFuture<Void> {
deleteTopic(name, tokens: tokens)
}

public func deleteTopic(_ name: String, tokens: String..., on eventLoop: EventLoop) -> EventLoopFuture<Void> {
deleteTopic(name, tokens: tokens).hop(to: eventLoop)
}

public func deleteTopic(_ name: String, tokens: [String]) -> EventLoopFuture<Void> {
_deleteTopic(name, tokens: tokens)
}

public func deleteTopic(_ name: String, tokens: [String], on eventLoop: EventLoop) -> EventLoopFuture<Void> {
_deleteTopic(name, tokens: tokens).hop(to: eventLoop)
}

private func _deleteTopic(_ name: String, tokens: [String]) -> EventLoopFuture<Void> {
guard let configuration = self.configuration else {
fatalError("FCM not configured. Use app.fcm.configuration = ...")
Expand All @@ -26,38 +26,25 @@ extension FCM {
fatalError("FCM: DeleteTopic: Server Key is missing.")
}
let url = self.iidURL + "batchRemove"
return getAccessToken().flatMapThrowing { accessToken throws -> HTTPClient.Request in
struct Payload: Codable {
let to: String
let registration_tokens: [String]

init (to: String, registration_tokens: [String]) {
self.to = "/topics/\(to)"
self.registration_tokens = registration_tokens
}
}
let payload = Payload(to: name, registration_tokens: tokens)
let payloadData = try JSONEncoder().encode(payload)
return getAccessToken().flatMap { accessToken -> EventLoopFuture<ClientResponse> in
var headers = HTTPHeaders()
headers.add(name: "Authorization", value: "key=\(serverKey)")
headers.add(name: "Content-Type", value: "application/json")
return try .init(url: url, method: .POST, headers: headers, body: .data(payloadData))
}.flatMap { request in
return self.client.execute(request: request).flatMapThrowing { res in
guard 200 ..< 300 ~= res.status.code else {
if let body = res.body, let googleError = try? JSONDecoder().decode(GoogleError.self, from: body) {
throw googleError
} else {
guard
let bb = res.body,
let bytes = bb.getBytes(at: 0, length: bb.readableBytes),
let reason = String(bytes: bytes, encoding: .utf8) else {
throw Abort(.internalServerError, reason: "FCM: DeleteTopic: unable to decode error response")
}
throw Abort(.internalServerError, reason: reason)
headers.add(name: .authorization, value: "key=\(serverKey)")

return self.client.post(URI(string: url), headers: headers) { (req) in
struct Payload: Content {
let to: String
let registration_tokens: [String]

init(to: String, registration_tokens: [String]) {
self.to = "/topics/\(to)"
self.registration_tokens = registration_tokens
}
}
let payload = Payload(to: name, registration_tokens: tokens)
try req.content.encode(payload)
}
}
.validate()
.map { _ in () }
}
}
57 changes: 22 additions & 35 deletions Sources/FCM/Helpers/FCM+RegisterAPNS.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ public struct RegisterAPNSID {
let appBundleId: String
let serverKey: String?
let sandbox: Bool

public init (appBundleId: String, serverKey: String? = nil, sandbox: Bool = false) {
self.appBundleId = appBundleId
self.serverKey = serverKey
Expand Down Expand Up @@ -37,7 +37,7 @@ public struct APNSToFirebaseToken {
extension FCM {
/// Helper method which registers your pure APNS token in Firebase Cloud Messaging
/// and returns firebase tokens for each APNS token
///
///
/// Convenient way
///
/// Declare `RegisterAPNSID` via extension
Expand All @@ -53,7 +53,7 @@ extension FCM {
on eventLoop: EventLoop? = nil) -> EventLoopFuture<[APNSToFirebaseToken]> {
registerAPNS(appBundleId: id.appBundleId, serverKey: id.serverKey, sandbox: id.sandbox, tokens: tokens, on: eventLoop)
}

/// Helper method which registers your pure APNS token in Firebase Cloud Messaging
/// and returns firebase tokens for each APNS token
///
Expand All @@ -72,7 +72,7 @@ extension FCM {
on eventLoop: EventLoop? = nil) -> EventLoopFuture<[APNSToFirebaseToken]> {
registerAPNS(appBundleId: id.appBundleId, serverKey: id.serverKey, sandbox: id.sandbox, tokens: tokens, on: eventLoop)
}

/// Helper method which registers your pure APNS token in Firebase Cloud Messaging
/// and returns firebase tokens for each APNS token
public func registerAPNS(
Expand All @@ -83,7 +83,7 @@ extension FCM {
on eventLoop: EventLoop? = nil) -> EventLoopFuture<[APNSToFirebaseToken]> {
registerAPNS(appBundleId: appBundleId, serverKey: serverKey, sandbox: sandbox, tokens: tokens, on: eventLoop)
}

/// Helper method which registers your pure APNS token in Firebase Cloud Messaging
/// and returns firebase tokens for each APNS token
public func registerAPNS(
Expand All @@ -110,43 +110,30 @@ extension FCM {
fatalError("FCM: Register APNS: Server Key is missing.")
}
let url = iidURL + "batchImport"
return eventLoop.future().flatMapThrowing { accessToken throws -> HTTPClient.Request in
struct Payload: Codable {

var headers = HTTPHeaders()
headers.add(name: .authorization, value: "key=\(serverKey)")

return self.client.post(URI(string: url), headers: headers) { (req) in
struct Payload: Content {
let application: String
let sandbox: Bool
let apns_tokens: [String]
}
let payload = Payload(application: appBundleId, sandbox: sandbox, apns_tokens: tokens)
let payloadData = try JSONEncoder().encode(payload)

var headers = HTTPHeaders()
headers.add(name: "Authorization", value: "key=\(serverKey)")
headers.add(name: "Content-Type", value: "application/json")

return try .init(url: url, method: .POST, headers: headers, body: .data(payloadData))
}.flatMap { request in
return self.client.execute(request: request).flatMapThrowing { res in
guard 200 ..< 300 ~= res.status.code else {
guard
let bb = res.body,
let bytes = bb.getBytes(at: 0, length: bb.readableBytes),
let reason = String(bytes: bytes, encoding: .utf8) else {
throw Abort(.internalServerError, reason: "FCM: Register APNS: unable to decode error response")
}
throw Abort(.internalServerError, reason: reason)
}
try req.content.encode(payload)
}
.validate()
.flatMapThrowing { res in
struct Result: Codable {
struct Result: Codable {
struct Result: Codable {
let registration_token, apns_token, status: String
}
var results: [Result]
}
guard let body = res.body, let result = try? JSONDecoder().decode(Result.self, from: body) else {
throw Abort(.notFound, reason: "FCM: Register APNS: empty response")
}
return result.results.map {
.init(registration_token: $0.registration_token, apns_token: $0.apns_token, isRegistered: $0.status == "OK")
let registration_token, apns_token, status: String
}
let results: [Result]
}
let result = try res.content.decode(Result.self)
return result.results.map {
.init(registration_token: $0.registration_token, apns_token: $0.apns_token, isRegistered: $0.status == "OK")
}
}
}
Expand Down
Loading