BirthdayLoader.swift 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. .accessToken
  41. .tokenString 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. GIDSignIn.sharedInstance.currentUser?.do { user, error in
  50. guard let token = user?.accessToken.tokenString else {
  51. completion(.failure(.couldNotCreateURLSession(error)))
  52. return
  53. }
  54. let configuration = URLSessionConfiguration.default
  55. configuration.httpAdditionalHeaders = [
  56. "Authorization": "Bearer \(token)"
  57. ]
  58. let session = URLSession(configuration: configuration)
  59. completion(.success(session))
  60. }
  61. }
  62. /// Creates a `Publisher` to fetch a user's `Birthday`.
  63. /// - parameter completion: A closure passing back the `AnyPublisher<Birthday, Error>`
  64. /// upon success.
  65. /// - note: The `AnyPublisher` passed back through the `completion` closure is created with a
  66. /// fresh token. See `sessionWithFreshToken(completion:)` for more details.
  67. func birthdayPublisher(completion: @escaping (AnyPublisher<Birthday, Error>) -> Void) {
  68. sessionWithFreshToken { [weak self] result in
  69. switch result {
  70. case .success(let authSession):
  71. guard let request = self?.request else {
  72. return completion(Fail(error: .couldNotCreateURLRequest).eraseToAnyPublisher())
  73. }
  74. let bdayPublisher = authSession.dataTaskPublisher(for: request)
  75. .tryMap { data, error -> Birthday in
  76. let decoder = JSONDecoder()
  77. let birthdayResponse = try decoder.decode(BirthdayResponse.self, from: data)
  78. return birthdayResponse.firstBirthday
  79. }
  80. .mapError { error -> Error in
  81. guard let loaderError = error as? Error else {
  82. return Error.couldNotFetchBirthday(underlying: error)
  83. }
  84. return loaderError
  85. }
  86. .receive(on: DispatchQueue.main)
  87. .eraseToAnyPublisher()
  88. completion(bdayPublisher)
  89. case .failure(let error):
  90. completion(Fail(error: error).eraseToAnyPublisher())
  91. }
  92. }
  93. }
  94. }
  95. extension BirthdayLoader {
  96. /// An error representing what went wrong in fetching a user's number of day until their birthday.
  97. enum Error: Swift.Error {
  98. case couldNotCreateURLSession(Swift.Error?)
  99. case couldNotCreateURLRequest
  100. case userHasNoBirthday
  101. case couldNotFetchBirthday(underlying: Swift.Error)
  102. }
  103. }