Skip to content

Commit f539667

Browse files
Pushkar Kulkarnimamabusi
authored andcommitted
Initial implementation of HTTPCookieStorage
1 parent daa1392 commit f539667

File tree

4 files changed

+407
-14
lines changed

4 files changed

+407
-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: 186 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,58 @@ 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 var cookieFilePath: String!
42+
private let workQueue: DispatchQueue = DispatchQueue(label: "HTTPCookieStorage.workqueue")
43+
var allCookies: [String: HTTPCookie]
44+
45+
private init(cookieStorageName: String) {
46+
allCookies = [:]
47+
cookieAcceptPolicy = .always
48+
super.init()
49+
//TODO: cookieFilePath = filePath(path: _CFXDGCreateConfigHomePath()._swiftObject, fileName: "/.cookies." + cookieStorageName)
50+
cookieFilePath = filePath(path: NSHomeDirectory() + "/.config", fileName: "/.cookies." + cookieStorageName)
51+
loadPersistedCookies()
52+
}
53+
54+
private func loadPersistedCookies() {
55+
guard let cookies = NSMutableDictionary(contentsOfFile: cookieFilePath) else { return }
56+
var cookies0 = _SwiftValue.fetch(cookies) as? [String: [String: Any]] ?? [:]
57+
for key in cookies0.keys {
58+
if let cookie = createCookie(cookies0[key]!) {
59+
allCookies[key] = cookie
60+
}
61+
}
62+
}
63+
64+
private func directory(with path: String) -> Bool {
65+
guard !FileManager.default.fileExists(atPath: path) else { return true }
66+
67+
do {
68+
try FileManager.default.createDirectory(atPath: path, withIntermediateDirectories: false, attributes: nil)
69+
return true
70+
} catch {
71+
return false
72+
}
73+
}
74+
75+
private func filePath(path: String, fileName: String) -> String {
76+
if directory(with: path) {
77+
return path + fileName
78+
}
79+
//if we were unable to create the desired directory, create the cookie file in the `pwd`
80+
return fileName
81+
}
82+
4183
open var cookies: [HTTPCookie]? {
42-
NSUnimplemented()
84+
var theCookies: [HTTPCookie]?
85+
workQueue.sync {
86+
theCookies = Array(self.allCookies.values)
87+
}
88+
return theCookies
4389
}
4490

4591
/*!
@@ -49,7 +95,14 @@ open class HTTPCookieStorage: NSObject {
4995
@discussion Starting in OS X 10.11, each app has its own sharedHTTPCookieStorage singleton,
5096
which will not be shared with other applications.
5197
*/
52-
class var shared: HTTPCookieStorage { get { NSUnimplemented() } }
98+
open class var shared: HTTPCookieStorage {
99+
get {
100+
if sharedStorage == nil {
101+
sharedStorage = HTTPCookieStorage(cookieStorageName: "shared")
102+
}
103+
return sharedStorage!
104+
}
105+
}
53106

54107
/*!
55108
@method sharedCookieStorageForGroupContainerIdentifier:
@@ -62,28 +115,100 @@ open class HTTPCookieStorage: NSObject {
62115
shared among all applications and extensions with access to the same application group. Subsequent calls to this
63116
method with the same identifier will return the same cookie storage instance.
64117
*/
65-
class func sharedCookieStorage(forGroupContainerIdentifier identifier: String) -> HTTPCookieStorage { NSUnimplemented() }
118+
open class func sharedCookieStorage(forGroupContainerIdentifier identifier: String) -> HTTPCookieStorage {
119+
guard let cookieStorage = sharedCookieStorages[identifier] else {
120+
let newCookieStorage = HTTPCookieStorage(cookieStorageName: identifier)
121+
sharedCookieStorages[identifier] = newCookieStorage
122+
return newCookieStorage
123+
}
124+
return cookieStorage
125+
}
126+
66127

67128
/*!
68129
@method setCookie:
69130
@abstract Set a cookie
70131
@discussion The cookie will override an existing cookie with the
71132
same name, domain and path, if any.
72133
*/
73-
open func setCookie(_ cookie: HTTPCookie) { NSUnimplemented() }
134+
open func setCookie(_ cookie: HTTPCookie) {
135+
workQueue.sync {
136+
guard cookieAcceptPolicy != .never else { return }
137+
138+
//add or override
139+
let key = cookie.domain + cookie.path + cookie.name
140+
if let _ = allCookies.index(forKey: key) {
141+
allCookies.updateValue(cookie, forKey: key)
142+
} else {
143+
allCookies[key] = cookie
144+
}
145+
146+
//remove stale cookies, these may include the one we just added
147+
let expired = allCookies.filter { (_, value) in value.expiresDate != nil && value.expiresDate!.timeIntervalSinceNow < 0 }
148+
for (key,_) in expired {
149+
self.allCookies.removeValue(forKey: key)
150+
}
151+
152+
updatePersistentStore()
153+
}
154+
}
74155

