-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathGravatarServiceRemote.swift
More file actions
164 lines (140 loc) · 5.95 KB
/
Copy pathGravatarServiceRemote.swift
File metadata and controls
164 lines (140 loc) · 5.95 KB
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
import Foundation
#if canImport(UIKit)
import UIKit
#endif
/// This ServiceRemote encapsulates all of the interaction with the Gravatar endpoint.
///
open class GravatarServiceRemote {
let baseGravatarURL = "https://www.gravatar.com/"
public init() {}
/// This method fetches the Gravatar profile for the specified email address.
///
/// - Parameters:
/// - email: The email address of the gravatar profile to fetch.
/// - success: A success block.
/// - failure: A failure block.
///
open func fetchProfile(_ email: String, success: @escaping ((_ profile: RemoteGravatarProfile) -> Void), failure: @escaping ((_ error: Error?) -> Void)) {
guard let hash = (email as NSString).md5() else {
assertionFailure()
return
}
fetchProfile(hash: hash, success: success, failure: failure)
}
/// This method fetches the Gravatar profile for the specified user hash value.
///
/// - Parameters:
/// - hash: The hash value of the email address of the gravatar profile to fetch.
/// - success: A success block.
/// - failure: A failure block.
///
open func fetchProfile(hash: String, success: @escaping ((_ profile: RemoteGravatarProfile) -> Void), failure: @escaping ((_ error: Error?) -> Void)) {
let path = baseGravatarURL + hash + ".json"
guard let targetURL = URL(string: path) else {
assertionFailure()
return
}
let session = URLSession.shared
let task = session.dataTask(with: targetURL) { (data: Data?, _: URLResponse?, error: Error?) in
guard error == nil, let data else {
failure(error)
return
}
do {
let jsonData = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
guard let jsonDictionary = jsonData as? [String: [Any]],
let entry = jsonDictionary["entry"],
let profileData = entry.first as? NSDictionary else {
DispatchQueue.main.async {
// This case typically happens when the endpoint does
// successfully return but doesn't find the user.
failure(nil)
}
return
}
let profile = RemoteGravatarProfile(dictionary: profileData)
DispatchQueue.main.async {
success(profile)
}
return
} catch {
failure(error)
return
}
}
task.resume()
}
#if canImport(UIKit)
/// This method hits the Gravatar Endpoint, and uploads a new image, to be used as profile.
///
/// - Parameters:
/// - image: The new Gravatar Image, to be uploaded
/// - completion: An optional closure to be executed on completion.
///
open func uploadImage(_ image: UIImage, accountEmail: String, accountToken: String, completion: ((_ error: NSError?) -> Void)?) {
guard let targetURL = URL(string: UploadParameters.endpointURL) else {
assertionFailure()
return
}
// Boundary
let boundary = boundaryForRequest()
// Request
let request = NSMutableURLRequest(url: targetURL)
request.httpMethod = UploadParameters.HTTPMethod
request.setValue("Bearer \(accountToken)", forHTTPHeaderField: "Authorization")
request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
// Body
let gravatarData = image.pngData()!
let requestBody = bodyWithGravatarData(gravatarData, account: accountEmail, boundary: boundary)
// Task
let session = URLSession.shared
let task = session.uploadTask(with: request as URLRequest, from: requestBody, completionHandler: { (_, _, error) in
completion?(error as NSError?)
})
task.resume()
}
#endif
// MARK: - Private Helpers
/// Returns a new (randomized) Boundary String
///
private func boundaryForRequest() -> String {
return "Boundary-" + UUID().uuidString
}
/// Returns the Body for a Gravatar Upload OP.
///
/// - Parameters:
/// - gravatarData: The NSData-Encoded Image
/// - account: The account that will get updated
/// - boundary: The request's Boundary String
///
/// - Returns: A NSData instance, containing the Request's Payload.
///
private func bodyWithGravatarData(_ gravatarData: Data, account: String, boundary: String) -> Data {
let body = NSMutableData()
// Image Payload
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\(UploadParameters.imageKey); ")
body.appendString("filename=\(UploadParameters.filename)\r\n")
body.appendString("Content-Type: \(UploadParameters.contentType);\r\n\r\n")
body.append(gravatarData)
body.appendString("\r\n")
// Account Payload
body.appendString("--\(boundary)\r\n")
body.appendString("Content-Disposition: form-data; name=\"\(UploadParameters.accountKey)\"\r\n\r\n")
body.appendString("\(account)\r\n")
// EOF!
body.appendString("--\(boundary)--\r\n")
return body as Data
}
// MARK: - Private Structs
private struct UploadParameters {
// swiftlint:disable operator_usage_whitespace
static let endpointURL = "https://api.gravatar.com/v1/upload-image"
static let HTTPMethod = "POST"
static let contentType = "application/octet-stream"
static let filename = "profile.png"
static let imageKey = "filedata"
static let accountKey = "account"
// swiftlint:enable operator_usage_whitespace
}
}