Skip to content

Commit 98f0897

Browse files
Merge pull request #284 from pusher/feature/283-refactor-string-literals
Refactor String literal usage
2 parents affbf77 + 93c1bed commit 98f0897

21 files changed

+1999
-90
lines changed

.swiftlint.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,4 +11,4 @@ identifier_name:
1111

1212
# This generates a compiler error if more than this many SwiftLint warnings are present
1313
# (This threshold can become more restrictive as remaining warnings are resolved via refactoring)
14-
warning_threshold: 25
14+
warning_threshold: 22

PusherSwift.xcodeproj/project.pbxproj

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,10 @@
3030
33BB997C1D21230100B25C2A /* PusherTopLevelAPITests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BB99661D21226C00B25C2A /* PusherTopLevelAPITests.swift */; };
3131
33C1FD6F1D81BFC300921AD7 /* ObjectiveC.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33C1FD6E1D81BFC300921AD7 /* ObjectiveC.swift */; };
3232
33C40CB91C1DFC9C008A54E3 /* PusherSwift.h in Headers */ = {isa = PBXBuildFile; fileRef = 33831CD61A9CFFF200B124F1 /* PusherSwift.h */; settings = {ATTRIBUTES = (Public, ); }; };
33+
539D9AFC2507F67300B5765A /* PusherLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 539D9AFB2507F67300B5765A /* PusherLogger.swift */; };
34+
539D9AFE2507F68400B5765A /* Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 539D9AFD2507F68400B5765A /* Constants.swift */; };
35+
539D9AFF2507F69400B5765A /* Constants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 539D9AFD2507F68400B5765A /* Constants.swift */; };
36+
539D9B002507F69B00B5765A /* PusherLogger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 539D9AFB2507F67300B5765A /* PusherLogger.swift */; };
3337
736E53F5242A378B0052CC1B /* String+Extensions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 736E53F3242A35D90052CC1B /* String+Extensions.swift */; };
3438
736E53F7242A45AC0052CC1B /* XCTest+Assertions.swift in Sources */ = {isa = PBXBuildFile; fileRef = 736E53F6242A45AC0052CC1B /* XCTest+Assertions.swift */; };
3539
73D8A1E72435E5F3001FDE05 /* PusherDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = 33BA541F1D9035BD00CD853B /* PusherDelegate.swift */; };
@@ -135,6 +139,8 @@
135139
33BB99661D21226C00B25C2A /* PusherTopLevelAPITests.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PusherTopLevelAPITests.swift; sourceTree = "<group>"; };
136140
33BB99671D21226C00B25C2A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = ../Tests/Info.plist; sourceTree = "<group>"; };
137141
33C1FD6E1D81BFC300921AD7 /* ObjectiveC.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ObjectiveC.swift; sourceTree = "<group>"; };
142+
539D9AFB2507F67300B5765A /* PusherLogger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = PusherLogger.swift; sourceTree = "<group>"; };
143+
539D9AFD2507F68400B5765A /* Constants.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Constants.swift; sourceTree = "<group>"; };
138144
736E53F3242A35D90052CC1B /* String+Extensions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "String+Extensions.swift"; sourceTree = "<group>"; };
139145
736E53F6242A45AC0052CC1B /* XCTest+Assertions.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "XCTest+Assertions.swift"; sourceTree = "<group>"; };
140146
73D8A1FE2435E5F3001FDE05 /* PusherSwiftWithEncryption.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = PusherSwiftWithEncryption.framework; sourceTree = BUILT_PRODUCTS_DIR; };
@@ -264,6 +270,7 @@
264270
5333ACFA24F8036B006E8DF0 /* Models */ = {
265271
isa = PBXGroup;
266272
children = (
273+
539D9AFD2507F68400B5765A /* Constants.swift */,
267274
3384C1B81CAECD9C00F10796 /* PusherChannel.swift */,
268275
3389F5711CAEDDF300563F49 /* PusherChannels.swift */,
269276
3389F5791CAEDEC800563F49 /* PusherClientOptions.swift */,
@@ -281,6 +288,7 @@
281288
E2F40FA423ED782B00985C40 /* PusherCrypto.swift */,
282289
E26B8605244A079E00735172 /* PusherEncryptionHelpers.swift */,
283290
E2B21EFE243F5B1E0049A35B /* PusherEventFactory.swift */,
291+
539D9AFB2507F67300B5765A /* PusherLogger.swift */,
284292
E2CFE43022D79CA7004187C3 /* PusherParser.swift */,
285293
);
286294
path = Helpers;
@@ -733,6 +741,7 @@
733741
buildActionMask = 2147483647;
734742
files = (
735743
E26B8606244A079E00735172 /* PusherEncryptionHelpers.swift in Sources */,
744+
539D9AFE2507F68400B5765A /* Constants.swift in Sources */,
736745
E2B21F0A243F5BB50049A35B /* PusherConnection.swift in Sources */,
737746
33BA54201D9035BD00CD853B /* PusherDelegate.swift in Sources */,
738747
E2498293231E612700CFBBD6 /* PusherError.swift in Sources */,
@@ -747,6 +756,7 @@
747756
E2B21F01243F5B1E0049A35B /* PusherEventFactory.swift in Sources */,
748757
3389F57A1CAEDEC800563F49 /* PusherClientOptions.swift in Sources */,
749758
E2B21F07243F5B860049A35B /* PusherEvent.swift in Sources */,
759+
539D9AFC2507F67300B5765A /* PusherLogger.swift in Sources */,
750760
E2B21EFF243F5B1E0049A35B /* PusherEventQueue.swift in Sources */,
751761
3389F56E1CAEDDD800563F49 /* PusherPresenceChannel.swift in Sources */,
752762
33C1FD6F1D81BFC300921AD7 /* ObjectiveC.swift in Sources */,
@@ -790,11 +800,13 @@
790800
73D8A1E82435E5F3001FDE05 /* PusherError.swift in Sources */,
791801
73D8A2292435F329001FDE05 /* PusherDecryptor.swift in Sources */,
792802
73D8A1EB2435E5F3001FDE05 /* PusherCrypto.swift in Sources */,
803+
539D9B002507F69B00B5765A /* PusherLogger.swift in Sources */,
793804
E2B21F0E243F5DC10049A35B /* PusherWebsocketDelegate.swift in Sources */,
794805
73D8A1EC2435E5F3001FDE05 /* PusherChannel.swift in Sources */,
795806
73D8A1ED2435E5F3001FDE05 /* Authorizer.swift in Sources */,
796807
73D8A1EE2435E5F3001FDE05 /* PusherChannels.swift in Sources */,
797808
73D8A1EF2435E5F3001FDE05 /* PusherParser.swift in Sources */,
809+
539D9AFF2507F69400B5765A /* Constants.swift in Sources */,
798810
73D8A1F02435E5F3001FDE05 /* PusherGlobalChannel.swift in Sources */,
799811
E2B21F02243F5B1E0049A35B /* PusherEventFactory.swift in Sources */,
800812
73D8A1F12435E5F3001FDE05 /* PusherClientOptions.swift in Sources */,

Sources/Extensions/PusherWebsocketDelegate.swift

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,18 @@ extension PusherConnection: WebSocketDelegate {
1010
- parameter text: The message received over the websocket
1111
*/
1212
public func websocketDidReceiveMessage(socket ws: WebSocketClient, text: String) {
13-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] websocketDidReceiveMessage \(text)")
13+
self.delegate?.debugLog?(message: PusherLogger.debug(for: .receivedMessage, context: text))
1414

1515
guard let payload = PusherParser.getPusherEventJSON(from: text),
16-
let event = payload["event"] as? String
16+
let event = payload[Constants.JSONKeys.event] as? String
1717
else {
18-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Unable to handle incoming Websocket message \(text)")
18+
self.delegate?.debugLog?(message: PusherLogger.debug(for: .unableToHandleIncomingMessage, context: text))
1919
return
2020
}
2121

22-
if event == "pusher:error" {
22+
if event == Constants.Events.Pusher.error {
2323
guard let error = PusherError(jsonObject: payload) else {
24-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Unable to handle incoming error \(text)")
24+
self.delegate?.debugLog?(message: PusherLogger.debug(for: .unableToHandleIncomingError, context: text))
2525
return
2626
}
2727
self.handleError(error: error)
@@ -51,16 +51,17 @@ extension PusherConnection: WebSocketDelegate {
5151
updateConnectionState(to: .disconnected)
5252

5353
guard !intentionalDisconnect else {
54-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Deliberate disconnection - skipping reconnect attempts")
54+
self.delegate?.debugLog?(message: PusherLogger.debug(for: .intentionalDisconnection))
5555
return
5656
}
5757

5858
// Handle error (if any)
5959

6060
if let error = error {
61-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Websocket is disconnected. Error (code: \((error as NSError).code)): \(error.localizedDescription)")
61+
self.delegate?.debugLog?(message: PusherLogger.debug(for: .disconnectionWithError,
62+
context: "Error (code: \((error as NSError).code)): \(error.localizedDescription)"))
6263
} else {
63-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Websocket is disconnected but no error received")
64+
self.delegate?.debugLog?(message: PusherLogger.debug(for: .disconnectionWithoutError))
6465
}
6566

6667
// Attempt reconnect if possible
@@ -70,12 +71,12 @@ extension PusherConnection: WebSocketDelegate {
7071
}
7172

7273
guard reconnectAttemptsMax == nil || reconnectAttempts < reconnectAttemptsMax! else {
73-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Max reconnect attempts reached")
74+
self.delegate?.debugLog?(message: PusherLogger.debug(for: .maxReconnectAttemptsLimitReached))
7475
return
7576
}
7677

7778
if let reachability = self.reachability, reachability.connection == .unavailable {
78-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Network unreachable so reconnect likely to fail")
79+
self.delegate?.debugLog?(message: PusherLogger.debug(for: .reconnectionFailureLikely))
7980
}
8081

8182
attemptReconnect()
@@ -103,9 +104,13 @@ extension PusherConnection: WebSocketDelegate {
103104
: reconnectInterval
104105

105106
if reconnectAttemptsMax != nil {
106-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Waiting \(timeInterval) seconds before attempting to reconnect (attempt \(reconnectAttempts + 1) of \(reconnectAttemptsMax!))")
107+
let message = PusherLogger.debug(for: .attemptReconnectionAfterWaiting,
108+
context: "\(timeInterval) seconds (attempt \(reconnectAttempts + 1) of \(reconnectAttemptsMax!))")
109+
self.delegate?.debugLog?(message: message)
107110
} else {
108-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Waiting \(timeInterval) seconds before attempting to reconnect (attempt \(reconnectAttempts + 1))")
111+
let message = PusherLogger.debug(for: .attemptReconnectionAfterWaiting,
112+
context: "\(timeInterval) seconds (attempt \(reconnectAttempts + 1))")
113+
self.delegate?.debugLog?(message: message)
109114
}
110115

111116
reconnectTimer = Timer.scheduledTimer(
@@ -133,7 +138,7 @@ extension PusherConnection: WebSocketDelegate {
133138
extension PusherConnection: WebSocketPongDelegate {
134139

135140
public func websocketDidReceivePong(socket: WebSocketClient, data: Data?) {
136-
self.delegate?.debugLog?(message: "[PUSHER DEBUG] Websocket received pong")
141+
self.delegate?.debugLog?(message: PusherLogger.debug(for: .pongReceived))
137142
resetActivityTimeoutTimer()
138143
}
139144

Sources/Helpers/PusherEncryptionHelpers.swift

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,11 @@ struct PusherEncryptionHelpers {
77
}
88

99
public static func isEncryptedChannel(channelName: String?) -> Bool {
10-
return channelName?.starts(with: "private-encrypted-") ?? false
10+
return channelName?.starts(with: "\(Constants.ChannelTypes.privateEncrypted)-") ?? false
1111
}
1212

1313
public static func isPusherSystemEvent(eventName: String) -> Bool {
14-
return eventName.starts(with: "pusher:") || eventName.starts(with: "pusher_internal:")
14+
return eventName.starts(with: "\(Constants.EventTypes.pusher):")
15+
|| eventName.starts(with: "\(Constants.EventTypes.pusherInternal):")
1516
}
1617
}

Sources/Helpers/PusherEventFactory.swift

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -14,16 +14,15 @@ struct PusherConcreteEventFactory: PusherEventFactory {
1414

1515
func makeEvent(fromJSON json: PusherEventPayload,
1616
withDecryptionKey decryptionKey: String? = nil) throws -> PusherEvent {
17-
guard let eventName = json["event"] as? String else {
17+
guard let eventName = json[Constants.JSONKeys.event] as? String else {
1818
throw PusherEventError.invalidFormat
1919
}
2020

21-
let channelName = json["channel"] as? String
21+
let channelName = json[Constants.JSONKeys.channel] as? String
2222
let data = try self.data(fromJSON: json,
2323
eventName: eventName,
24-
channelName: channelName,
25-
decryptionKey: decryptionKey)
26-
let userId = json["user_id"] as? String
24+
channelName: channelName, decryptionKey: decryptionKey)
25+
let userId = json[Constants.JSONKeys.userId] as? String
2726

2827
return PusherEvent(eventName: eventName, channelName: channelName, data: data, userId: userId, raw: json)
2928
}
@@ -34,7 +33,7 @@ struct PusherConcreteEventFactory: PusherEventFactory {
3433
eventName: String,
3534
channelName: String?,
3635
decryptionKey: String?) throws -> String? {
37-
let data = json["data"] as? String
36+
let data = json[Constants.JSONKeys.data] as? String
3837

3938
if PusherEncryptionHelpers.shouldDecryptMessage(eventName: eventName, channelName: channelName) {
4039
return try PusherDecryptor.decrypt(data: data, decryptionKey: decryptionKey)

Sources/Helpers/PusherLogger.swift

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
import Foundation
2+
3+
/// Used for logging events for informational purposes
4+
internal class PusherLogger {
5+
6+
// MARK: - Enum definitions
7+
8+
internal enum LoggingEvent: String {
9+
10+
// Channels
11+
12+
// swiftlint:disable:next identifier_name
13+
case presenceChannelSubscriptionAttemptWithoutChannelData =
14+
"Attempting to subscribe to presence channel but no channelData value provided"
15+
case subscriptionSucceededNoDataInPayload = "Subscription succeeded event received without data key in payload"
16+
17+
// Events
18+
19+
case clientEventSent = "sendClientEvent"
20+
case eventSent = "sendEvent"
21+
case skippedEventAfterDecryptionFailure = "Skipping event that failed to decrypt on channel"
22+
23+
// Network
24+
25+
case networkReachable = "Network reachable"
26+
case networkUnreachable = "Network unreachable"
27+
28+
// Websockets
29+
30+
// swiftlint:disable:next identifier_name
31+
case attemptReconnectionAfterReachabilityChange =
32+
"Connection state is 'connected' but received network reachability change so going to call attemptReconnect"
33+
case attemptReconnectionAfterWaiting = "Attempting to reconnect after waiting"
34+
case connectionEstablished = "Socket established with socket ID:"
35+
case disconnectionWithError = "Websocket is disconnected."
36+
case disconnectionWithoutError = "Websocket is disconnected but no error received"
37+
case intentionalDisconnection = "Deliberate disconnection - skipping reconnect attempts"
38+
case maxReconnectAttemptsLimitReached = "Max reconnect attempts reached"
39+
case reconnectionFailureLikely = "Network unreachable so reconnect likely to fail"
40+
case pingSent = "Ping sent"
41+
case pongReceived = "Websocket received pong"
42+
case receivedMessage = "websocketDidReceiveMessage"
43+
case unableToHandleIncomingError = "Unable to handle incoming error"
44+
case unableToHandleIncomingMessage = "Unable to handle incoming Websocket message"
45+
}
46+
47+
internal enum LoggingLevel: String {
48+
case debug = "[PUSHER DEBUG]"
49+
case info = "[PUSHER INFO]"
50+
case warning = "[PUSHER WARNING]"
51+
case error = "[PUSHER ERROR]"
52+
}
53+
54+
// MARK: - Event logging
55+
56+
/// A debug message relating to a particular event of interest.
57+
/// - Parameters:
58+
/// - event: A particular `LoggingEvent` of interest.
59+
/// - context: Additional context for the message.
60+
/// - Returns: A `String` with information to log concerning the event.
61+
internal static func debug(for event: LoggingEvent,
62+
context: CustomStringConvertible? = nil) -> String {
63+
return message(for: event, level: .debug, context: context)
64+
}
65+
66+
/// An informational message relating to a particular event of interest.
67+
/// - Parameters:
68+
/// - event: A particular `LoggingEvent` of interest.
69+
/// - context: Additional context for the message.
70+
/// - Returns: A `String` with information to log concerning the event.
71+
internal static func info(for event: LoggingEvent,
72+
context: CustomStringConvertible? = nil) -> String {
73+
return message(for: event, level: .info, context: context)
74+
}
75+
76+
/// A warning message relating to a particular event of interest.
77+
/// - Parameters:
78+
/// - event: A particular `LoggingEvent` of interest.
79+
/// - context: Additional context for the message.
80+
/// - Returns: A `String` with information to log concerning the event.
81+
internal static func warning(for event: LoggingEvent,
82+
context: CustomStringConvertible? = nil) -> String {
83+
return message(for: event, level: .warning, context: context)
84+
}
85+
86+
/// An error message relating to a particular event of interest.
87+
/// - Parameters:
88+
/// - event: A particular `LoggingEvent` of interest.
89+
/// - context: Additional context for the message.
90+
/// - Returns: A `String` with information to log concerning the event.
91+
internal static func error(for event: LoggingEvent,
92+
context: CustomStringConvertible? = nil) -> String {
93+
return message(for: event, level: .error, context: context)
94+
}
95+
96+
// MARK: - Private methods
97+
98+
/// An informational message relating to a particular event of interest.
99+
/// - Parameter event: A particular `LoggingEvent` of interest.
100+
/// - Parameter level: The `LoggingLevel` to set for the message.
101+
/// - Parameter context: Additional context for the message.
102+
/// - Returns: A `String` with information to log concerning the event.
103+
private static func message(for event: LoggingEvent,
104+
level: LoggingLevel,
105+
context: CustomStringConvertible? = nil) -> String {
106+
var message = "\(level.rawValue) \(event.rawValue)"
107+
if let context = context {
108+
message += " \(context)"
109+
}
110+
111+
return message
112+
}
113+
}

0 commit comments

Comments
 (0)