Skip to content

Commit e78f60e

Browse files
author
Pushkar Kulkarni
committed
Initial implementation of HTTPCookieStorage
1 parent 237eed2 commit e78f60e

File tree

3 files changed

+211
-11
lines changed

3 files changed

+211
-11
lines changed

Foundation/NSHTTPCookieStorage.swift

Lines changed: 140 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
// See http://swift.org/LICENSE.txt for license information
77
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
88
//
9-
9+
import Dispatch
1010

1111
/*!
1212
@enum NSHTTPCookieAcceptPolicy
@@ -35,11 +35,36 @@ extension HTTPCookie {
3535
generate cookie-related HTTP header fields.
3636
*/
3737
open class HTTPCookieStorage: NSObject {
38-
39-
public override init() { NSUnimplemented() }
40-
38+
39+
private static var sharedStorage: HTTPCookieStorage?
40+
41+
private let cookieFilePath: String = NSHomeDirectory() + "/.cookies"
42+
private let workQueue: DispatchQueue = DispatchQueue(label: "HTTPCookieStorage.workqueue")
43+
var allCookies: [String: HTTPCookie]
44+
45+
public override init() {
46+
allCookies = [:]
47+
cookieAcceptPolicy = .always
48+
super.init()
49+
loadPersistedCookies()
50+
}
51+
52+
private func loadPersistedCookies() {
53+
guard let cookies = NSMutableDictionary(contentsOfFile: cookieFilePath) else { return }
54+
var cookies0 = _SwiftValue.fetch(cookies) as? [String: [String: Any]] ?? [:]
55+
for key in cookies0.keys {
56+
if let cookie = createCookie(cookies0[key]!) {
57+
allCookies[key] = cookie
58+
}
59+
}
60+
}
61+
4162
open var cookies: [HTTPCookie]? {
42-
NSUnimplemented()
63+
var theCookies: [HTTPCookie]?
64+
workQueue.sync {
65+
theCookies = Array(self.allCookies.values)
66+
}
67+
return theCookies
4368
}
4469

4570
/*!
@@ -49,7 +74,14 @@ open class HTTPCookieStorage: NSObject {
4974
@discussion Starting in OS X 10.11, each app has its own sharedHTTPCookieStorage singleton,
5075
which will not be shared with other applications.
5176
*/
52-
class var shared: HTTPCookieStorage { get { NSUnimplemented() } }
77+
open class var shared: HTTPCookieStorage {
78+
get {
79+
if sharedStorage == nil {
80+
sharedStorage = HTTPCookieStorage()
81+
}
82+
return sharedStorage!
83+
}
84+
}
5385

5486
/*!
5587
@method sharedCookieStorageForGroupContainerIdentifier:
@@ -70,19 +102,80 @@ open class HTTPCookieStorage: NSObject {
70102
@discussion The cookie will override an existing cookie with the
71103
same name, domain and path, if any.
72104
*/
73-
open func setCookie(_ cookie: HTTPCookie) { NSUnimplemented() }
105+
open func setCookie(_ cookie: HTTPCookie) {
106+
workQueue.sync {
107+
if cookieAcceptPolicy == .never { return }
108+
109+
//add or replace
110+
let key = cookie.domain + cookie.path + cookie.name
111+
if let _ = allCookies.index(forKey: key) {
112+
allCookies.updateValue(cookie, forKey: key)
113+
} else {
114+
allCookies[key] = cookie
115+
}
116+
117+
//remove stale cookies, these may include the one we just added
118+
let expired = allCookies.filter { (_, value) in value.expiresDate != nil && value.expiresDate!.timeIntervalSinceNow < 0}
119+
for (key,_) in expired {
120+
self.allCookies.removeValue(forKey: key)
121+
}
122+
123+
updatePersistentStore()
124+
}
125+
}
74126

127+
private func createCookie(_ properties: [String: Any]) -> HTTPCookie? {
128+
var cookieProperties: [HTTPCookiePropertyKey: Any] = [:]
129+
for key in properties.keys {
130+
if key == "Expires" {
131+
let value = properties[key] as! NSNumber
132+
cookieProperties[HTTPCookiePropertyKey(rawValue: key)] = Date(timeIntervalSince1970: value.doubleValue)
133+
} else {
134+
cookieProperties[HTTPCookiePropertyKey(rawValue: key)] = properties[key]
135+
}
136+
}
137+
return HTTPCookie(properties: cookieProperties)
138+
}
139+
140+
private func updatePersistentStore() {
141+
//persist cookies
142+
var persistDictionary: [String : [String : Any]] = [:]
143+
let persistable = allCookies.filter { (_, value) in value.expiresDate != nil &&
144+
value.isSessionOnly == false &&
145+
value.expiresDate!.timeIntervalSinceNow > 0
146+
}
147+
148+
for (key,cookie) in persistable {
149+
persistDictionary[key] = cookie.simpleDictionary()
150+
}
151+
152+
let nsdict = _SwiftValue.store(persistDictionary) as! NSDictionary
153+
_ = nsdict.write(toFile: cookieFilePath, atomically: true)
154+
}
155+
75156
/*!
76157
@method deleteCookie:
77158
@abstract Delete the specified cookie
78159
*/
79-
open func deleteCookie(_ cookie: HTTPCookie) { NSUnimplemented() }
160+
open func deleteCookie(_ cookie: HTTPCookie) {
161+
workQueue.sync {
162+
let key = cookie.domain + cookie.path + cookie.name
163+
self.allCookies.removeValue(forKey: key)
164+
updatePersistentStore()
165+
}
166+
}
80167

81168
/*!
82169
@method removeCookiesSince:
83170
@abstract Delete all cookies from the cookie storage since the provided date.
84171
*/
85-
open func removeCookies(since date: Date) { NSUnimplemented() }
172+
open func removeCookies(since date: Date) {
173+
let cookiesSinceDate = allCookies.values.filter { $0.properties![.created] as! Double > date.timeIntervalSinceReferenceDate }
174+
for cookie in cookiesSinceDate {
175+
deleteCookie(cookie)
176+
}
177+
updatePersistentStore()
178+
}
86179

87180
/*!
88181
@method cookiesForURL:
@@ -94,7 +187,13 @@ open class HTTPCookieStorage: NSObject {
94187
<tt>+[NSCookie requestHeaderFieldsWithCookies:]</tt> to turn this array
95188
into a set of header fields to add to a request.
96189
*/
97-
open func cookies(for url: URL) -> [HTTPCookie]? { NSUnimplemented() }
190+
open func cookies(for url: URL) -> [HTTPCookie]? {
191+
var cookies: [HTTPCookie]?
192+
workQueue.sync {
193+
cookies = Array(allCookies.values.filter { url.host != nil && $0.domain + $0.path == url.host! + url.path })
194+
}
195+
return cookies
196+
}
98197

99198
/*!
100199
@method setCookies:forURL:mainDocumentURL:
@@ -113,7 +212,23 @@ open class HTTPCookieStorage: NSObject {
113212
dictionary and then use this method to store the resulting cookies
114213
in accordance with policy settings.
115214
*/
116-
open func setCookies(_ cookies: [HTTPCookie], for url: URL?, mainDocumentURL: URL?) { NSUnimplemented() }
215+
open func setCookies(_ cookies: [HTTPCookie], for url: URL?, mainDocumentURL: URL?) {
216+
workQueue.sync {
217+
guard cookieAcceptPolicy != .never else { return }
218+
guard let theUrl = url else { return }
219+
220+
var validCookies = [HTTPCookie]()
221+
if mainDocumentURL != nil && cookieAcceptPolicy == .onlyFromMainDocumentDomain {
222+
NSUnimplemented()
223+
} else {
224+
validCookies = cookies.filter { theUrl.host != nil && theUrl.host!.hasSuffix($0.domain) }
225+
}
226+
227+
for cookie in validCookies {
228+
setCookie(cookie)
229+
}
230+
}
231+
}
117232

118233
/*!
119234
@method cookieAcceptPolicy
@@ -129,6 +244,7 @@ open class HTTPCookieStorage: NSObject {
129244
@discussion proper sorting of cookies may require extensive string conversion, which can be avoided by allowing the system to perform the sorting. This API is to be preferred over the more generic -[NSHTTPCookieStorage cookies] API, if sorting is going to be performed.
130245
*/
131246
open func sortedCookies(using sortOrder: [SortDescriptor]) -> [HTTPCookie] { NSUnimplemented() }
247+
132248
}
133249

