-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathspark.go
421 lines (378 loc) · 11.6 KB
/
spark.go
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package main
import (
"encoding/json"
"fmt"
"github.com/go-resty/resty"
"sort"
"strings"
"sync"
"time"
)
var user = User{
Info: Person{},
ActiveSpaceId: "",
Locale: &time.Location{},
}
var spaces = Spaces{}
func GetMeInfo() {
f, _ := Request("GET", "/people/me", nil)
json.Unmarshal(f, &user.Info)
UpdateStatusName(user.Info.DisplayName)
UpdateStatusOwnStatus(user.Info.Status)
}
func GetMessagesForSpace(space_id string) {
if s, ok := maps.SpaceIdToSpace.Load(interface{}(space_id)); ok {
space := s.(*Space)
f, _ := Request("GET", fmt.Sprintf("/messages?roomId=%s", space_id), nil)
json.Unmarshal(f, &space.Messages)
sort.Sort(MessageSorter(space.Messages.Items))
}
}
func ShowMessages(space_title string) {
if s, ok := maps.SpaceTitleToSpace.Load(interface{}(space_title)); ok {
space := s.(*Space)
for _, m := range space.Messages.Items {
if m.PersonId == user.Info.Id {
AddOwnText(m.Text, user.Info.DisplayName, m.Created)
} else {
// Messages doesn't include DisplayNames, so find it in members.
found := false
for _, u := range space.Members.Items {
if strings.ToLower(u.PersonEmail) == strings.ToLower(m.PersonEmail) {
AddUserText(m.Text, u.PersonDisplayName, m.Created)
found = true
break
}
}
if !found {
AddUserText(m.Text, m.PersonEmail, m.Created)
}
}
}
}
}
func GetMembersOfSpace(space_id string) {
members := []Member{}
link := "_"
req := fmt.Sprintf("/memberships?roomId=%s&max=500", space_id)
for link != "" {
f := []byte{}
f, link = Request("GET", req, nil)
m := Members{}
json.Unmarshal(f, &m)
for _, item := range m.Items {
members = append(members, item)
}
if link != "" {
req = strings.TrimPrefix(link, config.ApiUrl)
}
}
if s, ok := maps.SpaceIdToSpace.Load(interface{}(space_id)); ok {
space := s.(*Space)
space.Members.Items = members
for i, m := range space.Members.Items {
maps.MemberIdToMember.Store(interface{}(m.PersonId), interface{}(&space.Members.Items[i]))
maps.MemberNameToMember.Store(interface{}(m.PersonDisplayName), interface{}(&space.Members.Items[i]))
}
if user.ActiveSpaceId == space_id {
ChangeSpace(space.Title)
}
}
}
func ChangeSpace(space string) {
if sm, ok := maps.SpaceTitleToSpace.Load(interface{}(space)); ok {
s := sm.(*Space)
SetInputLabelSpace(space)
ClearUsers()
UpdateStatusSpace(space)
user.ActiveSpaceId = s.Id
var ops []string
var monitor []string
var users []string
if len(s.Members.Items) == 0 {
AddUser("[red]Loading...")
} else {
for _, u := range s.Members.Items {
if u.IsModerator {
ops = append(ops, fmt.Sprintf("[%s]@[%s]%s", theme.ModeratorSign, theme.UserModerator, u.PersonDisplayName))
} else if u.IsMonitor {
monitor = append(monitor, fmt.Sprintf("[%s]+[%s]%s", theme.MonitorSign, theme.UserMonitor, u.PersonDisplayName))
} else {
//Check if it's a bot.
if strings.Contains(u.PersonEmail, "sparkbot.io") {
users = append(users, fmt.Sprintf("[%s][BOT[] %s", theme.UserBot, u.PersonDisplayName))
} else {
users = append(users, fmt.Sprintf("[%s]%s", theme.UserRegular, u.PersonDisplayName))
}
}
}
for _, o := range ops {
AddUser(o)
}
for _, o := range monitor {
AddUser(o)
}
for _, o := range users {
AddUser(o)
}
}
MarkActiveSpaceRead(space)
MarkSpaceRead(space)
ShowMessages(space)
} else {
if space != "status" {
AddStatusText(fmt.Sprintf("Could not change to space %v just yet.", space))
} else {
SetInputLabelSpace(space)
ClearUsers()
UpdateStatusSpace(space)
ShowMessages(space)
}
}
}
func SendMessageToChannel(msg string) {
data := map[string]interface{}{"roomId": user.ActiveSpaceId, "text": msg}
Request("POST", "/messages", data)
}
func DeleteCurrentSpace() {
Request("DELETE", fmt.Sprintf("/rooms/%s", user.ActiveSpaceId), nil)
}
func GetAllSpaces() {
f, _ := Request("GET", "/rooms", nil)
spaces = Spaces{}
json.Unmarshal(f, &spaces)
ClearPrivate()
ClearSpaces()
sort.Sort(SpaceSorter(spaces.Items))
count := 0
// Clear maps
maps.SpaceIdToSpace = &sync.Map{}
maps.SpaceTitleToSpace = &sync.Map{}
for i, m := range spaces.Items {
// Perform some mapping for faster lookup
if m.Title == "Empty Title" || m.Title == "DEPRACATED" {
count++
spaces.Items[i].Title = fmt.Sprintf("%v (%v)", m.Title, count)
}
maps.SpaceTitleToSpace.Store(interface{}(spaces.Items[i].Title), interface{}(&spaces.Items[i]))
maps.SpaceIdToSpace.Store(interface{}(spaces.Items[i].Id), interface{}(&spaces.Items[i]))
if m.Type == "direct" {
AddPrivate(m.Title)
} else if m.Type == "group" {
AddSpace(m.Title)
}
channels.Messages <- spaces.Items[i].Id
channels.Members <- spaces.Items[i].Id
if user.ActiveSpaceId == m.Id {
ChangeSpace(m.Title)
}
}
}
func LeaveCurrentRoom() {
var memberships Memberships
f, _ := Request("GET", "/memberships", nil)
json.Unmarshal(f, &memberships)
for _, m := range memberships.Items {
if m.PersonId == user.Info.Id && m.RoomId == user.ActiveSpaceId {
go Request("DELETE", fmt.Sprintf("/memberships/%s", m.Id), nil)
break
}
}
}
// Send private message to user
func MessageUser(usr []string) {
str := strings.Join(usr, " ")
posFirst := strings.Index(str, "<")
if posFirst == -1 {
return
}
posLast := strings.Index(str, ">")
if posLast == -1 {
return
}
posFirstAdjusted := posFirst + 1
if posFirstAdjusted >= posLast {
return
}
name := str[posFirstAdjusted:posLast]
// Get person Id
if ms, ok := maps.MemberNameToMember.Load(interface{}(name)); ok {
m := ms.(*Member)
message := strings.TrimLeft(str[posLast+1:], " ")
data := map[string]interface{}{"toPersonId": m.PersonId, "text": message}
Request("POST", "/messages", data)
} else {
AddStatusText(fmt.Sprintf("[red]Did not find any user ID for '%s'", name))
return
}
}
func CreateRoom(name []string) {
room_name := strings.Join(name, " ")
AddStatusText(fmt.Sprintf("Creating room %s...", room_name))
data := map[string]interface{}{"title": room_name}
Request("POST", "/rooms", data)
// It takes a while to create a room so wait a bit before updating spaces.
// TBD: Check if this can be handled by a created room event.
time.Sleep(3 * time.Second)
GetAllSpaces()
AddStatusText(fmt.Sprintf("Created room %s", room_name))
//ClearChat()
//ChangeSpace(room_name)
}
// Invite to current room
func InviteUser(usr []string) {
data := map[string]interface{}{
"roomId": user.ActiveSpaceId,
"personId": strings.Join(usr, " "),
}
Request("POST", "/memberships", data)
// TBD: Add user name + room name information
AddStatusText(fmt.Sprintf("Invited user to room."))
}
// Search for users by name or email
func WhoisUsers(usr []string) {
name := strings.Join(usr, "%20")
AddStatusText(fmt.Sprintf("Searching for user: %v", strings.Join(usr, " ")))
var persons Persons
f, _ := Request("GET", fmt.Sprintf("/people?displayName=%s", name), nil)
json.Unmarshal(f, &persons)
for i, p := range persons.Items {
status_color := "red"
if p.Status == "active" {
status_color = "green"
} else if p.Status == "inactive" {
status_color = "orange"
}
AddStatusText(fmt.Sprintf("[%v/%v]: [%s]%s", i+1, len(persons.Items), status_color, p.Status))
AddStatusText(fmt.Sprintf("\t [blue]Display Name:[white] %s", p.DisplayName))
AddStatusText(fmt.Sprintf("\t [blue]Nickname:[white] %s", p.NickName))
AddStatusText(fmt.Sprintf("\t [blue]E-mails:[white] %s", strings.Join(p.Emails, ",")))
AddStatusText(fmt.Sprintf("\t [blue]Created:[white] %s", p.Created))
AddStatusText(fmt.Sprintf("\t [blue]Last Activity:[white] %s", p.LastActivity))
AddStatusText(fmt.Sprintf("\t [blue]Type:[white] %s", p.Type))
AddStatusText(fmt.Sprintf("\t [blue]ID:[white] %s", p.Id))
}
if len(persons.Items) == 0 {
AddStatusText(fmt.Sprintf("[red] Did not find any people with name %s.", strings.Join(usr, " ")))
}
}
func UpdateOrCreateWebHook(name string, data map[string]interface{}, webhooks WebHooks) {
need_create := true
for _, w := range webhooks.Items {
if w.Name == name {
Request("PUT", fmt.Sprintf("/webhooks/%s", w.Id), data)
need_create = false
break
}
}
if need_create {
Request("POST", "/webhooks", data)
}
}
func DeleteAllWebHooks() {
webhooks := WebHooks{}
f, _ := Request("GET", "/webhooks", nil)
json.Unmarshal(f, &webhooks)
for _, w := range webhooks.Items {
Request("DELETE", fmt.Sprintf("/webhooks/%s", w.Id), nil)
}
}
func RegisterWebHooks() {
// Get all webhooks
webhooks := WebHooks{}
f, _ := Request("GET", "/webhooks", nil)
json.Unmarshal(f, &webhooks)
// Memberships created
data := map[string]interface{}{
"name": "spinc_mc",
"targetUrl": fmt.Sprintf("%s/%s", user.GrokUrl, "membership"),
"resource": "memberships",
"event": "created",
}
UpdateOrCreateWebHook("spinc_mc", data, webhooks)
// Memberships updated
data = map[string]interface{}{
"name": "spinc_mu",
"targetUrl": fmt.Sprintf("%s/%s", user.GrokUrl, "membership"),
"resource": "memberships",
"event": "updated",
}
UpdateOrCreateWebHook("spinc_mu", data, webhooks)
// Memberships deleted
data = map[string]interface{}{
"name": "spinc_md",
"targetUrl": fmt.Sprintf("%s/%s", user.GrokUrl, "membership"),
"resource": "memberships",
"event": "deleted",
}
UpdateOrCreateWebHook("spinc_md", data, webhooks)
// Messages created
data = map[string]interface{}{
"name": "spinc_msgc",
"targetUrl": fmt.Sprintf("%s/%s", user.GrokUrl, "message"),
"resource": "messages",
"event": "created",
}
UpdateOrCreateWebHook("spinc_msgc", data, webhooks)
// Messages deleted
data = map[string]interface{}{
"name": "spinc_msgd",
"targetUrl": fmt.Sprintf("%s/%s", user.GrokUrl, "message"),
"resource": "messages",
"event": "deleted",
}
UpdateOrCreateWebHook("spinc_msgd", data, webhooks)
// Room created
data = map[string]interface{}{
"name": "spinc_roomc",
"targetUrl": fmt.Sprintf("%s/%s", user.GrokUrl, "room"),
"resource": "rooms",
"event": "created",
}
UpdateOrCreateWebHook("spinc_roomc", data, webhooks)
// Room updated
data = map[string]interface{}{
"name": "spinc_roomu",
"targetUrl": fmt.Sprintf("%s/%s", user.GrokUrl, "room"),
"resource": "rooms",
"event": "updated",
}
UpdateOrCreateWebHook("spinc_roomu", data, webhooks)
}
func Request(method string, path string, data map[string]interface{}) ([]byte, string) {
r := resty.R().
SetHeader("Accept", "application/json").
SetHeader("Authorization", fmt.Sprintf("Bearer %s", user.Token))
resty.SetTimeout(10 * time.Second)
resty.SetCloseConnection(true)
link := ""
resp := &resty.Response{}
if method == "GET" {
resp, _ = r.Get(fmt.Sprintf("%v/%v", config.ApiUrl, path))
header := resp.Header()
if header["Link"] != nil {
if strings.Contains(header["Link"][0], "next") {
str := strings.Join(header["Link"], " ")
posFirst := strings.Index(str, "<")
posLast := strings.Index(str, ">")
link = str[posFirst+1 : posLast]
}
}
} else if method == "DELETE" {
resp, _ = r.Delete(fmt.Sprintf("%v/%v", config.ApiUrl, path))
} else if method == "POST" {
r.SetBody(data)
resp, _ = r.Post(fmt.Sprintf("%v/%v", config.ApiUrl, path))
} else if method == "PUT" {
r.SetBody(data)
resp, _ = r.Put(fmt.Sprintf("%v/%v", config.ApiUrl, path))
}
i := resp.StatusCode()
if i >= 250 {
AddStatusText(fmt.Sprintf("[red]%s Request Error(%v):[white] %v [%v]", method, resp.StatusCode(), path, resp.Status()))
if i == 401 {
AddStatusText("[red]Auth token may be expired. Get new token here: [white]https://developer.webex.com/getting-started.html#authentication")
}
}
return []byte(resp.Body()), link
}