My dotfiles for my Linux rice managed with stow and make
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

5080 lines
192 KiB

  1. # Copyright (c) 2014-2016 Ryan Huber <rhuber@gmail.com>
  2. # Copyright (c) 2015-2018 Tollef Fog Heen <tfheen@err.no>
  3. # Copyright (c) 2015-2020 Trygve Aaberge <trygveaa@gmail.com>
  4. # Released under the MIT license.
  5. from __future__ import print_function, unicode_literals
  6. from collections import OrderedDict
  7. from datetime import date, datetime, timedelta
  8. from functools import partial, wraps
  9. from io import StringIO
  10. from itertools import chain, count, islice
  11. import errno
  12. import textwrap
  13. import time
  14. import json
  15. import hashlib
  16. import os
  17. import re
  18. import sys
  19. import traceback
  20. import collections
  21. import ssl
  22. import random
  23. import socket
  24. import string
  25. # Prevent websocket from using numpy (it's an optional dependency). We do this
  26. # because numpy causes python (and thus weechat) to crash when it's reloaded.
  27. # See https://github.com/numpy/numpy/issues/11925
  28. sys.modules["numpy"] = None
  29. from websocket import ABNF, create_connection, WebSocketConnectionClosedException
  30. try:
  31. basestring # Python 2
  32. unicode
  33. str = unicode
  34. except NameError: # Python 3
  35. basestring = unicode = str
  36. try:
  37. from urllib.parse import urlencode
  38. except ImportError:
  39. from urllib import urlencode
  40. try:
  41. from json import JSONDecodeError
  42. except:
  43. JSONDecodeError = ValueError
  44. # hack to make tests possible.. better way?
  45. try:
  46. import weechat
  47. except ImportError:
  48. pass
  49. SCRIPT_NAME = "slack"
  50. SCRIPT_AUTHOR = "Ryan Huber <rhuber@gmail.com>"
  51. SCRIPT_VERSION = "2.5.0"
  52. SCRIPT_LICENSE = "MIT"
  53. SCRIPT_DESC = "Extends weechat for typing notification/search/etc on slack.com"
  54. REPO_URL = "https://github.com/wee-slack/wee-slack"
  55. BACKLOG_SIZE = 200
  56. SCROLLBACK_SIZE = 500
  57. RECORD_DIR = "/tmp/weeslack-debug"
  58. SLACK_API_TRANSLATOR = {
  59. "channel": {
  60. "history": "channels.history",
  61. "join": "conversations.join",
  62. "leave": "conversations.leave",
  63. "mark": "channels.mark",
  64. "info": "channels.info",
  65. },
  66. "im": {
  67. "history": "im.history",
  68. "join": "conversations.open",
  69. "leave": "conversations.close",
  70. "mark": "im.mark",
  71. },
  72. "mpim": {
  73. "history": "mpim.history",
  74. "join": "mpim.open", # conversations.open lacks unread_count_display
  75. "leave": "conversations.close",
  76. "mark": "mpim.mark",
  77. "info": "groups.info",
  78. },
  79. "group": {
  80. "history": "groups.history",
  81. "join": "conversations.join",
  82. "leave": "conversations.leave",
  83. "mark": "groups.mark",
  84. "info": "groups.info"
  85. },
  86. "private": {
  87. "history": "conversations.history",
  88. "join": "conversations.join",
  89. "leave": "conversations.leave",
  90. "mark": "conversations.mark",
  91. "info": "conversations.info",
  92. },
  93. "shared": {
  94. "history": "conversations.history",
  95. "join": "conversations.join",
  96. "leave": "conversations.leave",
  97. "mark": "channels.mark",
  98. "info": "conversations.info",
  99. },
  100. "thread": {
  101. "history": None,
  102. "join": None,
  103. "leave": None,
  104. "mark": None,
  105. }
  106. }
  107. ###### Decorators have to be up here
  108. def slack_buffer_or_ignore(f):
  109. """
  110. Only run this function if we're in a slack buffer, else ignore
  111. """
  112. @wraps(f)
  113. def wrapper(data, current_buffer, *args, **kwargs):
  114. if current_buffer not in EVENTROUTER.weechat_controller.buffers:
  115. return w.WEECHAT_RC_OK
  116. return f(data, current_buffer, *args, **kwargs)
  117. return wrapper
  118. def slack_buffer_required(f):
  119. """
  120. Only run this function if we're in a slack buffer, else print error
  121. """
  122. @wraps(f)
  123. def wrapper(data, current_buffer, *args, **kwargs):
  124. if current_buffer not in EVENTROUTER.weechat_controller.buffers:
  125. command_name = f.__name__.replace('command_', '', 1)
  126. w.prnt('', 'slack: command "{}" must be executed on slack buffer'.format(command_name))
  127. return w.WEECHAT_RC_ERROR
  128. return f(data, current_buffer, *args, **kwargs)
  129. return wrapper
  130. def utf8_decode(f):
  131. """
  132. Decode all arguments from byte strings to unicode strings. Use this for
  133. functions called from outside of this script, e.g. callbacks from weechat.
  134. """
  135. @wraps(f)
  136. def wrapper(*args, **kwargs):
  137. return f(*decode_from_utf8(args), **decode_from_utf8(kwargs))
  138. return wrapper
  139. NICK_GROUP_HERE = "0|Here"
  140. NICK_GROUP_AWAY = "1|Away"
  141. NICK_GROUP_EXTERNAL = "2|External"
  142. sslopt_ca_certs = {}
  143. if hasattr(ssl, "get_default_verify_paths") and callable(ssl.get_default_verify_paths):
  144. ssl_defaults = ssl.get_default_verify_paths()
  145. if ssl_defaults.cafile is not None:
  146. sslopt_ca_certs = {'ca_certs': ssl_defaults.cafile}
  147. EMOJI = {}
  148. EMOJI_WITH_SKIN_TONES_REVERSE = {}
  149. ###### Unicode handling
  150. def encode_to_utf8(data):
  151. if sys.version_info.major > 2:
  152. return data
  153. elif isinstance(data, unicode):
  154. return data.encode('utf-8')
  155. if isinstance(data, bytes):
  156. return data
  157. elif isinstance(data, collections.Mapping):
  158. return type(data)(map(encode_to_utf8, data.items()))
  159. elif isinstance(data, collections.Iterable):
  160. return type(data)(map(encode_to_utf8, data))
  161. else:
  162. return data
  163. def decode_from_utf8(data):
  164. if sys.version_info.major > 2:
  165. return data
  166. elif isinstance(data, bytes):
  167. return data.decode('utf-8')
  168. if isinstance(data, unicode):
  169. return data
  170. elif isinstance(data, collections.Mapping):
  171. return type(data)(map(decode_from_utf8, data.items()))
  172. elif isinstance(data, collections.Iterable):
  173. return type(data)(map(decode_from_utf8, data))
  174. else:
  175. return data
  176. class WeechatWrapper(object):
  177. def __init__(self, wrapped_class):
  178. self.wrapped_class = wrapped_class
  179. # Helper method used to encode/decode method calls.
  180. def wrap_for_utf8(self, method):
  181. def hooked(*args, **kwargs):
  182. result = method(*encode_to_utf8(args), **encode_to_utf8(kwargs))
  183. # Prevent wrapped_class from becoming unwrapped
  184. if result == self.wrapped_class:
  185. return self
  186. return decode_from_utf8(result)
  187. return hooked
  188. # Encode and decode everything sent to/received from weechat. We use the
  189. # unicode type internally in wee-slack, but has to send utf8 to weechat.
  190. def __getattr__(self, attr):
  191. orig_attr = self.wrapped_class.__getattribute__(attr)
  192. if callable(orig_attr):
  193. return self.wrap_for_utf8(orig_attr)
  194. else:
  195. return decode_from_utf8(orig_attr)
  196. # Ensure all lines sent to weechat specifies a prefix. For lines after the
  197. # first, we want to disable the prefix, which is done by specifying a space.
  198. def prnt_date_tags(self, buffer, date, tags, message):
  199. message = message.replace("\n", "\n \t")
  200. return self.wrap_for_utf8(self.wrapped_class.prnt_date_tags)(buffer, date, tags, message)
  201. class ProxyWrapper(object):
  202. def __init__(self):
  203. self.proxy_name = w.config_string(w.config_get('weechat.network.proxy_curl'))
  204. self.proxy_string = ""
  205. self.proxy_type = ""
  206. self.proxy_address = ""
  207. self.proxy_port = ""
  208. self.proxy_user = ""
  209. self.proxy_password = ""
  210. self.has_proxy = False
  211. if self.proxy_name:
  212. self.proxy_string = "weechat.proxy.{}".format(self.proxy_name)
  213. self.proxy_type = w.config_string(w.config_get("{}.type".format(self.proxy_string)))
  214. if self.proxy_type == "http":
  215. self.proxy_address = w.config_string(w.config_get("{}.address".format(self.proxy_string)))
  216. self.proxy_port = w.config_integer(w.config_get("{}.port".format(self.proxy_string)))
  217. self.proxy_user = w.config_string(w.config_get("{}.username".format(self.proxy_string)))
  218. self.proxy_password = w.config_string(w.config_get("{}.password".format(self.proxy_string)))
  219. self.has_proxy = True
  220. else:
  221. w.prnt("", "\nWarning: weechat.network.proxy_curl is set to {} type (name : {}, conf string : {}). Only HTTP proxy is supported.\n\n".format(self.proxy_type, self.proxy_name, self.proxy_string))
  222. def curl(self):
  223. if not self.has_proxy:
  224. return ""
  225. if self.proxy_user and self.proxy_password:
  226. user = "{}:{}@".format(self.proxy_user, self.proxy_password)
  227. else:
  228. user = ""
  229. if self.proxy_port:
  230. port = ":{}".format(self.proxy_port)
  231. else:
  232. port = ""
  233. return "-x{}{}{}".format(user, self.proxy_address, port)
  234. ##### Helpers
  235. def colorize_string(color, string, reset_color='reset'):
  236. if color:
  237. return w.color(color) + string + w.color(reset_color)
  238. else:
  239. return string
  240. def print_error(message, buffer='', warning=False):
  241. prefix = 'Warning' if warning else 'Error'
  242. w.prnt(buffer, '{}{}: {}'.format(w.prefix('error'), prefix, message))
  243. def token_for_print(token):
  244. return '{}...{}'.format(token[:15], token[-10:])
  245. def format_exc_tb():
  246. return decode_from_utf8(traceback.format_exc())
  247. def format_exc_only():
  248. etype, value, _ = sys.exc_info()
  249. return ''.join(decode_from_utf8(traceback.format_exception_only(etype, value)))
  250. def get_nick_color(nick):
  251. info_name_prefix = "irc_" if int(weechat_version) < 0x1050000 else ""
  252. return w.info_get(info_name_prefix + "nick_color_name", nick)
  253. def get_thread_color(thread_id):
  254. if config.color_thread_suffix == 'multiple':
  255. return get_nick_color(thread_id)
  256. else:
  257. return config.color_thread_suffix
  258. def sha1_hex(s):
  259. return hashlib.sha1(s.encode('utf-8')).hexdigest()
  260. def get_functions_with_prefix(prefix):
  261. return {name[len(prefix):]: ref for name, ref in globals().items()
  262. if name.startswith(prefix)}
  263. def handle_socket_error(exception, team, caller_name):
  264. if not (isinstance(exception, WebSocketConnectionClosedException) or
  265. exception.errno in (errno.EPIPE, errno.ECONNRESET, errno.ETIMEDOUT)):
  266. raise
  267. w.prnt(team.channel_buffer,
  268. 'Lost connection to slack team {} (on {}), reconnecting.'.format(
  269. team.domain, caller_name))
  270. dbg('Socket failed on {} with exception:\n{}'.format(
  271. caller_name, format_exc_tb()), level=5)
  272. team.set_disconnected()
  273. EMOJI_NAME_REGEX = re.compile(':([^: ]+):')
  274. EMOJI_REGEX_STRING = '[\U00000080-\U0010ffff]+'
  275. def regex_match_to_emoji(match, include_name=False):
  276. emoji = match.group(1)
  277. full_match = match.group()
  278. char = EMOJI.get(emoji, full_match)
  279. if include_name and char != full_match:
  280. return '{} ({})'.format(char, full_match)
  281. return char
  282. def replace_string_with_emoji(text):
  283. if config.render_emoji_as_string == 'both':
  284. return EMOJI_NAME_REGEX.sub(
  285. partial(regex_match_to_emoji, include_name=True),
  286. text,
  287. )
  288. elif config.render_emoji_as_string:
  289. return text
  290. return EMOJI_NAME_REGEX.sub(regex_match_to_emoji, text)
  291. def replace_emoji_with_string(text):
  292. return EMOJI_WITH_SKIN_TONES_REVERSE.get(text, text)
  293. ###### New central Event router
  294. class EventRouter(object):
  295. def __init__(self):
  296. """
  297. complete
  298. Eventrouter is the central hub we use to route:
  299. 1) incoming websocket data
  300. 2) outgoing http requests and incoming replies
  301. 3) local requests
  302. It has a recorder that, when enabled, logs most events
  303. to the location specified in RECORD_DIR.
  304. """
  305. self.queue = []
  306. self.slow_queue = []
  307. self.slow_queue_timer = 0
  308. self.teams = {}
  309. self.subteams = {}
  310. self.context = {}
  311. self.weechat_controller = WeechatController(self)
  312. self.previous_buffer = ""
  313. self.reply_buffer = {}
  314. self.cmds = get_functions_with_prefix("command_")
  315. self.proc = get_functions_with_prefix("process_")
  316. self.handlers = get_functions_with_prefix("handle_")
  317. self.local_proc = get_functions_with_prefix("local_process_")
  318. self.shutting_down = False
  319. self.recording = False
  320. self.recording_path = "/tmp"
  321. self.handle_next_hook = None
  322. self.handle_next_hook_interval = -1
  323. def record(self):
  324. """
  325. complete
  326. Toggles the event recorder and creates a directory for data if enabled.
  327. """
  328. self.recording = not self.recording
  329. if self.recording:
  330. if not os.path.exists(RECORD_DIR):
  331. os.makedirs(RECORD_DIR)
  332. def record_event(self, message_json, file_name_field, subdir=None):
  333. """
  334. complete
  335. Called each time you want to record an event.
  336. message_json is a json in dict form
  337. file_name_field is the json key whose value you want to be part of the file name
  338. """
  339. now = time.time()
  340. if subdir:
  341. directory = "{}/{}".format(RECORD_DIR, subdir)
  342. else:
  343. directory = RECORD_DIR
  344. if not os.path.exists(directory):
  345. os.makedirs(directory)
  346. mtype = message_json.get(file_name_field, 'unknown')
  347. f = open('{}/{}-{}.json'.format(directory, now, mtype), 'w')
  348. f.write("{}".format(json.dumps(message_json)))
  349. f.close()
  350. def store_context(self, data):
  351. """
  352. A place to store data and vars needed by callback returns. We need this because
  353. weechat's "callback_data" has a limited size and weechat will crash if you exceed
  354. this size.
  355. """
  356. identifier = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(40))
  357. self.context[identifier] = data
  358. dbg("stored context {} {} ".format(identifier, data.url))
  359. return identifier
  360. def retrieve_context(self, identifier):
  361. """
  362. A place to retrieve data and vars needed by callback returns. We need this because
  363. weechat's "callback_data" has a limited size and weechat will crash if you exceed
  364. this size.
  365. """
  366. return self.context.get(identifier)
  367. def delete_context(self, identifier):
  368. """
  369. Requests can span multiple requests, so we may need to delete this as a last step
  370. """
  371. if identifier in self.context:
  372. del self.context[identifier]
  373. def shutdown(self):
  374. """
  375. complete
  376. This toggles shutdown mode. Shutdown mode tells us not to
  377. talk to Slack anymore. Without this, typing /quit will trigger
  378. a race with the buffer close callback and may result in you
  379. leaving every slack channel.
  380. """
  381. self.shutting_down = not self.shutting_down
  382. def register_team(self, team):
  383. """
  384. complete
  385. Adds a team to the list of known teams for this EventRouter.
  386. """
  387. if isinstance(team, SlackTeam):
  388. self.teams[team.get_team_hash()] = team
  389. else:
  390. raise InvalidType(type(team))
  391. def reconnect_if_disconnected(self):
  392. for team in self.teams.values():
  393. time_since_last_ping = time.time() - team.last_ping_time
  394. time_since_last_pong = time.time() - team.last_pong_time
  395. if team.connected and time_since_last_ping < 5 and time_since_last_pong > 30:
  396. w.prnt(team.channel_buffer,
  397. 'Lost connection to slack team {} (no pong), reconnecting.'.format(
  398. team.domain))
  399. team.set_disconnected()
  400. if not team.connected:
  401. team.connect()
  402. dbg("reconnecting {}".format(team))
  403. @utf8_decode
  404. def receive_ws_callback(self, team_hash, fd):
  405. """
  406. This is called by the global method of the same name.
  407. It is triggered when we have incoming data on a websocket,
  408. which needs to be read. Once it is read, we will ensure
  409. the data is valid JSON, add metadata, and place it back
  410. on the queue for processing as JSON.
  411. """
  412. team = self.teams[team_hash]
  413. while True:
  414. try:
  415. # Read the data from the websocket associated with this team.
  416. opcode, data = team.ws.recv_data(control_frame=True)
  417. except ssl.SSLWantReadError:
  418. # No more data to read at this time.
  419. return w.WEECHAT_RC_OK
  420. except (WebSocketConnectionClosedException, socket.error) as e:
  421. handle_socket_error(e, team, 'receive')
  422. return w.WEECHAT_RC_OK
  423. if opcode == ABNF.OPCODE_PONG:
  424. team.last_pong_time = time.time()
  425. return w.WEECHAT_RC_OK
  426. elif opcode != ABNF.OPCODE_TEXT:
  427. return w.WEECHAT_RC_OK
  428. message_json = json.loads(data.decode('utf-8'))
  429. message_json["wee_slack_metadata_team"] = team
  430. if self.recording:
  431. self.record_event(message_json, 'type', 'websocket')
  432. self.receive(message_json)
  433. return w.WEECHAT_RC_OK
  434. @utf8_decode
  435. def receive_httprequest_callback(self, data, command, return_code, out, err):
  436. """
  437. complete
  438. Receives the result of an http request we previously handed
  439. off to weechat (weechat bundles libcurl). Weechat can fragment
  440. replies, so it buffers them until the reply is complete.
  441. It is then populated with metadata here so we can identify
  442. where the request originated and route properly.
  443. """
  444. request_metadata = self.retrieve_context(data)
  445. dbg("RECEIVED CALLBACK with request of {} id of {} and code {} of length {}".format(request_metadata.request, request_metadata.response_id, return_code, len(out)))
  446. if return_code == 0:
  447. if len(out) > 0:
  448. if request_metadata.response_id not in self.reply_buffer:
  449. self.reply_buffer[request_metadata.response_id] = StringIO()
  450. self.reply_buffer[request_metadata.response_id].write(out)
  451. try:
  452. j = json.loads(self.reply_buffer[request_metadata.response_id].getvalue())
  453. except:
  454. pass
  455. # dbg("Incomplete json, awaiting more", True)
  456. try:
  457. j["wee_slack_process_method"] = request_metadata.request_normalized
  458. if self.recording:
  459. self.record_event(j, 'wee_slack_process_method', 'http')
  460. j["wee_slack_request_metadata"] = request_metadata
  461. self.reply_buffer.pop(request_metadata.response_id)
  462. self.receive(j)
  463. self.delete_context(data)
  464. except:
  465. dbg("HTTP REQUEST CALLBACK FAILED", True)
  466. pass
  467. # We got an empty reply and this is weird so just ditch it and retry
  468. else:
  469. dbg("length was zero, probably a bug..")
  470. self.delete_context(data)
  471. self.receive(request_metadata)
  472. elif return_code == -1:
  473. if request_metadata.response_id not in self.reply_buffer:
  474. self.reply_buffer[request_metadata.response_id] = StringIO()
  475. self.reply_buffer[request_metadata.response_id].write(out)
  476. else:
  477. self.reply_buffer.pop(request_metadata.response_id, None)
  478. self.delete_context(data)
  479. if request_metadata.request.startswith('rtm.'):
  480. retry_text = ('retrying' if request_metadata.should_try() else
  481. 'will not retry after too many failed attempts')
  482. w.prnt('', ('Failed connecting to slack team with token {}, {}. ' +
  483. 'If this persists, try increasing slack_timeout. Error: {}')
  484. .format(token_for_print(request_metadata.token), retry_text, err))
  485. dbg('rtm.start failed with return_code {}. stack:\n{}'
  486. .format(return_code, ''.join(traceback.format_stack())), level=5)
  487. self.receive(request_metadata)
  488. return w.WEECHAT_RC_OK
  489. def receive(self, dataobj):
  490. """
  491. complete
  492. Receives a raw object and places it on the queue for
  493. processing. Object must be known to handle_next or
  494. be JSON.
  495. """
  496. dbg("RECEIVED FROM QUEUE")
  497. self.queue.append(dataobj)
  498. def receive_slow(self, dataobj):
  499. """
  500. complete
  501. Receives a raw object and places it on the slow queue for
  502. processing. Object must be known to handle_next or
  503. be JSON.
  504. """
  505. dbg("RECEIVED FROM QUEUE")
  506. self.slow_queue.append(dataobj)
  507. def handle_next(self):
  508. """
  509. complete
  510. Main handler of the EventRouter. This is called repeatedly
  511. via callback to drain events from the queue. It also attaches
  512. useful metadata and context to events as they are processed.
  513. """
  514. wanted_interval = 100
  515. if len(self.slow_queue) > 0 or len(self.queue) > 0:
  516. wanted_interval = 10
  517. if self.handle_next_hook is None or wanted_interval != self.handle_next_hook_interval:
  518. if self.handle_next_hook:
  519. w.unhook(self.handle_next_hook)
  520. self.handle_next_hook = w.hook_timer(wanted_interval, 0, 0, "handle_next", "")
  521. self.handle_next_hook_interval = wanted_interval
  522. if len(self.slow_queue) > 0 and ((self.slow_queue_timer + 1) < time.time()):
  523. dbg("from slow queue", 0)
  524. self.queue.append(self.slow_queue.pop())
  525. self.slow_queue_timer = time.time()
  526. if len(self.queue) > 0:
  527. j = self.queue.pop(0)
  528. # Reply is a special case of a json reply from websocket.
  529. kwargs = {}
  530. if isinstance(j, SlackRequest):
  531. if j.should_try():
  532. if j.retry_ready():
  533. local_process_async_slack_api_request(j, self)
  534. else:
  535. self.slow_queue.append(j)
  536. else:
  537. dbg("Max retries for Slackrequest")
  538. else:
  539. if "reply_to" in j:
  540. dbg("SET FROM REPLY")
  541. function_name = "reply"
  542. elif "type" in j:
  543. dbg("SET FROM type")
  544. function_name = j["type"]
  545. elif "wee_slack_process_method" in j:
  546. dbg("SET FROM META")
  547. function_name = j["wee_slack_process_method"]
  548. else:
  549. dbg("SET FROM NADA")
  550. function_name = "unknown"
  551. request = j.get("wee_slack_request_metadata")
  552. if request:
  553. team = request.team
  554. channel = request.channel
  555. metadata = request.metadata
  556. else:
  557. team = j.get("wee_slack_metadata_team")
  558. channel = None
  559. metadata = {}
  560. if team:
  561. if "channel" in j:
  562. channel_id = j["channel"]["id"] if type(j["channel"]) == dict else j["channel"]
  563. channel = team.channels.get(channel_id, channel)
  564. if "user" in j:
  565. user_id = j["user"]["id"] if type(j["user"]) == dict else j["user"]
  566. metadata['user'] = team.users.get(user_id)
  567. dbg("running {}".format(function_name))
  568. if function_name.startswith("local_") and function_name in self.local_proc:
  569. self.local_proc[function_name](j, self, team, channel, metadata)
  570. elif function_name in self.proc:
  571. self.proc[function_name](j, self, team, channel, metadata)
  572. elif function_name in self.handlers:
  573. self.handlers[function_name](j, self, team, channel, metadata)
  574. else:
  575. dbg("Callback not implemented for event: {}".format(function_name))
  576. def handle_next(data, remaining_calls):
  577. try:
  578. EVENTROUTER.handle_next()
  579. except:
  580. if config.debug_mode:
  581. traceback.print_exc()
  582. else:
  583. pass
  584. return w.WEECHAT_RC_OK
  585. class WeechatController(object):
  586. """
  587. Encapsulates our interaction with weechat
  588. """
  589. def __init__(self, eventrouter):
  590. self.eventrouter = eventrouter
  591. self.buffers = {}
  592. self.previous_buffer = None
  593. self.buffer_list_stale = False
  594. def iter_buffers(self):
  595. for b in self.buffers:
  596. yield (b, self.buffers[b])
  597. def register_buffer(self, buffer_ptr, channel):
  598. """
  599. complete
  600. Adds a weechat buffer to the list of handled buffers for this EventRouter
  601. """
  602. if isinstance(buffer_ptr, basestring):
  603. self.buffers[buffer_ptr] = channel
  604. else:
  605. raise InvalidType(type(buffer_ptr))
  606. def unregister_buffer(self, buffer_ptr, update_remote=False, close_buffer=False):
  607. """
  608. complete
  609. Adds a weechat buffer to the list of handled buffers for this EventRouter
  610. """
  611. channel = self.buffers.get(buffer_ptr)
  612. if channel:
  613. channel.destroy_buffer(update_remote)
  614. del self.buffers[buffer_ptr]
  615. if close_buffer:
  616. w.buffer_close(buffer_ptr)
  617. def get_channel_from_buffer_ptr(self, buffer_ptr):
  618. return self.buffers.get(buffer_ptr)
  619. def get_all(self, buffer_ptr):
  620. return self.buffers
  621. def get_previous_buffer_ptr(self):
  622. return self.previous_buffer
  623. def set_previous_buffer(self, data):
  624. self.previous_buffer = data
  625. def check_refresh_buffer_list(self):
  626. return self.buffer_list_stale and self.last_buffer_list_update + 1 < time.time()
  627. def set_refresh_buffer_list(self, setting):
  628. self.buffer_list_stale = setting
  629. ###### New Local Processors
  630. def local_process_async_slack_api_request(request, event_router):
  631. """
  632. complete
  633. Sends an API request to Slack. You'll need to give this a well formed SlackRequest object.
  634. DEBUGGING!!! The context here cannot be very large. Weechat will crash.
  635. """
  636. if not event_router.shutting_down:
  637. weechat_request = 'url:{}'.format(request.request_string())
  638. weechat_request += '&nonce={}'.format(''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(4)))
  639. params = {'useragent': 'wee_slack {}'.format(SCRIPT_VERSION)}
  640. request.tried()
  641. context = event_router.store_context(request)
  642. # TODO: let flashcode know about this bug - i have to 'clear' the hashtable or retry requests fail
  643. w.hook_process_hashtable('url:', params, config.slack_timeout, "", context)
  644. w.hook_process_hashtable(weechat_request, params, config.slack_timeout, "receive_httprequest_callback", context)
  645. ###### New Callbacks
  646. @utf8_decode
  647. def ws_ping_cb(data, remaining_calls):
  648. for team in EVENTROUTER.teams.values():
  649. if team.ws and team.connected:
  650. try:
  651. team.ws.ping()
  652. team.last_ping_time = time.time()
  653. except (WebSocketConnectionClosedException, socket.error) as e:
  654. handle_socket_error(e, team, 'ping')
  655. return w.WEECHAT_RC_OK
  656. @utf8_decode
  657. def reconnect_callback(*args):
  658. EVENTROUTER.reconnect_if_disconnected()
  659. return w.WEECHAT_RC_OK
  660. @utf8_decode
  661. def buffer_closing_callback(signal, sig_type, data):
  662. """
  663. Receives a callback from weechat when a buffer is being closed.
  664. """
  665. EVENTROUTER.weechat_controller.unregister_buffer(data, True, False)
  666. return w.WEECHAT_RC_OK
  667. @utf8_decode
  668. def buffer_input_callback(signal, buffer_ptr, data):
  669. """
  670. incomplete
  671. Handles everything a user types in the input bar. In our case
  672. this includes add/remove reactions, modifying messages, and
  673. sending messages.
  674. """
  675. eventrouter = eval(signal)
  676. channel = eventrouter.weechat_controller.get_channel_from_buffer_ptr(buffer_ptr)
  677. if not channel:
  678. return w.WEECHAT_RC_ERROR
  679. def get_id(message_id):
  680. if not message_id:
  681. return 1
  682. elif message_id[0] == "$":
  683. return message_id[1:]
  684. else:
  685. return int(message_id)
  686. message_id_regex = r"(\d*|\$[0-9a-fA-F]{3,})"
  687. reaction = re.match(r"^{}(\+|-)(:(.+):|{})\s*$".format(message_id_regex, EMOJI_REGEX_STRING), data)
  688. substitute = re.match("^{}s/".format(message_id_regex), data)
  689. if reaction:
  690. emoji_match = reaction.group(4) or reaction.group(3)
  691. emoji = replace_emoji_with_string(emoji_match)
  692. if reaction.group(2) == "+":
  693. channel.send_add_reaction(get_id(reaction.group(1)), emoji)
  694. elif reaction.group(2) == "-":
  695. channel.send_remove_reaction(get_id(reaction.group(1)), emoji)
  696. elif substitute:
  697. msg_id = get_id(substitute.group(1))
  698. try:
  699. old, new, flags = re.split(r'(?<!\\)/', data)[1:]
  700. except ValueError:
  701. pass
  702. else:
  703. # Replacement string in re.sub() is a string, not a regex, so get
  704. # rid of escapes.
  705. new = new.replace(r'\/', '/')
  706. old = old.replace(r'\/', '/')
  707. channel.edit_nth_previous_message(msg_id, old, new, flags)
  708. else:
  709. if data.startswith(('//', ' ')):
  710. data = data[1:]
  711. channel.send_message(data)
  712. # this is probably wrong channel.mark_read(update_remote=True, force=True)
  713. return w.WEECHAT_RC_OK
  714. # Workaround for supporting multiline messages. It intercepts before the input
  715. # callback is called, as this is called with the whole message, while it is
  716. # normally split on newline before being sent to buffer_input_callback
  717. def input_text_for_buffer_cb(data, modifier, current_buffer, string):
  718. if current_buffer not in EVENTROUTER.weechat_controller.buffers:
  719. return string
  720. message = decode_from_utf8(string)
  721. if not message.startswith("/") and "\n" in message:
  722. buffer_input_callback("EVENTROUTER", current_buffer, message)
  723. return ""
  724. return string
  725. @utf8_decode
  726. def buffer_switch_callback(signal, sig_type, data):
  727. """
  728. Every time we change channels in weechat, we call this to:
  729. 1) set read marker 2) determine if we have already populated
  730. channel history data 3) set presence to active
  731. """
  732. eventrouter = eval(signal)
  733. prev_buffer_ptr = eventrouter.weechat_controller.get_previous_buffer_ptr()
  734. # this is to see if we need to gray out things in the buffer list
  735. prev = eventrouter.weechat_controller.get_channel_from_buffer_ptr(prev_buffer_ptr)
  736. if prev:
  737. prev.mark_read()
  738. new_channel = eventrouter.weechat_controller.get_channel_from_buffer_ptr(data)
  739. if new_channel:
  740. if not new_channel.got_history:
  741. new_channel.get_history()
  742. set_own_presence_active(new_channel.team)
  743. eventrouter.weechat_controller.set_previous_buffer(data)
  744. return w.WEECHAT_RC_OK
  745. @utf8_decode
  746. def buffer_list_update_callback(data, somecount):
  747. """
  748. incomplete
  749. A simple timer-based callback that will update the buffer list
  750. if needed. We only do this max 1x per second, as otherwise it
  751. uses a lot of cpu for minimal changes. We use buffer short names
  752. to indicate typing via "#channel" <-> ">channel" and
  753. user presence via " name" <-> "+name".
  754. """
  755. eventrouter = eval(data)
  756. for b in eventrouter.weechat_controller.iter_buffers():
  757. b[1].refresh()
  758. # buffer_list_update = True
  759. # if eventrouter.weechat_controller.check_refresh_buffer_list():
  760. # # gray_check = False
  761. # # if len(servers) > 1:
  762. # # gray_check = True
  763. # eventrouter.weechat_controller.set_refresh_buffer_list(False)
  764. return w.WEECHAT_RC_OK
  765. def quit_notification_callback(signal, sig_type, data):
  766. stop_talking_to_slack()
  767. return w.WEECHAT_RC_OK
  768. @utf8_decode
  769. def typing_notification_cb(data, signal, current_buffer):
  770. msg = w.buffer_get_string(current_buffer, "input")
  771. if len(msg) > 8 and msg[0] != "/":
  772. global typing_timer
  773. now = time.time()
  774. if typing_timer + 4 < now:
  775. channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
  776. if channel and channel.type != "thread":
  777. identifier = channel.identifier
  778. request = {"type": "typing", "channel": identifier}
  779. channel.team.send_to_websocket(request, expect_reply=False)
  780. typing_timer = now
  781. return w.WEECHAT_RC_OK
  782. @utf8_decode
  783. def typing_update_cb(data, remaining_calls):
  784. w.bar_item_update("slack_typing_notice")
  785. return w.WEECHAT_RC_OK
  786. @utf8_decode
  787. def slack_never_away_cb(data, remaining_calls):
  788. if config.never_away:
  789. for team in EVENTROUTER.teams.values():
  790. set_own_presence_active(team)
  791. return w.WEECHAT_RC_OK
  792. @utf8_decode
  793. def typing_bar_item_cb(data, item, current_window, current_buffer, extra_info):
  794. """
  795. Privides a bar item indicating who is typing in the current channel AND
  796. why is typing a DM to you globally.
  797. """
  798. typers = []
  799. current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
  800. # first look for people typing in this channel
  801. if current_channel:
  802. # this try is mostly becuase server buffers don't implement is_someone_typing
  803. try:
  804. if current_channel.type != 'im' and current_channel.is_someone_typing():
  805. typers += current_channel.get_typing_list()
  806. except:
  807. pass
  808. # here is where we notify you that someone is typing in DM
  809. # regardless of which buffer you are in currently
  810. for team in EVENTROUTER.teams.values():
  811. for channel in team.channels.values():
  812. if channel.type == "im":
  813. if channel.is_someone_typing():
  814. typers.append("D/" + channel.slack_name)
  815. pass
  816. typing = ", ".join(typers)
  817. if typing != "":
  818. typing = colorize_string(config.color_typing_notice, "typing: " + typing)
  819. return typing
  820. @utf8_decode
  821. def away_bar_item_cb(data, item, current_window, current_buffer, extra_info):
  822. channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
  823. if not channel:
  824. return ''
  825. if channel.team.is_user_present(channel.team.myidentifier):
  826. return ''
  827. else:
  828. away_color = w.config_string(w.config_get('weechat.color.item_away'))
  829. if channel.team.my_manual_presence == 'away':
  830. return colorize_string(away_color, 'manual away')
  831. else:
  832. return colorize_string(away_color, 'auto away')
  833. @utf8_decode
  834. def channel_completion_cb(data, completion_item, current_buffer, completion):
  835. """
  836. Adds all channels on all teams to completion list
  837. """
  838. current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
  839. should_include_channel = lambda channel: channel.active and channel.type in ['channel', 'group', 'private', 'shared']
  840. other_teams = [team for team in EVENTROUTER.teams.values() if not current_channel or team != current_channel.team]
  841. for team in other_teams:
  842. for channel in team.channels.values():
  843. if should_include_channel(channel):
  844. w.hook_completion_list_add(completion, channel.name, 0, w.WEECHAT_LIST_POS_SORT)
  845. if current_channel:
  846. for channel in sorted(current_channel.team.channels.values(), key=lambda channel: channel.name, reverse=True):
  847. if should_include_channel(channel):
  848. w.hook_completion_list_add(completion, channel.name, 0, w.WEECHAT_LIST_POS_BEGINNING)
  849. if should_include_channel(current_channel):
  850. w.hook_completion_list_add(completion, current_channel.name, 0, w.WEECHAT_LIST_POS_BEGINNING)
  851. return w.WEECHAT_RC_OK
  852. @utf8_decode
  853. def dm_completion_cb(data, completion_item, current_buffer, completion):
  854. """
  855. Adds all dms/mpdms on all teams to completion list
  856. """
  857. for team in EVENTROUTER.teams.values():
  858. for channel in team.channels.values():
  859. if channel.active and channel.type in ['im', 'mpim']:
  860. w.hook_completion_list_add(completion, channel.name, 0, w.WEECHAT_LIST_POS_SORT)
  861. return w.WEECHAT_RC_OK
  862. @utf8_decode
  863. def nick_completion_cb(data, completion_item, current_buffer, completion):
  864. """
  865. Adds all @-prefixed nicks to completion list
  866. """
  867. current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
  868. if current_channel is None or current_channel.members is None:
  869. return w.WEECHAT_RC_OK
  870. base_command = w.hook_completion_get_string(completion, "base_command")
  871. if base_command in ['invite', 'msg', 'query', 'whois']:
  872. members = current_channel.team.members
  873. else:
  874. members = current_channel.members
  875. for member in members:
  876. user = current_channel.team.users.get(member)
  877. if user and not user.deleted:
  878. w.hook_completion_list_add(completion, user.name, 1, w.WEECHAT_LIST_POS_SORT)
  879. w.hook_completion_list_add(completion, "@" + user.name, 1, w.WEECHAT_LIST_POS_SORT)
  880. return w.WEECHAT_RC_OK
  881. @utf8_decode
  882. def emoji_completion_cb(data, completion_item, current_buffer, completion):
  883. """
  884. Adds all :-prefixed emoji to completion list
  885. """
  886. current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
  887. if current_channel is None:
  888. return w.WEECHAT_RC_OK
  889. base_word = w.hook_completion_get_string(completion, "base_word")
  890. if ":" not in base_word:
  891. return w.WEECHAT_RC_OK
  892. prefix = base_word.split(":")[0] + ":"
  893. for emoji in current_channel.team.emoji_completions:
  894. w.hook_completion_list_add(completion, prefix + emoji + ":", 0, w.WEECHAT_LIST_POS_SORT)
  895. return w.WEECHAT_RC_OK
  896. @utf8_decode
  897. def thread_completion_cb(data, completion_item, current_buffer, completion):
  898. """
  899. Adds all $-prefixed thread ids to completion list
  900. """
  901. current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
  902. if current_channel is None or not hasattr(current_channel, 'hashed_messages'):
  903. return w.WEECHAT_RC_OK
  904. threads = current_channel.hashed_messages.items()
  905. for thread_id, message_ts in sorted(threads, key=lambda item: item[1]):
  906. message = current_channel.messages.get(message_ts)
  907. if message and message.number_of_replies():
  908. w.hook_completion_list_add(completion, "$" + thread_id, 0, w.WEECHAT_LIST_POS_BEGINNING)
  909. return w.WEECHAT_RC_OK
  910. @utf8_decode
  911. def topic_completion_cb(data, completion_item, current_buffer, completion):
  912. """
  913. Adds topic for current channel to completion list
  914. """
  915. current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
  916. if current_channel is None:
  917. return w.WEECHAT_RC_OK
  918. topic = current_channel.render_topic()
  919. channel_names = [channel.name for channel in current_channel.team.channels.values()]
  920. if topic.split(' ', 1)[0] in channel_names:
  921. topic = '{} {}'.format(current_channel.name, topic)
  922. w.hook_completion_list_add(completion, topic, 0, w.WEECHAT_LIST_POS_SORT)
  923. return w.WEECHAT_RC_OK
  924. @utf8_decode
  925. def usergroups_completion_cb(data, completion_item, current_buffer, completion):
  926. """
  927. Adds all @-prefixed usergroups to completion list
  928. """
  929. current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
  930. if current_channel is None:
  931. return w.WEECHAT_RC_OK
  932. subteam_handles = [subteam.handle for subteam in current_channel.team.subteams.values()]
  933. for group in subteam_handles + ["@channel", "@everyone", "@here"]:
  934. w.hook_completion_list_add(completion, group, 1, w.WEECHAT_LIST_POS_SORT)
  935. return w.WEECHAT_RC_OK
  936. @utf8_decode
  937. def complete_next_cb(data, current_buffer, command):
  938. """Extract current word, if it is equal to a nick, prefix it with @ and
  939. rely on nick_completion_cb adding the @-prefixed versions to the
  940. completion lists, then let Weechat's internal completion do its
  941. thing
  942. """
  943. current_channel = EVENTROUTER.weechat_controller.buffers.get(current_buffer)
  944. if not hasattr(current_channel, 'members') or current_channel is None or current_channel.members is None:
  945. return w.WEECHAT_RC_OK
  946. line_input = w.buffer_get_string(current_buffer, "input")
  947. current_pos = w.buffer_get_integer(current_buffer, "input_pos") - 1
  948. input_length = w.buffer_get_integer(current_buffer, "input_length")
  949. word_start = 0
  950. word_end = input_length
  951. # If we're on a non-word, look left for something to complete
  952. while current_pos >= 0 and line_input[current_pos] != '@' and not line_input[current_pos].isalnum():
  953. current_pos = current_pos - 1
  954. if current_pos < 0:
  955. current_pos = 0
  956. for l in range(current_pos, 0, -1):
  957. if line_input[l] != '@' and not line_input[l].isalnum():
  958. word_start = l + 1
  959. break
  960. for l in range(current_pos, input_length):
  961. if not line_input[l].isalnum():
  962. word_end = l
  963. break
  964. word = line_input[word_start:word_end]
  965. for member in current_channel.members:
  966. user = current_channel.team.users.get(member)
  967. if user and user.name == word:
  968. # Here, we cheat. Insert a @ in front and rely in the @
  969. # nicks being in the completion list
  970. w.buffer_set(current_buffer, "input", line_input[:word_start] + "@" + line_input[word_start:])
  971. w.buffer_set(current_buffer, "input_pos", str(w.buffer_get_integer(current_buffer, "input_pos") + 1))
  972. return w.WEECHAT_RC_OK_EAT
  973. return w.WEECHAT_RC_OK
  974. def script_unloaded():
  975. stop_talking_to_slack()
  976. return w.WEECHAT_RC_OK
  977. def stop_talking_to_slack():
  978. """
  979. complete
  980. Prevents a race condition where quitting closes buffers
  981. which triggers leaving the channel because of how close
  982. buffer is handled
  983. """
  984. EVENTROUTER.shutdown()
  985. for team in EVENTROUTER.teams.values():
  986. team.ws.shutdown()
  987. return w.WEECHAT_RC_OK
  988. ##### New Classes
  989. class SlackRequest(object):
  990. """
  991. Encapsulates a Slack api request. Valuable as an object that we can add to the queue and/or retry.
  992. makes a SHA of the requst url and current time so we can re-tag this on the way back through.
  993. """
  994. def __init__(self, team, request, post_data=None, channel=None, metadata=None, retries=3, token=None):
  995. if team is None and token is None:
  996. raise ValueError("Both team and token can't be None")
  997. self.team = team
  998. self.request = request
  999. self.post_data = post_data if post_data else {}
  1000. self.channel = channel
  1001. self.metadata = metadata if metadata else {}
  1002. self.retries = retries
  1003. self.token = token if token else team.token
  1004. self.tries = 0
  1005. self.start_time = time.time()
  1006. self.request_normalized = re.sub(r'\W+', '', request)
  1007. self.domain = 'api.slack.com'
  1008. self.post_data['token'] = self.token
  1009. self.url = 'https://{}/api/{}?{}'.format(self.domain, self.request, urlencode(encode_to_utf8(self.post_data)))
  1010. self.params = {'useragent': 'wee_slack {}'.format(SCRIPT_VERSION)}
  1011. self.response_id = sha1_hex('{}{}'.format(self.url, self.start_time))
  1012. def __repr__(self):
  1013. return ("SlackRequest(team={}, request='{}', post_data={}, retries={}, token='{}', "
  1014. "tries={}, start_time={})").format(self.team, self.request, self.post_data,
  1015. self.retries, token_for_print(self.token), self.tries, self.start_time)
  1016. def request_string(self):
  1017. return "{}".format(self.url)
  1018. def tried(self):
  1019. self.tries += 1
  1020. self.response_id = sha1_hex("{}{}".format(self.url, time.time()))
  1021. def should_try(self):
  1022. return self.tries < self.retries
  1023. def retry_ready(self):
  1024. return (self.start_time + (self.tries**2)) < time.time()
  1025. class SlackSubteam(object):
  1026. """
  1027. Represents a slack group or subteam
  1028. """
  1029. def __init__(self, originating_team_id, is_member, **kwargs):
  1030. self.handle = '@{}'.format(kwargs['handle'])
  1031. self.identifier = kwargs['id']
  1032. self.name = kwargs['name']
  1033. self.description = kwargs.get('description')
  1034. self.team_id = originating_team_id
  1035. self.is_member = is_member
  1036. def __repr__(self):
  1037. return "Name:{} Identifier:{}".format(self.name, self.identifier)
  1038. def __eq__(self, compare_str):
  1039. return compare_str == self.identifier
  1040. class SlackTeam(object):
  1041. """
  1042. incomplete
  1043. Team object under which users and channels live.. Does lots.
  1044. """
  1045. def __init__(self, eventrouter, token, team_hash, websocket_url, team_info, subteams, nick, myidentifier, my_manual_presence, users, bots, channels, **kwargs):
  1046. self.identifier = team_info["id"]
  1047. self.active = True
  1048. self.team_hash = team_hash
  1049. self.ws_url = websocket_url
  1050. self.connected = False
  1051. self.connecting_rtm = False
  1052. self.connecting_ws = False
  1053. self.ws = None
  1054. self.ws_counter = 0
  1055. self.ws_replies = {}
  1056. self.last_ping_time = 0
  1057. self.last_pong_time = time.time()
  1058. self.eventrouter = eventrouter
  1059. self.token = token
  1060. self.team = self
  1061. self.subteams = subteams
  1062. self.team_info = team_info
  1063. self.subdomain = team_info["domain"]
  1064. self.domain = self.subdomain + ".slack.com"
  1065. self.preferred_name = self.domain
  1066. self.nick = nick
  1067. self.myidentifier = myidentifier
  1068. self.my_manual_presence = my_manual_presence
  1069. try:
  1070. if self.channels:
  1071. for c in channels.keys():
  1072. if not self.channels.get(c):
  1073. self.channels[c] = channels[c]
  1074. except:
  1075. self.channels = channels
  1076. self.users = users
  1077. self.bots = bots
  1078. self.name = self.domain
  1079. self.channel_buffer = None
  1080. self.got_history = True
  1081. self.create_buffer()
  1082. self.set_muted_channels(kwargs.get('muted_channels', ""))
  1083. self.set_highlight_words(kwargs.get('highlight_words', ""))
  1084. for c in self.channels.keys():
  1085. channels[c].set_related_server(self)
  1086. channels[c].check_should_open()
  1087. # Last step is to make sure my nickname is the set color
  1088. self.users[self.myidentifier].force_color(w.config_string(w.config_get('weechat.color.chat_nick_self')))
  1089. # This highlight step must happen after we have set related server
  1090. self.load_emoji_completions()
  1091. self.type = "team"
  1092. def __repr__(self):
  1093. return "domain={} nick={}".format(self.subdomain, self.nick)
  1094. def __eq__(self, compare_str):
  1095. return compare_str == self.token or compare_str == self.domain or compare_str == self.subdomain
  1096. @property
  1097. def members(self):
  1098. return self.users.keys()
  1099. def load_emoji_completions(self):
  1100. self.emoji_completions = list(EMOJI.keys())
  1101. if self.emoji_completions:
  1102. s = SlackRequest(self, "emoji.list")
  1103. self.eventrouter.receive(s)
  1104. def add_channel(self, channel):
  1105. self.channels[channel["id"]] = channel
  1106. channel.set_related_server(self)
  1107. def generate_usergroup_map(self):
  1108. return {s.handle: s.identifier for s in self.subteams.values()}
  1109. def create_buffer(self):
  1110. if not self.channel_buffer:
  1111. alias = config.server_aliases.get(self.subdomain)
  1112. if alias:
  1113. self.preferred_name = alias
  1114. elif config.short_buffer_names:
  1115. self.preferred_name = self.subdomain
  1116. else:
  1117. self.preferred_name = self.domain
  1118. self.channel_buffer = w.buffer_new(self.preferred_name, "buffer_input_callback", "EVENTROUTER", "", "")
  1119. self.eventrouter.weechat_controller.register_buffer(self.channel_buffer, self)
  1120. w.buffer_set(self.channel_buffer, "localvar_set_type", 'server')
  1121. w.buffer_set(self.channel_buffer, "localvar_set_nick", self.nick)
  1122. w.buffer_set(self.channel_buffer, "localvar_set_server", self.preferred_name)
  1123. self.buffer_merge()
  1124. def buffer_merge(self, config_value=None):
  1125. if not config_value:
  1126. config_value = w.config_string(w.config_get('irc.look.server_buffer'))
  1127. if config_value == 'merge_with_core':
  1128. w.buffer_merge(self.channel_buffer, w.buffer_search_main())
  1129. else:
  1130. w.buffer_unmerge(self.channel_buffer, 0)
  1131. def destroy_buffer(self, update_remote):
  1132. pass
  1133. def set_muted_channels(self, muted_str):
  1134. self.muted_channels = {x for x in muted_str.split(',') if x}
  1135. for channel in self.channels.values():
  1136. channel.set_highlights()
  1137. def set_highlight_words(self, highlight_str):
  1138. self.highlight_words = {x for x in highlight_str.split(',') if x}
  1139. for channel in self.channels.values():
  1140. channel.set_highlights()
  1141. def formatted_name(self, **kwargs):
  1142. return self.domain
  1143. def buffer_prnt(self, data, message=False):
  1144. tag_name = "team_message" if message else "team_info"
  1145. w.prnt_date_tags(self.channel_buffer, SlackTS().major, tag(tag_name), data)
  1146. def send_message(self, message, subtype=None, request_dict_ext={}):
  1147. w.prnt("", "ERROR: Sending a message in the team buffer is not supported")
  1148. def find_channel_by_members(self, members, channel_type=None):
  1149. for channel in self.channels.values():
  1150. if channel.get_members() == members and (
  1151. channel_type is None or channel.type == channel_type):
  1152. return channel
  1153. def get_channel_map(self):
  1154. return {v.name: k for k, v in self.channels.items()}
  1155. def get_username_map(self):
  1156. return {v.name: k for k, v in self.users.items()}
  1157. def get_team_hash(self):
  1158. return self.team_hash
  1159. @staticmethod
  1160. def generate_team_hash(team_id, subdomain):
  1161. return str(sha1_hex("{}{}".format(team_id, subdomain)))
  1162. def refresh(self):
  1163. self.rename()
  1164. def rename(self):
  1165. pass
  1166. def is_user_present(self, user_id):
  1167. user = self.users.get(user_id)
  1168. if user and user.presence == 'active':
  1169. return True
  1170. else:
  1171. return False
  1172. def mark_read(self, ts=None, update_remote=True, force=False):
  1173. pass
  1174. def connect(self):
  1175. if not self.connected and not self.connecting_ws:
  1176. if self.ws_url:
  1177. self.connecting_ws = True
  1178. try:
  1179. # only http proxy is currently supported
  1180. proxy = ProxyWrapper()
  1181. if proxy.has_proxy == True:
  1182. ws = create_connection(self.ws_url, sslopt=sslopt_ca_certs, http_proxy_host=proxy.proxy_address, http_proxy_port=proxy.proxy_port, http_proxy_auth=(proxy.proxy_user, proxy.proxy_password))
  1183. else:
  1184. ws = create_connection(self.ws_url, sslopt=sslopt_ca_certs)
  1185. self.hook = w.hook_fd(ws.sock.fileno(), 1, 0, 0, "receive_ws_callback", self.get_team_hash())
  1186. ws.sock.setblocking(0)
  1187. self.ws = ws
  1188. self.set_reconnect_url(None)
  1189. self.set_connected()
  1190. self.connecting_ws = False
  1191. except:
  1192. w.prnt(self.channel_buffer,
  1193. 'Failed connecting to slack team {}, retrying.'.format(self.domain))
  1194. dbg('connect failed with exception:\n{}'.format(format_exc_tb()), level=5)
  1195. self.connecting_ws = False
  1196. return False
  1197. elif not self.connecting_rtm:
  1198. # The fast reconnect failed, so start over-ish
  1199. for chan in self.channels:
  1200. self.channels[chan].got_history = False
  1201. s = initiate_connection(self.token, retries=999, team=self)
  1202. self.eventrouter.receive(s)
  1203. self.connecting_rtm = True
  1204. def set_connected(self):
  1205. self.connected = True
  1206. self.last_pong_time = time.time()
  1207. self.buffer_prnt('Connected to Slack team {} ({}) with username {}'.format(
  1208. self.team_info["name"], self.domain, self.nick))
  1209. dbg("connected to {}".format(self.domain))
  1210. def set_disconnected(self):
  1211. w.unhook(self.hook)
  1212. self.connected = False
  1213. def set_reconnect_url(self, url):
  1214. self.ws_url = url
  1215. def next_ws_transaction_id(self):
  1216. self.ws_counter += 1
  1217. return self.ws_counter
  1218. def send_to_websocket(self, data, expect_reply=True):
  1219. data["id"] = self.next_ws_transaction_id()
  1220. message = json.dumps(data)
  1221. try:
  1222. if expect_reply:
  1223. self.ws_replies[data["id"]] = data
  1224. self.ws.send(encode_to_utf8(message))
  1225. dbg("Sent {}...".format(message[:100]))
  1226. except (WebSocketConnectionClosedException, socket.error) as e:
  1227. handle_socket_error(e, self, 'send')
  1228. def update_member_presence(self, user, presence):
  1229. user.presence = presence
  1230. for c in self.channels:
  1231. c = self.channels[c]
  1232. if user.id in c.members:
  1233. c.update_nicklist(user.id)
  1234. def subscribe_users_presence(self):
  1235. # FIXME: There is a limitation in the API to the size of the
  1236. # json we can send.
  1237. # We should try to be smarter to fetch the users whom we want to
  1238. # subscribe to.
  1239. users = list(self.users.keys())[:750]
  1240. if self.myidentifier not in users:
  1241. users.append(self.myidentifier)
  1242. self.send_to_websocket({
  1243. "type": "presence_sub",
  1244. "ids": users,
  1245. }, expect_reply=False)
  1246. class SlackChannelCommon(object):
  1247. def send_add_reaction(self, msg_id, reaction):
  1248. self.send_change_reaction("reactions.add", msg_id, reaction)
  1249. def send_remove_reaction(self, msg_id, reaction):
  1250. self.send_change_reaction("reactions.remove", msg_id, reaction)
  1251. def send_change_reaction(self, method, msg_id, reaction):
  1252. if type(msg_id) is not int:
  1253. if msg_id in self.hashed_messages:
  1254. timestamp = str(self.hashed_messages[msg_id])
  1255. else:
  1256. return
  1257. elif 0 < msg_id <= len(self.messages):
  1258. keys = self.main_message_keys_reversed()
  1259. timestamp = next(islice(keys, msg_id - 1, None))
  1260. else:
  1261. return
  1262. data = {"channel": self.identifier, "timestamp": timestamp, "name": reaction}
  1263. s = SlackRequest(self.team, method, data, channel=self, metadata={'reaction': reaction})
  1264. self.eventrouter.receive(s)
  1265. def edit_nth_previous_message(self, msg_id, old, new, flags):
  1266. message = self.my_last_message(msg_id)
  1267. if message is None:
  1268. return
  1269. if new == "" and old == "":
  1270. s = SlackRequest(self.team, "chat.delete", {"channel": self.identifier, "ts": message['ts']}, channel=self)
  1271. self.eventrouter.receive(s)
  1272. else:
  1273. num_replace = 0 if 'g' in flags else 1
  1274. f = re.UNICODE
  1275. f |= re.IGNORECASE if 'i' in flags else 0
  1276. f |= re.MULTILINE if 'm' in flags else 0
  1277. f |= re.DOTALL if 's' in flags else 0
  1278. new_message = re.sub(old, new, message["text"], num_replace, f)
  1279. if new_message != message["text"]:
  1280. s = SlackRequest(self.team, "chat.update",
  1281. {"channel": self.identifier, "ts": message['ts'], "text": new_message}, channel=self)
  1282. self.eventrouter.receive(s)
  1283. def my_last_message(self, msg_id):
  1284. if type(msg_id) is not int:
  1285. ts = self.hashed_messages.get(msg_id)
  1286. m = self.messages.get(ts)
  1287. if m is not None and m.message_json.get("user") == self.team.myidentifier:
  1288. return m.message_json
  1289. else:
  1290. for key in self.main_message_keys_reversed():
  1291. m = self.messages[key]
  1292. if m.message_json.get("user") == self.team.myidentifier:
  1293. msg_id -= 1
  1294. if msg_id == 0:
  1295. return m.message_json
  1296. def change_message(self, ts, message_json=None, text=None):
  1297. ts = SlackTS(ts)
  1298. m = self.messages.get(ts)
  1299. if not m:
  1300. return
  1301. if message_json:
  1302. m.message_json.update(message_json)
  1303. if text:
  1304. m.change_text(text)
  1305. if type(m) == SlackMessage or config.thread_messages_in_channel:
  1306. new_text = self.render(m, force=True)
  1307. modify_buffer_line(self.channel_buffer, ts, new_text)
  1308. if type(m) == SlackThreadMessage:
  1309. thread_channel = m.parent_message.thread_channel
  1310. if thread_channel and thread_channel.active:
  1311. new_text = thread_channel.render(m, force=True)
  1312. modify_buffer_line(thread_channel.channel_buffer, ts, new_text)
  1313. def hash_message(self, ts):
  1314. ts = SlackTS(ts)
  1315. def calc_hash(ts):
  1316. return sha1_hex(str(ts))
  1317. if ts in self.messages and not self.messages[ts].hash:
  1318. message = self.messages[ts]
  1319. tshash = calc_hash(message.ts)
  1320. hl = 3
  1321. for i in range(hl, len(tshash) + 1):
  1322. shorthash = tshash[:i]
  1323. if self.hashed_messages.get(shorthash) == ts:
  1324. message.hash = shorthash
  1325. return shorthash
  1326. shorthash = tshash[:hl]
  1327. while any(x.startswith(shorthash) for x in self.hashed_messages):
  1328. hl += 1
  1329. shorthash = tshash[:hl]
  1330. if shorthash[:-1] in self.hashed_messages:
  1331. col_ts = self.hashed_messages.pop(shorthash[:-1])
  1332. col_new_hash = calc_hash(col_ts)[:hl]
  1333. self.hashed_messages[col_new_hash] = col_ts
  1334. col_msg = self.messages.get(col_ts)
  1335. if col_msg:
  1336. col_msg.hash = col_new_hash
  1337. self.change_message(str(col_msg.ts))
  1338. if col_msg.thread_channel:
  1339. col_msg.thread_channel.rename()
  1340. self.hashed_messages[shorthash] = message.ts
  1341. message.hash = shorthash
  1342. return shorthash
  1343. elif ts in self.messages:
  1344. return self.messages[ts].hash
  1345. class SlackChannel(SlackChannelCommon):
  1346. """
  1347. Represents an individual slack channel.
  1348. """
  1349. def __init__(self, eventrouter, **kwargs):
  1350. # We require these two things for a valid object,
  1351. # the rest we can just learn from slack
  1352. self.active = False
  1353. for key, value in kwargs.items():
  1354. setattr(self, key, value)
  1355. self.eventrouter = eventrouter
  1356. self.slack_name = kwargs["name"]
  1357. self.slack_purpose = kwargs.get("purpose", {"value": ""})
  1358. self.topic = kwargs.get("topic", {"value": ""})
  1359. self.identifier = kwargs["id"]
  1360. self.last_read = SlackTS(kwargs.get("last_read", SlackTS()))
  1361. self.channel_buffer = None
  1362. self.team = kwargs.get('team')
  1363. self.got_history = False
  1364. self.messages = OrderedDict()
  1365. self.hashed_messages = {}
  1366. self.thread_channels = {}
  1367. self.new_messages = False
  1368. self.typing = {}
  1369. self.type = 'channel'
  1370. self.set_name(self.slack_name)
  1371. # short name relates to the localvar we change for typing indication
  1372. self.current_short_name = self.name
  1373. self.set_members(kwargs.get('members', []))
  1374. self.unread_count_display = 0
  1375. self.last_line_from = None
  1376. def __eq__(self, compare_str):
  1377. if compare_str == self.slack_name or compare_str == self.formatted_name() or compare_str == self.formatted_name(style="long_default"):
  1378. return True
  1379. else:
  1380. return False
  1381. def __repr__(self):
  1382. return "Name:{} Identifier:{}".format(self.name, self.identifier)
  1383. @property
  1384. def muted(self):
  1385. return self.identifier in self.team.muted_channels
  1386. def set_name(self, slack_name):
  1387. self.name = "#" + slack_name
  1388. def refresh(self):
  1389. return self.rename()
  1390. def rename(self):
  1391. if self.channel_buffer:
  1392. new_name = self.formatted_name(typing=self.is_someone_typing(), style="sidebar")
  1393. if self.current_short_name != new_name:
  1394. self.current_short_name = new_name
  1395. w.buffer_set(self.channel_buffer, "short_name", new_name)
  1396. return True
  1397. return False
  1398. def set_members(self, members):
  1399. self.members = set(members)
  1400. self.update_nicklist()
  1401. def get_members(self):
  1402. return self.members
  1403. def set_unread_count_display(self, count):
  1404. self.unread_count_display = count
  1405. self.new_messages = bool(self.unread_count_display)
  1406. if self.muted and config.muted_channels_activity != "all":
  1407. return
  1408. for c in range(self.unread_count_display):
  1409. if self.type in ["im", "mpim"]:
  1410. w.buffer_set(self.channel_buffer, "hotlist", "2")
  1411. else:
  1412. w.buffer_set(self.channel_buffer, "hotlist", "1")
  1413. def formatted_name(self, style="default", typing=False, **kwargs):
  1414. if typing and config.channel_name_typing_indicator:
  1415. prepend = ">"
  1416. elif self.type == "group" or self.type == "private":
  1417. prepend = config.group_name_prefix
  1418. elif self.type == "shared":
  1419. prepend = config.shared_name_prefix
  1420. else:
  1421. prepend = "#"
  1422. sidebar_color = config.color_buflist_muted_channels if self.muted else ""
  1423. select = {
  1424. "default": prepend + self.slack_name,
  1425. "sidebar": colorize_string(sidebar_color, prepend + self.slack_name),
  1426. "base": self.slack_name,
  1427. "long_default": "{}.{}{}".format(self.team.preferred_name, prepend, self.slack_name),
  1428. "long_base": "{}.{}".format(self.team.preferred_name, self.slack_name),
  1429. }
  1430. return select[style]
  1431. def render_topic(self, fallback_to_purpose=False):
  1432. topic = self.topic['value']
  1433. if not topic and fallback_to_purpose:
  1434. topic = self.slack_purpose['value']
  1435. return unhtmlescape(unfurl_refs(topic))
  1436. def set_topic(self, value=None):
  1437. if value is not None:
  1438. self.topic = {"value": value}
  1439. if self.channel_buffer:
  1440. topic = self.render_topic(fallback_to_purpose=True)
  1441. w.buffer_set(self.channel_buffer, "title", topic)
  1442. def update_from_message_json(self, message_json):
  1443. for key, value in message_json.items():
  1444. setattr(self, key, value)
  1445. def open(self, update_remote=True):
  1446. if update_remote:
  1447. if "join" in SLACK_API_TRANSLATOR[self.type]:
  1448. s = SlackRequest(self.team, SLACK_API_TRANSLATOR[self.type]["join"],
  1449. {"channel": self.identifier}, channel=self)
  1450. self.eventrouter.receive(s)
  1451. self.create_buffer()
  1452. self.active = True
  1453. self.get_history()
  1454. def check_should_open(self, force=False):
  1455. if hasattr(self, "is_archived") and self.is_archived:
  1456. return
  1457. if force:
  1458. self.create_buffer()
  1459. return
  1460. # Only check is_member if is_open is not set, because in some cases
  1461. # (e.g. group DMs), is_member should be ignored in favor of is_open.
  1462. is_open = self.is_open if hasattr(self, "is_open") else self.is_member
  1463. if is_open or self.unread_count_display:
  1464. self.create_buffer()
  1465. if config.background_load_all_history:
  1466. self.get_history(slow_queue=True)
  1467. def set_related_server(self, team):
  1468. self.team = team
  1469. def highlights(self):
  1470. nick_highlights = {'@' + self.team.nick, self.team.myidentifier}
  1471. subteam_highlights = {subteam.handle for subteam in self.team.subteams.values()
  1472. if subteam.is_member}
  1473. highlights = nick_highlights | subteam_highlights | self.team.highlight_words
  1474. if self.muted and config.muted_channels_activity == "personal_highlights":
  1475. return highlights
  1476. else:
  1477. return highlights | {"@channel", "@everyone", "@group", "@here"}
  1478. def set_highlights(self):
  1479. # highlight my own name and any set highlights
  1480. if self.channel_buffer:
  1481. h_str = ",".join(self.highlights())
  1482. w.buffer_set(self.channel_buffer, "highlight_words", h_str)
  1483. if self.muted and config.muted_channels_activity != "all":
  1484. notify_level = "0" if config.muted_channels_activity == "none" else "1"
  1485. w.buffer_set(self.channel_buffer, "notify", notify_level)
  1486. else:
  1487. w.buffer_set(self.channel_buffer, "notify", "3")
  1488. if self.muted and config.muted_channels_activity == "none":
  1489. w.buffer_set(self.channel_buffer, "highlight_tags_restrict", "highlight_force")
  1490. else:
  1491. w.buffer_set(self.channel_buffer, "highlight_tags_restrict", "")
  1492. for thread_channel in self.thread_channels.values():
  1493. thread_channel.set_highlights(h_str)
  1494. def create_buffer(self):
  1495. """
  1496. Creates the weechat buffer where the channel magic happens.
  1497. """
  1498. if not self.channel_buffer:
  1499. self.active = True
  1500. self.channel_buffer = w.buffer_new(self.formatted_name(style="long_default"), "buffer_input_callback", "EVENTROUTER", "", "")
  1501. self.eventrouter.weechat_controller.register_buffer(self.channel_buffer, self)
  1502. if self.type == "im":
  1503. w.buffer_set(self.channel_buffer, "localvar_set_type", 'private')
  1504. else:
  1505. w.buffer_set(self.channel_buffer, "localvar_set_type", 'channel')
  1506. w.buffer_set(self.channel_buffer, "localvar_set_channel", self.formatted_name())
  1507. w.buffer_set(self.channel_buffer, "localvar_set_nick", self.team.nick)
  1508. w.buffer_set(self.channel_buffer, "short_name", self.formatted_name(style="sidebar", enable_color=True))
  1509. self.set_highlights()
  1510. self.set_topic()
  1511. self.eventrouter.weechat_controller.set_refresh_buffer_list(True)
  1512. if self.channel_buffer:
  1513. w.buffer_set(self.channel_buffer, "localvar_set_server", self.team.preferred_name)
  1514. self.update_nicklist()
  1515. if "info" in SLACK_API_TRANSLATOR[self.type]:
  1516. s = SlackRequest(self.team, SLACK_API_TRANSLATOR[self.type]["info"],
  1517. {"channel": self.identifier}, channel=self)
  1518. self.eventrouter.receive(s)
  1519. if self.type == "im":
  1520. if "join" in SLACK_API_TRANSLATOR[self.type]:
  1521. s = SlackRequest(self.team, SLACK_API_TRANSLATOR[self.type]["join"],
  1522. {"users": self.user, "return_im": True}, channel=self)
  1523. self.eventrouter.receive(s)
  1524. def clear_messages(self):
  1525. w.buffer_clear(self.channel_buffer)
  1526. self.messages = OrderedDict()
  1527. self.got_history = False
  1528. def destroy_buffer(self, update_remote):
  1529. self.clear_messages()
  1530. self.channel_buffer = None
  1531. self.active = False
  1532. if update_remote and not self.eventrouter.shutting_down:
  1533. s = SlackRequest(self.team, SLACK_API_TRANSLATOR[self.type]["leave"],
  1534. {"channel": self.identifier}, channel=self)
  1535. self.eventrouter.receive(s)
  1536. def buffer_prnt(self, nick, text, timestamp=str(time.time()), tagset=None, tag_nick=None, history_message=False, extra_tags=None):
  1537. data = "{}\t{}".format(format_nick(nick, self.last_line_from), text)
  1538. self.last_line_from = nick
  1539. ts = SlackTS(timestamp)
  1540. last_read = SlackTS(self.last_read)
  1541. # without this, DMs won't open automatically
  1542. if not self.channel_buffer and ts > last_read:
  1543. self.open(update_remote=False)
  1544. if self.channel_buffer:
  1545. # backlog messages - we will update the read marker as we print these
  1546. backlog = ts <= last_read
  1547. if not backlog:
  1548. self.new_messages = True
  1549. if not tagset:
  1550. if self.type in ["im", "mpim"]:
  1551. tagset = "dm"
  1552. else:
  1553. tagset = "channel"
  1554. no_log = history_message and backlog
  1555. self_msg = tag_nick == self.team.nick
  1556. tags = tag(tagset, user=tag_nick, self_msg=self_msg, backlog=backlog, no_log=no_log, extra_tags=extra_tags)
  1557. try:
  1558. if (config.unhide_buffers_with_activity
  1559. and not self.is_visible() and not self.muted):
  1560. w.buffer_set(self.channel_buffer, "hidden", "0")
  1561. w.prnt_date_tags(self.channel_buffer, ts.major, tags, data)
  1562. modify_last_print_time(self.channel_buffer, ts.minor)
  1563. if backlog or self_msg:
  1564. self.mark_read(ts, update_remote=False, force=True)
  1565. except:
  1566. dbg("Problem processing buffer_prnt")
  1567. def send_message(self, message, subtype=None, request_dict_ext={}):
  1568. message = linkify_text(message, self.team)
  1569. dbg(message)
  1570. if subtype == 'me_message':
  1571. s = SlackRequest(self.team, "chat.meMessage", {"channel": self.identifier, "text": message}, channel=self)
  1572. self.eventrouter.receive(s)
  1573. else:
  1574. request = {"type": "message", "channel": self.identifier,
  1575. "text": message, "user": self.team.myidentifier}
  1576. request.update(request_dict_ext)
  1577. self.team.send_to_websocket(request)
  1578. def store_message(self, message, team, from_me=False):
  1579. if not self.active:
  1580. return
  1581. if from_me:
  1582. message.message_json["user"] = team.myidentifier
  1583. self.messages[SlackTS(message.ts)] = message
  1584. sorted_messages = sorted(self.messages.items())
  1585. messages_to_delete = sorted_messages[:-SCROLLBACK_SIZE]
  1586. messages_to_keep = sorted_messages[-SCROLLBACK_SIZE:]
  1587. for message_hash in [m[1].hash for m in messages_to_delete]:
  1588. if message_hash in self.hashed_messages:
  1589. del self.hashed_messages[message_hash]
  1590. self.messages = OrderedDict(messages_to_keep)
  1591. def is_visible(self):
  1592. return w.buffer_get_integer(self.channel_buffer, "hidden") == 0
  1593. def get_history(self, slow_queue=False):
  1594. if not self.got_history:
  1595. # we have probably reconnected. flush the buffer
  1596. if self.team.connected:
  1597. self.clear_messages()
  1598. w.prnt_date_tags(self.channel_buffer, SlackTS().major,
  1599. tag(backlog=True, no_log=True), '\tgetting channel history...')
  1600. s = SlackRequest(self.team, SLACK_API_TRANSLATOR[self.type]["history"],
  1601. {"channel": self.identifier, "count": BACKLOG_SIZE}, channel=self, metadata={'clear': True})
  1602. if not slow_queue:
  1603. self.eventrouter.receive(s)
  1604. else:
  1605. self.eventrouter.receive_slow(s)
  1606. self.got_history = True
  1607. def main_message_keys_reversed(self):
  1608. return (key for key in reversed(self.messages)
  1609. if type(self.messages[key]) == SlackMessage)
  1610. # Typing related
  1611. def set_typing(self, user):
  1612. if self.channel_buffer and self.is_visible():
  1613. self.typing[user] = time.time()
  1614. self.eventrouter.weechat_controller.set_refresh_buffer_list(True)
  1615. def unset_typing(self, user):
  1616. if self.channel_buffer and self.is_visible():
  1617. u = self.typing.get(user)
  1618. if u:
  1619. self.eventrouter.weechat_controller.set_refresh_buffer_list(True)
  1620. def is_someone_typing(self):
  1621. """
  1622. Walks through dict of typing folks in a channel and fast
  1623. returns if any of them is actively typing. If none are,
  1624. nulls the dict and returns false.
  1625. """
  1626. for user, timestamp in self.typing.items():
  1627. if timestamp + 4 > time.time():
  1628. return True
  1629. if len(self.typing) > 0:
  1630. self.typing = {}
  1631. self.eventrouter.weechat_controller.set_refresh_buffer_list(True)
  1632. return False
  1633. def get_typing_list(self):
  1634. """
  1635. Returns the names of everyone in the channel who is currently typing.
  1636. """
  1637. typing = []
  1638. for user, timestamp in self.typing.items():
  1639. if timestamp + 4 > time.time():
  1640. typing.append(user)
  1641. else:
  1642. del self.typing[user]
  1643. return typing
  1644. def mark_read(self, ts=None, update_remote=True, force=False):
  1645. if self.new_messages or force:
  1646. if self.channel_buffer:
  1647. w.buffer_set(self.channel_buffer, "unread", "")
  1648. w.buffer_set(self.channel_buffer, "hotlist", "-1")
  1649. if not ts:
  1650. ts = next(reversed(self.messages), SlackTS())
  1651. if ts > self.last_read:
  1652. self.last_read = ts
  1653. if update_remote:
  1654. s = SlackRequest(self.team, SLACK_API_TRANSLATOR[self.type]["mark"],
  1655. {"channel": self.identifier, "ts": ts}, channel=self)
  1656. self.eventrouter.receive(s)
  1657. self.new_messages = False
  1658. def user_joined(self, user_id):
  1659. # ugly hack - for some reason this gets turned into a list
  1660. self.members = set(self.members)
  1661. self.members.add(user_id)
  1662. self.update_nicklist(user_id)
  1663. def user_left(self, user_id):
  1664. self.members.discard(user_id)
  1665. self.update_nicklist(user_id)
  1666. def update_nicklist(self, user=None):
  1667. if not self.channel_buffer:
  1668. return
  1669. if self.type not in ["channel", "group", "mpim", "private", "shared"]:
  1670. return
  1671. w.buffer_set(self.channel_buffer, "nicklist", "1")
  1672. # create nicklists for the current channel if they don't exist
  1673. # if they do, use the existing pointer
  1674. here = w.nicklist_search_group(self.channel_buffer, '', NICK_GROUP_HERE)
  1675. if not here:
  1676. here = w.nicklist_add_group(self.channel_buffer, '', NICK_GROUP_HERE, "weechat.color.nicklist_group", 1)
  1677. afk = w.nicklist_search_group(self.channel_buffer, '', NICK_GROUP_AWAY)
  1678. if not afk:
  1679. afk = w.nicklist_add_group(self.channel_buffer, '', NICK_GROUP_AWAY, "weechat.color.nicklist_group", 1)
  1680. # Add External nicklist group only for shared channels
  1681. if self.type == 'shared':
  1682. external = w.nicklist_search_group(self.channel_buffer, '', NICK_GROUP_EXTERNAL)
  1683. if not external:
  1684. external = w.nicklist_add_group(self.channel_buffer, '', NICK_GROUP_EXTERNAL, 'weechat.color.nicklist_group', 2)
  1685. if user and len(self.members) < 1000:
  1686. user = self.team.users.get(user)
  1687. # External users that have left shared channels won't exist
  1688. if not user or user.deleted:
  1689. return
  1690. nick = w.nicklist_search_nick(self.channel_buffer, "", user.name)
  1691. # since this is a change just remove it regardless of where it is
  1692. w.nicklist_remove_nick(self.channel_buffer, nick)
  1693. # now add it back in to whichever..
  1694. nick_group = afk
  1695. if user.is_external:
  1696. nick_group = external
  1697. elif self.team.is_user_present(user.identifier):
  1698. nick_group = here
  1699. if user.identifier in self.members:
  1700. w.nicklist_add_nick(self.channel_buffer, nick_group, user.name, user.color_name, "", "", 1)
  1701. # if we didn't get a user, build a complete list. this is expensive.
  1702. else:
  1703. if len(self.members) < 1000:
  1704. try:
  1705. for user in self.members:
  1706. user = self.team.users.get(user)
  1707. if user.deleted:
  1708. continue
  1709. nick_group = afk
  1710. if user.is_external:
  1711. nick_group = external
  1712. elif self.team.is_user_present(user.identifier):
  1713. nick_group = here
  1714. w.nicklist_add_nick(self.channel_buffer, nick_group, user.name, user.color_name, "", "", 1)
  1715. except:
  1716. dbg("DEBUG: {} {} {}".format(self.identifier, self.name, format_exc_only()))
  1717. else:
  1718. w.nicklist_remove_all(self.channel_buffer)
  1719. for fn in ["1| too", "2| many", "3| users", "4| to", "5| show"]:
  1720. w.nicklist_add_group(self.channel_buffer, '', fn, w.color('white'), 1)
  1721. def render(self, message, force=False):
  1722. text = message.render(force)
  1723. if isinstance(message, SlackThreadMessage):
  1724. thread_id = message.parent_message.hash or message.parent_message.ts
  1725. return colorize_string(get_thread_color(thread_id), '[{}]'.format(thread_id)) + ' {}'.format(text)
  1726. return text
  1727. class SlackDMChannel(SlackChannel):
  1728. """
  1729. Subclass of a normal channel for person-to-person communication, which
  1730. has some important differences.
  1731. """
  1732. def __init__(self, eventrouter, users, **kwargs):
  1733. dmuser = kwargs["user"]
  1734. kwargs["name"] = users[dmuser].name if dmuser in users else dmuser
  1735. super(SlackDMChannel, self).__init__(eventrouter, **kwargs)
  1736. self.type = 'im'
  1737. self.update_color()
  1738. self.set_name(self.slack_name)
  1739. if dmuser in users:
  1740. self.set_topic(create_user_status_string(users[dmuser].profile))
  1741. def set_related_server(self, team):
  1742. super(SlackDMChannel, self).set_related_server(team)
  1743. if self.user not in self.team.users:
  1744. s = SlackRequest(self.team, 'users.info', {'user': self.slack_name}, channel=self)
  1745. self.eventrouter.receive(s)
  1746. def set_name(self, slack_name):
  1747. self.name = slack_name
  1748. def get_members(self):
  1749. return {self.user}
  1750. def create_buffer(self):
  1751. if not self.channel_buffer:
  1752. super(SlackDMChannel, self).create_buffer()
  1753. w.buffer_set(self.channel_buffer, "localvar_set_type", 'private')
  1754. def update_color(self):
  1755. if config.colorize_private_chats:
  1756. self.color_name = get_nick_color(self.name)
  1757. else:
  1758. self.color_name = ""
  1759. def formatted_name(self, style="default", typing=False, present=True, enable_color=False, **kwargs):
  1760. prepend = ""
  1761. if config.show_buflist_presence:
  1762. prepend = "+" if present else " "
  1763. select = {
  1764. "default": self.slack_name,
  1765. "sidebar": prepend + self.slack_name,
  1766. "base": self.slack_name,
  1767. "long_default": "{}.{}".format(self.team.preferred_name, self.slack_name),
  1768. "long_base": "{}.{}".format(self.team.preferred_name, self.slack_name),
  1769. }
  1770. if config.colorize_private_chats and enable_color:
  1771. return colorize_string(self.color_name, select[style])
  1772. else:
  1773. return select[style]
  1774. def open(self, update_remote=True):
  1775. self.create_buffer()
  1776. self.get_history()
  1777. if "info" in SLACK_API_TRANSLATOR[self.type]:
  1778. s = SlackRequest(self.team, SLACK_API_TRANSLATOR[self.type]["info"],
  1779. {"name": self.identifier}, channel=self)
  1780. self.eventrouter.receive(s)
  1781. if update_remote:
  1782. if "join" in SLACK_API_TRANSLATOR[self.type]:
  1783. s = SlackRequest(self.team, SLACK_API_TRANSLATOR[self.type]["join"],
  1784. {"users": self.user, "return_im": True}, channel=self)
  1785. self.eventrouter.receive(s)
  1786. def rename(self):
  1787. if self.channel_buffer:
  1788. new_name = self.formatted_name(style="sidebar", present=self.team.is_user_present(self.user), enable_color=config.colorize_private_chats)
  1789. if self.current_short_name != new_name:
  1790. self.current_short_name = new_name
  1791. w.buffer_set(self.channel_buffer, "short_name", new_name)
  1792. return True
  1793. return False
  1794. def refresh(self):
  1795. return self.rename()
  1796. class SlackGroupChannel(SlackChannel):
  1797. """
  1798. A group channel is a private discussion group.
  1799. """
  1800. def __init__(self, eventrouter, **kwargs):
  1801. super(SlackGroupChannel, self).__init__(eventrouter, **kwargs)
  1802. self.type = "group"
  1803. self.set_name(self.slack_name)
  1804. def set_name(self, slack_name):
  1805. self.name = config.group_name_prefix + slack_name
  1806. class SlackPrivateChannel(SlackGroupChannel):
  1807. """
  1808. A private channel is a private discussion group. At the time of writing, it
  1809. differs from group channels in that group channels are channels initially
  1810. created as private, while private channels are public channels which are
  1811. later converted to private.
  1812. """
  1813. def __init__(self, eventrouter, **kwargs):
  1814. super(SlackPrivateChannel, self).__init__(eventrouter, **kwargs)
  1815. self.type = "private"
  1816. def set_related_server(self, team):
  1817. super(SlackPrivateChannel, self).set_related_server(team)
  1818. # Fetch members here (after the team is known) since they aren't
  1819. # included in rtm.start
  1820. s = SlackRequest(team, 'conversations.members', {'channel': self.identifier}, channel=self)
  1821. self.eventrouter.receive(s)
  1822. class SlackMPDMChannel(SlackChannel):
  1823. """
  1824. An MPDM channel is a special instance of a 'group' channel.
  1825. We change the name to look less terrible in weechat.
  1826. """
  1827. def __init__(self, eventrouter, team_users, myidentifier, **kwargs):
  1828. kwargs["name"] = ','.join(sorted(
  1829. getattr(team_users.get(user_id), 'name', user_id)
  1830. for user_id in kwargs["members"]
  1831. if user_id != myidentifier
  1832. ))
  1833. super(SlackMPDMChannel, self).__init__(eventrouter, **kwargs)
  1834. self.type = "mpim"
  1835. def open(self, update_remote=True):
  1836. self.create_buffer()
  1837. self.active = True
  1838. self.get_history()
  1839. if "info" in SLACK_API_TRANSLATOR[self.type]:
  1840. s = SlackRequest(self.team, SLACK_API_TRANSLATOR[self.type]["info"],
  1841. {"channel": self.identifier}, channel=self)
  1842. self.eventrouter.receive(s)
  1843. if update_remote and 'join' in SLACK_API_TRANSLATOR[self.type]:
  1844. s = SlackRequest(self.team, SLACK_API_TRANSLATOR[self.type]['join'],
  1845. {'users': ','.join(self.members)}, channel=self)
  1846. self.eventrouter.receive(s)
  1847. def set_name(self, slack_name):
  1848. self.name = slack_name
  1849. def formatted_name(self, style="default", typing=False, **kwargs):
  1850. if typing and config.channel_name_typing_indicator:
  1851. prepend = ">"
  1852. else:
  1853. prepend = "@"
  1854. select = {
  1855. "default": self.name,
  1856. "sidebar": prepend + self.name,
  1857. "base": self.name,
  1858. "long_default": "{}.{}".format(self.team.preferred_name, self.name),
  1859. "long_base": "{}.{}".format(self.team.preferred_name, self.name),
  1860. }
  1861. return select[style]
  1862. def rename(self):
  1863. pass
  1864. class SlackSharedChannel(SlackChannel):
  1865. def __init__(self, eventrouter, **kwargs):
  1866. super(SlackSharedChannel, self).__init__(eventrouter, **kwargs)
  1867. self.type = 'shared'
  1868. def set_related_server(self, team):
  1869. super(SlackSharedChannel, self).set_related_server(team)
  1870. # Fetch members here (after the team is known) since they aren't
  1871. # included in rtm.start
  1872. s = SlackRequest(team, 'conversations.members', {'channel': self.identifier}, channel=self)
  1873. self.eventrouter.receive(s)
  1874. def get_history(self, slow_queue=False):
  1875. # Get info for external users in the channel
  1876. for user in self.members - set(self.team.users.keys()):
  1877. s = SlackRequest(self.team, 'users.info', {'user': user}, channel=self)
  1878. self.eventrouter.receive(s)
  1879. super(SlackSharedChannel, self).get_history(slow_queue)
  1880. def set_name(self, slack_name):
  1881. self.name = config.shared_name_prefix + slack_name
  1882. class SlackThreadChannel(SlackChannelCommon):
  1883. """
  1884. A thread channel is a virtual channel. We don't inherit from
  1885. SlackChannel, because most of how it operates will be different.
  1886. """
  1887. def __init__(self, eventrouter, parent_message):
  1888. self.eventrouter = eventrouter
  1889. self.parent_message = parent_message
  1890. self.hashed_messages = {}
  1891. self.channel_buffer = None
  1892. self.type = "thread"
  1893. self.got_history = False
  1894. self.label = None
  1895. self.members = self.parent_message.channel.members
  1896. self.team = self.parent_message.team
  1897. self.last_line_from = None
  1898. @property
  1899. def identifier(self):
  1900. return self.parent_message.channel.identifier
  1901. @property
  1902. def messages(self):
  1903. return self.parent_message.channel.messages
  1904. @property
  1905. def muted(self):
  1906. return self.parent_message.channel.muted
  1907. def formatted_name(self, style="default", **kwargs):
  1908. hash_or_ts = self.parent_message.hash or self.parent_message.ts
  1909. styles = {
  1910. "default": " +{}".format(hash_or_ts),
  1911. "long_default": "{}.{}".format(self.parent_message.channel.formatted_name(style="long_default"), hash_or_ts),
  1912. "sidebar": " +{}".format(hash_or_ts),
  1913. }
  1914. return styles[style]
  1915. def refresh(self):
  1916. self.rename()
  1917. def mark_read(self, ts=None, update_remote=True, force=False):
  1918. if self.channel_buffer:
  1919. w.buffer_set(self.channel_buffer, "unread", "")
  1920. w.buffer_set(self.channel_buffer, "hotlist", "-1")
  1921. def buffer_prnt(self, nick, text, timestamp, tag_nick=None):
  1922. data = "{}\t{}".format(format_nick(nick, self.last_line_from), text)
  1923. self.last_line_from = nick
  1924. ts = SlackTS(timestamp)
  1925. if self.channel_buffer:
  1926. if self.parent_message.channel.type in ["im", "mpim"]:
  1927. tagset = "dm"
  1928. else:
  1929. tagset = "channel"
  1930. self_msg = tag_nick == self.team.nick
  1931. tags = tag(tagset, user=tag_nick, self_msg=self_msg)
  1932. w.prnt_date_tags(self.channel_buffer, ts.major, tags, data)
  1933. modify_last_print_time(self.channel_buffer, ts.minor)
  1934. if self_msg:
  1935. self.mark_read(ts, update_remote=False, force=True)
  1936. def get_history(self):
  1937. self.got_history = True
  1938. for message in chain([self.parent_message], self.parent_message.submessages):
  1939. text = self.render(message)
  1940. self.buffer_prnt(message.sender, text, message.ts, tag_nick=message.sender_plain)
  1941. if len(self.parent_message.submessages) < self.parent_message.number_of_replies():
  1942. s = SlackRequest(self.team, "conversations.replies",
  1943. {"channel": self.identifier, "ts": self.parent_message.ts},
  1944. channel=self.parent_message.channel)
  1945. self.eventrouter.receive(s)
  1946. def main_message_keys_reversed(self):
  1947. return (message.ts for message in reversed(self.parent_message.submessages))
  1948. def send_message(self, message, subtype=None, request_dict_ext={}):
  1949. if subtype == 'me_message':
  1950. w.prnt("", "ERROR: /me is not supported in threads")
  1951. return w.WEECHAT_RC_ERROR
  1952. message = linkify_text(message, self.team)
  1953. dbg(message)
  1954. request = {"type": "message", "text": message,
  1955. "channel": self.parent_message.channel.identifier,
  1956. "thread_ts": str(self.parent_message.ts),
  1957. "user": self.team.myidentifier}
  1958. request.update(request_dict_ext)
  1959. self.team.send_to_websocket(request)
  1960. def open(self, update_remote=True):
  1961. self.create_buffer()
  1962. self.active = True
  1963. self.get_history()
  1964. def rename(self):
  1965. if self.channel_buffer and not self.label:
  1966. w.buffer_set(self.channel_buffer, "short_name", self.formatted_name(style="sidebar", enable_color=True))
  1967. def set_highlights(self, highlight_string=None):
  1968. if self.channel_buffer:
  1969. if highlight_string is None:
  1970. highlight_string = ",".join(self.parent_message.channel.highlights())
  1971. w.buffer_set(self.channel_buffer, "highlight_words", highlight_string)
  1972. def create_buffer(self):
  1973. """
  1974. Creates the weechat buffer where the thread magic happens.
  1975. """
  1976. if not self.channel_buffer:
  1977. self.channel_buffer = w.buffer_new(self.formatted_name(style="long_default"), "buffer_input_callback", "EVENTROUTER", "", "")
  1978. self.eventrouter.weechat_controller.register_buffer(self.channel_buffer, self)
  1979. w.buffer_set(self.channel_buffer, "localvar_set_type", 'channel')
  1980. w.buffer_set(self.channel_buffer, "localvar_set_nick", self.team.nick)
  1981. w.buffer_set(self.channel_buffer, "localvar_set_channel", self.formatted_name())
  1982. w.buffer_set(self.channel_buffer, "localvar_set_server", self.team.preferred_name)
  1983. w.buffer_set(self.channel_buffer, "short_name", self.formatted_name(style="sidebar", enable_color=True))
  1984. self.set_highlights()
  1985. time_format = w.config_string(w.config_get("weechat.look.buffer_time_format"))
  1986. parent_time = time.localtime(SlackTS(self.parent_message.ts).major)
  1987. topic = '{} {} | {}'.format(time.strftime(time_format, parent_time), self.parent_message.sender, self.render(self.parent_message) )
  1988. w.buffer_set(self.channel_buffer, "title", topic)
  1989. # self.eventrouter.weechat_controller.set_refresh_buffer_list(True)
  1990. def destroy_buffer(self, update_remote):
  1991. self.channel_buffer = None
  1992. self.got_history = False
  1993. self.active = False
  1994. def render(self, message, force=False):
  1995. return message.render(force)
  1996. class SlackUser(object):
  1997. """
  1998. Represends an individual slack user. Also where you set their name formatting.
  1999. """
  2000. def __init__(self, originating_team_id, **kwargs):
  2001. self.identifier = kwargs["id"]
  2002. # These attributes may be missing in the response, so we have to make
  2003. # sure they're set
  2004. self.profile = {}
  2005. self.presence = kwargs.get("presence", "unknown")
  2006. self.deleted = kwargs.get("deleted", False)
  2007. self.is_external = (not kwargs.get("is_bot") and
  2008. kwargs.get("team_id") != originating_team_id)
  2009. for key, value in kwargs.items():
  2010. setattr(self, key, value)
  2011. self.name = nick_from_profile(self.profile, kwargs["name"])
  2012. self.username = kwargs["name"]
  2013. self.update_color()
  2014. def __repr__(self):
  2015. return "Name:{} Identifier:{}".format(self.name, self.identifier)
  2016. def force_color(self, color_name):
  2017. self.color_name = color_name
  2018. def update_color(self):
  2019. # This will automatically be none/"" if the user has disabled nick
  2020. # colourization.
  2021. self.color_name = get_nick_color(self.name)
  2022. def update_status(self, status_emoji, status_text):
  2023. self.profile["status_emoji"] = status_emoji
  2024. self.profile["status_text"] = status_text
  2025. def formatted_name(self, prepend="", enable_color=True):
  2026. name = prepend + self.name
  2027. if enable_color:
  2028. return colorize_string(self.color_name, name)
  2029. else:
  2030. return name
  2031. class SlackBot(SlackUser):
  2032. """
  2033. Basically the same as a user, but split out to identify and for future
  2034. needs
  2035. """
  2036. def __init__(self, originating_team_id, **kwargs):
  2037. super(SlackBot, self).__init__(originating_team_id, is_bot=True, **kwargs)
  2038. class SlackMessage(object):
  2039. """
  2040. Represents a single slack message and associated context/metadata.
  2041. These are modifiable and can be rerendered to change a message,
  2042. delete a message, add a reaction, add a thread.
  2043. Note: these can't be tied to a SlackUser object because users
  2044. can be deleted, so we have to store sender in each one.
  2045. """
  2046. def __init__(self, message_json, team, channel, override_sender=None):
  2047. self.team = team
  2048. self.channel = channel
  2049. self.message_json = message_json
  2050. self.submessages = []
  2051. self.hash = None
  2052. if override_sender:
  2053. self.sender = override_sender
  2054. self.sender_plain = override_sender
  2055. else:
  2056. senders = self.get_sender()
  2057. self.sender, self.sender_plain = senders[0], senders[1]
  2058. self.ts = SlackTS(message_json['ts'])
  2059. def __hash__(self):
  2060. return hash(self.ts)
  2061. @property
  2062. def thread_channel(self):
  2063. return self.channel.thread_channels.get(self.ts)
  2064. def open_thread(self, switch=False):
  2065. if not self.thread_channel or not self.thread_channel.active:
  2066. self.channel.thread_channels[self.ts] = SlackThreadChannel(EVENTROUTER, self)
  2067. self.thread_channel.open()
  2068. if switch:
  2069. w.buffer_set(self.thread_channel.channel_buffer, "display", "1")
  2070. def render(self, force=False):
  2071. # If we already have a rendered version in the object, just return that.
  2072. if not force and self.message_json.get("_rendered_text"):
  2073. return self.message_json["_rendered_text"]
  2074. if "fallback" in self.message_json:
  2075. text = self.message_json["fallback"]
  2076. elif self.message_json.get("text"):
  2077. text = self.message_json["text"]
  2078. else:
  2079. text = ""
  2080. if self.message_json.get('mrkdwn', True):
  2081. text = render_formatting(text)
  2082. if (self.message_json.get('subtype') in ('channel_join', 'group_join') and
  2083. self.message_json.get('inviter')):
  2084. inviter_id = self.message_json.get('inviter')
  2085. text += " by invitation from <@{}>".format(inviter_id)
  2086. if "blocks" in self.message_json:
  2087. text += unfurl_blocks(self.message_json)
  2088. text = unfurl_refs(text)
  2089. if (self.message_json.get('subtype') == 'me_message' and
  2090. not self.message_json['text'].startswith(self.sender)):
  2091. text = "{} {}".format(self.sender, text)
  2092. if "edited" in self.message_json:
  2093. text += " " + colorize_string(config.color_edited_suffix, '(edited)')
  2094. text += unfurl_refs(unwrap_attachments(self.message_json, text))
  2095. text += unfurl_refs(unwrap_files(self.message_json, text))
  2096. text = unhtmlescape(text.lstrip().replace("\t", " "))
  2097. text += create_reactions_string(
  2098. self.message_json.get("reactions", ""), self.team.myidentifier)
  2099. if self.number_of_replies():
  2100. self.channel.hash_message(self.ts)
  2101. text += " " + colorize_string(get_thread_color(self.hash), "[ Thread: {} Replies: {} ]".format(
  2102. self.hash, self.number_of_replies()))
  2103. text = replace_string_with_emoji(text)
  2104. self.message_json["_rendered_text"] = text
  2105. return text
  2106. def change_text(self, new_text):
  2107. self.message_json["text"] = new_text
  2108. dbg(self.message_json)
  2109. def get_sender(self):
  2110. name = ""
  2111. name_plain = ""
  2112. user = self.team.users.get(self.message_json.get('user'))
  2113. if user:
  2114. name = "{}".format(user.formatted_name())
  2115. name_plain = "{}".format(user.formatted_name(enable_color=False))
  2116. if user.is_external:
  2117. name += config.external_user_suffix
  2118. name_plain += config.external_user_suffix
  2119. elif 'username' in self.message_json:
  2120. username = self.message_json["username"]
  2121. if self.message_json.get("subtype") == "bot_message":
  2122. name = "{} :]".format(username)
  2123. name_plain = "{}".format(username)
  2124. else:
  2125. name = "-{}-".format(username)
  2126. name_plain = "{}".format(username)
  2127. elif 'service_name' in self.message_json:
  2128. name = "-{}-".format(self.message_json["service_name"])
  2129. name_plain = "{}".format(self.message_json["service_name"])
  2130. elif self.message_json.get('bot_id') in self.team.bots:
  2131. name = "{} :]".format(self.team.bots[self.message_json["bot_id"]].formatted_name())
  2132. name_plain = "{}".format(self.team.bots[self.message_json["bot_id"]].formatted_name(enable_color=False))
  2133. return (name, name_plain)
  2134. def add_reaction(self, reaction, user):
  2135. m = self.message_json.get('reactions')
  2136. if m:
  2137. found = False
  2138. for r in m:
  2139. if r["name"] == reaction and user not in r["users"]:
  2140. r["users"].append(user)
  2141. found = True
  2142. if not found:
  2143. self.message_json["reactions"].append({"name": reaction, "users": [user]})
  2144. else:
  2145. self.message_json["reactions"] = [{"name": reaction, "users": [user]}]
  2146. def remove_reaction(self, reaction, user):
  2147. m = self.message_json.get('reactions')
  2148. if m:
  2149. for r in m:
  2150. if r["name"] == reaction and user in r["users"]:
  2151. r["users"].remove(user)
  2152. def has_mention(self):
  2153. return w.string_has_highlight(unfurl_refs(self.message_json.get('text')),
  2154. ",".join(self.channel.highlights()))
  2155. def number_of_replies(self):
  2156. return max(len(self.submessages), len(self.message_json.get("replies", [])))
  2157. def notify_thread(self, action=None, sender_id=None):
  2158. if config.auto_open_threads:
  2159. self.open_thread()
  2160. elif sender_id != self.team.myidentifier:
  2161. if action == "mention":
  2162. template = "You were mentioned in thread {hash}, channel {channel}"
  2163. elif action == "participant":
  2164. template = "New message in thread {hash}, channel {channel} in which you participated"
  2165. elif action == "response":
  2166. template = "New message in thread {hash} in response to own message in {channel}"
  2167. else:
  2168. template = "Notification for message in thread {hash}, channel {channel}"
  2169. message = template.format(hash=self.hash, channel=self.channel.formatted_name())
  2170. self.team.buffer_prnt(message, message=True)
  2171. class SlackThreadMessage(SlackMessage):
  2172. def __init__(self, parent_message, *args):
  2173. super(SlackThreadMessage, self).__init__(*args)
  2174. self.parent_message = parent_message
  2175. class Hdata(object):
  2176. def __init__(self, w):
  2177. self.buffer = w.hdata_get('buffer')
  2178. self.line = w.hdata_get('line')
  2179. self.line_data = w.hdata_get('line_data')
  2180. self.lines = w.hdata_get('lines')
  2181. class SlackTS(object):
  2182. def __init__(self, ts=None):
  2183. if ts:
  2184. self.major, self.minor = [int(x) for x in ts.split('.', 1)]
  2185. else:
  2186. self.major = int(time.time())
  2187. self.minor = 0
  2188. def __cmp__(self, other):
  2189. if isinstance(other, SlackTS):
  2190. if self.major < other.major:
  2191. return -1
  2192. elif self.major > other.major:
  2193. return 1
  2194. elif self.major == other.major:
  2195. if self.minor < other.minor:
  2196. return -1
  2197. elif self.minor > other.minor:
  2198. return 1
  2199. else:
  2200. return 0
  2201. elif isinstance(other, str):
  2202. s = self.__str__()
  2203. if s < other:
  2204. return -1
  2205. elif s > other:
  2206. return 1
  2207. elif s == other:
  2208. return 0
  2209. def __lt__(self, other):
  2210. return self.__cmp__(other) < 0
  2211. def __le__(self, other):
  2212. return self.__cmp__(other) <= 0
  2213. def __eq__(self, other):
  2214. return self.__cmp__(other) == 0
  2215. def __ge__(self, other):
  2216. return self.__cmp__(other) >= 0
  2217. def __gt__(self, other):
  2218. return self.__cmp__(other) > 0
  2219. def __hash__(self):
  2220. return hash("{}.{}".format(self.major, self.minor))
  2221. def __repr__(self):
  2222. return str("{0}.{1:06d}".format(self.major, self.minor))
  2223. def split(self, *args, **kwargs):
  2224. return [self.major, self.minor]
  2225. def majorstr(self):
  2226. return str(self.major)
  2227. def minorstr(self):
  2228. return str(self.minor)
  2229. ###### New handlers
  2230. def handle_rtmstart(login_data, eventrouter, team, channel, metadata):
  2231. """
  2232. This handles the main entry call to slack, rtm.start
  2233. """
  2234. metadata = login_data["wee_slack_request_metadata"]
  2235. if not login_data["ok"]:
  2236. w.prnt("", "ERROR: Failed connecting to Slack with token {}: {}"
  2237. .format(token_for_print(metadata.token), login_data["error"]))
  2238. if not re.match(r"^xo\w\w(-\d+){3}-[0-9a-f]+$", metadata.token):
  2239. w.prnt("", "ERROR: Token does not look like a valid Slack token. "
  2240. "Ensure it is a valid token and not just a OAuth code.")
  2241. return
  2242. self_profile = next(
  2243. user["profile"]
  2244. for user in login_data["users"]
  2245. if user["id"] == login_data["self"]["id"]
  2246. )
  2247. self_nick = nick_from_profile(self_profile, login_data["self"]["name"])
  2248. # Let's reuse a team if we have it already.
  2249. th = SlackTeam.generate_team_hash(login_data['team']['id'], login_data['team']['domain'])
  2250. if not eventrouter.teams.get(th):
  2251. users = {}
  2252. for item in login_data["users"]:
  2253. users[item["id"]] = SlackUser(login_data['team']['id'], **item)
  2254. bots = {}
  2255. for item in login_data["bots"]:
  2256. bots[item["id"]] = SlackBot(login_data['team']['id'], **item)
  2257. subteams = {}
  2258. for item in login_data["subteams"]["all"]:
  2259. is_member = item['id'] in login_data["subteams"]["self"]
  2260. subteams[item['id']] = SlackSubteam(
  2261. login_data['team']['id'], is_member=is_member, **item)
  2262. channels = {}
  2263. for item in login_data["channels"]:
  2264. if item["is_shared"]:
  2265. channels[item["id"]] = SlackSharedChannel(eventrouter, **item)
  2266. elif item["is_private"]:
  2267. channels[item["id"]] = SlackPrivateChannel(eventrouter, **item)
  2268. else:
  2269. channels[item["id"]] = SlackChannel(eventrouter, **item)
  2270. for item in login_data["ims"]:
  2271. channels[item["id"]] = SlackDMChannel(eventrouter, users, **item)
  2272. for item in login_data["groups"]:
  2273. if item["is_mpim"]:
  2274. channels[item["id"]] = SlackMPDMChannel(eventrouter, users, login_data["self"]["id"], **item)
  2275. else:
  2276. channels[item["id"]] = SlackGroupChannel(eventrouter, **item)
  2277. t = SlackTeam(
  2278. eventrouter,
  2279. metadata.token,
  2280. th,
  2281. login_data['url'],
  2282. login_data["team"],
  2283. subteams,
  2284. self_nick,
  2285. login_data["self"]["id"],
  2286. login_data["self"]["manual_presence"],
  2287. users,
  2288. bots,
  2289. channels,
  2290. muted_channels=login_data["self"]["prefs"]["muted_channels"],
  2291. highlight_words=login_data["self"]["prefs"]["highlight_words"],
  2292. )
  2293. eventrouter.register_team(t)
  2294. else:
  2295. t = eventrouter.teams.get(th)
  2296. if t.myidentifier != login_data["self"]["id"]:
  2297. print_error(
  2298. 'The Slack team {} has tokens for two different users, this is not supported. The '
  2299. 'token {} is for user {}, and the token {} is for user {}. Please remove one of '
  2300. 'them.'.format(t.team_info["name"], token_for_print(t.token), t.nick,
  2301. token_for_print(metadata.token), self_nick)
  2302. )
  2303. return
  2304. elif metadata.metadata.get('initial_connection'):
  2305. print_error(
  2306. 'Ignoring duplicate Slack tokens for the same team ({}) and user ({}). The two '
  2307. 'tokens are {} and {}.'.format(t.team_info["name"], t.nick,
  2308. token_for_print(t.token), token_for_print(metadata.token)),
  2309. warning=True
  2310. )
  2311. return
  2312. else:
  2313. t.set_reconnect_url(login_data['url'])
  2314. t.connecting_rtm = False
  2315. t.connect()
  2316. def handle_rtmconnect(login_data, eventrouter, team, channel, metadata):
  2317. metadata = login_data["wee_slack_request_metadata"]
  2318. team = metadata.team
  2319. team.connecting_rtm = False
  2320. if not login_data["ok"]:
  2321. w.prnt("", "ERROR: Failed reconnecting to Slack with token {}: {}"
  2322. .format(token_for_print(metadata.token), login_data["error"]))
  2323. return
  2324. team.set_reconnect_url(login_data['url'])
  2325. team.connect()
  2326. def handle_emojilist(emoji_json, eventrouter, team, channel, metadata):
  2327. if emoji_json["ok"]:
  2328. team.emoji_completions.extend(emoji_json["emoji"].keys())
  2329. def handle_channelsinfo(channel_json, eventrouter, team, channel, metadata):
  2330. channel.set_unread_count_display(channel_json['channel'].get('unread_count_display', 0))
  2331. channel.set_members(channel_json['channel']['members'])
  2332. def handle_groupsinfo(group_json, eventrouter, team, channel, metadatas):
  2333. channel.set_unread_count_display(group_json['group'].get('unread_count_display', 0))
  2334. def handle_conversationsopen(conversation_json, eventrouter, team, channel, metadata, object_name='channel'):
  2335. # Set unread count if the channel isn't new
  2336. if channel:
  2337. unread_count_display = conversation_json[object_name].get('unread_count_display', 0)
  2338. channel.set_unread_count_display(unread_count_display)
  2339. def handle_mpimopen(mpim_json, eventrouter, team, channel, metadata, object_name='group'):
  2340. handle_conversationsopen(mpim_json, eventrouter, team, channel, metadata, object_name)
  2341. def handle_history(message_json, eventrouter, team, channel, metadata):
  2342. if metadata['clear']:
  2343. channel.clear_messages()
  2344. channel.got_history = True
  2345. for message in reversed(message_json["messages"]):
  2346. process_message(message, eventrouter, team, channel, metadata, history_message=True)
  2347. handle_channelshistory = handle_history
  2348. handle_conversationshistory = handle_history
  2349. handle_groupshistory = handle_history
  2350. handle_imhistory = handle_history
  2351. handle_mpimhistory = handle_history
  2352. def handle_conversationsreplies(message_json, eventrouter, team, channel, metadata):
  2353. for message in message_json['messages']:
  2354. process_message(message, eventrouter, team, channel, metadata)
  2355. def handle_conversationsmembers(members_json, eventrouter, team, channel, metadata):
  2356. if members_json['ok']:
  2357. channel.set_members(members_json['members'])
  2358. else:
  2359. w.prnt(team.channel_buffer, '{}Couldn\'t load members for channel {}. Error: {}'
  2360. .format(w.prefix('error'), channel.name, members_json['error']))
  2361. def handle_usersinfo(user_json, eventrouter, team, channel, metadata):
  2362. user_info = user_json['user']
  2363. if not metadata.get('user'):
  2364. user = SlackUser(team.identifier, **user_info)
  2365. team.users[user_info['id']] = user
  2366. if channel.type == 'shared':
  2367. channel.update_nicklist(user_info['id'])
  2368. elif channel.type == 'im':
  2369. channel.slack_name = user.name
  2370. channel.set_topic(create_user_status_string(user.profile))
  2371. def handle_usergroupsuserslist(users_json, eventrouter, team, channel, metadata):
  2372. header = 'Users in {}'.format(metadata['usergroup_handle'])
  2373. users = [team.users[key] for key in users_json['users']]
  2374. return print_users_info(team, header, users)
  2375. def handle_usersprofileset(json, eventrouter, team, channel, metadata):
  2376. if not json['ok']:
  2377. w.prnt('', 'ERROR: Failed to set profile: {}'.format(json['error']))
  2378. def handle_conversationsinvite(json, eventrouter, team, channel, metadata):
  2379. nicks = ', '.join(metadata['nicks'])
  2380. if json['ok']:
  2381. w.prnt(team.channel_buffer, 'Invited {} to {}'.format(nicks, channel.name))
  2382. else:
  2383. w.prnt(team.channel_buffer, 'ERROR: Couldn\'t invite {} to {}. Error: {}'
  2384. .format(nicks, channel.name, json['error']))
  2385. def handle_chatcommand(json, eventrouter, team, channel, metadata):
  2386. command = '{} {}'.format(metadata['command'], metadata['command_args']).rstrip()
  2387. response = unfurl_refs(json['response']) if 'response' in json else ''
  2388. if json['ok']:
  2389. response_text = 'Response: {}'.format(response) if response else 'No response'
  2390. w.prnt(team.channel_buffer, 'Ran command "{}". {}' .format(command, response_text))
  2391. else:
  2392. response_text = '. Response: {}'.format(response) if response else ''
  2393. w.prnt(team.channel_buffer, 'ERROR: Couldn\'t run command "{}". Error: {}{}'
  2394. .format(command, json['error'], response_text))
  2395. def handle_reactionsadd(json, eventrouter, team, channel, metadata):
  2396. if not json['ok']:
  2397. print_error("Couldn't add reaction {}: {}".format(metadata['reaction'], json['error']))
  2398. def handle_reactionsremove(json, eventrouter, team, channel, metadata):
  2399. if not json['ok']:
  2400. print_error("Couldn't remove reaction {}: {}".format(metadata['reaction'], json['error']))
  2401. ###### New/converted process_ and subprocess_ methods
  2402. def process_hello(message_json, eventrouter, team, channel, metadata):
  2403. team.subscribe_users_presence()
  2404. def process_reconnect_url(message_json, eventrouter, team, channel, metadata):
  2405. team.set_reconnect_url(message_json['url'])
  2406. def process_presence_change(message_json, eventrouter, team, channel, metadata):
  2407. users = [team.users[user_id] for user_id in message_json.get("users", [])]
  2408. if "user" in metadata:
  2409. users.append(metadata["user"])
  2410. for user in users:
  2411. team.update_member_presence(user, message_json["presence"])
  2412. if team.myidentifier in users:
  2413. w.bar_item_update("away")
  2414. w.bar_item_update("slack_away")
  2415. def process_manual_presence_change(message_json, eventrouter, team, channel, metadata):
  2416. team.my_manual_presence = message_json["presence"]
  2417. w.bar_item_update("away")
  2418. w.bar_item_update("slack_away")
  2419. def process_pref_change(message_json, eventrouter, team, channel, metadata):
  2420. if message_json['name'] == 'muted_channels':
  2421. team.set_muted_channels(message_json['value'])
  2422. elif message_json['name'] == 'highlight_words':
  2423. team.set_highlight_words(message_json['value'])
  2424. else:
  2425. dbg("Preference change not implemented: {}\n".format(message_json['name']))
  2426. def process_user_change(message_json, eventrouter, team, channel, metadata):
  2427. """
  2428. Currently only used to update status, but lots here we could do.
  2429. """
  2430. user = metadata['user']
  2431. profile = message_json['user']['profile']
  2432. if user:
  2433. user.update_status(profile.get('status_emoji'), profile.get('status_text'))
  2434. dmchannel = team.find_channel_by_members({user.identifier}, channel_type='im')
  2435. if dmchannel:
  2436. dmchannel.set_topic(create_user_status_string(profile))
  2437. def process_user_typing(message_json, eventrouter, team, channel, metadata):
  2438. if channel:
  2439. channel.set_typing(metadata["user"].name)
  2440. w.bar_item_update("slack_typing_notice")
  2441. def process_team_join(message_json, eventrouter, team, channel, metadata):
  2442. user = message_json['user']
  2443. team.users[user["id"]] = SlackUser(team.identifier, **user)
  2444. def process_pong(message_json, eventrouter, team, channel, metadata):
  2445. team.last_pong_time = time.time()
  2446. def process_message(message_json, eventrouter, team, channel, metadata, history_message=False):
  2447. if SlackTS(message_json["ts"]) in channel.messages:
  2448. return
  2449. if "thread_ts" in message_json and "reply_count" not in message_json and "subtype" not in message_json:
  2450. if message_json.get("reply_broadcast"):
  2451. message_json["subtype"] = "thread_broadcast"
  2452. else:
  2453. message_json["subtype"] = "thread_message"
  2454. subtype = message_json.get("subtype")
  2455. subtype_functions = get_functions_with_prefix("subprocess_")
  2456. if subtype in subtype_functions:
  2457. subtype_functions[subtype](message_json, eventrouter, team, channel, history_message)
  2458. else:
  2459. message = SlackMessage(message_json, team, channel)
  2460. channel.store_message(message, team)
  2461. text = channel.render(message)
  2462. dbg("Rendered message: %s" % text)
  2463. dbg("Sender: %s (%s)" % (message.sender, message.sender_plain))
  2464. if subtype == 'me_message':
  2465. prefix = w.prefix("action").rstrip()
  2466. else:
  2467. prefix = message.sender
  2468. channel.buffer_prnt(prefix, text, message.ts, tag_nick=message.sender_plain, history_message=history_message)
  2469. channel.unread_count_display += 1
  2470. dbg("NORMAL REPLY {}".format(message_json))
  2471. if not history_message:
  2472. download_files(message_json, team)
  2473. def download_files(message_json, team):
  2474. download_location = config.files_download_location
  2475. if not download_location:
  2476. return
  2477. download_location = w.string_eval_path_home(download_location, {}, {}, {})
  2478. if not os.path.exists(download_location):
  2479. try:
  2480. os.makedirs(download_location)
  2481. except:
  2482. w.prnt('', 'ERROR: Failed to create directory at files_download_location: {}'
  2483. .format(format_exc_only()))
  2484. def fileout_iter(path):
  2485. yield path
  2486. main, ext = os.path.splitext(path)
  2487. for i in count(start=1):
  2488. yield main + "-{}".format(i) + ext
  2489. for f in message_json.get('files', []):
  2490. if f.get('mode') == 'tombstone':
  2491. continue
  2492. filetype = '' if f['title'].endswith(f['filetype']) else '.' + f['filetype']
  2493. filename = '{}_{}{}'.format(team.preferred_name, f['title'], filetype)
  2494. for fileout in fileout_iter(os.path.join(download_location, filename)):
  2495. if os.path.isfile(fileout):
  2496. continue
  2497. w.hook_process_hashtable(
  2498. "url:" + f['url_private'],
  2499. {
  2500. 'file_out': fileout,
  2501. 'httpheader': 'Authorization: Bearer ' + team.token
  2502. },
  2503. config.slack_timeout, "", "")
  2504. break
  2505. def subprocess_thread_message(message_json, eventrouter, team, channel, history_message):
  2506. parent_ts = message_json.get('thread_ts')
  2507. if parent_ts:
  2508. parent_message = channel.messages.get(SlackTS(parent_ts))
  2509. if parent_message:
  2510. message = SlackThreadMessage(
  2511. parent_message, message_json, team, channel)
  2512. parent_message.submessages.append(message)
  2513. channel.hash_message(parent_ts)
  2514. channel.store_message(message, team)
  2515. channel.change_message(parent_ts)
  2516. if parent_message.thread_channel and parent_message.thread_channel.active:
  2517. parent_message.thread_channel.buffer_prnt(message.sender, parent_message.thread_channel.render(message), message.ts, tag_nick=message.sender_plain)
  2518. elif message.ts > channel.last_read and message.has_mention():
  2519. parent_message.notify_thread(action="mention", sender_id=message_json["user"])
  2520. if config.thread_messages_in_channel or message_json["subtype"] == "thread_broadcast":
  2521. thread_tag = "thread_broadcast" if message_json["subtype"] == "thread_broadcast" else "thread_message"
  2522. channel.buffer_prnt(
  2523. message.sender,
  2524. channel.render(message),
  2525. message.ts,
  2526. tag_nick=message.sender_plain,
  2527. history_message=history_message,
  2528. extra_tags=[thread_tag],
  2529. )
  2530. subprocess_thread_broadcast = subprocess_thread_message
  2531. def subprocess_channel_join(message_json, eventrouter, team, channel, history_message):
  2532. prefix_join = w.prefix("join").strip()
  2533. message = SlackMessage(message_json, team, channel, override_sender=prefix_join)
  2534. channel.buffer_prnt(prefix_join, channel.render(message), message_json["ts"], tagset='join', tag_nick=message.get_sender()[1], history_message=history_message)
  2535. channel.user_joined(message_json['user'])
  2536. channel.store_message(message, team)
  2537. def subprocess_channel_leave(message_json, eventrouter, team, channel, history_message):
  2538. prefix_leave = w.prefix("quit").strip()
  2539. message = SlackMessage(message_json, team, channel, override_sender=prefix_leave)
  2540. channel.buffer_prnt(prefix_leave, channel.render(message), message_json["ts"], tagset='leave', tag_nick=message.get_sender()[1], history_message=history_message)
  2541. channel.user_left(message_json['user'])
  2542. channel.store_message(message, team)
  2543. def subprocess_channel_topic(message_json, eventrouter, team, channel, history_message):
  2544. prefix_topic = w.prefix("network").strip()
  2545. message = SlackMessage(message_json, team, channel, override_sender=prefix_topic)
  2546. channel.buffer_prnt(prefix_topic, channel.render(message), message_json["ts"], tagset="topic", tag_nick=message.get_sender()[1], history_message=history_message)
  2547. channel.set_topic(message_json["topic"])
  2548. channel.store_message(message, team)
  2549. subprocess_group_join = subprocess_channel_join
  2550. subprocess_group_leave = subprocess_channel_leave
  2551. subprocess_group_topic = subprocess_channel_topic
  2552. def subprocess_message_replied(message_json, eventrouter, team, channel, history_message):
  2553. parent_ts = message_json["message"].get("thread_ts")
  2554. parent_message = channel.messages.get(SlackTS(parent_ts))
  2555. # Thread exists but is not open yet
  2556. if parent_message is not None \
  2557. and not (parent_message.thread_channel and parent_message.thread_channel.active):
  2558. channel.hash_message(parent_ts)
  2559. last_message = max(message_json["message"]["replies"], key=lambda x: x["ts"])
  2560. if message_json["message"].get("user") == team.myidentifier:
  2561. parent_message.notify_thread(action="response", sender_id=last_message["user"])
  2562. elif any(team.myidentifier == r["user"] for r in message_json["message"]["replies"]):
  2563. parent_message.notify_thread(action="participant", sender_id=last_message["user"])
  2564. def subprocess_message_changed(message_json, eventrouter, team, channel, history_message):
  2565. new_message = message_json.get("message")
  2566. channel.change_message(new_message["ts"], message_json=new_message)
  2567. def subprocess_message_deleted(message_json, eventrouter, team, channel, history_message):
  2568. message = colorize_string(config.color_deleted, '(deleted)')
  2569. channel.change_message(message_json["deleted_ts"], text=message)
  2570. def process_reply(message_json, eventrouter, team, channel, metadata):
  2571. reply_to = int(message_json["reply_to"])
  2572. original_message_json = team.ws_replies.pop(reply_to, None)
  2573. if original_message_json:
  2574. original_message_json.update(message_json)
  2575. channel = team.channels[original_message_json.get('channel')]
  2576. process_message(original_message_json, eventrouter, team=team, channel=channel, metadata={})
  2577. dbg("REPLY {}".format(message_json))
  2578. else:
  2579. dbg("Unexpected reply {}".format(message_json))
  2580. def process_channel_marked(message_json, eventrouter, team, channel, metadata):
  2581. ts = message_json.get("ts")
  2582. if ts:
  2583. channel.mark_read(ts=ts, force=True, update_remote=False)
  2584. else:
  2585. dbg("tried to mark something weird {}".format(message_json))
  2586. process_group_marked = process_channel_marked
  2587. process_im_marked = process_channel_marked
  2588. process_mpim_marked = process_channel_marked
  2589. def process_channel_joined(message_json, eventrouter, team, channel, metadata):
  2590. channel.update_from_message_json(message_json["channel"])
  2591. channel.open()
  2592. def process_channel_created(message_json, eventrouter, team, channel, metadata):
  2593. item = message_json["channel"]
  2594. item['is_member'] = False
  2595. channel = SlackChannel(eventrouter, team=team, **item)
  2596. team.channels[item["id"]] = channel
  2597. team.buffer_prnt('Channel created: {}'.format(channel.slack_name))
  2598. def process_channel_rename(message_json, eventrouter, team, channel, metadata):
  2599. channel.slack_name = message_json['channel']['name']
  2600. def process_im_created(message_json, eventrouter, team, channel, metadata):
  2601. item = message_json["channel"]
  2602. channel = SlackDMChannel(eventrouter, team=team, users=team.users, **item)
  2603. team.channels[item["id"]] = channel
  2604. team.buffer_prnt('IM channel created: {}'.format(channel.name))
  2605. def process_im_open(message_json, eventrouter, team, channel, metadata):
  2606. channel.check_should_open(True)
  2607. w.buffer_set(channel.channel_buffer, "hotlist", "2")
  2608. def process_im_close(message_json, eventrouter, team, channel, metadata):
  2609. if channel.channel_buffer:
  2610. w.prnt(team.channel_buffer,
  2611. 'IM {} closed by another client or the server'.format(channel.name))
  2612. eventrouter.weechat_controller.unregister_buffer(channel.channel_buffer, False, True)
  2613. def process_group_joined(message_json, eventrouter, team, channel, metadata):
  2614. item = message_json["channel"]
  2615. if item["name"].startswith("mpdm-"):
  2616. channel = SlackMPDMChannel(eventrouter, team.users, team.myidentifier, team=team, **item)
  2617. else:
  2618. channel = SlackGroupChannel(eventrouter, team=team, **item)
  2619. team.channels[item["id"]] = channel
  2620. channel.open()
  2621. def process_reaction_added(message_json, eventrouter, team, channel, metadata):
  2622. channel = team.channels.get(message_json["item"].get("channel"))
  2623. if message_json["item"].get("type") == "message":
  2624. ts = SlackTS(message_json['item']["ts"])
  2625. message = channel.messages.get(ts)
  2626. if message:
  2627. message.add_reaction(message_json["reaction"], message_json["user"])
  2628. channel.change_message(ts)
  2629. else:
  2630. dbg("reaction to item type not supported: " + str(message_json))
  2631. def process_reaction_removed(message_json, eventrouter, team, channel, metadata):
  2632. channel = team.channels.get(message_json["item"].get("channel"))
  2633. if message_json["item"].get("type") == "message":
  2634. ts = SlackTS(message_json['item']["ts"])
  2635. message = channel.messages.get(ts)
  2636. if message:
  2637. message.remove_reaction(message_json["reaction"], message_json["user"])
  2638. channel.change_message(ts)
  2639. else:
  2640. dbg("Reaction to item type not supported: " + str(message_json))
  2641. def process_subteam_created(subteam_json, eventrouter, team, channel, metadata):
  2642. subteam_json_info = subteam_json['subteam']
  2643. is_member = team.myidentifier in subteam_json_info.get('users', [])
  2644. subteam = SlackSubteam(team.identifier, is_member=is_member, **subteam_json_info)
  2645. team.subteams[subteam_json_info['id']] = subteam
  2646. def process_subteam_updated(subteam_json, eventrouter, team, channel, metadata):
  2647. current_subteam_info = team.subteams[subteam_json['subteam']['id']]
  2648. is_member = team.myidentifier in subteam_json['subteam'].get('users', [])
  2649. new_subteam_info = SlackSubteam(team.identifier, is_member=is_member, **subteam_json['subteam'])
  2650. team.subteams[subteam_json['subteam']['id']] = new_subteam_info
  2651. if current_subteam_info.is_member != new_subteam_info.is_member:
  2652. for channel in team.channels.values():
  2653. channel.set_highlights()
  2654. if config.notify_usergroup_handle_updated and current_subteam_info.handle != new_subteam_info.handle:
  2655. message = 'User group {old_handle} has updated its handle to {new_handle} in team {team}.'.format(
  2656. name=current_subteam_info.handle, handle=new_subteam_info.handle, team=team.preferred_name)
  2657. team.buffer_prnt(message, message=True)
  2658. def process_emoji_changed(message_json, eventrouter, team, channel, metadata):
  2659. team.load_emoji_completions()
  2660. ###### New module/global methods
  2661. def render_formatting(text):
  2662. text = re.sub(r'(^| )\*([^*\n`]+)\*(?=[^\w]|$)',
  2663. r'\1{}*\2*{}'.format(w.color(config.render_bold_as),
  2664. w.color('-' + config.render_bold_as)),
  2665. text,
  2666. flags=re.UNICODE)
  2667. text = re.sub(r'(^| )_([^_\n`]+)_(?=[^\w]|$)',
  2668. r'\1{}_\2_{}'.format(w.color(config.render_italic_as),
  2669. w.color('-' + config.render_italic_as)),
  2670. text,
  2671. flags=re.UNICODE)
  2672. return text
  2673. def linkify_text(message, team, only_users=False):
  2674. # The get_username_map function is a bit heavy, but this whole
  2675. # function is only called on message send..
  2676. usernames = team.get_username_map()
  2677. channels = team.get_channel_map()
  2678. usergroups = team.generate_usergroup_map()
  2679. message_escaped = (message
  2680. # Replace IRC formatting chars with Slack formatting chars.
  2681. .replace('\x02', '*')
  2682. .replace('\x1D', '_')
  2683. .replace('\x1F', config.map_underline_to)
  2684. # Escape chars that have special meaning to Slack. Note that we do not
  2685. # (and should not) perform full HTML entity-encoding here.
  2686. # See https://api.slack.com/docs/message-formatting for details.
  2687. .replace('&', '&amp;')
  2688. .replace('<', '&lt;')
  2689. .replace('>', '&gt;'))
  2690. def linkify_word(match):
  2691. word = match.group(0)
  2692. prefix, name = match.groups()
  2693. if prefix == "@":
  2694. if name in ["channel", "everyone", "group", "here"]:
  2695. return "<!{}>".format(name)
  2696. elif name in usernames:
  2697. return "<@{}>".format(usernames[name])
  2698. elif word in usergroups.keys():
  2699. return "<!subteam^{}|{}>".format(usergroups[word], word)
  2700. elif prefix == "#" and not only_users:
  2701. if word in channels:
  2702. return "<#{}|{}>".format(channels[word], name)
  2703. return word
  2704. linkify_regex = r'(?:^|(?<=\s))([@#])([\w\(\)\'.-]+)'
  2705. return re.sub(linkify_regex, linkify_word, message_escaped, flags=re.UNICODE)
  2706. def unfurl_blocks(message_json):
  2707. block_text = [""]
  2708. for block in message_json["blocks"]:
  2709. try:
  2710. if block["type"] == "section":
  2711. fields = block.get("fields", [])
  2712. if "text" in block:
  2713. fields.insert(0, block["text"])
  2714. block_text.extend(unfurl_block_element(field) for field in fields)
  2715. elif block["type"] == "actions":
  2716. elements = []
  2717. for element in block["elements"]:
  2718. if element["type"] == "button":
  2719. elements.append(unfurl_block_element(element["text"]))
  2720. else:
  2721. elements.append(colorize_string(config.color_deleted,
  2722. '<<Unsupported block action type "{}">>'.format(element["type"])))
  2723. block_text.append(" | ".join(elements))
  2724. elif block["type"] == "call":
  2725. block_text.append("Join via " + block["call"]["v1"]["join_url"])
  2726. elif block["type"] == "divider":
  2727. block_text.append("---")
  2728. elif block["type"] == "context":
  2729. block_text.append(" | ".join(unfurl_block_element(el) for el in block["elements"]))
  2730. elif block["type"] == "image":
  2731. if "title" in block:
  2732. block_text.append(unfurl_block_element(block["title"]))
  2733. block_text.append(unfurl_block_element(block))
  2734. elif block["type"] == "rich_text":
  2735. continue
  2736. else:
  2737. block_text.append(colorize_string(config.color_deleted,
  2738. '<<Unsupported block type "{}">>'.format(block["type"])))
  2739. dbg('Unsupported block: "{}"'.format(json.dumps(block)), level=4)
  2740. except Exception as e:
  2741. dbg("Failed to unfurl block ({}): {}".format(repr(e), json.dumps(block)), level=4)
  2742. return "\n".join(block_text)
  2743. def unfurl_block_element(text):
  2744. if text["type"] == "mrkdwn":
  2745. return render_formatting(text["text"])
  2746. elif text["type"] == "plain_text":
  2747. return text["text"]
  2748. elif text["type"] == "image":
  2749. return "{} ({})".format(text["image_url"], text["alt_text"])
  2750. def unfurl_refs(text):
  2751. """
  2752. input : <@U096Q7CQM|someuser> has joined the channel
  2753. ouput : someuser has joined the channel
  2754. """
  2755. # Find all strings enclosed by <>
  2756. # - <https://example.com|example with spaces>
  2757. # - <#C2147483705|#otherchannel>
  2758. # - <@U2147483697|@othernick>
  2759. # - <!subteam^U2147483697|@group>
  2760. # Test patterns lives in ./_pytest/test_unfurl.py
  2761. def unfurl_ref(match):
  2762. ref, fallback = match.groups()
  2763. resolved_ref = resolve_ref(ref)
  2764. if resolved_ref != ref:
  2765. return resolved_ref
  2766. if fallback and not config.unfurl_ignore_alt_text:
  2767. if ref.startswith("#"):
  2768. return "#{}".format(fallback)
  2769. elif ref.startswith("@"):
  2770. return fallback
  2771. elif ref.startswith("!subteam"):
  2772. prefix = "@" if not fallback.startswith("@") else ""
  2773. return prefix + fallback
  2774. elif ref.startswith("!date"):
  2775. return fallback
  2776. else:
  2777. match_url = r"^\w+:(//)?{}$".format(re.escape(fallback))
  2778. url_matches_desc = re.match(match_url, ref)
  2779. if url_matches_desc and config.unfurl_auto_link_display == "text":
  2780. return fallback
  2781. elif url_matches_desc and config.unfurl_auto_link_display == "url":
  2782. return ref
  2783. else:
  2784. return "{} ({})".format(ref, fallback)
  2785. return ref
  2786. return re.sub(r"<([^|>]*)(?:\|([^>]*))?>", unfurl_ref, text)
  2787. def unhtmlescape(text):
  2788. return text.replace("&lt;", "<") \
  2789. .replace("&gt;", ">") \
  2790. .replace("&amp;", "&")
  2791. def unwrap_attachments(message_json, text_before):
  2792. text_before_unescaped = unhtmlescape(text_before)
  2793. attachment_texts = []
  2794. a = message_json.get("attachments")
  2795. if a:
  2796. if text_before:
  2797. attachment_texts.append('')
  2798. for attachment in a:
  2799. # Attachments should be rendered roughly like:
  2800. #
  2801. # $pretext
  2802. # $author: (if rest of line is non-empty) $title ($title_link) OR $from_url
  2803. # $author: (if no $author on previous line) $text
  2804. # $fields
  2805. t = []
  2806. prepend_title_text = ''
  2807. if 'author_name' in attachment:
  2808. prepend_title_text = attachment['author_name'] + ": "
  2809. if 'pretext' in attachment:
  2810. t.append(attachment['pretext'])
  2811. title = attachment.get('title')
  2812. title_link = attachment.get('title_link', '')
  2813. if title_link in text_before_unescaped:
  2814. title_link = ''
  2815. if title and title_link:
  2816. t.append('%s%s (%s)' % (prepend_title_text, title, title_link,))
  2817. prepend_title_text = ''
  2818. elif title and not title_link:
  2819. t.append('%s%s' % (prepend_title_text, title,))
  2820. prepend_title_text = ''
  2821. from_url = attachment.get('from_url', '')
  2822. if from_url not in text_before_unescaped and from_url != title_link:
  2823. t.append(from_url)
  2824. atext = attachment.get("text")
  2825. if atext:
  2826. tx = re.sub(r' *\n[\n ]+', '\n', atext)
  2827. t.append(prepend_title_text + tx)
  2828. prepend_title_text = ''
  2829. image_url = attachment.get('image_url', '')
  2830. if image_url not in text_before_unescaped and image_url != title_link:
  2831. t.append(image_url)
  2832. fields = attachment.get("fields")
  2833. if fields:
  2834. for f in fields:
  2835. if f.get('title'):
  2836. t.append('%s %s' % (f['title'], f['value'],))
  2837. else:
  2838. t.append(f['value'])
  2839. fallback = attachment.get("fallback")
  2840. if t == [] and fallback:
  2841. t.append(fallback)
  2842. attachment_texts.append("\n".join([x.strip() for x in t if x]))
  2843. return "\n".join(attachment_texts)
  2844. def unwrap_files(message_json, text_before):
  2845. files_texts = []
  2846. for f in message_json.get('files', []):
  2847. if f.get('mode', '') != 'tombstone':
  2848. text = '{} ({})'.format(f['url_private'], f['title'])
  2849. else:
  2850. text = colorize_string(config.color_deleted, '(This file was deleted.)')
  2851. files_texts.append(text)
  2852. if text_before:
  2853. files_texts.insert(0, '')
  2854. return "\n".join(files_texts)
  2855. def resolve_ref(ref):
  2856. if ref in ['!channel', '!everyone', '!group', '!here']:
  2857. return ref.replace('!', '@')
  2858. for team in EVENTROUTER.teams.values():
  2859. if ref.startswith('@'):
  2860. user = team.users.get(ref[1:])
  2861. if user:
  2862. suffix = config.external_user_suffix if user.is_external else ''
  2863. return '@{}{}'.format(user.name, suffix)
  2864. elif ref.startswith('#'):
  2865. channel = team.channels.get(ref[1:])
  2866. if channel:
  2867. return channel.name
  2868. elif ref.startswith('!subteam'):
  2869. _, subteam_id = ref.split('^')
  2870. subteam = team.subteams.get(subteam_id)
  2871. if subteam:
  2872. return subteam.handle
  2873. elif ref.startswith("!date"):
  2874. parts = ref.split('^')
  2875. ref_datetime = datetime.fromtimestamp(int(parts[1]))
  2876. link_suffix = ' ({})'.format(parts[3]) if len(parts) > 3 else ''
  2877. token_to_format = {
  2878. 'date_num': '%Y-%m-%d',
  2879. 'date': '%B %d, %Y',
  2880. 'date_short': '%b %d, %Y',
  2881. 'date_long': '%A, %B %d, %Y',
  2882. 'time': '%H:%M',
  2883. 'time_secs': '%H:%M:%S'
  2884. }
  2885. def replace_token(match):
  2886. token = match.group(1)
  2887. if token.startswith('date_') and token.endswith('_pretty'):
  2888. if ref_datetime.date() == date.today():
  2889. return 'today'
  2890. elif ref_datetime.date() == date.today() - timedelta(days=1):
  2891. return 'yesterday'
  2892. elif ref_datetime.date() == date.today() + timedelta(days=1):
  2893. return 'tomorrow'
  2894. else:
  2895. token = token.replace('_pretty', '')
  2896. if token in token_to_format:
  2897. return ref_datetime.strftime(token_to_format[token])
  2898. else:
  2899. return match.group(0)
  2900. return re.sub(r"{([^}]+)}", replace_token, parts[2]) + link_suffix
  2901. # Something else, just return as-is
  2902. return ref
  2903. def create_user_status_string(profile):
  2904. real_name = profile.get("real_name")
  2905. status_emoji = replace_string_with_emoji(profile.get("status_emoji", ""))
  2906. status_text = profile.get("status_text")
  2907. if status_emoji or status_text:
  2908. return "{} | {} {}".format(real_name, status_emoji, status_text)
  2909. else:
  2910. return real_name
  2911. def create_reaction_string(reaction, myidentifier):
  2912. if config.show_reaction_nicks:
  2913. nicks = [resolve_ref('@{}'.format(user)) for user in reaction['users']]
  2914. users = '({})'.format(','.join(nicks))
  2915. else:
  2916. users = len(reaction['users'])
  2917. reaction_string = ':{}:{}'.format(reaction['name'], users)
  2918. if myidentifier in reaction['users']:
  2919. return colorize_string(config.color_reaction_suffix_added_by_you, reaction_string,
  2920. reset_color=config.color_reaction_suffix)
  2921. else:
  2922. return reaction_string
  2923. def create_reactions_string(reactions, myidentifier):
  2924. reactions_with_users = [r for r in reactions if len(r['users']) > 0]
  2925. reactions_string = ' '.join(create_reaction_string(r, myidentifier) for r in reactions_with_users)
  2926. if reactions_string:
  2927. return ' ' + colorize_string(config.color_reaction_suffix, '[{}]'.format(reactions_string))
  2928. else:
  2929. return ''
  2930. def hdata_line_ts(line_pointer):
  2931. data = w.hdata_pointer(hdata.line, line_pointer, 'data')
  2932. ts_major = w.hdata_time(hdata.line_data, data, 'date')
  2933. ts_minor = w.hdata_time(hdata.line_data, data, 'date_printed')
  2934. return (ts_major, ts_minor)
  2935. def modify_buffer_line(buffer_pointer, ts, new_text):
  2936. own_lines = w.hdata_pointer(hdata.buffer, buffer_pointer, 'own_lines')
  2937. line_pointer = w.hdata_pointer(hdata.lines, own_lines, 'last_line')
  2938. # Find the last line with this ts
  2939. while line_pointer and hdata_line_ts(line_pointer) != (ts.major, ts.minor):
  2940. line_pointer = w.hdata_move(hdata.line, line_pointer, -1)
  2941. # Find all lines for the message
  2942. pointers = []
  2943. while line_pointer and hdata_line_ts(line_pointer) == (ts.major, ts.minor):
  2944. pointers.append(line_pointer)
  2945. line_pointer = w.hdata_move(hdata.line, line_pointer, -1)
  2946. pointers.reverse()
  2947. # Split the message into at most the number of existing lines as we can't insert new lines
  2948. lines = new_text.split('\n', len(pointers) - 1)
  2949. # Replace newlines to prevent garbled lines in bare display mode
  2950. lines = [line.replace('\n', ' | ') for line in lines]
  2951. # Extend lines in case the new message is shorter than the old as we can't delete lines
  2952. lines += [''] * (len(pointers) - len(lines))
  2953. for pointer, line in zip(pointers, lines):
  2954. data = w.hdata_pointer(hdata.line, pointer, 'data')
  2955. w.hdata_update(hdata.line_data, data, {"message": line})
  2956. return w.WEECHAT_RC_OK
  2957. def modify_last_print_time(buffer_pointer, ts_minor):
  2958. """
  2959. This overloads the time printed field to let us store the slack
  2960. per message unique id that comes after the "." in a slack ts
  2961. """
  2962. own_lines = w.hdata_pointer(hdata.buffer, buffer_pointer, 'own_lines')
  2963. line_pointer = w.hdata_pointer(hdata.lines, own_lines, 'last_line')
  2964. while line_pointer:
  2965. data = w.hdata_pointer(hdata.line, line_pointer, 'data')
  2966. w.hdata_update(hdata.line_data, data, {"date_printed": str(ts_minor)})
  2967. if w.hdata_string(hdata.line_data, data, 'prefix'):
  2968. # Reached the first line of the message, so stop here
  2969. break
  2970. # Move one line backwards so all lines of the message are set
  2971. line_pointer = w.hdata_move(hdata.line, line_pointer, -1)
  2972. return w.WEECHAT_RC_OK
  2973. def nick_from_profile(profile, username):
  2974. full_name = profile.get('real_name') or username
  2975. if config.use_full_names:
  2976. nick = full_name
  2977. else:
  2978. nick = profile.get('display_name') or full_name
  2979. return nick.replace(' ', '')
  2980. def format_nick(nick, previous_nick=None):
  2981. if nick == previous_nick:
  2982. nick = w.config_string(w.config_get('weechat.look.prefix_same_nick')) or nick
  2983. nick_prefix = w.config_string(w.config_get('weechat.look.nick_prefix'))
  2984. nick_prefix_color_name = w.config_string(w.config_get('weechat.color.chat_nick_prefix'))
  2985. nick_suffix = w.config_string(w.config_get('weechat.look.nick_suffix'))
  2986. nick_suffix_color_name = w.config_string(w.config_get('weechat.color.chat_nick_prefix'))
  2987. return colorize_string(nick_prefix_color_name, nick_prefix) + nick + colorize_string(nick_suffix_color_name, nick_suffix)
  2988. def tag(tagset=None, user=None, self_msg=False, backlog=False, no_log=False, extra_tags=None):
  2989. tagsets = {
  2990. "team_info": {"no_highlight", "log3"},
  2991. "team_message": {"irc_privmsg", "notify_message", "log1"},
  2992. "dm": {"irc_privmsg", "notify_private", "log1"},
  2993. "join": {"irc_join", "no_highlight", "log4"},
  2994. "leave": {"irc_part", "no_highlight", "log4"},
  2995. "topic": {"irc_topic", "no_highlight", "log3"},
  2996. "channel": {"irc_privmsg", "notify_message", "log1"},
  2997. }
  2998. nick_tag = {"nick_{}".format(user).replace(" ", "_")} if user else set()
  2999. slack_tag = {"slack_{}".format(tagset or "default")}
  3000. tags = nick_tag | slack_tag | tagsets.get(tagset, set())
  3001. if self_msg or backlog:
  3002. tags -= {"notify_highlight", "notify_message", "notify_private"}
  3003. tags |= {"notify_none", "no_highlight"}
  3004. if self_msg:
  3005. tags |= {"self_msg"}
  3006. if backlog:
  3007. tags |= {"logger_backlog"}
  3008. if no_log:
  3009. tags |= {"no_log"}
  3010. tags = {tag for tag in tags if not tag.startswith("log") or tag == "logger_backlog"}
  3011. if extra_tags:
  3012. tags |= set(extra_tags)
  3013. return ",".join(tags)
  3014. def set_own_presence_active(team):
  3015. slackbot = team.get_channel_map()['Slackbot']
  3016. channel = team.channels[slackbot]
  3017. request = {"type": "typing", "channel": channel.identifier}
  3018. channel.team.send_to_websocket(request, expect_reply=False)
  3019. ###### New/converted command_ commands
  3020. @slack_buffer_or_ignore
  3021. @utf8_decode
  3022. def invite_command_cb(data, current_buffer, args):
  3023. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3024. split_args = args.split()[1:]
  3025. if not split_args:
  3026. w.prnt('', 'Too few arguments for command "/invite" (help on command: /help invite)')
  3027. return w.WEECHAT_RC_OK_EAT
  3028. if split_args[-1].startswith("#") or split_args[-1].startswith(config.group_name_prefix):
  3029. nicks = split_args[:-1]
  3030. channel = team.channels.get(team.get_channel_map().get(split_args[-1]))
  3031. if not nicks or not channel:
  3032. w.prnt('', '{}: No such nick/channel'.format(split_args[-1]))
  3033. return w.WEECHAT_RC_OK_EAT
  3034. else:
  3035. nicks = split_args
  3036. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3037. all_users = team.get_username_map()
  3038. users = set()
  3039. for nick in nicks:
  3040. user = all_users.get(nick.lstrip('@'))
  3041. if not user:
  3042. w.prnt('', 'ERROR: Unknown user: {}'.format(nick))
  3043. return w.WEECHAT_RC_OK_EAT
  3044. users.add(user)
  3045. s = SlackRequest(team, "conversations.invite", {"channel": channel.identifier, "users": ",".join(users)},
  3046. channel=channel, metadata={"nicks": nicks})
  3047. EVENTROUTER.receive(s)
  3048. return w.WEECHAT_RC_OK_EAT
  3049. @slack_buffer_or_ignore
  3050. @utf8_decode
  3051. def part_command_cb(data, current_buffer, args):
  3052. e = EVENTROUTER
  3053. args = args.split()
  3054. if len(args) > 1:
  3055. team = e.weechat_controller.buffers[current_buffer].team
  3056. cmap = team.get_channel_map()
  3057. channel = "".join(args[1:])
  3058. if channel in cmap:
  3059. buffer_ptr = team.channels[cmap[channel]].channel_buffer
  3060. e.weechat_controller.unregister_buffer(buffer_ptr, update_remote=True, close_buffer=True)
  3061. else:
  3062. w.prnt(team.channel_buffer, "{}: No such channel".format(channel))
  3063. else:
  3064. e.weechat_controller.unregister_buffer(current_buffer, update_remote=True, close_buffer=True)
  3065. return w.WEECHAT_RC_OK_EAT
  3066. def parse_topic_command(command):
  3067. args = command.split()[1:]
  3068. channel_name = None
  3069. topic = None
  3070. if args:
  3071. if args[0].startswith('#'):
  3072. channel_name = args[0]
  3073. topic = args[1:]
  3074. else:
  3075. topic = args
  3076. if topic == []:
  3077. topic = None
  3078. if topic:
  3079. topic = ' '.join(topic)
  3080. if topic == '-delete':
  3081. topic = ''
  3082. return channel_name, topic
  3083. @slack_buffer_or_ignore
  3084. @utf8_decode
  3085. def topic_command_cb(data, current_buffer, command):
  3086. """
  3087. Change the topic of a channel
  3088. /topic [<channel>] [<topic>|-delete]
  3089. """
  3090. channel_name, topic = parse_topic_command(command)
  3091. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3092. if channel_name:
  3093. channel = team.channels.get(team.get_channel_map().get(channel_name))
  3094. else:
  3095. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3096. if not channel:
  3097. w.prnt(team.channel_buffer, "{}: No such channel".format(channel_name))
  3098. return w.WEECHAT_RC_OK_EAT
  3099. if topic is None:
  3100. w.prnt(channel.channel_buffer,
  3101. 'Topic for {} is "{}"'.format(channel.name, channel.render_topic()))
  3102. else:
  3103. s = SlackRequest(team, "conversations.setTopic",
  3104. {"channel": channel.identifier, "topic": linkify_text(topic, team)}, channel=channel)
  3105. EVENTROUTER.receive(s)
  3106. return w.WEECHAT_RC_OK_EAT
  3107. @slack_buffer_or_ignore
  3108. @utf8_decode
  3109. def whois_command_cb(data, current_buffer, command):
  3110. """
  3111. Get real name of user
  3112. /whois <nick>
  3113. """
  3114. args = command.split()
  3115. if len(args) < 2:
  3116. w.prnt(current_buffer, "Not enough arguments")
  3117. return w.WEECHAT_RC_OK_EAT
  3118. user = args[1]
  3119. if (user.startswith('@')):
  3120. user = user[1:]
  3121. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3122. u = team.users.get(team.get_username_map().get(user))
  3123. if u:
  3124. def print_profile(field):
  3125. value = u.profile.get(field)
  3126. if value:
  3127. team.buffer_prnt("[{}]: {}: {}".format(user, field, value))
  3128. team.buffer_prnt("[{}]: {}".format(user, u.real_name))
  3129. status_emoji = replace_string_with_emoji(u.profile.get("status_emoji", ""))
  3130. status_text = u.profile.get("status_text", "")
  3131. if status_emoji or status_text:
  3132. team.buffer_prnt("[{}]: {} {}".format(user, status_emoji, status_text))
  3133. team.buffer_prnt("[{}]: username: {}".format(user, u.username))
  3134. team.buffer_prnt("[{}]: id: {}".format(user, u.identifier))
  3135. print_profile('title')
  3136. print_profile('email')
  3137. print_profile('phone')
  3138. print_profile('skype')
  3139. else:
  3140. team.buffer_prnt("[{}]: No such user".format(user))
  3141. return w.WEECHAT_RC_OK_EAT
  3142. @slack_buffer_or_ignore
  3143. @utf8_decode
  3144. def me_command_cb(data, current_buffer, args):
  3145. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3146. message = args.split(' ', 1)[1]
  3147. channel.send_message(message, subtype='me_message')
  3148. return w.WEECHAT_RC_OK_EAT
  3149. @utf8_decode
  3150. def command_register(data, current_buffer, args):
  3151. """
  3152. /slack register [code/token]
  3153. Register a Slack team in wee-slack. Call this without any arguments and
  3154. follow the instructions to register a new team. If you already have a token
  3155. for a team, you can call this with that token to add it.
  3156. """
  3157. CLIENT_ID = "2468770254.51917335286"
  3158. CLIENT_SECRET = "dcb7fe380a000cba0cca3169a5fe8d70" # Not really a secret.
  3159. REDIRECT_URI = "https%3A%2F%2Fwee-slack.github.io%2Fwee-slack%2Foauth%23"
  3160. if not args:
  3161. message = textwrap.dedent("""
  3162. ### Connecting to a Slack team with OAuth ###
  3163. 1) Paste this link into a browser: https://slack.com/oauth/authorize?client_id={}&scope=client&redirect_uri={}
  3164. 2) Select the team you wish to access from wee-slack in your browser. If you want to add multiple teams, you will have to repeat this whole process for each team.
  3165. 3) Click "Authorize" in the browser.
  3166. If you get a message saying you are not authorized to install wee-slack, the team has restricted Slack app installation and you will have to request it from an admin. To do that, go to https://my.slack.com/apps/A1HSZ9V8E-wee-slack and click "Request to Install".
  3167. 4) The web page will show a command in the form `/slack register <code>`. Run this command in weechat.
  3168. """).strip().format(CLIENT_ID, REDIRECT_URI)
  3169. w.prnt("", message)
  3170. return w.WEECHAT_RC_OK_EAT
  3171. elif args.startswith('xox'):
  3172. add_token(args)
  3173. return w.WEECHAT_RC_OK_EAT
  3174. uri = (
  3175. "https://slack.com/api/oauth.access?"
  3176. "client_id={}&client_secret={}&redirect_uri={}&code={}"
  3177. ).format(CLIENT_ID, CLIENT_SECRET, REDIRECT_URI, args)
  3178. params = {'useragent': 'wee_slack {}'.format(SCRIPT_VERSION)}
  3179. w.hook_process_hashtable('url:', params, config.slack_timeout, "", "")
  3180. w.hook_process_hashtable("url:{}".format(uri), params, config.slack_timeout, "register_callback", "")
  3181. return w.WEECHAT_RC_OK_EAT
  3182. @utf8_decode
  3183. def register_callback(data, command, return_code, out, err):
  3184. if return_code != 0:
  3185. w.prnt("", "ERROR: problem when trying to get Slack OAuth token. Got return code {}. Err: {}".format(return_code, err))
  3186. w.prnt("", "Check the network or proxy settings")
  3187. return w.WEECHAT_RC_OK_EAT
  3188. if len(out) <= 0:
  3189. w.prnt("", "ERROR: problem when trying to get Slack OAuth token. Got 0 length answer. Err: {}".format(err))
  3190. w.prnt("", "Check the network or proxy settings")
  3191. return w.WEECHAT_RC_OK_EAT
  3192. d = json.loads(out)
  3193. if not d["ok"]:
  3194. w.prnt("",
  3195. "ERROR: Couldn't get Slack OAuth token: {}".format(d['error']))
  3196. return w.WEECHAT_RC_OK_EAT
  3197. add_token(d['access_token'], d['team_name'])
  3198. return w.WEECHAT_RC_OK_EAT
  3199. def add_token(token, team_name=None):
  3200. if config.is_default('slack_api_token'):
  3201. w.config_set_plugin('slack_api_token', token)
  3202. else:
  3203. # Add new token to existing set, joined by comma.
  3204. existing_tokens = config.get_string('slack_api_token')
  3205. if token in existing_tokens:
  3206. print_error('This token is already registered')
  3207. return
  3208. w.config_set_plugin('slack_api_token', ','.join([existing_tokens, token]))
  3209. if team_name:
  3210. w.prnt("", "Success! Added team \"{}\"".format(team_name))
  3211. else:
  3212. w.prnt("", "Success! Added token")
  3213. w.prnt("", "Please reload wee-slack with: /python reload slack")
  3214. w.prnt("", "If you want to add another team you can repeat this process from step 1 before reloading wee-slack.")
  3215. @slack_buffer_or_ignore
  3216. @utf8_decode
  3217. def msg_command_cb(data, current_buffer, args):
  3218. aargs = args.split(None, 2)
  3219. who = aargs[1].lstrip('@')
  3220. if who == "*":
  3221. who = EVENTROUTER.weechat_controller.buffers[current_buffer].name
  3222. else:
  3223. join_query_command_cb(data, current_buffer, '/query ' + who)
  3224. if len(aargs) > 2:
  3225. message = aargs[2]
  3226. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3227. cmap = team.get_channel_map()
  3228. if who in cmap:
  3229. channel = team.channels[cmap[who]]
  3230. channel.send_message(message)
  3231. return w.WEECHAT_RC_OK_EAT
  3232. def print_team_items_info(team, header, items, extra_info_function):
  3233. team.buffer_prnt("{}:".format(header))
  3234. if items:
  3235. max_name_length = max(len(item.name) for item in items)
  3236. for item in sorted(items, key=lambda item: item.name.lower()):
  3237. extra_info = extra_info_function(item)
  3238. team.buffer_prnt(" {:<{}}({})".format(item.name, max_name_length + 2, extra_info))
  3239. return w.WEECHAT_RC_OK_EAT
  3240. def print_users_info(team, header, users):
  3241. def extra_info_function(user):
  3242. external_text = ", external" if user.is_external else ""
  3243. return user.presence + external_text
  3244. return print_team_items_info(team, header, users, extra_info_function)
  3245. @slack_buffer_required
  3246. @utf8_decode
  3247. def command_teams(data, current_buffer, args):
  3248. """
  3249. /slack teams
  3250. List the connected Slack teams.
  3251. """
  3252. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3253. teams = EVENTROUTER.teams.values()
  3254. extra_info_function = lambda team: "token: {}".format(token_for_print(team.token))
  3255. return print_team_items_info(team, "Slack teams", teams, extra_info_function)
  3256. @slack_buffer_required
  3257. @utf8_decode
  3258. def command_channels(data, current_buffer, args):
  3259. """
  3260. /slack channels
  3261. List the channels in the current team.
  3262. """
  3263. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3264. channels = [channel for channel in team.channels.values() if channel.type not in ['im', 'mpim']]
  3265. def extra_info_function(channel):
  3266. if channel.active:
  3267. return "member"
  3268. elif getattr(channel, "is_archived", None):
  3269. return "archived"
  3270. else:
  3271. return "not a member"
  3272. return print_team_items_info(team, "Channels", channels, extra_info_function)
  3273. @slack_buffer_required
  3274. @utf8_decode
  3275. def command_users(data, current_buffer, args):
  3276. """
  3277. /slack users
  3278. List the users in the current team.
  3279. """
  3280. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3281. return print_users_info(team, "Users", team.users.values())
  3282. @slack_buffer_required
  3283. @utf8_decode
  3284. def command_usergroups(data, current_buffer, args):
  3285. """
  3286. /slack usergroups [handle]
  3287. List the usergroups in the current team
  3288. If handle is given show the members in the usergroup
  3289. """
  3290. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3291. usergroups = team.generate_usergroup_map()
  3292. usergroup_key = usergroups.get(args)
  3293. if usergroup_key:
  3294. s = SlackRequest(team, "usergroups.users.list", {"usergroup": usergroup_key},
  3295. metadata={'usergroup_handle': args})
  3296. EVENTROUTER.receive(s)
  3297. elif args:
  3298. w.prnt('', 'ERROR: Unknown usergroup handle: {}'.format(args))
  3299. return w.WEECHAT_RC_ERROR
  3300. else:
  3301. def extra_info_function(subteam):
  3302. is_member = 'member' if subteam.is_member else 'not a member'
  3303. return '{}, {}'.format(subteam.handle, is_member)
  3304. return print_team_items_info(team, "Usergroups", team.subteams.values(), extra_info_function)
  3305. return w.WEECHAT_RC_OK_EAT
  3306. command_usergroups.completion = '%(usergroups)'
  3307. @slack_buffer_required
  3308. @utf8_decode
  3309. def command_talk(data, current_buffer, args):
  3310. """
  3311. /slack talk <user>[,<user2>[,<user3>...]]
  3312. Open a chat with the specified user(s).
  3313. """
  3314. if not args:
  3315. w.prnt('', 'Usage: /slack talk <user>[,<user2>[,<user3>...]]')
  3316. return w.WEECHAT_RC_ERROR
  3317. return join_query_command_cb(data, current_buffer, '/query ' + args)
  3318. command_talk.completion = '%(nicks)'
  3319. @slack_buffer_or_ignore
  3320. @utf8_decode
  3321. def join_query_command_cb(data, current_buffer, args):
  3322. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3323. split_args = args.split(' ', 1)
  3324. if len(split_args) < 2 or not split_args[1]:
  3325. w.prnt('', 'Too few arguments for command "{}" (help on command: /help {})'
  3326. .format(split_args[0], split_args[0].lstrip('/')))
  3327. return w.WEECHAT_RC_OK_EAT
  3328. query = split_args[1]
  3329. # Try finding the channel by name
  3330. channel = team.channels.get(team.get_channel_map().get(query))
  3331. # If the channel doesn't exist, try finding a DM or MPDM instead
  3332. if not channel:
  3333. if query.startswith('#'):
  3334. w.prnt('', 'ERROR: Unknown channel: {}'.format(query))
  3335. return w.WEECHAT_RC_OK_EAT
  3336. # Get the IDs of the users
  3337. all_users = team.get_username_map()
  3338. users = set()
  3339. for username in query.split(','):
  3340. user = all_users.get(username.lstrip('@'))
  3341. if not user:
  3342. w.prnt('', 'ERROR: Unknown user: {}'.format(username))
  3343. return w.WEECHAT_RC_OK_EAT
  3344. users.add(user)
  3345. if users:
  3346. if len(users) > 1:
  3347. channel_type = 'mpim'
  3348. # Add the current user since MPDMs include them as a member
  3349. users.add(team.myidentifier)
  3350. else:
  3351. channel_type = 'im'
  3352. channel = team.find_channel_by_members(users, channel_type=channel_type)
  3353. # If the DM or MPDM doesn't exist, create it
  3354. if not channel:
  3355. s = SlackRequest(team, SLACK_API_TRANSLATOR[channel_type]['join'],
  3356. {'users': ','.join(users)})
  3357. EVENTROUTER.receive(s)
  3358. if channel:
  3359. channel.open()
  3360. if config.switch_buffer_on_join:
  3361. w.buffer_set(channel.channel_buffer, "display", "1")
  3362. return w.WEECHAT_RC_OK_EAT
  3363. @slack_buffer_required
  3364. @utf8_decode
  3365. def command_showmuted(data, current_buffer, args):
  3366. """
  3367. /slack showmuted
  3368. List the muted channels in the current team.
  3369. """
  3370. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3371. muted_channels = [team.channels[key].name
  3372. for key in team.muted_channels if key in team.channels]
  3373. team.buffer_prnt("Muted channels: {}".format(', '.join(muted_channels)))
  3374. return w.WEECHAT_RC_OK_EAT
  3375. def get_msg_from_id(channel, msg_id):
  3376. if msg_id[0] == '$':
  3377. msg_id = msg_id[1:]
  3378. ts = channel.hashed_messages.get(msg_id)
  3379. return channel.messages.get(ts)
  3380. @slack_buffer_required
  3381. @utf8_decode
  3382. def command_thread(data, current_buffer, args):
  3383. """
  3384. /thread [message_id]
  3385. Open the thread for the message.
  3386. If no message id is specified the last thread in channel will be opened.
  3387. """
  3388. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3389. if not isinstance(channel, SlackChannelCommon):
  3390. print_error('/thread can not be used in the team buffer, only in a channel')
  3391. return w.WEECHAT_RC_ERROR
  3392. if args:
  3393. msg = get_msg_from_id(channel, args)
  3394. if not msg:
  3395. w.prnt('', 'ERROR: Invalid id given, must be an existing id')
  3396. return w.WEECHAT_RC_OK_EAT
  3397. else:
  3398. for message in reversed(channel.messages.values()):
  3399. if type(message) == SlackMessage and message.number_of_replies():
  3400. msg = message
  3401. break
  3402. else:
  3403. w.prnt('', 'ERROR: No threads found in channel')
  3404. return w.WEECHAT_RC_OK_EAT
  3405. msg.open_thread(switch=config.switch_buffer_on_join)
  3406. return w.WEECHAT_RC_OK_EAT
  3407. command_thread.completion = '%(threads)'
  3408. @slack_buffer_required
  3409. @utf8_decode
  3410. def command_reply(data, current_buffer, args):
  3411. """
  3412. /reply [-alsochannel] [<count/message_id>] <message>
  3413. When in a channel buffer:
  3414. /reply [-alsochannel] <count/message_id> <message>
  3415. Reply in a thread on the message. Specify either the message id or a count
  3416. upwards to the message from the last message.
  3417. When in a thread buffer:
  3418. /reply [-alsochannel] <message>
  3419. Reply to the current thread. This can be used to send the reply to the
  3420. rest of the channel.
  3421. In either case, -alsochannel also sends the reply to the parent channel.
  3422. """
  3423. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3424. parts = args.split(None, 1)
  3425. if parts[0] == "-alsochannel":
  3426. args = parts[1]
  3427. broadcast = True
  3428. else:
  3429. broadcast = False
  3430. if isinstance(channel, SlackThreadChannel):
  3431. text = args
  3432. msg = channel.parent_message
  3433. else:
  3434. try:
  3435. msg_id, text = args.split(None, 1)
  3436. except ValueError:
  3437. w.prnt('', 'Usage (when in a channel buffer): /reply [-alsochannel] <count/message_id> <message>')
  3438. return w.WEECHAT_RC_OK_EAT
  3439. msg = get_msg_from_id(channel, msg_id)
  3440. if msg:
  3441. if isinstance(msg, SlackThreadMessage):
  3442. parent_id = str(msg.parent_message.ts)
  3443. else:
  3444. parent_id = str(msg.ts)
  3445. elif msg_id.isdigit() and int(msg_id) >= 1:
  3446. mkeys = channel.main_message_keys_reversed()
  3447. parent_id = str(next(islice(mkeys, int(msg_id) - 1, None)))
  3448. else:
  3449. w.prnt('', 'ERROR: Invalid id given, must be a number greater than 0 or an existing id')
  3450. return w.WEECHAT_RC_OK_EAT
  3451. channel.send_message(text, request_dict_ext={'thread_ts': parent_id, 'reply_broadcast': broadcast})
  3452. return w.WEECHAT_RC_OK_EAT
  3453. command_reply.completion = '-alsochannel %(threads)||%(threads)'
  3454. @slack_buffer_required
  3455. @utf8_decode
  3456. def command_rehistory(data, current_buffer, args):
  3457. """
  3458. /rehistory
  3459. Reload the history in the current channel.
  3460. """
  3461. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3462. channel.clear_messages()
  3463. channel.get_history()
  3464. return w.WEECHAT_RC_OK_EAT
  3465. @slack_buffer_required
  3466. @utf8_decode
  3467. def command_hide(data, current_buffer, args):
  3468. """
  3469. /hide
  3470. Hide the current channel if it is marked as distracting.
  3471. """
  3472. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3473. name = channel.formatted_name(style='long_default')
  3474. if name in config.distracting_channels:
  3475. w.buffer_set(channel.channel_buffer, "hidden", "1")
  3476. return w.WEECHAT_RC_OK_EAT
  3477. @utf8_decode
  3478. def slack_command_cb(data, current_buffer, args):
  3479. split_args = args.split(' ', 1)
  3480. cmd_name = split_args[0]
  3481. cmd_args = split_args[1] if len(split_args) > 1 else ''
  3482. cmd = EVENTROUTER.cmds.get(cmd_name or 'help')
  3483. if not cmd:
  3484. w.prnt('', 'Command not found: ' + cmd_name)
  3485. return w.WEECHAT_RC_OK
  3486. return cmd(data, current_buffer, cmd_args)
  3487. @utf8_decode
  3488. def command_help(data, current_buffer, args):
  3489. """
  3490. /slack help [command]
  3491. Print help for /slack commands.
  3492. """
  3493. if args:
  3494. cmd = EVENTROUTER.cmds.get(args)
  3495. if cmd:
  3496. cmds = {args: cmd}
  3497. else:
  3498. w.prnt('', 'Command not found: ' + args)
  3499. return w.WEECHAT_RC_OK
  3500. else:
  3501. cmds = EVENTROUTER.cmds
  3502. w.prnt('', '\n{}'.format(colorize_string('bold', 'Slack commands:')))
  3503. script_prefix = '{0}[{1}python{0}/{1}slack{0}]{1}'.format(w.color('green'), w.color('reset'))
  3504. for _, cmd in sorted(cmds.items()):
  3505. name, cmd_args, description = parse_help_docstring(cmd)
  3506. w.prnt('', '\n{} {} {}\n\n{}'.format(
  3507. script_prefix, colorize_string('white', name), cmd_args, description))
  3508. return w.WEECHAT_RC_OK
  3509. @slack_buffer_required
  3510. @utf8_decode
  3511. def command_distracting(data, current_buffer, args):
  3512. """
  3513. /slack distracting
  3514. Add or remove the current channel from distracting channels. You can hide
  3515. or unhide these channels with /slack nodistractions.
  3516. """
  3517. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3518. fullname = channel.formatted_name(style="long_default")
  3519. if fullname in config.distracting_channels:
  3520. config.distracting_channels.remove(fullname)
  3521. else:
  3522. config.distracting_channels.append(fullname)
  3523. w.config_set_plugin('distracting_channels', ','.join(config.distracting_channels))
  3524. return w.WEECHAT_RC_OK_EAT
  3525. @slack_buffer_required
  3526. @utf8_decode
  3527. def command_slash(data, current_buffer, args):
  3528. """
  3529. /slack slash /customcommand arg1 arg2 arg3
  3530. Run a custom slack command.
  3531. """
  3532. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3533. team = channel.team
  3534. split_args = args.split(' ', 1)
  3535. command = split_args[0]
  3536. text = split_args[1] if len(split_args) > 1 else ""
  3537. text_linkified = linkify_text(text, team, only_users=True)
  3538. s = SlackRequest(team, "chat.command",
  3539. {"command": command, "text": text_linkified, 'channel': channel.identifier},
  3540. channel=channel, metadata={'command': command, 'command_args': text})
  3541. EVENTROUTER.receive(s)
  3542. return w.WEECHAT_RC_OK_EAT
  3543. @slack_buffer_required
  3544. @utf8_decode
  3545. def command_mute(data, current_buffer, args):
  3546. """
  3547. /slack mute
  3548. Toggle mute on the current channel.
  3549. """
  3550. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3551. team = channel.team
  3552. team.muted_channels ^= {channel.identifier}
  3553. muted_str = "Muted" if channel.identifier in team.muted_channels else "Unmuted"
  3554. team.buffer_prnt("{} channel {}".format(muted_str, channel.name))
  3555. s = SlackRequest(team, "users.prefs.set",
  3556. {"name": "muted_channels", "value": ",".join(team.muted_channels)}, channel=channel)
  3557. EVENTROUTER.receive(s)
  3558. return w.WEECHAT_RC_OK_EAT
  3559. @slack_buffer_required
  3560. @utf8_decode
  3561. def command_linkarchive(data, current_buffer, args):
  3562. """
  3563. /slack linkarchive [message_id]
  3564. Place a link to the channel or message in the input bar.
  3565. Use cursor or mouse mode to get the id.
  3566. """
  3567. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3568. url = 'https://{}/'.format(channel.team.domain)
  3569. if isinstance(channel, SlackChannelCommon):
  3570. url += 'archives/{}/'.format(channel.identifier)
  3571. if args:
  3572. if args[0] == '$':
  3573. message_id = args[1:]
  3574. else:
  3575. message_id = args
  3576. ts = channel.hashed_messages.get(message_id)
  3577. message = channel.messages.get(ts)
  3578. if message:
  3579. url += 'p{}{:0>6}'.format(message.ts.majorstr(), message.ts.minorstr())
  3580. if isinstance(message, SlackThreadMessage):
  3581. url += "?thread_ts={}&cid={}".format(message.parent_message.ts, channel.identifier)
  3582. else:
  3583. w.prnt('', 'ERROR: Invalid id given, must be an existing id')
  3584. return w.WEECHAT_RC_OK_EAT
  3585. w.command(current_buffer, "/input insert {}".format(url))
  3586. return w.WEECHAT_RC_OK_EAT
  3587. command_linkarchive.completion = '%(threads)'
  3588. @utf8_decode
  3589. def command_nodistractions(data, current_buffer, args):
  3590. """
  3591. /slack nodistractions
  3592. Hide or unhide all channels marked as distracting.
  3593. """
  3594. global hide_distractions
  3595. hide_distractions = not hide_distractions
  3596. channels = [channel for channel in EVENTROUTER.weechat_controller.buffers.values()
  3597. if channel in config.distracting_channels]
  3598. for channel in channels:
  3599. w.buffer_set(channel.channel_buffer, "hidden", str(int(hide_distractions)))
  3600. return w.WEECHAT_RC_OK_EAT
  3601. @slack_buffer_required
  3602. @utf8_decode
  3603. def command_upload(data, current_buffer, args):
  3604. """
  3605. /slack upload <filename>
  3606. Uploads a file to the current buffer.
  3607. """
  3608. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3609. weechat_dir = w.info_get("weechat_dir", "")
  3610. file_path = os.path.join(weechat_dir, os.path.expanduser(args))
  3611. if channel.type == 'team':
  3612. w.prnt('', "ERROR: Can't upload a file to the team buffer")
  3613. return w.WEECHAT_RC_ERROR
  3614. if not os.path.isfile(file_path):
  3615. unescaped_file_path = file_path.replace(r'\ ', ' ')
  3616. if os.path.isfile(unescaped_file_path):
  3617. file_path = unescaped_file_path
  3618. else:
  3619. w.prnt('', 'ERROR: Could not find file: {}'.format(file_path))
  3620. return w.WEECHAT_RC_ERROR
  3621. post_data = {
  3622. 'channels': channel.identifier,
  3623. }
  3624. if isinstance(channel, SlackThreadChannel):
  3625. post_data['thread_ts'] = channel.parent_message.ts
  3626. url = SlackRequest(channel.team, 'files.upload', post_data, channel=channel).request_string()
  3627. options = [
  3628. '-s',
  3629. '-Ffile=@{}'.format(file_path),
  3630. url
  3631. ]
  3632. proxy_string = ProxyWrapper().curl()
  3633. if proxy_string:
  3634. options.append(proxy_string)
  3635. options_hashtable = {'arg{}'.format(i + 1): arg for i, arg in enumerate(options)}
  3636. w.hook_process_hashtable('curl', options_hashtable, config.slack_timeout, 'upload_callback', '')
  3637. return w.WEECHAT_RC_OK_EAT
  3638. command_upload.completion = '%(filename)'
  3639. @utf8_decode
  3640. def upload_callback(data, command, return_code, out, err):
  3641. if return_code != 0:
  3642. w.prnt("", "ERROR: Couldn't upload file. Got return code {}. Error: {}".format(return_code, err))
  3643. return w.WEECHAT_RC_OK_EAT
  3644. try:
  3645. response = json.loads(out)
  3646. except JSONDecodeError:
  3647. w.prnt("", "ERROR: Couldn't process response from file upload. Got: {}".format(out))
  3648. return w.WEECHAT_RC_OK_EAT
  3649. if not response["ok"]:
  3650. w.prnt("", "ERROR: Couldn't upload file. Error: {}".format(response["error"]))
  3651. return w.WEECHAT_RC_OK_EAT
  3652. @utf8_decode
  3653. def away_command_cb(data, current_buffer, args):
  3654. all_servers, message = re.match('^/away( -all)? ?(.*)', args).groups()
  3655. if all_servers:
  3656. team_buffers = [team.channel_buffer for team in EVENTROUTER.teams.values()]
  3657. elif current_buffer in EVENTROUTER.weechat_controller.buffers:
  3658. team_buffers = [current_buffer]
  3659. else:
  3660. return w.WEECHAT_RC_OK
  3661. for team_buffer in team_buffers:
  3662. if message:
  3663. command_away(data, team_buffer, args)
  3664. else:
  3665. command_back(data, team_buffer, args)
  3666. return w.WEECHAT_RC_OK
  3667. @slack_buffer_required
  3668. @utf8_decode
  3669. def command_away(data, current_buffer, args):
  3670. """
  3671. /slack away
  3672. Sets your status as 'away'.
  3673. """
  3674. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3675. s = SlackRequest(team, "users.setPresence", {"presence": "away"})
  3676. EVENTROUTER.receive(s)
  3677. return w.WEECHAT_RC_OK
  3678. @slack_buffer_required
  3679. @utf8_decode
  3680. def command_status(data, current_buffer, args):
  3681. """
  3682. /slack status [<emoji> [<status_message>]|-delete]
  3683. Lets you set your Slack Status (not to be confused with away/here).
  3684. Prints current status if no arguments are given, unsets the status if -delete is given.
  3685. """
  3686. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3687. split_args = args.split(" ", 1)
  3688. if not split_args[0]:
  3689. profile = team.users[team.myidentifier].profile
  3690. team.buffer_prnt("Status: {} {}".format(
  3691. replace_string_with_emoji(profile.get("status_emoji", "")),
  3692. profile.get("status_text", "")))
  3693. return w.WEECHAT_RC_OK
  3694. emoji = "" if split_args[0] == "-delete" else split_args[0]
  3695. text = split_args[1] if len(split_args) > 1 else ""
  3696. new_profile = {"status_text": text, "status_emoji": emoji}
  3697. s = SlackRequest(team, "users.profile.set", {"profile": new_profile})
  3698. EVENTROUTER.receive(s)
  3699. return w.WEECHAT_RC_OK
  3700. command_status.completion = "-delete|%(emoji)"
  3701. @utf8_decode
  3702. def line_event_cb(data, signal, hashtable):
  3703. buffer_pointer = hashtable["_buffer"]
  3704. line_timestamp = hashtable["_chat_line_date"]
  3705. line_time_id = hashtable["_chat_line_date_printed"]
  3706. channel = EVENTROUTER.weechat_controller.buffers.get(buffer_pointer)
  3707. if line_timestamp and line_time_id and isinstance(channel, SlackChannelCommon):
  3708. ts = SlackTS("{}.{}".format(line_timestamp, line_time_id))
  3709. message_hash = channel.hash_message(ts)
  3710. if message_hash is None:
  3711. return w.WEECHAT_RC_OK
  3712. message_hash = "$" + message_hash
  3713. if data == "message":
  3714. w.command(buffer_pointer, "/cursor stop")
  3715. w.command(buffer_pointer, "/input insert {}".format(message_hash))
  3716. elif data == "delete":
  3717. w.command(buffer_pointer, "/input send {}s///".format(message_hash))
  3718. elif data == "linkarchive":
  3719. w.command(buffer_pointer, "/cursor stop")
  3720. w.command(buffer_pointer, "/slack linkarchive {}".format(message_hash[1:]))
  3721. elif data == "reply":
  3722. w.command(buffer_pointer, "/cursor stop")
  3723. w.command(buffer_pointer, "/input insert /reply {}\\x20".format(message_hash))
  3724. elif data == "thread":
  3725. w.command(buffer_pointer, "/cursor stop")
  3726. w.command(buffer_pointer, "/thread {}".format(message_hash))
  3727. return w.WEECHAT_RC_OK
  3728. @slack_buffer_required
  3729. @utf8_decode
  3730. def command_back(data, current_buffer, args):
  3731. """
  3732. /slack back
  3733. Sets your status as 'back'.
  3734. """
  3735. team = EVENTROUTER.weechat_controller.buffers[current_buffer].team
  3736. s = SlackRequest(team, "users.setPresence", {"presence": "auto"})
  3737. EVENTROUTER.receive(s)
  3738. set_own_presence_active(team)
  3739. return w.WEECHAT_RC_OK
  3740. @slack_buffer_required
  3741. @utf8_decode
  3742. def command_label(data, current_buffer, args):
  3743. """
  3744. /label <name>
  3745. Rename a thread buffer. Note that this is not permanent. It will only last
  3746. as long as you keep the buffer and wee-slack open.
  3747. """
  3748. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3749. if channel.type == 'thread':
  3750. new_name = " +" + args
  3751. channel.label = new_name
  3752. w.buffer_set(channel.channel_buffer, "short_name", new_name)
  3753. return w.WEECHAT_RC_OK
  3754. @utf8_decode
  3755. def set_unread_cb(data, current_buffer, command):
  3756. for channel in EVENTROUTER.weechat_controller.buffers.values():
  3757. channel.mark_read()
  3758. return w.WEECHAT_RC_OK
  3759. @slack_buffer_or_ignore
  3760. @utf8_decode
  3761. def set_unread_current_buffer_cb(data, current_buffer, command):
  3762. channel = EVENTROUTER.weechat_controller.buffers[current_buffer]
  3763. channel.mark_read()
  3764. return w.WEECHAT_RC_OK
  3765. ###### NEW EXCEPTIONS
  3766. class InvalidType(Exception):
  3767. """
  3768. Raised when we do type checking to ensure objects of the wrong
  3769. type are not used improperly.
  3770. """
  3771. def __init__(self, type_str):
  3772. super(InvalidType, self).__init__(type_str)
  3773. ###### New but probably old and need to migrate
  3774. def closed_slack_debug_buffer_cb(data, buffer):
  3775. global slack_debug
  3776. slack_debug = None
  3777. return w.WEECHAT_RC_OK
  3778. def create_slack_debug_buffer():
  3779. global slack_debug, debug_string
  3780. if slack_debug is None:
  3781. debug_string = None
  3782. slack_debug = w.buffer_new("slack-debug", "", "", "closed_slack_debug_buffer_cb", "")
  3783. w.buffer_set(slack_debug, "notify", "0")
  3784. w.buffer_set(slack_debug, "highlight_tags_restrict", "highlight_force")
  3785. def load_emoji():
  3786. try:
  3787. DIR = w.info_get('weechat_dir', '')
  3788. with open('{}/weemoji.json'.format(DIR), 'r') as ef:
  3789. emojis = json.loads(ef.read())
  3790. if 'emoji' in emojis:
  3791. print_error('The weemoji.json file is in an old format. Please update it.')
  3792. else:
  3793. emoji_unicode = {key: value['unicode'] for key, value in emojis.items()}
  3794. emoji_skin_tones = {skin_tone['name']: skin_tone['unicode']
  3795. for emoji in emojis.values()
  3796. for skin_tone in emoji.get('skinVariations', {}).values()}
  3797. emoji_with_skin_tones = chain(emoji_unicode.items(), emoji_skin_tones.items())
  3798. emoji_with_skin_tones_reverse = {v: k for k, v in emoji_with_skin_tones}
  3799. return emoji_unicode, emoji_with_skin_tones_reverse
  3800. except:
  3801. dbg("Couldn't load emoji list: {}".format(format_exc_only()), 5)
  3802. return {}, {}
  3803. def parse_help_docstring(cmd):
  3804. doc = textwrap.dedent(cmd.__doc__).strip().split('\n', 1)
  3805. cmd_line = doc[0].split(None, 1)
  3806. args = ''.join(cmd_line[1:])
  3807. return cmd_line[0], args, doc[1].strip()
  3808. def setup_hooks():
  3809. w.bar_item_new('slack_typing_notice', '(extra)typing_bar_item_cb', '')
  3810. w.bar_item_new('away', '(extra)away_bar_item_cb', '')
  3811. w.bar_item_new('slack_away', '(extra)away_bar_item_cb', '')
  3812. w.hook_timer(5000, 0, 0, "ws_ping_cb", "")
  3813. w.hook_timer(1000, 0, 0, "typing_update_cb", "")
  3814. w.hook_timer(1000, 0, 0, "buffer_list_update_callback", "EVENTROUTER")
  3815. w.hook_timer(3000, 0, 0, "reconnect_callback", "EVENTROUTER")
  3816. w.hook_timer(1000 * 60 * 5, 0, 0, "slack_never_away_cb", "")
  3817. w.hook_signal('buffer_closing', "buffer_closing_callback", "")
  3818. w.hook_signal('buffer_switch', "buffer_switch_callback", "EVENTROUTER")
  3819. w.hook_signal('window_switch', "buffer_switch_callback", "EVENTROUTER")
  3820. w.hook_signal('quit', "quit_notification_callback", "")
  3821. if config.send_typing_notice:
  3822. w.hook_signal('input_text_changed', "typing_notification_cb", "")
  3823. command_help.completion = '|'.join(EVENTROUTER.cmds.keys())
  3824. completions = '||'.join(
  3825. '{} {}'.format(name, getattr(cmd, 'completion', ''))
  3826. for name, cmd in EVENTROUTER.cmds.items())
  3827. w.hook_command(
  3828. # Command name and description
  3829. 'slack', 'Plugin to allow typing notification and sync of read markers for slack.com',
  3830. # Usage
  3831. '<command> [<command options>]',
  3832. # Description of arguments
  3833. 'Commands:\n' +
  3834. '\n'.join(sorted(EVENTROUTER.cmds.keys())) +
  3835. '\nUse /slack help <command> to find out more\n',
  3836. # Completions
  3837. completions,
  3838. # Function name
  3839. 'slack_command_cb', '')
  3840. w.hook_command_run('/me', 'me_command_cb', '')
  3841. w.hook_command_run('/query', 'join_query_command_cb', '')
  3842. w.hook_command_run('/join', 'join_query_command_cb', '')
  3843. w.hook_command_run('/part', 'part_command_cb', '')
  3844. w.hook_command_run('/topic', 'topic_command_cb', '')
  3845. w.hook_command_run('/msg', 'msg_command_cb', '')
  3846. w.hook_command_run('/invite', 'invite_command_cb', '')
  3847. w.hook_command_run("/input complete_next", "complete_next_cb", "")
  3848. w.hook_command_run("/input set_unread", "set_unread_cb", "")
  3849. w.hook_command_run("/input set_unread_current_buffer", "set_unread_current_buffer_cb", "")
  3850. w.hook_command_run('/away', 'away_command_cb', '')
  3851. w.hook_command_run('/whois', 'whois_command_cb', '')
  3852. for cmd_name in ['hide', 'label', 'rehistory', 'reply', 'thread']:
  3853. cmd = EVENTROUTER.cmds[cmd_name]
  3854. _, args, description = parse_help_docstring(cmd)
  3855. completion = getattr(cmd, 'completion', '')
  3856. w.hook_command(cmd_name, description, args, '', completion, 'command_' + cmd_name, '')
  3857. w.hook_completion("irc_channel_topic", "complete topic for slack", "topic_completion_cb", "")
  3858. w.hook_completion("irc_channels", "complete channels for slack", "channel_completion_cb", "")
  3859. w.hook_completion("irc_privates", "complete dms/mpdms for slack", "dm_completion_cb", "")
  3860. w.hook_completion("nicks", "complete @-nicks for slack", "nick_completion_cb", "")
  3861. w.hook_completion("threads", "complete thread ids for slack", "thread_completion_cb", "")
  3862. w.hook_completion("usergroups", "complete @-usergroups for slack", "usergroups_completion_cb", "")
  3863. w.hook_completion("emoji", "complete :emoji: for slack", "emoji_completion_cb", "")
  3864. w.key_bind("mouse", {
  3865. "@chat(python.*):button2": "hsignal:slack_mouse",
  3866. })
  3867. w.key_bind("cursor", {
  3868. "@chat(python.*):D": "hsignal:slack_cursor_delete",
  3869. "@chat(python.*):L": "hsignal:slack_cursor_linkarchive",
  3870. "@chat(python.*):M": "hsignal:slack_cursor_message",
  3871. "@chat(python.*):R": "hsignal:slack_cursor_reply",
  3872. "@chat(python.*):T": "hsignal:slack_cursor_thread",
  3873. })
  3874. w.hook_hsignal("slack_mouse", "line_event_cb", "message")
  3875. w.hook_hsignal("slack_cursor_delete", "line_event_cb", "delete")
  3876. w.hook_hsignal("slack_cursor_linkarchive", "line_event_cb", "linkarchive")
  3877. w.hook_hsignal("slack_cursor_message", "line_event_cb", "message")
  3878. w.hook_hsignal("slack_cursor_reply", "line_event_cb", "reply")
  3879. w.hook_hsignal("slack_cursor_thread", "line_event_cb", "thread")
  3880. # Hooks to fix/implement
  3881. # w.hook_signal('buffer_opened', "buffer_opened_cb", "")
  3882. # w.hook_signal('window_scrolled', "scrolled_cb", "")
  3883. # w.hook_timer(3000, 0, 0, "slack_connection_persistence_cb", "")
  3884. ##### END NEW
  3885. def dbg(message, level=0, main_buffer=False, fout=False):
  3886. """
  3887. send debug output to the slack-debug buffer and optionally write to a file.
  3888. """
  3889. # TODO: do this smarter
  3890. if level >= config.debug_level:
  3891. global debug_string
  3892. message = "DEBUG: {}".format(message)
  3893. if fout:
  3894. with open('/tmp/debug.log', 'a+') as log_file:
  3895. log_file.writelines(message + '\n')
  3896. if main_buffer:
  3897. w.prnt("", "slack: " + message)
  3898. else:
  3899. if slack_debug and (not debug_string or debug_string in message):
  3900. w.prnt(slack_debug, message)
  3901. ###### Config code
  3902. class PluginConfig(object):
  3903. Setting = collections.namedtuple('Setting', ['default', 'desc'])
  3904. # Default settings.
  3905. # These are, initially, each a (default, desc) tuple; the former is the
  3906. # default value of the setting, in the (string) format that weechat
  3907. # expects, and the latter is the user-friendly description of the setting.
  3908. # At __init__ time these values are extracted, the description is used to
  3909. # set or update the setting description for use with /help, and the default
  3910. # value is used to set the default for any settings not already defined.
  3911. # Following this procedure, the keys remain the same, but the values are
  3912. # the real (python) values of the settings.
  3913. default_settings = {
  3914. 'auto_open_threads': Setting(
  3915. default='false',
  3916. desc='Automatically open threads when mentioned or in'
  3917. 'response to own messages.'),
  3918. 'background_load_all_history': Setting(
  3919. default='false',
  3920. desc='Load history for each channel in the background as soon as it'
  3921. ' opens, rather than waiting for the user to look at it.'),
  3922. 'channel_name_typing_indicator': Setting(
  3923. default='true',
  3924. desc='Change the prefix of a channel from # to > when someone is'
  3925. ' typing in it. Note that this will (temporarily) affect the sort'
  3926. ' order if you sort buffers by name rather than by number.'),
  3927. 'color_buflist_muted_channels': Setting(
  3928. default='darkgray',
  3929. desc='Color to use for muted channels in the buflist'),
  3930. 'color_deleted': Setting(
  3931. default='red',
  3932. desc='Color to use for deleted messages and files.'),
  3933. 'color_edited_suffix': Setting(
  3934. default='095',
  3935. desc='Color to use for (edited) suffix on messages that have been edited.'),
  3936. 'color_reaction_suffix': Setting(
  3937. default='darkgray',
  3938. desc='Color to use for the [:wave:(@user)] suffix on messages that'
  3939. ' have reactions attached to them.'),
  3940. 'color_reaction_suffix_added_by_you': Setting(
  3941. default='blue',
  3942. desc='Color to use for reactions that you have added.'),
  3943. 'color_thread_suffix': Setting(
  3944. default='lightcyan',
  3945. desc='Color to use for the [thread: XXX] suffix on messages that'
  3946. ' have threads attached to them. The special value "multiple" can'
  3947. ' be used to use a different color for each thread.'),
  3948. 'color_typing_notice': Setting(
  3949. default='yellow',
  3950. desc='Color to use for the typing notice.'),
  3951. 'colorize_private_chats': Setting(
  3952. default='false',
  3953. desc='Whether to use nick-colors in DM windows.'),
  3954. 'debug_mode': Setting(
  3955. default='false',
  3956. desc='Open a dedicated buffer for debug messages and start logging'
  3957. ' to it. How verbose the logging is depends on log_level.'),
  3958. 'debug_level': Setting(
  3959. default='3',
  3960. desc='Show only this level of debug info (or higher) when'
  3961. ' debug_mode is on. Lower levels -> more messages.'),
  3962. 'distracting_channels': Setting(
  3963. default='',
  3964. desc='List of channels to hide.'),
  3965. 'external_user_suffix': Setting(
  3966. default='*',
  3967. desc='The suffix appended to nicks to indicate external users.'),
  3968. 'files_download_location': Setting(
  3969. default='',
  3970. desc='If set, file attachments will be automatically downloaded'
  3971. ' to this location. "%h" will be replaced by WeeChat home,'
  3972. ' "~/.weechat" by default.'),
  3973. 'group_name_prefix': Setting(
  3974. default='&',
  3975. desc='The prefix of buffer names for groups (private channels).'),
  3976. 'map_underline_to': Setting(
  3977. default='_',
  3978. desc='When sending underlined text to slack, use this formatting'
  3979. ' character for it. The default ("_") sends it as italics. Use'
  3980. ' "*" to send bold instead.'),
  3981. 'muted_channels_activity': Setting(
  3982. default='personal_highlights',
  3983. desc="Control which activity you see from muted channels, either"
  3984. " none, personal_highlights, all_highlights or all. none: Don't"
  3985. " show any activity. personal_highlights: Only show personal"
  3986. " highlights, i.e. not @channel and @here. all_highlights: Show"
  3987. " all highlights, but not other messages. all: Show all activity,"
  3988. " like other channels."),
  3989. 'notify_usergroup_handle_updated': Setting(
  3990. default='false',
  3991. desc="Control if you want to see notification when a usergroup's"
  3992. " handle has changed, either true or false."),
  3993. 'never_away': Setting(
  3994. default='false',
  3995. desc='Poke Slack every five minutes so that it never marks you "away".'),
  3996. 'record_events': Setting(
  3997. default='false',
  3998. desc='Log all traffic from Slack to disk as JSON.'),
  3999. 'render_bold_as': Setting(
  4000. default='bold',
  4001. desc='When receiving bold text from Slack, render it as this in weechat.'),
  4002. 'render_emoji_as_string': Setting(
  4003. default='false',
  4004. desc="Render emojis as :emoji_name: instead of emoji characters. Enable this"
  4005. " if your terminal doesn't support emojis, or set to 'both' if you want to"
  4006. " see both renderings. Note that even though this is"
  4007. " disabled by default, you need to place {}/blob/master/weemoji.json in your"
  4008. " weechat directory to enable rendering emojis as emoji characters."
  4009. .format(REPO_URL)),
  4010. 'render_italic_as': Setting(
  4011. default='italic',
  4012. desc='When receiving bold text from Slack, render it as this in weechat.'
  4013. ' If your terminal lacks italic support, consider using "underline" instead.'),
  4014. 'send_typing_notice': Setting(
  4015. default='true',
  4016. desc='Alert Slack users when you are typing a message in the input bar '
  4017. '(Requires reload)'),
  4018. 'server_aliases': Setting(
  4019. default='',
  4020. desc='A comma separated list of `subdomain:alias` pairs. The alias'
  4021. ' will be used instead of the actual name of the slack (in buffer'
  4022. ' names, logging, etc). E.g `work:no_fun_allowed` would make your'
  4023. ' work slack show up as `no_fun_allowed` rather than `work.slack.com`.'),
  4024. 'shared_name_prefix': Setting(
  4025. default='%',
  4026. desc='The prefix of buffer names for shared channels.'),
  4027. 'short_buffer_names': Setting(
  4028. default='false',
  4029. desc='Use `foo.#channel` rather than `foo.slack.com.#channel` as the'
  4030. ' internal name for Slack buffers.'),
  4031. 'show_buflist_presence': Setting(
  4032. default='true',
  4033. desc='Display a `+` character in the buffer list for present users.'),
  4034. 'show_reaction_nicks': Setting(
  4035. default='false',
  4036. desc='Display the name of the reacting user(s) alongside each reactji.'),
  4037. 'slack_api_token': Setting(
  4038. default='INSERT VALID KEY HERE!',
  4039. desc='List of Slack API tokens, one per Slack instance you want to'
  4040. ' connect to. See the README for details on how to get these.'),
  4041. 'slack_timeout': Setting(
  4042. default='20000',
  4043. desc='How long (ms) to wait when communicating with Slack.'),
  4044. 'switch_buffer_on_join': Setting(
  4045. default='true',
  4046. desc='When /joining a channel, automatically switch to it as well.'),
  4047. 'thread_messages_in_channel': Setting(
  4048. default='false',
  4049. desc='When enabled shows thread messages in the parent channel.'),
  4050. 'unfurl_ignore_alt_text': Setting(
  4051. default='false',
  4052. desc='When displaying ("unfurling") links to channels/users/etc,'
  4053. ' ignore the "alt text" present in the message and instead use the'
  4054. ' canonical name of the thing being linked to.'),
  4055. 'unfurl_auto_link_display': Setting(
  4056. default='both',
  4057. desc='When displaying ("unfurling") links to channels/users/etc,'
  4058. ' determine what is displayed when the text matches the url'
  4059. ' without the protocol. This happens when Slack automatically'
  4060. ' creates links, e.g. from words separated by dots or email'
  4061. ' addresses. Set it to "text" to only display the text written by'
  4062. ' the user, "url" to only display the url or "both" (the default)'
  4063. ' to display both.'),
  4064. 'unhide_buffers_with_activity': Setting(
  4065. default='false',
  4066. desc='When activity occurs on a buffer, unhide it even if it was'
  4067. ' previously hidden (whether by the user or by the'
  4068. ' distracting_channels setting).'),
  4069. 'use_full_names': Setting(
  4070. default='false',
  4071. desc='Use full names as the nicks for all users. When this is'
  4072. ' false (the default), display names will be used if set, with a'
  4073. ' fallback to the full name if display name is not set.'),
  4074. }
  4075. # Set missing settings to their defaults. Load non-missing settings from
  4076. # weechat configs.
  4077. def __init__(self):
  4078. self.settings = {}
  4079. # Set all descriptions, replace the values in the dict with the
  4080. # default setting value rather than the (setting,desc) tuple.
  4081. for key, (default, desc) in self.default_settings.items():
  4082. w.config_set_desc_plugin(key, desc)
  4083. self.settings[key] = default
  4084. # Migrate settings from old versions of Weeslack...
  4085. self.migrate()
  4086. # ...and then set anything left over from the defaults.
  4087. for key, default in self.settings.items():
  4088. if not w.config_get_plugin(key):
  4089. w.config_set_plugin(key, default)
  4090. self.config_changed(None, None, None)
  4091. def __str__(self):
  4092. return "".join([x + "\t" + str(self.settings[x]) + "\n" for x in self.settings.keys()])
  4093. def config_changed(self, data, key, value):
  4094. for key in self.settings:
  4095. self.settings[key] = self.fetch_setting(key)
  4096. if self.debug_mode:
  4097. create_slack_debug_buffer()
  4098. return w.WEECHAT_RC_OK
  4099. def fetch_setting(self, key):
  4100. try:
  4101. return getattr(self, 'get_' + key)(key)
  4102. except AttributeError:
  4103. # Most settings are on/off, so make get_boolean the default
  4104. return self.get_boolean(key)
  4105. except:
  4106. # There was setting-specific getter, but it failed.
  4107. return self.settings[key]
  4108. def __getattr__(self, key):
  4109. try:
  4110. return self.settings[key]
  4111. except KeyError:
  4112. raise AttributeError(key)
  4113. def get_boolean(self, key):
  4114. return w.config_string_to_boolean(w.config_get_plugin(key))
  4115. def get_string(self, key):
  4116. return w.config_get_plugin(key)
  4117. def get_int(self, key):
  4118. return int(w.config_get_plugin(key))
  4119. def is_default(self, key):
  4120. default = self.default_settings.get(key).default
  4121. return w.config_get_plugin(key) == default
  4122. get_color_buflist_muted_channels = get_string
  4123. get_color_deleted = get_string
  4124. get_color_edited_suffix = get_string
  4125. get_color_reaction_suffix = get_string
  4126. get_color_reaction_suffix_added_by_you = get_string
  4127. get_color_thread_suffix = get_string
  4128. get_color_typing_notice = get_string
  4129. get_debug_level = get_int
  4130. get_external_user_suffix = get_string
  4131. get_files_download_location = get_string
  4132. get_group_name_prefix = get_string
  4133. get_map_underline_to = get_string
  4134. get_muted_channels_activity = get_string
  4135. get_render_bold_as = get_string
  4136. get_render_italic_as = get_string
  4137. get_shared_name_prefix = get_string
  4138. get_slack_timeout = get_int
  4139. get_unfurl_auto_link_display = get_string
  4140. def get_distracting_channels(self, key):
  4141. return [x.strip() for x in w.config_get_plugin(key).split(',') if x]
  4142. def get_server_aliases(self, key):
  4143. alias_list = w.config_get_plugin(key)
  4144. return dict(item.split(":") for item in alias_list.split(",") if ':' in item)
  4145. def get_slack_api_token(self, key):
  4146. token = w.config_get_plugin("slack_api_token")
  4147. if token.startswith('${sec.data'):
  4148. return w.string_eval_expression(token, {}, {}, {})
  4149. else:
  4150. return token
  4151. def get_render_emoji_as_string(self, key):
  4152. s = w.config_get_plugin(key)
  4153. if s == 'both':
  4154. return s
  4155. return w.config_string_to_boolean(s)
  4156. def migrate(self):
  4157. """
  4158. This is to migrate the extension name from slack_extension to slack
  4159. """
  4160. if not w.config_get_plugin("migrated"):
  4161. for k in self.settings.keys():
  4162. if not w.config_is_set_plugin(k):
  4163. p = w.config_get("plugins.var.python.slack_extension.{}".format(k))
  4164. data = w.config_string(p)
  4165. if data != "":
  4166. w.config_set_plugin(k, data)
  4167. w.config_set_plugin("migrated", "true")
  4168. old_thread_color_config = w.config_get_plugin("thread_suffix_color")
  4169. new_thread_color_config = w.config_get_plugin("color_thread_suffix")
  4170. if old_thread_color_config and not new_thread_color_config:
  4171. w.config_set_plugin("color_thread_suffix", old_thread_color_config)
  4172. def config_server_buffer_cb(data, key, value):
  4173. for team in EVENTROUTER.teams.values():
  4174. team.buffer_merge(value)
  4175. return w.WEECHAT_RC_OK
  4176. # to Trace execution, add `setup_trace()` to startup
  4177. # and to a function and sys.settrace(trace_calls) to a function
  4178. def setup_trace():
  4179. global f
  4180. now = time.time()
  4181. f = open('{}/{}-trace.json'.format(RECORD_DIR, now), 'w')
  4182. def trace_calls(frame, event, arg):
  4183. global f
  4184. if event != 'call':
  4185. return
  4186. co = frame.f_code
  4187. func_name = co.co_name
  4188. if func_name == 'write':
  4189. # Ignore write() calls from print statements
  4190. return
  4191. func_line_no = frame.f_lineno
  4192. func_filename = co.co_filename
  4193. caller = frame.f_back
  4194. caller_line_no = caller.f_lineno
  4195. caller_filename = caller.f_code.co_filename
  4196. print('Call to %s on line %s of %s from line %s of %s' % \
  4197. (func_name, func_line_no, func_filename,
  4198. caller_line_no, caller_filename), file=f)
  4199. f.flush()
  4200. return
  4201. def initiate_connection(token, retries=3, team=None):
  4202. return SlackRequest(team,
  4203. 'rtm.{}'.format('connect' if team else 'start'),
  4204. {"batch_presence_aware": 1},
  4205. retries=retries,
  4206. token=token,
  4207. metadata={'initial_connection': True})
  4208. if __name__ == "__main__":
  4209. w = WeechatWrapper(weechat)
  4210. if w.register(SCRIPT_NAME, SCRIPT_AUTHOR, SCRIPT_VERSION, SCRIPT_LICENSE,
  4211. SCRIPT_DESC, "script_unloaded", ""):
  4212. weechat_version = w.info_get("version_number", "") or 0
  4213. if int(weechat_version) < 0x1030000:
  4214. w.prnt("", "\nERROR: Weechat version 1.3+ is required to use {}.\n\n".format(SCRIPT_NAME))
  4215. else:
  4216. global EVENTROUTER
  4217. EVENTROUTER = EventRouter()
  4218. receive_httprequest_callback = EVENTROUTER.receive_httprequest_callback
  4219. receive_ws_callback = EVENTROUTER.receive_ws_callback
  4220. # Global var section
  4221. slack_debug = None
  4222. config = PluginConfig()
  4223. config_changed_cb = config.config_changed
  4224. typing_timer = time.time()
  4225. hide_distractions = False
  4226. w.hook_config("plugins.var.python." + SCRIPT_NAME + ".*", "config_changed_cb", "")
  4227. w.hook_config("irc.look.server_buffer", "config_server_buffer_cb", "")
  4228. w.hook_modifier("input_text_for_buffer", "input_text_for_buffer_cb", "")
  4229. EMOJI, EMOJI_WITH_SKIN_TONES_REVERSE = load_emoji()
  4230. setup_hooks()
  4231. # attach to the weechat hooks we need
  4232. tokens = [token.strip() for token in config.slack_api_token.split(',')]
  4233. w.prnt('', 'Connecting to {} slack team{}.'
  4234. .format(len(tokens), '' if len(tokens) == 1 else 's'))
  4235. for t in tokens:
  4236. s = initiate_connection(t)
  4237. EVENTROUTER.receive(s)
  4238. if config.record_events:
  4239. EVENTROUTER.record()
  4240. EVENTROUTER.handle_next()
  4241. # END attach to the weechat hooks we need
  4242. hdata = Hdata(w)