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

Default Header Locale Formatter #520

Merged
merged 3 commits into from
Jan 22, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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
12 changes: 12 additions & 0 deletions AEPCore.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,9 @@
3FF829692509937100483C74 /* SignalIntegrationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3FF829682509937100483C74 /* SignalIntegrationTests.swift */; };
3FF8296C2509942300483C74 /* rules_signal.zip in Resources */ = {isa = PBXBuildFile; fileRef = 3FF8296A2509942200483C74 /* rules_signal.zip */; };
3FF8296D2509942300483C74 /* rules_signal.json in Resources */ = {isa = PBXBuildFile; fileRef = 3FF8296B2509942300483C74 /* rules_signal.json */; };
786C000525B8EE2100F26D34 /* DefaultHeadersFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 786C000425B8EE2100F26D34 /* DefaultHeadersFormatter.swift */; };
786C001525B8EE6200F26D34 /* HttpConnectionConstants.swift in Sources */ = {isa = PBXBuildFile; fileRef = 786C001425B8EE6200F26D34 /* HttpConnectionConstants.swift */; };
786C004825B8F43E00F26D34 /* DefaultHeadersFormatterTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 786C004725B8F43E00F26D34 /* DefaultHeadersFormatterTests.swift */; };
787505E025A67BE200E5203E /* TestZipSlip.zip in Resources */ = {isa = PBXBuildFile; fileRef = 787505DF25A67BE200E5203E /* TestZipSlip.zip */; };
78AA4EBA2502DF2200205AE9 /* ZipArchiveTest.swift in Sources */ = {isa = PBXBuildFile; fileRef = 78AA4EB92502DF2200205AE9 /* ZipArchiveTest.swift */; };
78AA4EBC2502E42400205AE9 /* TestCorruptFile.zip in Resources */ = {isa = PBXBuildFile; fileRef = 78AA4EBB2502E42400205AE9 /* TestCorruptFile.zip */; };
Expand Down Expand Up @@ -848,6 +851,9 @@
3FF8296B2509942300483C74 /* rules_signal.json */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.json; path = rules_signal.json; sourceTree = "<group>"; };
42E2B003910D73C12B88CC06 /* Pods_AEPIdentityTests.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_AEPIdentityTests.framework; sourceTree = BUILT_PRODUCTS_DIR; };
4E248A93FA9CBDD50605A356 /* Pods-AEPIntegrationTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-AEPIntegrationTests.release.xcconfig"; path = "Target Support Files/Pods-AEPIntegrationTests/Pods-AEPIntegrationTests.release.xcconfig"; sourceTree = "<group>"; };
786C000425B8EE2100F26D34 /* DefaultHeadersFormatter.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultHeadersFormatter.swift; sourceTree = "<group>"; };
786C001425B8EE6200F26D34 /* HttpConnectionConstants.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = HttpConnectionConstants.swift; sourceTree = "<group>"; };
786C004725B8F43E00F26D34 /* DefaultHeadersFormatterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DefaultHeadersFormatterTests.swift; sourceTree = "<group>"; };
787505DF25A67BE200E5203E /* TestZipSlip.zip */ = {isa = PBXFileReference; lastKnownFileType = archive.zip; path = TestZipSlip.zip; sourceTree = "<group>"; };
78AA4EB92502DF2200205AE9 /* ZipArchiveTest.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ZipArchiveTest.swift; sourceTree = "<group>"; };
78AA4EBB2502E42400205AE9 /* TestCorruptFile.zip */ = {isa = PBXFileReference; lastKnownFileType = archive.zip; path = TestCorruptFile.zip; sourceTree = "<group>"; };
Expand Down Expand Up @@ -1349,6 +1355,8 @@
3F0397AB24BE5FF30019F095 /* NetworkService.swift */,
3F0397AC24BE5FF30019F095 /* NetworkServiceConstants.swift */,
3F0397AE24BE5FF30019F095 /* Networking.swift */,
786C000425B8EE2100F26D34 /* DefaultHeadersFormatter.swift */,
786C001425B8EE6200F26D34 /* HttpConnectionConstants.swift */,
);
path = network;
sourceTree = "<group>";
Expand Down Expand Up @@ -1432,6 +1440,7 @@
78AA4EBF2509731A00205AE9 /* FileManager+ZipTests.swift */,
3F03980524BE61520019F095 /* URLServiceTest.swift */,
3F03980724BE61520019F095 /* UserDefaultsNamedCollectionTest.swift */,
786C004725B8F43E00F26D34 /* DefaultHeadersFormatterTests.swift */,
);
path = services;
sourceTree = "<group>";
Expand Down Expand Up @@ -2816,6 +2825,7 @@
buildActionMask = 2147483647;
files = (
3F0397CE24BE5FF30019F095 /* LoggingService.swift in Sources */,
786C000525B8EE2100F26D34 /* DefaultHeadersFormatter.swift in Sources */,
3F0397C924BE5FF30019F095 /* Logging.swift in Sources */,
3F0397D224BE5FF30019F095 /* NetworkRequest.swift in Sources */,
3F0397F224BE60910019F095 /* HitProcessing.swift in Sources */,
Expand All @@ -2835,6 +2845,7 @@
3F0397FD24BE60910019F095 /* ThreadSafeDictionary.swift in Sources */,
3F0397F824BE60910019F095 /* ZipEntry.swift in Sources */,
3F0397F424BE60910019F095 /* HitQueuing.swift in Sources */,
786C001525B8EE6200F26D34 /* HttpConnectionConstants.swift in Sources */,
3F0397DB24BE5FF30019F095 /* NamedCollectionDataStore.swift in Sources */,
3F0397C524BE5FF30019F095 /* CacheEntry.swift in Sources */,
3F0397F524BE60910019F095 /* AtomicCounter.swift in Sources */,
Expand Down Expand Up @@ -2883,6 +2894,7 @@
3F03981724BE61520019F095 /* DataQueueService+Testable.swift in Sources */,
3F03981824BE61520019F095 /* DataQueueServiceTests.swift in Sources */,
3F03981B24BE61520019F095 /* UserDefaultsNamedCollectionTest.swift in Sources */,
786C004825B8F43E00F26D34 /* DefaultHeadersFormatterTests.swift in Sources */,
78AA4EC02509731B00205AE9 /* FileManager+ZipTests.swift in Sources */,
3F03981C24BE61520019F095 /* SQLiteWrapperTests.swift in Sources */,
3F03982524BE61520019F095 /* ThreadSafeArrayTests.swift in Sources */,
Expand Down
Binary file modified AEPIntegrationTests/resources/rules_lifecycle.zip
Binary file not shown.
Binary file modified AEPIntegrationTests/resources/rules_pii.zip
Binary file not shown.
Binary file modified AEPIntegrationTests/resources/rules_signal.zip
Binary file not shown.
62 changes: 62 additions & 0 deletions AEPServices/Sources/network/DefaultHeadersFormatter.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
/*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

import Foundation

///
/// Helper class used to format the default http headers
///
public struct DefaultHeadersFormatter {

typealias httpHeaderConstants = HttpConnectionConstants.Header
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we still need this line?


///
/// Gets the formatted locale
/// - Parameter unformattedLocale: The unformatted locale as a string
/// - Returns: The formatted locale as a string or nil if not able to format it.
///
public static func getFormattedLocale(unformattedLocale: String) -> String {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

_ unformattedLocale

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Decided to change the name as well. Lmk what you think.

// "^" // beginning of line
// "([a-zA-Z]{2,3})" // language (required) (match group 1)
// "(?:(?:-|_)[a-zA-Z]{3})?" // extlang (optional)
// "(?:(?:-|_)[a-zA-Z]{4})?" // script (optional)
// "(?:(?:-|_)([a-zA-Z]{2}|[0-9]{3}))?" // region (optional) (match group 2)
// "(?:(?:\\.|-|_).*)?" // variant, extension, private, or anything else
// "$"
let pattern = #"^([a-zA-Z]{2,3})(?:(?:-|_)[a-zA-Z]{3})?(?:(?:-|_)[a-zA-Z]{4})?(?:(?:-|_)([a-zA-Z]{2}|[0-9]{3}))?(?:(?:\.|-|_).*)?$"#

guard let regex = try? NSRegularExpression(pattern: pattern, options: []) else {
return unformattedLocale
}

let localeRange = NSRange(unformattedLocale.startIndex ..< unformattedLocale.endIndex, in: unformattedLocale)
var language: String?
var region: String?
regex.enumerateMatches(in: unformattedLocale, options: [], range: localeRange) { match, _, _ in
guard let match = match else { return }
guard let languageCaptureRange = Range(match.range(at: 1), in: unformattedLocale) else { return }
language = String(unformattedLocale[languageCaptureRange])
guard let regionCaptureRange = Range(match.range(at: 2), in: unformattedLocale) else { return }
region = String(unformattedLocale[regionCaptureRange])
}

if let language = language {
if let region = region {
return language + "-" + region
}
return language
}

// Default return if no language or region is found
return "en-US"
}
}
33 changes: 33 additions & 0 deletions AEPServices/Sources/network/HttpConnectionConstants.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
/*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

import Foundation

public enum HttpConnectionConstants {
public enum ResponseCodes {
static let HTTP_OK = 200
static let HTTP_NOT_FOUND = 404
static let HTTP_CLIENT_TIMEOUT = 408
static let HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416
static let HTTP_GATEWAY_TIMEOUT = 504
static let HTTP_UNAVAILABLE = 503
}

public enum Header {
static let HTTP_HEADER_KEY_CONTENT_TYPE = "Content-Type"
static let HTTP_HEADER_KEY_ACCEPT_LANGUAGE = "Accept-Language"
static let HTTP_HEADER_KEY_ACCEPT = "Accept"
static let HTTP_HEADER_CONTENT_TYPE_JSON_APPLICATION = "application/json"
static let HTTP_HEADER_CONTENT_TYPE_WWW_FORM_URLENCODED = "application/x-www-form-urlencoded"
static let HTTP_HEADER_ACCEPT_TEXT_HTML = "text/html"
}
}
4 changes: 2 additions & 2 deletions AEPServices/Sources/network/NetworkRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ import Foundation

/// NetworkRequest struct to be used by the NetworkService and the HttpConnectionPerformer when initiating network calls
@objc(AEPNetworkRequest) public class NetworkRequest: NSObject {

private static let REQUEST_HEADER_KEY_USER_AGENT = "User-Agent"
private static let REQUEST_HEADER_KEY_LANGUAGE = "Accept-Language"

public let url: URL
public let httpMethod: HttpMethod
Expand All @@ -40,7 +40,7 @@ import Foundation

let systemInfoService = ServiceProvider.shared.systemInfoService
let defaultHeaders = [NetworkRequest.REQUEST_HEADER_KEY_USER_AGENT: systemInfoService.getDefaultUserAgent(),
NetworkRequest.REQUEST_HEADER_KEY_LANGUAGE: systemInfoService.getActiveLocaleName()]
HttpConnectionConstants.Header.HTTP_HEADER_KEY_ACCEPT_LANGUAGE: DefaultHeadersFormatter.getFormattedLocale(unformattedLocale: systemInfoService.getActiveLocaleName())]
self.httpHeaders = defaultHeaders.merging(httpHeaders) { _, new in new } // add in default headers and apply `httpHeaders` on top

self.connectTimeout = connectTimeout
Expand Down
63 changes: 63 additions & 0 deletions AEPServices/Tests/services/DefaultHeadersFormatterTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
Copyright 2021 Adobe. All rights reserved.
This file is licensed to you under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License. You may obtain a copy
of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under
the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/

import XCTest

@testable import AEPServices

class DefaultHeadersFormatterTest: XCTestCase {
private var localeStringArr: [[String: String]] = {
[
["en-US": "C"],
["en-US": "*"],
["en-US": "POSIX"],
["en-GB": "en_GB"],
["en-US": "en_US.UTF-8"],
["it-CH": "it_CH.ISO8859-1"],
["it-CH": "it_CH.ISO8859-15"],
["ja-JP": "ja_JP.SJIS"],
["ru-RU": "ru_RU.KOI8-R"],
["zh-HK": "zh_HK.Big5HKSCS"],
["de-DE": "de-DE_phoneb"],
["en": "en"],
["ast": "ast"],
["zh": "zh-Hant"],
["zh-HK": "zh_Hant_HK"],
["zh": "zh-yue"],
["zh-HK": "zh_yue_HK"],
["zh-HK": "zh-yue-Hant-HK"],
["es-005": "es_005"],
["de-DE": "de_DE_u_co_phonebk"],
["sl": "sl_nedis"],
["es-ES": "es-ES-i-klingon"]
]
}()

func testDifferentFormattedLocales() {
for dict in localeStringArr {
guard let (k, v) = dict.first else {
XCTFail()
return
}

let formattedLocale = DefaultHeadersFormatter.getFormattedLocale(unformattedLocale: v)

XCTAssertEqual(k, formattedLocale)
}
}

func testEmptyLocale() {
let formattedLocale = DefaultHeadersFormatter.getFormattedLocale(unformattedLocale: "")
XCTAssertEqual("en-US", formattedLocale)
}
}

3 changes: 2 additions & 1 deletion AEPServices/Tests/services/NetworkServiceTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ class NetworkServiceTests: XCTestCase {

func testConnectAsync_initiatesConnection_whenValidNetworkRequest() {
let mockUserAgent = "mock-user-agent"
let mockLocaleName = "mock-locale-name"
// The formatted locale name default
let mockLocaleName = "en-US"
systemInfoService?.defaultUserAgent = mockUserAgent
systemInfoService?.activeLocaleName = mockLocaleName
let expectation = XCTestExpectation(description: "Completion handler called")
Expand Down
2 changes: 1 addition & 1 deletion Podfile.lock
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,4 @@ SPEC CHECKSUMS:

PODFILE CHECKSUM: 2f62254a30b50ed814c4364b36843ce9076bb9be

COCOAPODS: 1.9.3
COCOAPODS: 1.10.1