-
Notifications
You must be signed in to change notification settings - Fork 27
/
NSURLExtensions.swift
315 lines (271 loc) · 11.4 KB
/
NSURLExtensions.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
private struct ETLDEntry: CustomStringConvertible {
let entry: String
var isNormal: Bool { return isWild || !isException }
var isWild: Bool = false
var isException: Bool = false
init(entry: String) {
self.entry = entry
self.isWild = entry.hasPrefix("*")
self.isException = entry.hasPrefix("!")
}
private var description: String {
return "{ Entry: \(entry), isWildcard: \(isWild), isException: \(isException) }"
}
}
private typealias TLDEntryMap = [String:ETLDEntry]
private func loadEntriesFromDisk() -> TLDEntryMap? {
if let data = NSString.contentsOfFileWithResourceName("effective_tld_names", ofType: "dat", fromBundle: NSBundle(identifier: "org.mozilla.Shared")!, encoding: NSUTF8StringEncoding, error: nil) {
let lines = data.componentsSeparatedByString("\n")
let trimmedLines = lines.filter { !$0.hasPrefix("//") && $0 != "\n" && $0 != "" }
var entries = TLDEntryMap()
for line in trimmedLines {
let entry = ETLDEntry(entry: line)
let key: String
if entry.isWild {
// Trim off the '*.' part of the line
key = line.substringFromIndex(line.startIndex.advancedBy(2))
} else if entry.isException {
// Trim off the '!' part of the line
key = line.substringFromIndex(line.startIndex.advancedBy(1))
} else {
key = line
}
entries[key] = entry
}
return entries
}
return nil
}
private var etldEntries: TLDEntryMap? = {
return loadEntriesFromDisk()
}()
// MARK: - Local Resource URL Extensions
extension NSURL {
public func allocatedFileSize() -> Int64 {
// First try to get the total allocated size and in failing that, get the file allocated size
return getResourceLongLongForKey(NSURLTotalFileAllocatedSizeKey)
?? getResourceLongLongForKey(NSURLFileAllocatedSizeKey)
?? 0
}
public func getResourceValueForKey(key: String) -> AnyObject? {
var val: AnyObject?
do {
try getResourceValue(&val, forKey: key)
} catch _ {
return nil
}
return val
}
public func getResourceLongLongForKey(key: String) -> Int64? {
return (getResourceValueForKey(key) as? NSNumber)?.longLongValue
}
public func getResourceBoolForKey(key: String) -> Bool? {
return getResourceValueForKey(key) as? Bool
}
public var isRegularFile: Bool {
return getResourceBoolForKey(NSURLIsRegularFileKey) ?? false
}
public func lastComponentIsPrefixedBy(prefix: String) -> Bool {
return (pathComponents?.last?.hasPrefix(prefix) ?? false)
}
}
extension NSURL {
public func withQueryParams(params: [NSURLQueryItem]) -> NSURL {
let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)!
var items = (components.queryItems ?? [])
for param in params {
items.append(param)
}
components.queryItems = items
return components.URL!
}
public func withQueryParam(name: String, value: String) -> NSURL {
let components = NSURLComponents(URL: self, resolvingAgainstBaseURL: false)!
let item = NSURLQueryItem(name: name, value: value)
components.queryItems = (components.queryItems ?? []) + [item]
return components.URL!
}
public func getQuery() -> [String: String] {
var results = [String: String]()
let keyValues = self.query?.componentsSeparatedByString("&")
if keyValues?.count > 0 {
for pair in keyValues! {
let kv = pair.componentsSeparatedByString("=")
if kv.count > 1 {
results[kv[0]] = kv[1]
}
}
}
return results
}
public var hostPort: String? {
if let host = self.host {
if let port = self.port?.intValue {
return "\(host):\(port)"
}
return host
}
return nil
}
public func normalizedHostAndPath() -> String? {
if let normalizedHost = self.normalizedHost() {
return normalizedHost + (self.path ?? "/")
}
return nil
}
public func absoluteDisplayString() -> String? {
var urlString = self.absoluteString
// For http URLs, get rid of the trailing slash if the path is empty or '/'
if (self.scheme == "http" || self.scheme == "https") && (self.path == "/" || self.path == nil) && urlString.endsWith("/") {
urlString = urlString.substringToIndex(urlString.endIndex.advancedBy(-1))
}
// If it's basic http, strip out the string but leave anything else in
if urlString.hasPrefix("http://") ?? false {
return urlString.substringFromIndex(urlString.startIndex.advancedBy(7))
} else {
return urlString
}
}
/**
Returns the base domain from a given hostname. The base domain name is defined as the public domain suffix
with the base private domain attached to the front. For example, for the URL www.bbc.co.uk, the base domain
would be bbc.co.uk. The base domain includes the public suffix (co.uk) + one level down (bbc).
:returns: The base domain string for the given host name.
*/
public func baseDomain() -> String? {
if let host = self.host {
// If this is just a hostname and not a FQDN, use the entire hostname.
if !host.contains(".") {
return host
}
return publicSuffixFromHost(host, withAdditionalParts: 1)
} else {
return nil
}
}
/**
* Returns just the domain, but with the same scheme, and a trailing '/'.
*
* E.g., https://m.foo.com/bar/baz?noo=abc#123 => https://foo.com/
*
* Any failure? Return this URL.
*/
public func domainURL() -> NSURL {
if let normalized = self.normalizedHost() {
return NSURL(scheme: self.scheme, host: normalized, path: "/") ?? self
}
return self
}
public func normalizedHost() -> String? {
if var host = self.host {
if let range = host.rangeOfString("^(www|mobile|m)\\.", options: .RegularExpressionSearch) {
host.replaceRange(range, with: "")
}
return host
}
return nil
}
/**
Returns the public portion of the host name determined by the public suffix list found here: https://publicsuffix.org/list/.
For example for the url www.bbc.co.uk, based on the entries in the TLD list, the public suffix would return co.uk.
:returns: The public suffix for within the given hostname.
*/
public func publicSuffix() -> String? {
if let host = self.host {
return publicSuffixFromHost(host, withAdditionalParts: 0)
} else {
return nil
}
}
public func isWebPage() -> Bool {
let httpSchemes = ["http", "https"]
if let _ = httpSchemes.indexOf(scheme) {
return true
}
return false
}
}
//MARK: Private Helpers
private extension NSURL {
private func publicSuffixFromHost( host: String, withAdditionalParts additionalPartCount: Int) -> String? {
if host.isEmpty {
return nil
}
// Check edge case where the host is either a single or double '.'.
if host.isEmpty || NSString(string: host).lastPathComponent == "." {
return ""
}
/**
* The following algorithm breaks apart the domain and checks each sub domain against the effective TLD
* entries from the effective_tld_names.dat file. It works like this:
*
* Example Domain: test.bbc.co.uk
* TLD Entry: bbc
*
* 1. Start off by checking the current domain (test.bbc.co.uk)
* 2. Also store the domain after the next dot (bbc.co.uk)
* 3. If we find an entry that matches the current domain (test.bbc.co.uk), perform the following checks:
* i. If the domain is a wildcard AND the previous entry is not nil, then the current domain matches
* since it satisfies the wildcard requirement.
* ii. If the domain is normal (no wildcard) and we don't have anything after the next dot, then
* currentDomain is a valid TLD
* iii. If the entry we matched is an exception case, then the base domain is the part after the next dot
*
* On the next run through the loop, we set the new domain to check as the part after the next dot,
* update the next dot reference to be the string after the new next dot, and check the TLD entries again.
* If we reach the end of the host (nextDot = nil) and we haven't found anything, then we've hit the
* top domain level so we use it by default.
*/
let tokens = host.componentsSeparatedByString(".")
let tokenCount = tokens.count
var suffix: String?
var previousDomain: String? = nil
var currentDomain: String = host
for offset in 0..<tokenCount {
// Store the offset for use outside of this scope so we can add additional parts if needed
let nextDot: String? = offset + 1 < tokenCount ? tokens[offset + 1..<tokenCount].joinWithSeparator(".") : nil
if let entry = etldEntries?[currentDomain] {
if entry.isWild && (previousDomain != nil) {
suffix = previousDomain
break;
} else if entry.isNormal || (nextDot == nil) {
suffix = currentDomain
break;
} else if entry.isException {
suffix = nextDot
break;
}
}
previousDomain = currentDomain
if let nextDot = nextDot {
currentDomain = nextDot
} else {
break
}
}
var baseDomain: String?
if additionalPartCount > 0 {
if let suffix = suffix {
// Take out the public suffixed and add in the additional parts we want.
let literalFromEnd: NSStringCompareOptions = [NSStringCompareOptions.LiteralSearch, // Match the string exactly.
NSStringCompareOptions.BackwardsSearch, // Search from the end.
NSStringCompareOptions.AnchoredSearch] // Stick to the end.
let suffixlessHost = host.stringByReplacingOccurrencesOfString(suffix, withString: "", options: literalFromEnd, range: nil)
let suffixlessTokens = suffixlessHost.componentsSeparatedByString(".").filter { $0 != "" }
let maxAdditionalCount = max(0, suffixlessTokens.count - additionalPartCount)
let additionalParts = suffixlessTokens[maxAdditionalCount..<suffixlessTokens.count]
let partsString = additionalParts.joinWithSeparator(".")
baseDomain = [partsString, suffix].joinWithSeparator(".")
} else {
return nil
}
} else {
baseDomain = suffix
}
return baseDomain
}
}