156+
private func createCookie(_ properties: [String: Any]) -> HTTPCookie? {
157+
var cookieProperties: [HTTPCookiePropertyKey: Any] = [:]
158+
for (key, value) in properties {
159+
if key == "Expires" {
160+
guard let timestamp = value as? NSNumber else { continue }
161+
cookieProperties[HTTPCookiePropertyKey(rawValue: key)] = Date(timeIntervalSince1970: timestamp.doubleValue)
162+
} else {
163+
cookieProperties[HTTPCookiePropertyKey(rawValue: key)] = properties[key]
164+
}
165+
}
166+
return HTTPCookie(properties: cookieProperties)
167+
}
168+
169+
private func updatePersistentStore() {
170+
//persist cookies
171+
var persistDictionary: [String : [String : Any]] = [:]
172+
let persistable = allCookies.filter { (_, value) in
173+
value.expiresDate != nil &&
174+
value.isSessionOnly == false &&
175+
value.expiresDate!.timeIntervalSinceNow > 0
176+
}
177+
178+
for (key,cookie) in persistable {
179+
persistDictionary[key] = cookie.persistableDictionary()
180+
}
181+
182+
let nsdict = _SwiftValue.store(persistDictionary) as! NSDictionary
183+
_ = nsdict.write(toFile: cookieFilePath, atomically: true)
184+
}
185+
75186
/*!
76187
@method deleteCookie:
77188
@abstract Delete the specified cookie
78189
*/
79-
open func deleteCookie(_ cookie: HTTPCookie) { NSUnimplemented() }
190+
open func deleteCookie(_ cookie: HTTPCookie) {
191+
let key = cookie.domain + cookie.path + cookie.name
192+
workQueue.sync {
193+
self.allCookies.removeValue(forKey: key)
194+
updatePersistentStore()
195+
}
196+
}
80197

81198
/*!
82199
@method removeCookiesSince:
83200
@abstract Delete all cookies from the cookie storage since the provided date.
84201
*/
85-
open func removeCookies(since date: Date) { NSUnimplemented() }
86-
202+
open func removeCookies(since date: Date) {
203+
let cookiesSinceDate = allCookies.values.filter {
204+
$0.properties![.created] as! Double > date.timeIntervalSinceReferenceDate
205+
}
206+
for cookie in cookiesSinceDate {
207+
deleteCookie(cookie)
208+
}
209+
updatePersistentStore()
210+
}
211+
87212
/*!
88213
@method cookiesForURL:
89214
@abstract Returns an array of cookies to send to the given URL.
@@ -94,7 +219,14 @@ open class HTTPCookieStorage: NSObject {
94219
<tt>+[NSCookie requestHeaderFieldsWithCookies:]</tt> to turn this array
95220
into a set of header fields to add to a request.
96221
*/
97-
open func cookies(for url: URL) -> [HTTPCookie]? { NSUnimplemented() }
222+
open func cookies(for url: URL) -> [HTTPCookie]? {
223+
var cookies: [HTTPCookie]?
224+
guard let host = url.host else { return nil }
225+
workQueue.sync {
226+
cookies = Array(allCookies.values.filter{ $0.domain == host })
227+
}
228+
return cookies
229+
}
98230

99231
/*!
100232
@method setCookies:forURL:mainDocumentURL:
@@ -113,7 +245,26 @@ open class HTTPCookieStorage: NSObject {
113245
dictionary and then use this method to store the resulting cookies
114246
in accordance with policy settings.
115247
*/
116-
open func setCookies(_ cookies: [HTTPCookie], for url: URL?, mainDocumentURL: URL?) { NSUnimplemented() }
248+
open func setCookies(_ cookies: [HTTPCookie], for url: URL?, mainDocumentURL: URL?) {
249+
//if the cookieAcceptPolicy is `never` we don't have anything to do
250+
guard cookieAcceptPolicy != .never else { return }
251+
252+
//if the urls don't have a host, we cannot do anything
253+
guard let urlHost = url?.host else { return }
254+
255+
if mainDocumentURL != nil && cookieAcceptPolicy == .onlyFromMainDocumentDomain {
256+
guard let mainDocumentHost = mainDocumentURL?.host else { return }
257+
258+
//the url.host must be a suffix of manDocumentURL.host, this is based on Darwin's behaviour
259+
guard mainDocumentHost.hasSuffix(urlHost) else { return }
260+
}
261+
262+
//save only those cookies whose domain matches with the url.host
263+
let validCookies = cookies.filter { urlHost == $0.domain }
264+
for cookie in validCookies {
265+
setCookie(cookie)
266+
}
267+
}
117268

118269
/*!
119270
@method cookieAcceptPolicy
@@ -138,3 +289,24 @@ public extension Notification.Name {
138289
*/
139290
public static let NSHTTPCookieManagerCookiesChanged = Notification.Name(rawValue: "NSHTTPCookieManagerCookiesChangedNotification")
140291
}
292+
293+
extension HTTPCookie {
294+
internal func persistableDictionary() -> [String: Any] {
295+
var properties: [String: Any] = [:]
296+
properties[HTTPCookiePropertyKey.name.rawValue] = name
297+
properties[HTTPCookiePropertyKey.path.rawValue] = path
298+
properties[HTTPCookiePropertyKey.value.rawValue] = _value
299+
properties[HTTPCookiePropertyKey.secure.rawValue] = _secure
300+
properties[HTTPCookiePropertyKey.version.rawValue] = _version
301+
properties[HTTPCookiePropertyKey.expires.rawValue] = _expiresDate?.timeIntervalSince1970 ?? Date().timeIntervalSince1970 //OK?
302+
properties[HTTPCookiePropertyKey.domain.rawValue] = _domain
303+
if let commentURL = _commentURL {
304+
properties[HTTPCookiePropertyKey.commentURL.rawValue] = commentURL.absoluteString
305+
}
306+
if let comment = _comment {
307+
properties[HTTPCookiePropertyKey.comment.rawValue] = comment
308+
}
309+
properties[HTTPCookiePropertyKey.port.rawValue] = portList
310+
return properties
311+
}
312+
}

0 commit comments

Comments
 (0)