Skip to content

Commit 87bdd3d

Browse files
author
Pushkar Kulkarni
committed
Initial implementation of HTTPCookieStorage
1 parent 9d603e2 commit 87bdd3d

File tree

4 files changed

+314
-14
lines changed

4 files changed

+314
-14
lines changed

Foundation.xcodeproj/project.pbxproj

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
/* Begin PBXBuildFile section */
1010
0383A1751D2E558A0052E5D1 /* TestNSStream.swift in Sources */ = {isa = PBXBuildFile; fileRef = 0383A1741D2E558A0052E5D1 /* TestNSStream.swift */; };
1111
1520469B1D8AEABE00D02E36 /* HTTPServer.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1520469A1D8AEABE00D02E36 /* HTTPServer.swift */; };
12+
159884921DCC877700E3314C /* TestNSHTTPCookieStorage.swift in Sources */ = {isa = PBXBuildFile; fileRef = 159884911DCC877700E3314C /* TestNSHTTPCookieStorage.swift */; };
1213
231503DB1D8AEE5D0061694D /* TestNSDecimal.swift in Sources */ = {isa = PBXBuildFile; fileRef = 231503DA1D8AEE5D0061694D /* TestNSDecimal.swift */; };
1314
294E3C1D1CC5E19300E4F44C /* TestNSAttributedString.swift in Sources */ = {isa = PBXBuildFile; fileRef = 294E3C1C1CC5E19300E4F44C /* TestNSAttributedString.swift */; };
1415
2EBE67A51C77BF0E006583D5 /* TestNSDateFormatter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 2EBE67A31C77BF05006583D5 /* TestNSDateFormatter.swift */; };
@@ -466,6 +467,7 @@
466467
/* Begin PBXFileReference section */
467468
0383A1741D2E558A0052E5D1 /* TestNSStream.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSStream.swift; sourceTree = "<group>"; };
468469
1520469A1D8AEABE00D02E36 /* HTTPServer.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = HTTPServer.swift; sourceTree = "<group>"; };
470+
159884911DCC877700E3314C /* TestNSHTTPCookieStorage.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = TestNSHTTPCookieStorage.swift; sourceTree = "<group>"; };
469471
22B9C1E01C165D7A00DECFF9 /* TestNSDate.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSDate.swift; sourceTree = "<group>"; };
470472
231503DA1D8AEE5D0061694D /* TestNSDecimal.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSDecimal.swift; sourceTree = "<group>"; };
471473
294E3C1C1CC5E19300E4F44C /* TestNSAttributedString.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TestNSAttributedString.swift; sourceTree = "<group>"; };
@@ -1338,6 +1340,7 @@
13381340
EA66F65A1BF1976100136161 /* Tests */ = {
13391341
isa = PBXGroup;
13401342
children = (
1343+
159884911DCC877700E3314C /* TestNSHTTPCookieStorage.swift */,
13411344
D4FE895A1D703D1100DA7986 /* TestURLRequest.swift */,
13421345
C93559281C12C49F009FD6A9 /* TestNSAffineTransform.swift */,
13431346
EA66F63C1BF1619600136161 /* TestNSArray.swift */,
@@ -2235,6 +2238,7 @@
22352238
isa = PBXSourcesBuildPhase;
22362239
buildActionMask = 2147483647;
22372240
files = (
2241+
159884921DCC877700E3314C /* TestNSHTTPCookieStorage.swift in Sources */,
22382242
5FE52C951D147D1C00F7D270 /* TestNSTextCheckingResult.swift in Sources */,
22392243
5B13B3451C582D4C00651CE2 /* TestNSString.swift in Sources */,
22402244
1520469B1D8AEABE00D02E36 /* HTTPServer.swift in Sources */,

Foundation/NSHTTPCookieStorage.swift

Lines changed: 162 additions & 14 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
@@ -18,7 +18,6 @@
1818
*/
1919
extension HTTPCookie {
2020
public enum AcceptPolicy : UInt {
21-
2221
case always
2322
case never
2423
case onlyFromMainDocumentDomain
@@ -35,11 +34,37 @@ extension HTTPCookie {
3534
generate cookie-related HTTP header fields.
3635
*/
3736
open class HTTPCookieStorage: NSObject {
38-
39-
public override init() { NSUnimplemented() }
40-
37+
38+
private static var sharedStorage: HTTPCookieStorage?
39+
private static var sharedCookieStorages: [String: HTTPCookieStorage] = [:] //for group storage containers
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:
@@ -62,28 +94,100 @@ open class HTTPCookieStorage: NSObject {
6294
shared among all applications and extensions with access to the same application group. Subsequent calls to this
6395
method with the same identifier will return the same cookie storage instance.
6496
*/
65-
class func sharedCookieStorage(forGroupContainerIdentifier identifier: String) -> HTTPCookieStorage { NSUnimplemented() }
97+
class func sharedCookieStorage(forGroupContainerIdentifier identifier: String) -> HTTPCookieStorage {
98+
guard let cookieStorage = sharedCookieStorages[identifier] else {
99+
let newCookieStorage = HTTPCookieStorage()
100+
sharedCookieStorages[identifier] = newCookieStorage
101+
return newCookieStorage
102+
}
103+
return cookieStorage
104+
}
105+
66106

67107
/*!
68108
@method setCookie:
69109
@abstract Set a cookie
70110
@discussion The cookie will override an existing cookie with the
71111
same name, domain and path, if any.
72112
*/
73-
open func setCookie(_ cookie: HTTPCookie) { NSUnimplemented() }
113+
open func setCookie(_ cookie: HTTPCookie) {
114+
workQueue.sync {
115+
if cookieAcceptPolicy == .never { return }
116+
117+
//add or replace
118+
let key = cookie.domain + cookie.path + cookie.name
119+
if let _ = allCookies.index(forKey: key) {
120+
allCookies.updateValue(cookie, forKey: key)
121+
} else {
122+
allCookies[key] = cookie
123+
}
124+
125+
//remove stale cookies, these may include the one we just added
126+
let expired = allCookies.filter { (_, value) in value.expiresDate != nil && value.expiresDate!.timeIntervalSinceNow < 0}
127+
for (key,_) in expired {
128+
self.allCookies.removeValue(forKey: key)
129+
}
130+
131+
updatePersistentStore()
132+
}
133+
}
74134

135+
private func createCookie(_ properties: [String: Any]) -> HTTPCookie? {
136+
var cookieProperties: [HTTPCookiePropertyKey: Any] = [:]
137+
for (key, value) in properties {
138+
if key == "Expires" {
139+
guard let timestamp = value as? NSNumber else { continue }
140+
cookieProperties[HTTPCookiePropertyKey(rawValue: key)] = Date(timeIntervalSince1970: timestamp.doubleValue)
141+
} else {
142+
cookieProperties[HTTPCookiePropertyKey(rawValue: key)] = properties[key]
143+
}
144+
}
145+
return HTTPCookie(properties: cookieProperties)
146+
}
147+
148+
private func updatePersistentStore() {
149+
//persist cookies
150+
var persistDictionary: [String : [String : Any]] = [:]
151+
let persistable = allCookies.filter { (_, value) in
152+
value.expiresDate != nil &&
153+
value.isSessionOnly == false &&
154+
value.expiresDate!.timeIntervalSinceNow > 0
155+
}
156+
157+
for (key,cookie) in persistable {
158+
persistDictionary[key] = cookie.persistableDictionary()
159+
}
160+
161+
let nsdict = _SwiftValue.store(persistDictionary) as! NSDictionary
162+
_ = nsdict.write(toFile: cookieFilePath, atomically: true)
163+
}
164+
75165
/*!
76166
@method deleteCookie:
77167
@abstract Delete the specified cookie
78168
*/
79-
open func deleteCookie(_ cookie: HTTPCookie) { NSUnimplemented() }
169+
open func deleteCookie(_ cookie: HTTPCookie) {
170+
let key = cookie.domain + cookie.path + cookie.name
171+
workQueue.sync {
172+
self.allCookies.removeValue(forKey: key)
173+
updatePersistentStore()
174+
}
175+
}
80176

81177
/*!
82178
@method removeCookiesSince:
83179
@abstract Delete all cookies from the cookie storage since the provided date.
84180
*/
85-
open func removeCookies(since date: Date) { NSUnimplemented() }
86-
181+
open func removeCookies(since date: Date) {
182+
let cookiesSinceDate = allCookies.values.filter {
183+
$0.properties![.created] as! Double > date.timeIntervalSinceReferenceDate
184+
}
185+
for cookie in cookiesSinceDate {
186+
deleteCookie(cookie)
187+
}
188+
updatePersistentStore()
189+
}
190+
87191
/*!
88192
@method cookiesForURL:
89193
@abstract Returns an array of cookies to send to the given URL.
@@ -94,7 +198,15 @@ open class HTTPCookieStorage: NSObject {
94198
<tt>+[NSCookie requestHeaderFieldsWithCookies:]</tt> to turn this array
95199
into a set of header fields to add to a request.
96200
*/
97-
open func cookies(for url: URL) -> [HTTPCookie]? { NSUnimplemented() }
201+
open func cookies(for url: URL) -> [HTTPCookie]? {
202+
var cookies: [HTTPCookie]?
203+
guard let host = url.host else { return nil }
204+
let path = url.path == "" ? "/" : url.path
205+
workQueue.sync {
206+
cookies = Array(allCookies.values.filter{ $0.domain + $0.path == host + path })
207+
}
208+
return cookies
209+
}
98210

99211
/*!
100212
@method setCookies:forURL:mainDocumentURL:
@@ -113,7 +225,22 @@ open class HTTPCookieStorage: NSObject {
113225
dictionary and then use this method to store the resulting cookies
114226
in accordance with policy settings.
115227
*/
116-
open func setCookies(_ cookies: [HTTPCookie], for url: URL?, mainDocumentURL: URL?) { NSUnimplemented() }
228+
open func setCookies(_ cookies: [HTTPCookie], for url: URL?, mainDocumentURL: URL?) {
229+
guard cookieAcceptPolicy != .never else { return }
230+
guard let theUrl = url else { return }
231+
232+
var validCookies = [HTTPCookie]()
233+
if mainDocumentURL != nil && cookieAcceptPolicy == .onlyFromMainDocumentDomain {
234+
//TODO: needs a careful study of the behaviour on Darwin
235+
NSUnimplemented()
236+
} else {
237+
validCookies = cookies.filter { theUrl.host != nil && theUrl.host!.hasSuffix($0.domain) }
238+
}
239+
240+
for cookie in validCookies {
241+
setCookie(cookie)
242+
}
243+
}
117244

118245
/*!
119246
@method cookieAcceptPolicy
@@ -138,3 +265,24 @@ public extension Notification.Name {
138265
*/
139266
public static let NSHTTPCookieManagerCookiesChanged = Notification.Name(rawValue: "NSHTTPCookieManagerCookiesChangedNotification")
140267
}
268+
269+
extension HTTPCookie {
270+
internal func persistableDictionary() -> [String: Any] {
271+
var properties: [String: Any] = [:]
272+
properties[HTTPCookiePropertyKey.name.rawValue] = name
273+
properties[HTTPCookiePropertyKey.path.rawValue] = path
274+
properties[HTTPCookiePropertyKey.value.rawValue] = _value
275+
properties[HTTPCookiePropertyKey.secure.rawValue] = _secure
276+
properties[HTTPCookiePropertyKey.version.rawValue] = _version
277+
properties[HTTPCookiePropertyKey.expires.rawValue] = _expiresDate?.timeIntervalSince1970 ?? Date().timeIntervalSince1970 //OK?
278+
properties[HTTPCookiePropertyKey.domain.rawValue] = _domain
279+
if let commentURL = _commentURL {
280+
properties[HTTPCookiePropertyKey.commentURL.rawValue] = commentURL.absoluteString
281+
}
282+
if let comment = _comment {
283+
properties[HTTPCookiePropertyKey.comment.rawValue] = comment
284+
}
285+
properties[HTTPCookiePropertyKey.port.rawValue] = portList
286+
return properties
287+
}
288+
}

0 commit comments

Comments
 (0)