forked from CatchChat/Yep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Service.swift
324 lines (229 loc) · 12 KB
/
Service.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
316
317
318
319
320
321
322
323
//
// Service.swift
// Yep
//
// Created by NIX on 16/5/20.
// Copyright © 2016年 Catch Inc. All rights reserved.
//
import Foundation
import YepNetworking
import Alamofire
import Kanna
public func titleOfURL(URL: NSURL, failureHandler: FailureHandler?, completion: (title: String) -> Void) {
Alamofire.request(.GET, URL.absoluteString, parameters: nil, encoding: .URL).responseString(encoding: NSUTF8StringEncoding, completionHandler: { response in
let error = response.result.error
guard error == nil else {
if let failureHandler = failureHandler {
failureHandler(reason: .Other(error), errorMessage: NSLocalizedString("Get title of URL failed!", comment: ""))
} else {
defaultFailureHandler(reason: .Other(error), errorMessage: NSLocalizedString("Get title of URL failed!", comment: ""))
}
return
}
guard let HTMLString = response.result.value, data = response.data else {
if let failureHandler = failureHandler {
failureHandler(reason: .CouldNotParseJSON, errorMessage: "No HTMLString or data!")
} else {
defaultFailureHandler(reason: .CouldNotParseJSON, errorMessage: "No HTMLString or data!")
}
return
}
//println("\ntitleOfURL: \(URL)\n\(HTMLString)")
// 编码转换
let newHTMLString = getUTF8HTMLStringFromHTMLString(HTMLString, withData: data)
guard let
doc = Kanna.HTML(html: newHTMLString, encoding: NSUTF8StringEncoding),
title = doc.head?.css("title").first?.text where !title.isEmpty else {
if let failureHandler = failureHandler {
failureHandler(reason: .CouldNotParseJSON, errorMessage: NSLocalizedString("No title for URL!", comment: ""))
} else {
defaultFailureHandler(reason: .CouldNotParseJSON, errorMessage: NSLocalizedString("No title for URL!", comment: ""))
}
return
}
completion(title: title)
})
}
public func openGraphWithURL(URL: NSURL, failureHandler: FailureHandler?, completion: OpenGraph -> Void) {
Alamofire.request(.GET, URL.absoluteString, parameters: nil, encoding: .URL).responseString(encoding: NSUTF8StringEncoding, completionHandler: { response in
let error = response.result.error
guard error == nil else {
if let failureHandler = failureHandler {
failureHandler(reason: .Other(error), errorMessage: nil)
} else {
defaultFailureHandler(reason: .Other(error), errorMessage: nil)
}
return
}
if let HTMLString = response.result.value, data = response.data {
//println("\n openGraphWithURLString: \(URL)\n\(HTMLString)")
// 尽量使用长链接
var finalURL = URL
if let _finalURL = response.response?.URL {
finalURL = _finalURL
}
// 编码转换
let newHTMLString = getUTF8HTMLStringFromHTMLString(HTMLString, withData: data)
//println("newHTMLString: \(newHTMLString)")
if let openGraph = OpenGraph.fromHTMLString(newHTMLString, forURL: finalURL) {
completion(openGraph)
/*
var openGraph = openGraph
guard let URL = response.response?.URL, host = URL.host, _ = NSURL.AppleOnlineStoreHost(rawValue: host) else {
completion(openGraph)
return
}
if let lookupID = URL.yep_iTunesArtworkID {
iTunesLookupWithID(lookupID, failureHandler: nil, completion: { artworkInfo in
//println("iTunesLookupWithID: \(lookupID), \(artworkInfo)")
if let kind = artworkInfo["kind"] as? String {
switch kind.lowercaseString {
case "song":
openGraph.kind = .AppleMusic
openGraph.previewAudioURLString = artworkInfo["previewUrl"] as? String
var appleMusic = OpenGraph.AppleMusic()
appleMusic.artistName = artworkInfo["artistName"] as? String
appleMusic.artworkURLString30 = artworkInfo["artworkUrl30"] as? String
appleMusic.artworkURLString60 = artworkInfo["artworkUrl60"] as? String
appleMusic.artworkURLString100 = artworkInfo["artworkUrl100"] as? String
appleMusic.collectionName = artworkInfo["collectionName"] as? String
appleMusic.collectionViewURLString = artworkInfo["collectionViewUrl"] as? String
appleMusic.trackTimeMillis = artworkInfo["trackTimeMillis"] as? Int
appleMusic.trackViewURLString = artworkInfo["trackViewUrl"] as? String
openGraph.appleMusic = appleMusic
case "feature-movie":
openGraph.kind = .AppleMovie
openGraph.previewVideoURLString = artworkInfo["previewUrl"] as? String
var appleMovie = OpenGraph.AppleMovie()
appleMovie.artistName = artworkInfo["artistName"] as? String
appleMovie.artworkURLString30 = artworkInfo["artworkUrl30"] as? String
appleMovie.artworkURLString60 = artworkInfo["artworkUrl60"] as? String
appleMovie.artworkURLString100 = artworkInfo["artworkUrl100"] as? String
appleMovie.shortDescription = artworkInfo["shortDescription"] as? String
appleMovie.longDescription = artworkInfo["longDescription"] as? String
appleMovie.trackTimeMillis = artworkInfo["trackTimeMillis"] as? Int
appleMovie.trackViewURLString = artworkInfo["trackViewUrl"] as? String
openGraph.appleMovie = appleMovie
case "ebook":
openGraph.kind = .AppleEBook
var appleEBook = OpenGraph.AppleEBook()
appleEBook.artistName = artworkInfo["artistName"] as? String
appleEBook.artworkURLString60 = artworkInfo["artworkUrl60"] as? String
appleEBook.artworkURLString100 = artworkInfo["artworkUrl100"] as? String
appleEBook.description = artworkInfo["description"] as? String
appleEBook.trackName = artworkInfo["trackName"] as? String
appleEBook.trackViewURLString = artworkInfo["trackViewUrl"] as? String
openGraph.appleEBook = appleEBook
default:
break
}
}
if let collectionType = artworkInfo["collectionType"] as? String {
switch collectionType.lowercaseString {
case "album":
var appleMusic = OpenGraph.AppleMusic()
appleMusic.artistName = artworkInfo["artistName"] as? String
appleMusic.artworkURLString100 = artworkInfo["artworkUrl100"] as? String
appleMusic.artworkURLString160 = artworkInfo["artworkUrl160"] as? String
appleMusic.collectionType = collectionType
appleMusic.collectionName = artworkInfo["collectionName"] as? String
appleMusic.collectionViewURLString = artworkInfo["collectionViewUrl"] as? String
openGraph.appleMusic = appleMusic
default:
break
}
}
completion(openGraph)
})
}
*/
return
}
}
if let failureHandler = failureHandler {
failureHandler(reason: .CouldNotParseJSON, errorMessage: nil)
} else {
defaultFailureHandler(reason: .CouldNotParseJSON, errorMessage: nil)
}
})
}
// ref http://a4esl.org/c/charset.html
private enum WeirdCharset: String {
// China
case GB2312 = "GB2312"
case GBK = "GBK"
case GB18030 = "GB18030"
// Taiwan, HongKong ...
case BIG5 = "BIG5"
case BIG5HKSCS = "BIG5-HKSCS"
// Korean
case EUCKR = "EUC-KR"
}
private func getUTF8HTMLStringFromHTMLString(HTMLString: String, withData data: NSData) -> String {
let pattern = "charset=([A-Za-z0-9\\-]+)"
guard let
charsetRegex = try? NSRegularExpression(pattern: pattern, options: [.CaseInsensitive]),
result = charsetRegex.firstMatchInString(HTMLString, options: [.ReportCompletion], range: NSMakeRange(0, (HTMLString as NSString).length))
else {
return HTMLString
}
let charsetStringRange = result.rangeAtIndex(1)
let charsetString = (HTMLString as NSString).substringWithRange(charsetStringRange).uppercaseString
guard let weirdCharset = WeirdCharset(rawValue: charsetString) else {
return HTMLString
}
let encoding: NSStringEncoding
switch weirdCharset {
case .GB2312, .GBK, .GB18030:
let china = CFStringEncodings.GB_18030_2000
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(china.rawValue))
case .BIG5, .BIG5HKSCS:
let taiwan = CFStringEncodings.Big5_HKSCS_1999
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(taiwan.rawValue))
case .EUCKR:
let korean = CFStringEncodings.EUC_KR
encoding = CFStringConvertEncodingToNSStringEncoding(CFStringEncoding(korean.rawValue))
}
guard let newHTMLString = String(data: data, encoding: encoding) else {
return HTMLString
}
return newHTMLString
}
private enum iTunesCountry: String {
case China = "cn"
case USA = "us"
}
private func iTunesLookupWithID(lookupID: String, inCountry country: iTunesCountry, failureHandler: ((Reason, String?) -> Void)?, completion: JSONDictionary? -> Void) {
let lookUpURLString = "https://itunes.apple.com/lookup?id=\(lookupID)&country=\(country.rawValue)"
Alamofire.request(.GET, lookUpURLString).responseJSON { response in
print("iTunesLookupWithID \(lookupID): \(response)")
guard
let info = response.result.value as? JSONDictionary,
let resultCount = info["resultCount"] as? Int where resultCount > 0,
let result = (info["results"] as? [JSONDictionary])?.first
else {
completion(nil)
return
}
completion(result)
}
}
private func iTunesLookupWithID(lookupID: String, failureHandler: ((Reason, String?) -> Void)?, completion: JSONDictionary -> Void) {
iTunesLookupWithID(lookupID, inCountry: .China, failureHandler: failureHandler, completion: { result in
if let result = result {
completion(result)
} else {
iTunesLookupWithID(lookupID, inCountry: .USA, failureHandler: failureHandler, completion: { result in
if let result = result {
completion(result)
} else {
if let failureHandler = failureHandler {
failureHandler(.NoData, nil)
} else {
defaultFailureHandler(reason: .NoData, errorMessage: nil)
}
}
})
}
})
}