-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCiscoSpark.py
669 lines (516 loc) · 20.1 KB
/
CiscoSpark.py
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
import sys
import time
import logging
import requests
from markdown import markdown
from errbot.errBot import ErrBot
from errbot.backends.base import Message, Person, Room, RoomOccupant
import ciscosparkapi as sparkapi
log = logging.getLogger('errbot.backends.CiscoSpark')
CISCO_SPARK_WEBHOOK_ID = 'CiscoSparkBackend'
CISCO_SPARK_WEBHOOK_URI = 'errbot/spark'
CISCO_SPARK_MESSAGE_SIZE_LIMIT = 7439
class CiscoSparkMessage(Message):
"""
A Cisco Spark Message
"""
@property
def is_direct(self) -> bool:
return self.extras['roomType'] == 'direct'
@property
def is_group(self) -> bool:
return not self.is_direct
class CiscoSparkPerson(Person):
"""
A Cisco Spark Person
"""
def __init__(self, bot, attributes={}):
self._bot = bot
if isinstance(attributes, sparkapi.Person):
self._spark_person = attributes
else:
self._spark_person = sparkapi.Person(attributes)
@property
def id(self):
return self._spark_person.id
@id.setter
def id(self, val):
self._spark_person._json_data['id'] = val
@property
def emails(self):
return self._spark_person.emails
@property
def displayName(self):
return self._spark_person.displayName
@property
def created(self):
return self._spark_person.created
@property
def avatar(self):
return self._spark_person.avatar
@staticmethod
def build_from_json(obj):
return CiscoSparkPerson(sparkapi.Person(obj))
@classmethod
def find_using_email(cls, session, value):
"""
Return the FIRST Cisco Spark person found when searching using an email address
:param session: The CiscoSparkAPI session handle
:param value: the value to search for
:return: A CiscoSparkPerson
"""
for person in session.people.list(email=value):
return CiscoSparkPerson(person)
return CiscoSparkPerson()
@classmethod
def find_using_name(cls, session, value):
"""
Return the FIRST Cisco Spark person found when searching using the display name
:param session: The CiscoSparkAPI session handle
:param value: the value to search for
:return: A CiscoSparkPerson
"""
for person in session.people.list(displayName=value):
return CiscoSparkPerson(person)
return CiscoSparkPerson()
@classmethod
def get_using_id(cls, session, value):
"""
Return a Cisco Spark person when searching using an ID
:param session: The CiscoSparkAPI session handle
:param value: the Spark ID
:return: A CiscoSparkPerson
"""
return CiscoSparkPerson(session.people.get(value))
def load(self):
self._spark_person = self._bot.session.Person(self.id)
# Err API
@property
def person(self):
return self.id
@property
def client(self):
return ''
@property
def nick(self):
return ''
@property
def fullname(self):
return self.displayName
def json(self):
return self._spark_person.json()
def __eq__(self, other):
return str(self) == str(other)
def __unicode__(self):
return self.id
__str__ = __unicode__
aclattr = id
class CiscoSparkRoomOccupant(CiscoSparkPerson, RoomOccupant):
"""
A Cisco Spark Person that Occupies a Cisco Spark Room
"""
def __init__(self, bot, room={}, person={}):
if isinstance(room, CiscoSparkRoom):
self._room = room
else:
self._room = CiscoSparkRoom(bot, room)
if isinstance(person, CiscoSparkPerson):
self._spark_person = person
else:
super().__init__(person)
@property
def room(self):
return self._room
class CiscoSparkRoom(Room):
"""
A Cisco Spark Room
"""
def __init__(self, bot, val={}):
self._bot = bot
self._webhook = None
self._occupants = []
if isinstance(val, sparkapi.Room):
self._spark_room = val
else:
self._spark_room = sparkapi.Room(val)
@property
def sipAddress(self):
return self._spark_room.sipAddress
@property
def created(self):
return self._spark_room.created
@property
def id(self):
return self._spark_room.id
@id.setter
def id(self, val):
self._spark_room._json_data['id'] = val
@property
def title(self):
return self._spark_room.title
@classmethod
def get_using_id(cls, backend, val):
return CiscoSparkRoom(backend, backend.session.rooms.get(val))
def update_occupants(self):
log.debug("Updating occupants for room {} ({})".format(self.title, self.id))
self._occupants.clear()
for member in self._bot.session.memberships.get(self.id):
self._occupants.append(CiscoSparkRoomOccupant(self.id, membership=member))
log.debug("Total occupants for room {} ({}) is {} ".format(self.title, self.id, len(self._occupants)))
def load(self):
self._spark_room = self._bot.session.Room(self.id)
# Errbot API
def join(self, username=None, password=None):
log.debug("Joining room {} ({})".format(self.title, self.id))
try:
self._bot.session.memberships.create(self.id, self._bot.bot_identifier.id)
log.debug("{} is NOW a member of {} ({})".format(self._bot.bot_identifier.displayName, self.title, self.id))
except sparkapi.exceptions.SparkApiError as error:
# API now returning a 403 when trying to add user to a direct conversation and they are already in the
# conversation. For groups if the user is already a member a 409 is returned.
if error.response.status_code == 403 or error.response.status_code == 409:
log.debug("{} is already a member of {} ({})".format(self._bot.bot_identifier.displayName, self.title,
self.id))
else:
log.exception("HTTP Exception: Failed to join room {} ({})".format(self.title, self.id))
return
except Exception:
log.exception("Failed to join room {} ({})".format(self.title, self.id))
return
# When errbot joins rooms we need to create a new webhook for the integration
self.webhook_create()
def webhook_create(self):
"""
Create a webhook that listens to new messages for this room (id)
"""
self._webhook = self._bot.create_webhook(filter="roomId={}".format(self.id))
def webhook_delete(self):
"""
Delete the webhook for this room
"""
self._bot.delete_webhook(self._webhook)
def leave(self, reason=None):
log.debug("Leave room yet to be implemented") # TODO
pass
def create(self):
log.debug("Create room yet to be implemented") # TODO
pass
def destroy(self):
log.debug("Destroy room yet to be implemented") # TODO
pass
exists = True # TODO
joined = True # TODO
@property
def topic(self):
log.debug("Topic room yet to be implemented") # TODO
return "TODO"
@topic.setter
def topic(self, topic: str) -> None:
log.debug("Topic room yet to be implemented") # TODO
pass
@property
def occupants(self, session=None):
return self._occupants
def invite(self, *args) -> None:
log.debug("Invite room yet to be implemented") # TODO
pass
def __eq_(self, other):
return str(self) == str(other)
def __unicode__(self):
return self.id
__str__ = __unicode__
class CiscoSparkBackend(ErrBot):
"""
This is the CiscoSpark backend for errbot.
"""
def __init__(self, config):
super().__init__(config)
bot_identity = config.BOT_IDENTITY
# Do we have the basic mandatory config needed to operate the bot
self._bot_token = bot_identity.get('TOKEN', None)
if not self._bot_token:
log.fatal('You need to define the Cisco Spark Bot TOKEN in the BOT_IDENTITY of config.py.')
sys.exit(1)
self._webhook_destination = bot_identity.get('WEBHOOK_DESTINATION', None)
if not self._webhook_destination:
log.fatal('You need to define WEBHOOK_DESTINATION in the BOT_IDENTITY of config.py.')
sys.exit(1)
self._webhook_secret = bot_identity.get('WEBHOOK_SECRET', None)
if not self._webhook_secret:
log.fatal('You need to define WEBHOOK_SECRET in the BOT_IDENTITY of config.py.')
sys.exit(1)
self._bot_rooms = config.CHATROOM_PRESENCE
if not self._bot_rooms:
log.fatal('You need to define CHATROOM_PRESENCE in config.py.')
sys.exit(1)
log.debug("Room presence: {}".format(self._bot_rooms))
# Adjust message size limit to cater for the non-standard size limit
if config.MESSAGE_SIZE_LIMIT > CISCO_SPARK_MESSAGE_SIZE_LIMIT:
log.info(
"Capping MESSAGE_SIZE_LIMIT to {} which is the maximum length allowed by CiscoSpark".
format(CISCO_SPARK_MESSAGE_SIZE_LIMIT)
)
config.MESSAGE_SIZE_LIMIT = CISCO_SPARK_MESSAGE_SIZE_LIMIT
# Build the complete path to the Webhook URI
if self._webhook_destination[len(self._webhook_destination) - 1] != '/':
self._webhook_destination += '/'
self._webhook_destination += CISCO_SPARK_WEBHOOK_URI
# Initialize the CiscoSparkAPI session used to manage the Spark integration
log.debug("Fetching and building identifier for the bot itself.")
self._session = sparkapi.CiscoSparkAPI(self._bot_token)
self.bot_identifier = CiscoSparkPerson(self, self._session.people.me())
log.debug("Done! I'm connected as {} : {} ".format(self.bot_identifier, self.bot_identifier.emails))
@property
def mode(self):
return 'CiscoSpark'
@property
def webhook_secret(self):
return self._webhook_secret
def create_webhook(self, url=None, name=CISCO_SPARK_WEBHOOK_ID, resource='messages', event='created', filter=None,
secret=None):
"""
Create a webhook that the bot can consume
:param url: The URL the webhook is to publish towards (by default the bots webhook will be used)
:param name: The name that will be given to the Webhook
:param resource: The type of resource that we want Cisco Spark to monitor
:param event: The type of event that we want Cisco Spark to monitor
:param filter: Any filters that will limit to which events Cisco Spark will listen (e.g. roomId)
:param secret: The secret used to create a signature for the JSON payload
:return: A Webhook object
"""
if not url:
url = self._webhook_destination
if not secret:
secret = self.webhook_secret
log.debug("Registering webhook {} with filter {}".format(url, filter))
hook = self.session.webhooks.create(name, url, resource, event, filter, secret)
log.debug("Registration successful")
return hook
def delete_webhook(self, webhook):
"""
Delete a webhook
:param webhook: Cisco Spark Webhook ID
"""
log.debug("Deleting webhook id {}".format(webhook.id))
self.session.webhooks.delete(webhook.id)
log.debug("Done! Webhook deleted")
def delete_webhooks(self):
"""
Delete all webhooks for the bot that have the webhook name CISCO_SPARK_WEBHOOK_ID
"""
log.debug("Deleting ALL webhooks attached to rooms")
for hook in self.session.webhooks.list():
if hook.name == CISCO_SPARK_WEBHOOK_ID:
filer, filter_id = hook.filter.split("=")
if filer == 'roomId':
if filter_id in self._bot_rooms:
self.delete_webhook(hook)
log.debug("Done! ALL webhooks deleted")
# The following are convenience methods to make it easier to create objects from the err-cisco-spark-webhook plugin
def get_person_using_email(self, email):
"""
Loads a person from Spark using the email address for the search criteria
:param email: The email address to use for the search
:return: CiscoSparkPerson
"""
return CiscoSparkPerson.find_using_email(self._session, email)
def get_person_using_id(self, id):
"""
Loads a person from Spark using the spark id for the search criteria
:param id: The spark id to use for the search
:return: CiscoSparkPerson
"""
return CiscoSparkPerson.get_using_id(self._session, id)
def create_person_using_id(self, id):
"""
Create a new person and sets the ID. This method DOES NOT load the person details from Spark
:param id: The spark id of the person
:return: CiscoSparkPerson
"""
person = CiscoSparkPerson(self)
person.id = id
return person
def get_room_using_id(self, id):
"""
Loads a room from Spark using the id for the search criteria
:param id: The Spark id of the room
:return: CiscoSparkRoom
"""
return CiscoSparkRoom.get_using_id(self, id)
def create_room_using_id(self, id):
"""
Create a new room and sets the ID. This method DOES NOT load the room details from Spark
:param id:
:return:
"""
room = CiscoSparkRoom(self)
room.id = id
return room
def create_message(self, body, frm, to, extras):
"""
Creates a new message ready for sending
:param body: The text that contains the message to be sent
:param frm: A CiscoSparkPerson from whom the message will originate
:param to: A CiscoSparkPerson to whom the message will be sent
:param extras: A dictionary of extra items
:return: CiscoSparkMessage
"""
return CiscoSparkMessage(body=body, frm=frm, to=to, extras=extras)
def get_message_using_id(self, id):
"""
Loads a message from Spark using the id for the search criteria
:param id: The id of the message to load
:return: Message
"""
return self.session.messages.get(id)
def get_occupant_using_id(self, person, room):
"""
Builds a CiscoSparkRoomOccupant using a person and a room
:param person: A CiscoSparkPerson
:param room: A CiscoSparkRoom
:return: CiscoSparkRoomOccupant
"""
return CiscoSparkRoomOccupant(bot=self, person=person, room=room)
@property
def session(self):
"""
The session handle for sparkapi.CiscoSparkAPI
:return:
"""
return self._session
def follow_room(self, room):
"""
Backend: Follow Room yet to be implemented
:param room:
:return:
"""
log.debug("Backend: Follow Room yet to be implemented") # TODO
pass
def rooms(self):
"""
Backend: Rooms yet to be implemented
:return:
"""
log.debug("Backend: Rooms yet to be implemented") # TODO
pass
def contacts(self):
"""
Backend: Contacts yet to be implemented
:return:
"""
log.debug("Backend: Contacts yet to be implemented") # TODO
pass
def build_identifier(self, strrep):
"""
Build an errbot identifier using the Spark ID of the person
:param strrep: The ID of the Cisco Spark person
:return: CiscoSparkPerson
"""
return self.create_person_using_id(strrep)
def query_room(self, room):
"""
Create a CiscoSparkRoom object identified by the ID of the room
:param room: The Cisco Spark room ID
:return: CiscoSparkRoom object
"""
return CiscoSparkRoom.get_using_id(self, room)
def send_message(self, mess):
"""
Send a message to Cisco Spark
:param mess: A CiscoSparkMessage
"""
md = markdown(mess.body, extensions=['markdown.extensions.nl2br', 'markdown.extensions.fenced_code'])
if type(mess.to) == CiscoSparkPerson:
self.session.messages.create(toPersonId=mess.to.id, text=mess.body, markdown=md)
else:
self.session.messages.create(roomId=mess.to.room.id, text=mess.body, markdown=md)
def build_reply(self, mess, text=None, private=False, threaded=False):
"""
Build a reply in the format expected by errbot by swapping the to and from source and destination
:param mess: The original CiscoSparkMessage object that will be replied to
:param text: The text that is to be sent in reply to the message
:param private: Boolean indiciating whether the message should be directed as a private message in lieu of
sending it back to the room
:return: CiscoSparkMessage
"""
response = self.build_message(text)
response.frm = mess.to
response.to = mess.frm
return response
def disconnect_callback(self):
"""
Disconnection has been requested, lets make sure we clean up our per-room webhooks
"""
self.delete_webhooks()
super().disconnect_callback()
def serve_once(self):
"""
Signal that we are connected to the Spark Service and hang around waiting for disconnection request
As Cisco Spark uses Webhooks for integration there is no need to kick-off threads to listen to channels/rooms.
We just hand around relying on the err-backend-cisco-spark plugin to feed the backend.
"""
self.connect_callback()
try:
while True:
time.sleep(2)
except KeyboardInterrupt:
log.info("Interrupt received, shutting down..")
return True
finally:
self.disconnect_callback()
def change_presence(self, status, message):
"""
Backend: Change presence yet to be implemented
:param status:
:param message:
:return:
"""
log.debug("Backend: Change presence yet to be implemented") # TODO
pass
def prefix_groupchat_reply(self, message, identifier):
"""
Backend: Prefix group chat reply yet to be implemented
:param message:
:param identifier:
:return:
"""
log.debug("Backend: Prefix group chat reply yet to be implemented") # TODO
pass
def remember(self, id, key, value):
"""
Save the value of a key to a dictionary specific to a Spark room or person
This is available in backend to provide easy access to variables that can be shared between plugins
:param id: Spark ID of room or person
:param key: The dictionary key
:param value: The value to be assigned to the key
"""
values = self.recall(id)
values[key] = value
self[id] = values
def forget(self, id, key):
"""
Delete a key from a dictionary specific to a Spark room or person
:param id: Spark ID of room or person
:param key: The dictionary key
:return: The popped value or None if the key was not found
"""
values = self.recall(id)
value = values.pop(key, None)
self[id] = values
return value
def recall(self, id):
"""
Access a dictionary for a room or person using the Spark ID as the key
:param id: Spark ID of room or person
:return: A dictionary. If no dictionary was found an empty dictionary will be returned.
"""
values = self.get(id)
return values if values else {}
def recall_key(self, id, key):
"""
Access the value of a specific key from a Spark room or person dictionary
:param id: Spark ID of room or person
:param key: The dictionary key
:return: Either the value of the key or None if the key is not found
"""
return self.recall(id).get(key)