SessionGenerator.swift 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. //
  2. // Copyright 2022 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. import Foundation
  16. internal import FirebaseInstallations
  17. struct SessionInfo {
  18. let sessionId: String
  19. let firstSessionId: String
  20. let shouldDispatchEvents: Bool
  21. let sessionIndex: Int32
  22. init(sessionId: String, firstSessionId: String, dispatchEvents: Bool, sessionIndex: Int32) {
  23. self.sessionId = sessionId
  24. self.firstSessionId = firstSessionId
  25. shouldDispatchEvents = dispatchEvents
  26. self.sessionIndex = sessionIndex
  27. }
  28. }
  29. ///
  30. /// Generator is responsible for:
  31. /// 1) Generating the Session ID
  32. /// 2) Persisting and reading the Session ID from the last session
  33. /// (Maybe) 3) Persisting, reading, and incrementing an increasing index
  34. ///
  35. class SessionGenerator {
  36. private var thisSession: SessionInfo?
  37. private var firstSessionId = ""
  38. private var sessionIndex: Int32
  39. private var collectEvents: Bool
  40. init(collectEvents: Bool) {
  41. // This will be incremented to 0 on the first generation
  42. sessionIndex = -1
  43. self.collectEvents = collectEvents
  44. }
  45. // Generates a new Session ID. If there was already a generated Session ID
  46. // from the last session during the app's lifecycle, it will also set the last Session ID
  47. func generateNewSession() -> SessionInfo {
  48. let newSessionId = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
  49. // If firstSessionId is set, use it. Otherwise set it to the
  50. // first generated Session ID
  51. firstSessionId = firstSessionId.isEmpty ? newSessionId : firstSessionId
  52. sessionIndex += 1
  53. let newSession = SessionInfo(sessionId: newSessionId,
  54. firstSessionId: firstSessionId,
  55. dispatchEvents: collectEvents,
  56. sessionIndex: sessionIndex)
  57. thisSession = newSession
  58. return newSession
  59. }
  60. var currentSession: SessionInfo? {
  61. return thisSession
  62. }
  63. }