sparker.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. #
  2. # Copyright (c) 2017-2019 Joe Clarke <jclarke@cisco.com>
  3. # All rights reserved.
  4. #
  5. # Redistribution and use in source and binary forms, with or without
  6. # modification, are permitted provided that the following conditions
  7. # are met:
  8. # 1. Redistributions of source code must retain the above copyright
  9. # notice, this list of conditions and the following disclaimer.
  10. # 2. Redistributions in binary form must reproduce the above copyright
  11. # notice, this list of conditions and the following disclaimer in the
  12. # documentation and/or other materials provided with the distribution.
  13. #
  14. # THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  15. # ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  16. # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  17. # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  18. # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  19. # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  20. # OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  21. # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  22. # LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  23. # OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  24. # SUCH DAMAGE.
  25. import requests
  26. from requests_toolbelt import MultipartEncoder
  27. from io import BytesIO
  28. import logging
  29. import time
  30. from enum import Enum, unique
  31. @unique
  32. class ResourceType(Enum):
  33. ROOM = 1
  34. TEAM = 2
  35. @unique
  36. class MessageType(Enum):
  37. GOOD = "✅ "
  38. BAD = "🚨🚨 "
  39. WARNING = "✴️ "
  40. NEUTRAL = ""
  41. class Sparker:
  42. SPARK_API = "https://api.ciscospark.com/v1/"
  43. RETRIES = 5
  44. MAX_MSG_LEN = 7430
  45. _headers = {"authorization": None, "content-type": "application/json"}
  46. _logit = False
  47. def __init__(self, **kwargs):
  48. if "logit" in kwargs:
  49. self._logit = kwargs["logit"]
  50. if "token" in kwargs:
  51. self._headers["authorization"] = "Bearer " + kwargs["token"]
  52. self._team_cache = {}
  53. self._room_cache = {}
  54. @staticmethod
  55. def _request_with_retry(*args, **kwargs):
  56. backoff = 1
  57. i = 0
  58. while True:
  59. try:
  60. response = requests.request(*args, **kwargs)
  61. response.raise_for_status()
  62. return response
  63. except Exception as e:
  64. if (response.status_code != 429 and response.status_code != 503 and response.status_code != 400) or i == Sparker.RETRIES:
  65. return response
  66. if response.status_code == 400:
  67. print("XXX: Body is {}".format(response.text))
  68. time.sleep(backoff)
  69. backoff *= 2
  70. i += 1
  71. @staticmethod
  72. def _get_items_pages(*args, **kwargs):
  73. more_pages = True
  74. result = []
  75. while more_pages:
  76. try:
  77. response = Sparker._request_with_retry(*args, **kwargs)
  78. response.raise_for_status()
  79. result += response.json()["items"]
  80. if "Link" in response.headers:
  81. links = requests.utils.parse_header_links(response.headers["Link"])
  82. found_next = False
  83. for link in links:
  84. if link["rel"] == "next":
  85. args = (args[0], link["url"])
  86. kwargs.pop("params", None)
  87. found_next = True
  88. break
  89. if found_next:
  90. continue
  91. more_pages = False
  92. else:
  93. more_pages = False
  94. except Exception as e:
  95. raise e
  96. return result
  97. def set_token(self, token):
  98. self._headers["authorization"] = "Bearer " + token
  99. def check_token(self):
  100. if self._headers["authorization"] is None:
  101. if self._logit:
  102. logging.error("Spark token is not set!")
  103. else:
  104. print("Spark token is not set!")
  105. return False
  106. return True
  107. def get_message(self, mid):
  108. if not self.check_token():
  109. return None
  110. url = self.SPARK_API + "messages" + "/" + mid
  111. try:
  112. response = Sparker._request_with_retry("GET", url, headers=self._headers)
  113. response.raise_for_status()
  114. except Exception as e:
  115. msg = "Error getting message with ID {}: {}".format(mid, getattr(e, "message", repr(e)))
  116. if self._logit:
  117. logging.error(msg)
  118. else:
  119. print(msg)
  120. return None
  121. return response.json()
  122. def get_team_id(self, team):
  123. if not self.check_token():
  124. return None
  125. if team in self._team_cache:
  126. return self._team_cache[team]
  127. url = self.SPARK_API + "teams"
  128. try:
  129. items = Sparker._get_items_pages("GET", url, headers=self._headers)
  130. except Exception as e:
  131. msg = "Error retrieving teams: {}".format(getattr(e, "message", repr(e)))
  132. if self._logit:
  133. logging.error(msg)
  134. else:
  135. print(msg)
  136. return None
  137. team_id = None
  138. for t in items:
  139. if "name" in t and t["name"] == team:
  140. self._team_cache[team] = t["id"]
  141. return t["id"]
  142. if team_id is None:
  143. msg = "Error finding team ID for {}".format(team)
  144. if self._logit:
  145. logging.error(msg)
  146. else:
  147. print(msg)
  148. return None
  149. def get_room_id(self, team_id, room):
  150. if not self.check_token():
  151. return None
  152. if team_id is None:
  153. team_id = ""
  154. if "{}:{}".format(team_id, room) in self._room_cache:
  155. return self._room_cache["{}:{}".format(team_id, room)]
  156. url = self.SPARK_API + "rooms"
  157. params = {}
  158. if team_id != "":
  159. params["teamId"] = team_id
  160. try:
  161. items = Sparker._get_items_pages("GET", url, headers=self._headers, params=params)
  162. except Exception as e:
  163. msg = "Error retrieving room {}: {}".format(room, getattr(e, "message", repr(e)))
  164. if self._logit:
  165. logging.error(msg)
  166. else:
  167. print(msg)
  168. return None
  169. room_id = None
  170. for r in items:
  171. if "title" in r and r["title"] == room:
  172. self._room_cache["{}:{}".format(team_id, room)] = r["id"]
  173. return r["id"]
  174. if room_id is None:
  175. msg = "Failed to find room ID for {}".format(room)
  176. if self._logit:
  177. logging.error(msg)
  178. else:
  179. print(msg)
  180. return None
  181. def get_members(self, resource, type=ResourceType.TEAM):
  182. if not self.check_token():
  183. return None
  184. payload = {}
  185. url = self.SPARK_API
  186. if type == ResourceType.TEAM:
  187. rid = self.get_team_id(resource)
  188. if rid is None:
  189. return None
  190. url += "team/memberships"
  191. payload["teamId"] = rid
  192. elif type == ResourceType.ROOM:
  193. rid = self.get_room_id(None, resource)
  194. if rid is None:
  195. return None
  196. url += "memberships"
  197. payload["roomId"] = rid
  198. else:
  199. msg = "Resource type must be TEAM or ROOM"
  200. if self._logit:
  201. logging.error(msg)
  202. else:
  203. print(msg)
  204. return None
  205. try:
  206. items = Sparker._get_items_pages("GET", url, params=payload, headers=self._headers)
  207. except Exception as e:
  208. msg = "Error getting resource membership: {}".format(getattr(e, "message", repr(e)))
  209. if self._logit:
  210. logging.error(msg)
  211. else:
  212. print(msg)
  213. return None
  214. return items
  215. def add_members(self, members, resource, type=ResourceType.TEAM):
  216. if not self.check_token():
  217. return None
  218. payload = {"isModerator": False}
  219. url = self.SPARK_API
  220. err_occurred = False
  221. if type == ResourceType.TEAM:
  222. rid = self.get_team_id(resource)
  223. if rid is None:
  224. return False
  225. url += "team/memberships"
  226. payload["teamId"] = rid
  227. elif type == ResourceType.ROOM:
  228. rid = self.get_room_id(None, resource)
  229. if rid is None:
  230. return False
  231. url += "memberships"
  232. payload["roomId"] = rid
  233. else:
  234. msg = "Resource type must be TEAM or ROOM"
  235. if self._logit:
  236. logging.error(msg)
  237. else:
  238. print(msg)
  239. return False
  240. mem_list = members
  241. if not isinstance(members, list):
  242. mem_list = [members]
  243. for member in mem_list:
  244. try:
  245. if "personId" in member:
  246. payload["personId"] = member["personId"]
  247. payload.pop("personEmail", None)
  248. else:
  249. payload["personEmail"] = member["personEmail"]
  250. payload.pop("personId", None)
  251. response = Sparker._request_with_retry("POST", url, json=payload, headers=self._headers)
  252. response.raise_for_status()
  253. except Exception as e:
  254. msg = "Error adding member %s to %s: %s" % (member, resource, getattr(e, "message", repr(e)),)
  255. if self._logit:
  256. logging.error(msg)
  257. else:
  258. print(msg)
  259. err_occurred = True
  260. return not err_occurred
  261. def post_to_spark(self, team, room, msg, mtype=MessageType.NEUTRAL):
  262. if not self.check_token():
  263. return None
  264. mt = None
  265. try:
  266. mt = MessageType(mtype)
  267. except Exception as e:
  268. msg = "Invalid message type: {}".format(getattr(e, "message", repr(e)))
  269. if self._logit:
  270. logging.error(msg)
  271. else:
  272. print(msg)
  273. return False
  274. team_id = None
  275. if team is not None:
  276. team_id = self.get_team_id(team)
  277. if team_id is None:
  278. return False
  279. room_id = self.get_room_id(team_id, room)
  280. if room_id is None:
  281. return False
  282. url = self.SPARK_API + "messages"
  283. payload = {
  284. "roomId": room_id,
  285. "markdown": mt.value + ((msg[: Sparker.MAX_MSG_LEN] + "...") if len(msg) > Sparker.MAX_MSG_LEN else msg),
  286. }
  287. try:
  288. response = Sparker._request_with_retry("POST", url, json=payload, headers=self._headers)
  289. response.raise_for_status()
  290. except Exception as e:
  291. msg = "Error posting message: {}".format(getattr(e, "message", repr(e)))
  292. if self._logit:
  293. logging.error(msg)
  294. else:
  295. print(msg)
  296. return False
  297. return True
  298. def post_to_spark_with_attach(self, team, room, msg, attach, fname, ftype, mtype=MessageType.NEUTRAL):
  299. if not self.check_token():
  300. return None
  301. mt = None
  302. try:
  303. mt = MessageType(mtype)
  304. except Exception as e:
  305. msg = "Invalid message type: {}".format(getattr(e, "message", repr(e)))
  306. if self._logit:
  307. logging.error(msg)
  308. else:
  309. print(msg)
  310. return False
  311. team_id = None
  312. if team is not None:
  313. team_id = self.get_team_id(team)
  314. if team_id is None:
  315. return False
  316. room_id = self.get_room_id(team_id, room)
  317. if room_id is None:
  318. return False
  319. url = self.SPARK_API + "messages"
  320. bio = BytesIO(attach)
  321. payload = {
  322. "roomId": room_id,
  323. "markdown": mt.value + ((msg[: Sparker.MAX_MSG_LEN] + "...") if len(msg) > Sparker.MAX_MSG_LEN else msg),
  324. "files": (fname, bio, ftype),
  325. }
  326. m = MultipartEncoder(fields=payload)
  327. headers = self._headers
  328. headers["content-type"] = m.content_type
  329. try:
  330. response = Sparker._request_with_retry("POST", url, data=m, headers=headers)
  331. response.raise_for_status()
  332. except Exception as e:
  333. msg = "Error posting message: {}".format(getattr(e, "message", repr(e)))
  334. if self._logit:
  335. logging.error(msg)
  336. else:
  337. print(msg)
  338. return False
  339. return True