134250
/*!
@@ -137,3 +253,16 @@ open class HTTPCookieStorage: NSObject {
137253
*/
138254
public let NSHTTPCookieManagerCookiesChangedNotification: String = "" // NSUnimplemented
139255

256+
extension HTTPCookie {
257+
public func simpleDictionary() -> [String: Any] {
258+
var properties: [String: Any] = [:]
259+
properties["Name"] = _name
260+
properties["Path"] = _path
261+
properties["Value"] = _value
262+
properties["Secure"] = _secure
263+
properties["Version"] = _version
264+
properties["Expires"] = _expiresDate!.timeIntervalSince1970
265+
properties["Domain"] = _domain
266+
return properties
267+
}
268+
}
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
// This source file is part of the Swift.org open source project
2+
//
3+
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
4+
// Licensed under Apache License v2.0 with Runtime Library Exception
5+
//
6+
// See http://swift.org/LICENSE.txt for license information
7+
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
8+
//
9+
10+
#if DEPLOYMENT_RUNTIME_OBJC || os(Linux)
11+
import Foundation
12+
import XCTest
13+
#else
14+
import SwiftFoundation
15+
import SwiftXCTest
16+
#endif
17+
18+
class TestNSHTTPCookieStorage: XCTestCase {
19+
20+
static var allTests: [(String, (TestNSHTTPCookieStorage) -> () throws -> Void)] {
21+
return [
22+
("test_BasicStorageAndRetrieval", test_BasicStorageAndRetrieval),
23+
]
24+
}
25+
26+
func test_BasicStorageAndRetrieval() {
27+
let storage = HTTPCookieStorage.shared
28+
29+
let simpleCookie = HTTPCookie(properties: [
30+
.name: "TestCookie1",
31+
.value: "Test value @#$%^$&*99",
32+
.path: "/",
33+
.domain: "swift.org",
34+
.expires: Date(timeIntervalSince1970: 1475767775) //expired cookie
35+
])!
36+
37+
storage.setCookie(simpleCookie)
38+
XCTAssertEqual(storage.cookies!.count, 0)
39+
40+
let simpleCookie0 = HTTPCookie(properties: [ //no expiry date
41+
.name: "TestCookie1",
42+
.value: "Test @#$%^$&*99",
43+
.path: "/",
44+
.domain: "swift.org",
45+
])!
46+
47+
storage.setCookie(simpleCookie0)
48+
XCTAssertEqual(storage.cookies!.count, 1)
49+
50+
let simpleCookie1 = HTTPCookie(properties: [
51+
.name: "TestCookie1",
52+
.value: "Test @#$%^$&*99",
53+
.path: "/",
54+
.domain: "swift.org",
55+
])!
56+
57+
storage.setCookie(simpleCookie1)
58+
XCTAssertEqual(storage.cookies!.count, 1) //test for replacement
59+
60+
let simpleCookie2 = HTTPCookie(properties: [
61+
.name: "TestCookie1",
62+
.value: "Test @#$%^$&*99",
63+
.path: "/",
64+
.domain: "example.com",
65+
])!
66+
67+
storage.setCookie(simpleCookie2)
68+
XCTAssertEqual(storage.cookies!.count, 2)
69+
}
70+
}

TestFoundation/main.swift

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ XCTMain([
3737
testCase(TestNSFileManager.allTests),
3838
testCase(TestNSGeometry.allTests),
3939
testCase(TestNSHTTPCookie.allTests),
40+
testCase(TestNSHTTPCookieStorage.allTests),
4041
testCase(TestNSIndexPath.allTests),
4142
testCase(TestNSIndexSet.allTests),
4243
testCase(TestNSJSONSerialization.allTests),

0 commit comments

Comments
 (0)