BirthdayLoader.swift 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*
  2. * Copyright 2021 Google LLC
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. import Combine
  17. import GoogleSignIn
  18. /// An observable class to load the current user's birthday.
  19. final class BirthdayLoader: ObservableObject {
  20. /// The scope required to read a user's birthday.
  21. static let birthdayReadScope = "https://www.googleapis.com/auth/user.birthday.read"
  22. private let baseUrlString = "https://people.googleapis.com/v1/people/me"
  23. private let personFieldsQuery = URLQueryItem(name: "personFields", value: "birthdays")
  24. private let birthdaySubject = PassthroughSubject<Birthday, Error>()
  25. private lazy var components: URLComponents? = {
  26. var comps = URLComponents(string: baseUrlString)
  27. comps?.queryItems = [personFieldsQuery]
  28. return comps
  29. }()
  30. private lazy var request: URLRequest? = {
  31. guard let components = components, let url = components.url else {
  32. return nil
  33. }
  34. return URLRequest(url: url)
  35. }()
  36. private lazy var session: URLSession? = {
  37. guard let accessToken = GIDSignIn
  38. .sharedInstance
  39. .currentUser?
  40. .authentication
  41. .accessToken else { return nil }
  42. let configuration = URLSessionConfiguration.default
  43. configuration.httpAdditionalHeaders = [
  44. "Authorization": "Bearer \(accessToken)"
  45. ]
  46. return URLSession(configuration: configuration)
  47. }()
  48. private func sessionWithFreshToken(completion: @escaping (Result<URLSession, Error>) -> Void) {
  49. let authentication = GIDSignIn.sharedInstance.currentUser?.authentication
  50. authentication?.do { auth, error in
  51. guard let token = auth?.accessToken else {
  52. completion(.failure(.couldNotCreateURLSession(error)))
  53. return
  54. }
  55. let configuration = URLSessionConfiguration.default
  56. configuration.httpAdditionalHeaders = [
  57. "Authorization": "Bearer \(token)"
  58. ]
  59. let session = URLSession(configuration: configuration)
  60. completion(.success(session))
  61. }
  62. }
  63. /// Creates a `Publisher` to fetch a user's `Birthday`.
  64. /// - parameter completion: A closure passing back the `AnyPublisher<Birthday, Error>`
  65. /// upon success.
  66. /// - note: The `AnyPublisher` passed back through the `completion` closure is created with a
  67. /// fresh token. See `sessionWithFreshToken(completion:)` for more details.
  68. func birthdayPublisher(completion: @escaping (AnyPublisher<Birthday, Error>) -> Void) {
  69. sessionWithFreshToken { [weak self] result in
  70. switch result {
  71. case .success(let authSession):
  72. guard let request = self?.request else {
  73. return completion(Fail(error: .couldNotCreateURLRequest).eraseToAnyPublisher())
  74. }
  75. let bdayPublisher = authSession.dataTaskPublisher(for: request)
  76. .tryMap { data, error -> Birthday in
  77. let decoder = JSONDecoder()
  78. let birthdayResponse = try decoder.decode(BirthdayResponse.self, from: data)
  79. return birthdayResponse.firstBirthday
  80. }
  81. .mapError { error -> Error in
  82. guard let loaderError = error as? Error else {
  83. return Error.couldNotFetchBirthday(underlying: error)
  84. }
  85. return loaderError
  86. }
  87. .receive(on: DispatchQueue.main)
  88. .eraseToAnyPublisher()
  89. completion(bdayPublisher)
  90. case .failure(let error):
  91. completion(Fail(error: error).eraseToAnyPublisher())
  92. }
  93. }
  94. }
  95. }
  96. extension BirthdayLoader {
  97. /// An error representing what went wrong in fetching a user's number of day until their birthday.
  98. enum Error: Swift.Error {
  99. case couldNotCreateURLSession(Swift.Error?)
  100. case couldNotCreateURLRequest
  101. case userHasNoBirthday
  102. case couldNotFetchBirthday(underlying: Swift.Error)
  103. }
  104. }