-
Notifications
You must be signed in to change notification settings - Fork 0
/
SlackWebhookClient.swift
246 lines (196 loc) · 6.45 KB
/
SlackWebhookClient.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
//
// SlackWebhookClient.swift
// SlackTest
//
import Foundation
import CoreFoundation
import UIKit
typealias slackClientCompletionHandler = ((Bool, NSHTTPURLResponse?, NSError?) -> (Void))?
class SlackWebhookClient
{
let webhookURL: NSURL
let channel: String?
let username: String?
let iconEmoji: String?
let iconURL: NSURL?
var maxLengthForShortField = 40
private let session = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration())
init(webhookURL: NSURL, channel: String?, username: String?, iconEmoji: String?, iconURL: NSURL?)
{
self.webhookURL = webhookURL
self.channel = channel
self.username = username
self.iconURL = iconURL
if var givenIconEmoji = iconEmoji {
// add ":" character at start and end of iconEmoji if not present
if givenIconEmoji.first() != ":" {
givenIconEmoji = ":" + givenIconEmoji
}
if givenIconEmoji.last() != ":" {
givenIconEmoji = givenIconEmoji + ":"
}
self.iconEmoji = givenIconEmoji
}
else {
self.iconEmoji = iconEmoji
}
}
convenience init(webhookURL givenURL: NSURL)
{
self.init(webhookURL: givenURL, channel: nil, username: nil, iconEmoji: nil, iconURL: nil)
}
func sendMessage(messageText: String, completionHandler: slackClientCompletionHandler)
{
var messageDict = self.messageParametersToDictionary()
messageDict["text"] = messageText
var err: NSError?
var messageData = NSJSONSerialization.dataWithJSONObject(messageDict, options: nil, error: &err)
if let err = err, completionHandler = completionHandler {
completionHandler(false, nil, err)
}
var request = NSMutableURLRequest(URL: self.webhookURL)
request.HTTPBody = messageData
request.HTTPMethod = "POST"
self.sendRequest(request, completionHandler: completionHandler)
}
func sendAttachment(attachment: SlackAttachment, completionHandler: slackClientCompletionHandler)
{
var request = NSMutableURLRequest(URL: self.webhookURL)
var attachmentDict = attachment.toDict()
var messageDict = ["attachments": [attachmentDict]]
var err: NSError?
var messageData = NSJSONSerialization.dataWithJSONObject(messageDict, options: nil, error: &err)
if let err = err, completionHandler = completionHandler {
completionHandler(false, nil, err)
}
request.HTTPBody = messageData
request.HTTPMethod = "POST"
self.sendRequest(request, completionHandler: completionHandler);
}
private func sendRequest(request: NSURLRequest, completionHandler givenCompletionHandler: slackClientCompletionHandler)
{
var task = session.dataTaskWithRequest(request, completionHandler: {(data, response, error) in
if let completion = givenCompletionHandler {
let success = error == nil && (response as! NSHTTPURLResponse).statusCode == 200
completion(success, response as? NSHTTPURLResponse, error)
}
})
task.resume()
}
func messageParametersToDictionary () -> [String:String]
{
var paramsDict = [String:String]()
if let channel = self.channel {
paramsDict["channel"] = channel
}
if let username = self.username {
paramsDict["username"] = username
}
if let iconEmoji = self.iconEmoji {
paramsDict["iconEmoji"] = iconEmoji
}
if let iconURL = self.iconURL {
paramsDict["iconURL"] = iconURL.absoluteString
}
return paramsDict
}
}
class SlackAttachment
{
var fallback: String
var text: String
var title: String
var titleLink: NSURL?
var color: UIColor?
var pretext: String?
var authorName: String?
var authorLink: NSURL?
var authorIcon: NSURL?
var fields: [SlackAttachmentField]?
var imageURL: NSURL?
init(fallback: String, title: String, text: String)
{
self.fallback = fallback
self.title = title
self.text = text
}
func toDict() -> ([String: AnyObject])
{
var messageDict: [String: AnyObject] = [
"fallback": self.fallback,
"title": self.title,
"text": self.text
]
if let pretext = self.pretext {
messageDict["pretext"] = self.pretext
}
if let authorName = self.authorName {
messageDict["author_name"] = self.authorName
}
if let authorLink = self.authorLink {
messageDict["author_link"] = authorLink.absoluteString
}
if let authorIcon = self.authorIcon {
messageDict["author_icon"] = authorIcon.absoluteString
}
if let titleLink = self.titleLink {
messageDict["title_link"] = titleLink.absoluteString
}
if let imageURL = self.imageURL {
messageDict["image_url"] = imageURL.absoluteString
}
if let color = self.color {
messageDict["color"] = color.hexRGB
}
if let fields = self.fields {
var fieldList: [[String:AnyObject]] = []
for f in fields {
fieldList.append( f.toDict() )
}
messageDict["fields"] = fieldList
}
return messageDict
}
}
struct SlackAttachmentField
{
static var maxLengthForShortField = 40
var title: String
var value: String
func isShort () -> (Bool) {
return title.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= SlackAttachmentField.maxLengthForShortField
&& value.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) <= SlackAttachmentField.maxLengthForShortField
}
func toDict() -> ([String: AnyObject]) {
return [
"title": self.title,
"value": self.value,
"short": self.isShort()
]
}
}
private extension String {
func first() -> String
{
return self.substringWithRange(Range(start: self.startIndex, end: advance(self.startIndex, 1)))
}
func last() -> String
{
return self.substringWithRange(Range(start: advance(self.endIndex, -1), end:self.endIndex))
}
}
// via http://stackoverflow.com/q/28696862
private extension UIColor
{
typealias RGBComponents = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
var rgbComponents: RGBComponents {
var c: RGBComponents = (0,0,0,0)
if getRed(&c.red, green: &c.green, blue: &c.blue, alpha: &c.alpha) {
return c
}
return (0,0,0,0)
}
var hexRGB: String {
return String(format: "#%02x%02x%02x", Int(rgbComponents.red * 255), Int(rgbComponents.green * 255), Int(rgbComponents.blue * 255))
}
}