Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

slack.py 2.10.2: Merge with mainline #550

Merged
merged 1 commit into from
Feb 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 54 additions & 50 deletions python/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@

SCRIPT_NAME = "slack"
SCRIPT_AUTHOR = "Trygve Aaberge <[email protected]>"
SCRIPT_VERSION = "2.10.1"
SCRIPT_VERSION = "2.10.2"
SCRIPT_LICENSE = "MIT"
SCRIPT_DESC = "Extends WeeChat for typing notification/search/etc on slack.com"
REPO_URL = "https://github.com/wee-slack/wee-slack"
Expand Down Expand Up @@ -3402,7 +3402,7 @@ def render(self, force=False):
if blocks_rendered:
text = blocks_rendered
else:
text = self.message_json.get("text", "")
text = unhtmlescape(unfurl_refs(self.message_json.get("text", "")))

if self.message_json.get("mrkdwn", True):
text = render_formatting(text)
Expand All @@ -3412,9 +3412,7 @@ def render(self, force=False):
"group_join",
) and self.message_json.get("inviter"):
inviter_id = self.message_json.get("inviter")
text += " by invitation from <@{}>".format(inviter_id)

text = unfurl_refs(text)
text += unfurl_refs(" by invitation from <@{}>".format(inviter_id))

if self.subtype == "me_message" and not self.message_json["text"].startswith(
self.sender
Expand All @@ -3424,10 +3422,10 @@ def render(self, force=False):
if "edited" in self.message_json:
text += " " + colorize_string(config.color_edited_suffix, "(edited)")

text += unfurl_refs(unwrap_attachments(self, text))
text += unfurl_refs(unwrap_files(self, self.message_json, text))
text += unfurl_refs(unwrap_huddle(self, self.message_json, text))
text = unhtmlescape(text.lstrip().replace("\t", " "))
text += unwrap_attachments(self, text)
text += unhtmlescape(unfurl_refs(unwrap_files(self, self.message_json, text)))
text += unwrap_huddle(self, self.message_json, text)
text = text.lstrip().replace("\t", " ")

text += create_reactions_string(
self.message_json.get("reactions", ""), self.team.myidentifier
Expand Down Expand Up @@ -3507,17 +3505,19 @@ def get_reaction(self, reaction_name):
def add_reaction(self, reaction_name, user):
reaction = self.get_reaction(reaction_name)
if reaction:
reaction["count"] += 1
if user not in reaction["users"]:
reaction["users"].append(user)
else:
if "reactions" not in self.message_json:
self.message_json["reactions"] = []
self.message_json["reactions"].append(
{"name": reaction_name, "users": [user]}
{"name": reaction_name, "count": 1, "users": [user]}
)

def remove_reaction(self, reaction_name, user):
reaction = self.get_reaction(reaction_name)
reaction["count"] -= 1
if user in reaction["users"]:
reaction["users"].remove(user)

Expand Down Expand Up @@ -3553,7 +3553,7 @@ def notify_thread(self, message=None):

self.last_notify = max(message.ts, SlackTS())

if config.auto_open_threads:
if config.auto_open_threads and self.subscribed:
self.open_thread()

if message.user_identifier != self.team.myidentifier and (
Expand Down Expand Up @@ -3584,6 +3584,9 @@ def __init__(self, parent_channel, thread_ts, message_json, *args):
def parent_message(self):
return self.parent_channel.messages.get(self.thread_ts)

def open_thread(self, switch=False):
self.parent_message.open_thread(switch)


class Hdata(object):
def __init__(self, w):
Expand Down Expand Up @@ -4729,35 +4732,29 @@ def unfurl_rich_text_section(block):
colors_remove = []
characters_apply = []
characters_remove = []
if element.get("style", {}).get("bold") != prev_element.get("style", {}).get(
"bold"
):
if element.get("style", {}).get("bold"):
prev_style = prev_element.get("style", {})
cur_style = element.get("style", {})
if cur_style.get("bold", False) != prev_style.get("bold", False):
if cur_style.get("bold"):
colors_apply.append(w.color(config.render_bold_as))
characters_apply.append("*")
else:
colors_remove.append(w.color("-" + config.render_bold_as))
characters_remove.append("*")
if element.get("style", {}).get("italic") != prev_element.get("style", {}).get(
"italic"
):
if element.get("style", {}).get("italic"):
if cur_style.get("italic", False) != prev_style.get("italic", False):
if cur_style.get("italic"):
colors_apply.append(w.color(config.render_italic_as))
characters_apply.append("_")
else:
colors_remove.append(w.color("-" + config.render_italic_as))
characters_remove.append("_")
if element.get("style", {}).get("strike") != prev_element.get("style", {}).get(
"strike"
):
if element.get("style", {}).get("strike"):
if cur_style.get("strike", False) != prev_style.get("strike", False):
if cur_style.get("strike"):
characters_apply.append("~")
else:
characters_remove.append("~")
if element.get("style", {}).get("code") != prev_element.get("style", {}).get(
"code"
):
if element.get("style", {}).get("code"):
if cur_style.get("code", False) != prev_style.get("code", False):
if cur_style.get("code"):
characters_apply.append("`")
else:
characters_remove.append("`")
Expand All @@ -4779,7 +4776,7 @@ def unfurl_rich_text_section(block):

def unfurl_block_rich_text_element(element):
if element["type"] == "text":
return htmlescape(element["text"])
return element["text"]
elif element["type"] == "link":
text = element.get("text")
if text and text != element["url"]:
Expand All @@ -4791,6 +4788,10 @@ def unfurl_block_rich_text_element(element):
return element["url"]
elif element["type"] == "emoji":
return replace_string_with_emoji(":{}:".format(element["name"]))
elif element["type"] == "color":
rgb_int = int(element["value"].lstrip("#"), 16)
weechat_color = w.info_get("color_rgb2term", str(rgb_int))
return "{} {}".format(element["value"], colorize_string(weechat_color, "■"))
elif element["type"] == "user":
return resolve_ref("@{}".format(element["user_id"]))
elif element["type"] == "usergroup":
Expand All @@ -4809,9 +4810,9 @@ def unfurl_block_rich_text_element(element):

def unfurl_block_element(element):
if element["type"] == "mrkdwn":
return render_formatting(element["text"])
return render_formatting(unhtmlescape(unfurl_refs(element["text"])))
elif element["type"] == "plain_text":
return element["text"]
return unhtmlescape(unfurl_refs(element["text"]))
elif element["type"] == "image":
if element.get("alt_text"):
return "{} ({})".format(element["image_url"], element["alt_text"])
Expand Down Expand Up @@ -4881,7 +4882,6 @@ def unhtmlescape(text):


def unwrap_attachments(message, text_before):
text_before_unescaped = unhtmlescape(text_before)
attachment_texts = []
a = message.message_json.get("attachments")
if a:
Expand All @@ -4907,9 +4907,7 @@ def unwrap_attachments(message, text_before):
link_shown = False
title = attachment.get("title")
title_link = attachment.get("title_link", "")
if title_link and (
title_link in text_before or title_link in text_before_unescaped
):
if title_link and title_link in text_before:
title_link = ""
link_shown = True
if title and title_link:
Expand All @@ -4918,7 +4916,7 @@ def unwrap_attachments(message, text_before):
% (
prepend_title_text,
title,
title_link,
htmlescape(title_link),
)
)
prepend_title_text = ""
Expand All @@ -4932,12 +4930,8 @@ def unwrap_attachments(message, text_before):
)
prepend_title_text = ""
from_url = attachment.get("from_url", "")
if (
from_url not in text_before
and from_url not in text_before_unescaped
and from_url != title_link
):
t.append(from_url)
if from_url not in text_before and from_url != title_link:
t.append(htmlescape(from_url))
elif from_url:
link_shown = True

Expand All @@ -4947,17 +4941,13 @@ def unwrap_attachments(message, text_before):
t.append(prepend_title_text + tx)
prepend_title_text = ""

blocks = attachment.get("blocks", [])
t.extend(unfurl_blocks(blocks))

image_url = attachment.get("image_url", "")
if (
image_url not in text_before
and image_url not in text_before_unescaped
and image_url != from_url
and image_url != title_link
):
t.append(image_url)
t.append(htmlescape(image_url))
elif image_url:
link_shown = True

Expand All @@ -4971,6 +4961,11 @@ def unwrap_attachments(message, text_before):
if files:
t.append(files)

t = [unhtmlescape(unfurl_refs(x)) for x in t]

blocks = attachment.get("blocks", [])
t.extend(unfurl_blocks(blocks))

if attachment.get("is_msg_unfurl"):
channel_name = resolve_ref("#{}".format(attachment["channel_id"]))
if attachment.get("is_reply_unfurl"):
Expand All @@ -4984,14 +4979,19 @@ def unwrap_attachments(message, text_before):
ts = attachment.get("ts")
if ts:
ts_int = ts if isinstance(ts, int) else SlackTS(ts).major
if ts_int > 100000000000:
# The Slack web interface interprets very large timestamps
# as milliseconds after the epoch instead of regular Unix
# timestamps. We use the same heuristic here.
ts_int = ts_int // 1000
time_string = ""
if date.today() - date.fromtimestamp(ts_int) <= timedelta(days=1):
time_string = " at {time}"
timestamp_formatted = resolve_ref(
"!date^{}^{{date_short_pretty}}{}".format(ts_int, time_string)
).capitalize()
footer += " | {}".format(timestamp_formatted)
t.append(footer)
t.append(unhtmlescape(unfurl_refs(footer)))

fallback = attachment.get("fallback")
if t == [] and fallback and not link_shown:
Expand Down Expand Up @@ -5144,9 +5144,12 @@ def create_user_status_string(profile):
def create_reaction_string(reaction, myidentifier):
if config.show_reaction_nicks:
nicks = [resolve_ref("@{}".format(user)) for user in reaction["users"]]
users = "({})".format(", ".join(nicks))
nicks_extra = (
["and others"] if len(reaction["users"]) < reaction["count"] else []
)
users = "({})".format(", ".join(nicks + nicks_extra))
else:
users = len(reaction["users"])
users = reaction["count"]
reaction_string = ":{}:{}".format(reaction["name"], users)
if myidentifier in reaction["users"]:
return colorize_string(
Expand All @@ -5159,7 +5162,7 @@ def create_reaction_string(reaction, myidentifier):


def create_reactions_string(reactions, myidentifier):
reactions_with_users = [r for r in reactions if len(r["users"]) > 0]
reactions_with_users = [r for r in reactions if r["count"] > 0]
reactions_string = " ".join(
create_reaction_string(r, myidentifier) for r in reactions_with_users
)
Expand Down Expand Up @@ -6622,6 +6625,7 @@ def setup_hooks():
w.hook_command_run(
"/input set_unread_current_buffer", "set_unread_current_buffer_cb", ""
)
w.hook_command_run("/buffer set unread", "set_unread_current_buffer_cb", "")
w.hook_command_run("/away", "away_command_cb", "")
w.hook_command_run("/whois", "whois_command_cb", "")

Expand Down
Loading