code
stringlengths 501
5.19M
| package
stringlengths 2
81
| path
stringlengths 9
304
| filename
stringlengths 4
145
|
---|---|---|---|
# YouTube bot
The YouTube bot is a Zulip bot that can search for videos from [YouTube](https://www.youtube.com/).
To use the YouTube bot, you can simply call it with `@YouTube` followed
by a keyword(s), like so:
```
@YouTube funny cats
```
## Setup
Before starting you will need a Developer's API key to run the bot.
To obtain a API key, follow the following steps :
1. Create a project in the [Google Developers Console](https://console.developers.google.com/)
2. Open the [API Library](https://console.developers.google.com/apis/library?project=_)
in the Google Developers Console. If prompted, select a project or create a new one.
In the list of APIs, select `Youtube Data API v3` and make sure it is enabled .
3. Open the [Credentials](https://console.developers.google.com/apis/credentials?project=_) page.
4. In the Credentials page , select *Create Credentials > API key*
5. Open `zulip_bots/bots/youtube/youtube.conf` in an editor and
and change the value of the `key` attribute to the API key
you generated above.
6. And that's it ! See Configuration section on configuring the bot.
## Configuration
This section explains the usage of options `youtube.conf` file in configuring the bot.
- `key` - Used for setting the API key. See the above section on setting up the bot.
- `number_of_results` - The maximum number of videos to show when searching
for a list of videos with the `@YouTube list <keyword>` command.
- `video_region` - The location to be used for searching.
The bot shows only the videos that are available in the given `<video_region>`
Run this bot as described in [here](https://zulip.com/api/running-bots#running-a-bot).
## Usage
1. `@YouTube <keyword>`
- This command search YouTube with the given keyword and gives the top result of the search.
This can also be done with the command `@YouTube top <keyword>`
- Example usage: `@YouTube funny cats` , `@YouTube top funny dogs`

2. `@YouTube list <keyword>`
- This command search YouTube with the given keyword and gives a list of videos associated with the keyword.
- Example usage: `@YouTube list origami`

2. If a video can't be found for a given keyword, the bot will
respond with an error message

3. If there's a error while searching, the bot will respond with an
error message

| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/youtube/doc.md | doc.md |
import html
import json
import random
import re
from typing import Any, Dict, Optional, Tuple
import requests
from zulip_bots.lib import BotHandler
class NotAvailableException(Exception):
pass
class InvalidAnswerException(Exception):
pass
class TriviaQuizHandler:
def usage(self) -> str:
return """
This plugin will give users a trivia question from
the open trivia database at opentdb.com."""
def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> None:
query = message["content"]
if query == "new":
try:
start_new_quiz(message, bot_handler)
return
except NotAvailableException:
bot_response = "Uh-Oh! Trivia service is down."
bot_handler.send_reply(message, bot_response)
return
elif query.startswith("answer"):
try:
(quiz_id, answer) = parse_answer(query)
except InvalidAnswerException:
bot_response = "Invalid answer format"
bot_handler.send_reply(message, bot_response)
return
try:
quiz_payload = get_quiz_from_id(quiz_id, bot_handler)
except (KeyError, TypeError):
bot_response = "Invalid quiz id"
bot_handler.send_reply(message, bot_response)
return
quiz = json.loads(quiz_payload)
start_new_question, bot_response = handle_answer(
quiz, answer, quiz_id, bot_handler, message["sender_full_name"]
)
bot_handler.send_reply(message, bot_response)
if start_new_question:
start_new_quiz(message, bot_handler)
return
else:
bot_response = 'type "new" for a new question'
bot_handler.send_reply(message, bot_response)
def get_quiz_from_id(quiz_id: str, bot_handler: BotHandler) -> str:
return bot_handler.storage.get(quiz_id)
def start_new_quiz(message: Dict[str, Any], bot_handler: BotHandler) -> None:
quiz = get_trivia_quiz()
quiz_id = generate_quiz_id(bot_handler.storage)
bot_response = format_quiz_for_markdown(quiz_id, quiz)
widget_content = format_quiz_for_widget(quiz_id, quiz)
bot_handler.storage.put(quiz_id, json.dumps(quiz))
bot_handler.send_reply(message, bot_response, widget_content)
def parse_answer(query: str) -> Tuple[str, str]:
m = re.match(r"answer\s+(Q...)\s+(.)", query)
if not m:
raise InvalidAnswerException()
quiz_id = m.group(1)
answer = m.group(2).upper()
if answer not in "ABCD":
raise InvalidAnswerException()
return (quiz_id, answer)
def get_trivia_quiz() -> Dict[str, Any]:
payload = get_trivia_payload()
quiz = get_quiz_from_payload(payload)
return quiz
def get_trivia_payload() -> Dict[str, Any]:
url = "https://opentdb.com/api.php?amount=1&type=multiple"
try:
data = requests.get(url)
except requests.exceptions.RequestException:
raise NotAvailableException()
if data.status_code != 200:
raise NotAvailableException()
payload = data.json()
return payload
def fix_quotes(s: str) -> Optional[str]:
# opentdb is nice enough to escape HTML for us, but
# we are sending this to code that does that already :)
#
# Meanwhile Python took until version 3.4 to have a
# simple html.unescape function.
try:
return html.unescape(s)
except Exception:
raise Exception("Please use python3.4 or later for this bot.")
def get_quiz_from_payload(payload: Dict[str, Any]) -> Dict[str, Any]:
result = payload["results"][0]
question = result["question"]
letters = ["A", "B", "C", "D"]
random.shuffle(letters)
correct_letter = letters[0]
answers = dict()
answers[correct_letter] = result["correct_answer"]
for i in range(3):
answers[letters[i + 1]] = result["incorrect_answers"][i]
answers = {letter: fix_quotes(answer) for letter, answer in answers.items()}
quiz = dict(
question=fix_quotes(question),
answers=answers,
answered_options=[],
pending=True,
correct_letter=correct_letter,
) # type: Dict[str, Any]
return quiz
def generate_quiz_id(storage: Any) -> str:
try:
quiz_num = storage.get("quiz_id")
except (KeyError, TypeError):
quiz_num = 0
quiz_num += 1
quiz_num = quiz_num % (1000)
storage.put("quiz_id", quiz_num)
quiz_id = "Q%03d" % (quiz_num,)
return quiz_id
def format_quiz_for_widget(quiz_id: str, quiz: Dict[str, Any]) -> str:
widget_type = "zform"
question = quiz["question"]
answers = quiz["answers"]
heading = quiz_id + ": " + question
def get_choice(letter: str) -> Dict[str, str]:
answer = answers[letter]
reply = "answer " + quiz_id + " " + letter
return dict(
type="multiple_choice",
short_name=letter,
long_name=answer,
reply=reply,
)
choices = [get_choice(letter) for letter in "ABCD"]
extra_data = dict(
type="choices",
heading=heading,
choices=choices,
)
widget_content = dict(
widget_type=widget_type,
extra_data=extra_data,
)
payload = json.dumps(widget_content)
return payload
def format_quiz_for_markdown(quiz_id: str, quiz: Dict[str, Any]) -> str:
question = quiz["question"]
answers = quiz["answers"]
answer_list = "\n".join(
"* **{letter}** {answer}".format(
letter=letter,
answer=answers[letter],
)
for letter in "ABCD"
)
how_to_respond = f"""**reply**: answer {quiz_id} <letter>"""
content = """
Q: {question}
{answer_list}
{how_to_respond}""".format(
question=question,
answer_list=answer_list,
how_to_respond=how_to_respond,
)
return content
def update_quiz(quiz: Dict[str, Any], quiz_id: str, bot_handler: BotHandler) -> None:
bot_handler.storage.put(quiz_id, json.dumps(quiz))
def build_response(is_correct: bool, num_answers: int) -> str:
if is_correct:
response = ":tada: **{answer}** is correct, {sender_name}!"
else:
if num_answers >= 3:
response = ":disappointed: WRONG, {sender_name}! The correct answer is **{answer}**."
else:
response = ":disappointed: WRONG, {sender_name}! {option} is not correct."
return response
def handle_answer(
quiz: Dict[str, Any], option: str, quiz_id: str, bot_handler: BotHandler, sender_name: str
) -> Tuple[bool, str]:
answer = quiz["answers"][quiz["correct_letter"]]
is_new_answer = option not in quiz["answered_options"]
if is_new_answer:
quiz["answered_options"].append(option)
num_answers = len(quiz["answered_options"])
is_correct = option == quiz["correct_letter"]
start_new_question = quiz["pending"] and (is_correct or num_answers >= 3)
if start_new_question or is_correct:
quiz["pending"] = False
if is_new_answer or start_new_question:
update_quiz(quiz, quiz_id, bot_handler)
response = build_response(is_correct, num_answers).format(
option=option, answer=answer, id=quiz_id, sender_name=sender_name
)
return start_new_question, response
handler_class = TriviaQuizHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/trivia_quiz/trivia_quiz.py | trivia_quiz.py |
import logging
import random
from typing import Dict, Optional
import requests
from zulip_bots.lib import BotHandler
XKCD_TEMPLATE_URL = "https://xkcd.com/%s/info.0.json"
LATEST_XKCD_URL = "https://xkcd.com/info.0.json"
class XkcdHandler:
"""
This plugin provides several commands that can be used for fetch a comic
strip from https://xkcd.com. The bot looks for messages starting with
"@mention-bot" and responds with a message with the comic based on provided
commands.
"""
META = {
"name": "XKCD",
"description": "Fetches comic strips from https://xkcd.com.",
}
def usage(self) -> str:
return """
This plugin allows users to fetch a comic strip provided by
https://xkcd.com. Users should preface the command with "@mention-bot".
There are several commands to use this bot:
- @mention-bot help -> To show all commands the bot supports.
- @mention-bot latest -> To fetch the latest comic strip from xkcd.
- @mention-bot random -> To fetch a random comic strip from xkcd.
- @mention-bot <comic_id> -> To fetch a comic strip based on
`<comic_id>`, e.g `@mention-bot 1234`.
"""
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
quoted_name = bot_handler.identity().mention
xkcd_bot_response = get_xkcd_bot_response(message, quoted_name)
bot_handler.send_reply(message, xkcd_bot_response)
class XkcdBotCommand:
LATEST = 0
RANDOM = 1
COMIC_ID = 2
class XkcdNotFoundError(Exception):
pass
class XkcdServerError(Exception):
pass
def get_xkcd_bot_response(message: Dict[str, str], quoted_name: str) -> str:
original_content = message["content"].strip()
command = original_content.strip()
commands_help = (
"%s"
"\n* `{0} help` to show this help message."
"\n* `{0} latest` to fetch the latest comic strip from xkcd."
"\n* `{0} random` to fetch a random comic strip from xkcd."
"\n* `{0} <comic id>` to fetch a comic strip based on `<comic id>` "
"e.g `{0} 1234`.".format(quoted_name)
)
try:
if command == "help":
return commands_help % ("xkcd bot supports these commands:",)
elif command == "latest":
fetched = fetch_xkcd_query(XkcdBotCommand.LATEST)
elif command == "random":
fetched = fetch_xkcd_query(XkcdBotCommand.RANDOM)
elif command.isdigit():
fetched = fetch_xkcd_query(XkcdBotCommand.COMIC_ID, command)
else:
return commands_help % (f"xkcd bot only supports these commands, not `{command}`:",)
except (requests.exceptions.ConnectionError, XkcdServerError):
logging.exception("Connection error occurred when trying to connect to xkcd server")
return "Sorry, I cannot process your request right now, please try again later!"
except XkcdNotFoundError:
logging.exception(f"XKCD server responded 404 when trying to fetch comic with id {command}")
return f"Sorry, there is likely no xkcd comic strip with id: #{command}"
else:
return "#{}: **{}**\n[{}]({})".format(
fetched["num"],
fetched["title"],
fetched["alt"],
fetched["img"],
)
def fetch_xkcd_query(mode: int, comic_id: Optional[str] = None) -> Dict[str, str]:
try:
if mode == XkcdBotCommand.LATEST: # Fetch the latest comic strip.
url = LATEST_XKCD_URL
elif mode == XkcdBotCommand.RANDOM: # Fetch a random comic strip.
latest = requests.get(LATEST_XKCD_URL)
if latest.status_code != 200:
raise XkcdServerError()
latest_id = latest.json()["num"]
random_id = random.randint(1, latest_id)
url = XKCD_TEMPLATE_URL % (str(random_id),)
elif mode == XkcdBotCommand.COMIC_ID: # Fetch specific comic strip by id number.
if comic_id is None:
raise Exception("Missing comic_id argument")
url = XKCD_TEMPLATE_URL % (comic_id,)
fetched = requests.get(url)
if fetched.status_code == 404:
raise XkcdNotFoundError()
elif fetched.status_code != 200:
raise XkcdServerError()
xkcd_json = fetched.json()
except requests.exceptions.ConnectionError:
logging.exception("Connection Error")
raise
return xkcd_json
handler_class = XkcdHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/xkcd/xkcd.py | xkcd.py |
from typing import Any, List
from zulip_bots.game_handler import GameAdapter, SamePlayerMove
from .libraries import database, game, game_data, mechanics
class Storage:
data = {}
def __init__(self, topic_name):
self.data[topic_name] = '["X", 0, 0, "NNNNNNNNNNNNNNNNNNNNNNNN", "", 0]'
def put(self, topic_name, value: str):
self.data[topic_name] = value
def get(self, topic_name):
return self.data[topic_name]
class MerelsModel:
def __init__(self, board: Any = None) -> None:
self.topic = "merels"
self.storage = Storage(self.topic)
self.current_board = mechanics.display_game(self.topic, self.storage)
self.token = ["O", "X"]
def determine_game_over(self, players: List[str]) -> str:
if self.contains_winning_move(self.current_board):
return "current turn"
return ""
def contains_winning_move(self, board: Any) -> bool:
merels = database.MerelsStorage(self.topic, self.storage)
data = game_data.GameData(merels.get_game_data(self.topic))
if data.get_phase() > 1:
if (mechanics.get_piece("X", data.grid()) <= 2) or (
mechanics.get_piece("O", data.grid()) <= 2
):
return True
return False
def make_move(self, move: str, player_number: int, computer_move: bool = False) -> Any:
if self.storage.get(self.topic) == '["X", 0, 0, "NNNNNNNNNNNNNNNNNNNNNNNN", "", 0]':
self.storage.put(
self.topic,
f'["{self.token[player_number]}", 0, 0, "NNNNNNNNNNNNNNNNNNNNNNNN", "", 0]',
)
self.current_board, same_player_move = game.beat(move, self.topic, self.storage)
if same_player_move != "":
raise SamePlayerMove(same_player_move)
return self.current_board
class MerelsMessageHandler:
tokens = [":o_button:", ":cross_mark_button:"]
def parse_board(self, board: Any) -> str:
return board
def get_player_color(self, turn: int) -> str:
return self.tokens[turn]
def alert_move_message(self, original_player: str, move_info: str) -> str:
return original_player + " :" + move_info
def game_start_message(self) -> str:
return game.getHelp()
class MerelsHandler(GameAdapter):
"""
You can play merels! Make sure your message starts with
"@mention-bot".
"""
META = {
"name": "merels",
"description": "Lets you play merels against any player.",
}
def usage(self) -> str:
return game.getInfo()
def __init__(self) -> None:
game_name = "Merels"
bot_name = "merels"
move_help_message = ""
move_regex = ".*"
model = MerelsModel
rules = game.getInfo()
gameMessageHandler = MerelsMessageHandler
super().__init__(
game_name,
bot_name,
move_help_message,
move_regex,
model,
gameMessageHandler,
rules,
max_players=2,
min_players=2,
supports_computer=False,
)
handler_class = MerelsHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/merels/merels.py | merels.py |
import re
from zulip_bots.game_handler import BadMoveException
from . import database, mechanics
COMMAND_PATTERN = re.compile("^(\\w*).*(\\d,\\d).*(\\d,\\d)|^(\\w+).*(\\d,\\d)")
def getInfo():
"""Gets the info on starting the game
:return: Info on how to start the game
"""
return "To start a game, mention me and add `create`. A game will start " "in that topic. "
def getHelp():
"""Gets the help message
:return: Help message
"""
return """Commands:
put (v,h): Put a man into the grid in phase 1
move (v,h) -> (v,h): Moves a man from one point to -> another point
take (v,h): Take an opponent's man from the grid in phase 2/3
v: vertical position of grid
h: horizontal position of grid"""
def unknown_command():
"""Returns an unknown command info
:return: A string containing info about available commands
"""
message = "Unknown command. Available commands: put (v,h), take (v,h), move (v,h) -> (v,h)"
raise BadMoveException(message)
def beat(message, topic_name, merels_storage):
"""This gets triggered every time a user send a message in any topic
:param message: User's message
:param topic_name: User's current topic
:param merels_storage: Merels' storage
:return: a tuple of response string and message, non-empty string
we want to keep the turn of the same played,
an empty string otherwise.
"""
database.MerelsStorage(topic_name, merels_storage)
match = COMMAND_PATTERN.match(message)
same_player_move = "" # message indicating move of the same player
if match is None:
return unknown_command()
if match.group(1) is not None and match.group(2) is not None and match.group(3) is not None:
responses = ""
command = match.group(1)
if command.lower() == "move":
p1 = [int(x) for x in match.group(2).split(",")]
p2 = [int(x) for x in match.group(3).split(",")]
if mechanics.get_take_status(topic_name, merels_storage) == 1:
raise BadMoveException("Take is required to proceed." " Please try again.\n")
responses += mechanics.move_man(topic_name, p1, p2, merels_storage) + "\n"
no_moves = after_event_checkup(responses, topic_name, merels_storage)
mechanics.update_hill_uid(topic_name, merels_storage)
responses += mechanics.display_game(topic_name, merels_storage) + "\n"
if no_moves != "":
same_player_move = no_moves
else:
return unknown_command()
if mechanics.get_take_status(topic_name, merels_storage) == 1:
same_player_move = "Take is required to proceed.\n"
return responses, same_player_move
elif match.group(4) is not None and match.group(5) is not None:
command = match.group(4)
p1 = [int(x) for x in match.group(5).split(",")]
# put 1,2
if command == "put":
responses = ""
if mechanics.get_take_status(topic_name, merels_storage) == 1:
raise BadMoveException("Take is required to proceed." " Please try again.\n")
responses += mechanics.put_man(topic_name, p1[0], p1[1], merels_storage) + "\n"
no_moves = after_event_checkup(responses, topic_name, merels_storage)
mechanics.update_hill_uid(topic_name, merels_storage)
responses += mechanics.display_game(topic_name, merels_storage) + "\n"
if no_moves != "":
same_player_move = no_moves
if mechanics.get_take_status(topic_name, merels_storage) == 1:
same_player_move = "Take is required to proceed.\n"
return responses, same_player_move
# take 5,3
elif command == "take":
responses = ""
if mechanics.get_take_status(topic_name, merels_storage) == 1:
responses += mechanics.take_man(topic_name, p1[0], p1[1], merels_storage) + "\n"
if "Failed" in responses:
raise BadMoveException(responses)
mechanics.update_toggle_take_mode(topic_name, merels_storage)
no_moves = after_event_checkup(responses, topic_name, merels_storage)
mechanics.update_hill_uid(topic_name, merels_storage)
responses += mechanics.display_game(topic_name, merels_storage) + "\n"
responses += check_win(topic_name, merels_storage)
if no_moves != "":
same_player_move = no_moves
return responses, same_player_move
else:
raise BadMoveException("Taking is not possible.")
else:
return unknown_command()
def check_take_mode(response, topic_name, merels_storage):
"""This checks whether the previous action can result in a take mode for
current player. This assumes that the previous action is successful and not
failed.
:param response: A response string
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: None
"""
if not ("Failed" in response):
if mechanics.can_take_mode(topic_name, merels_storage):
mechanics.update_toggle_take_mode(topic_name, merels_storage)
else:
mechanics.update_change_turn(topic_name, merels_storage)
def check_any_moves(topic_name, merels_storage):
"""Check whether the player can make any moves, if can't switch to another
player
:param topic_name: Topic name
:param merels_storage: MerelsDatabase object
:return: A response string
"""
if not mechanics.can_make_any_move(topic_name, merels_storage):
mechanics.update_change_turn(topic_name, merels_storage)
return "Cannot make any move on the grid. Switching to " "previous player.\n"
return ""
def after_event_checkup(response, topic_name, merels_storage):
"""After doing certain moves in the game, it will check for take mode
availability and check for any possible moves
:param response: Current response string. This is useful for checking
any failed previous commands
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: A response string
"""
check_take_mode(response, topic_name, merels_storage)
return check_any_moves(topic_name, merels_storage)
def check_win(topic_name, merels_storage):
"""Checks whether the current grid has a winner, if it does, finish the
game and remove it from the database
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return:
"""
merels = database.MerelsStorage(topic_name, merels_storage)
win = mechanics.who_won(topic_name, merels_storage)
if win != "None":
merels.remove_game(topic_name)
return f"{win} wins the game!"
return "" | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/merels/libraries/game.py | game.py |
from . import mechanics
from .interface import construct_grid
class GameData:
def __init__(self, game_data=("merels", "X", 0, 0, "NNNNNNNNNNNNNNNNNNNNNNNN", "", 0)):
self.topic_name = game_data[0]
self.turn = game_data[1]
self.x_taken = game_data[2]
self.o_taken = game_data[3]
self.board = game_data[4]
self.hill_uid = game_data[5]
self.take_mode = game_data[6]
def __len__(self):
return len(self.construct())
def construct(self):
"""Constructs a tuple based on existing records
:return: A tuple containing all the game records
"""
res = (
self.topic_name,
self.turn,
self.x_taken,
self.o_taken,
self.board,
self.hill_uid,
self.take_mode,
)
return res
def grid(self):
"""Returns the grid
:return: A 2-dimensional 7x7 list (the grid)
"""
return construct_grid(self.board)
def get_x_piece_possessed_not_on_grid(self):
"""Gets the amount of X pieces that the player X still have, but not
put yet on the grid
:return: Amount of pieces that X has, but not on grid
"""
return 9 - self.x_taken - mechanics.get_piece("X", self.grid())
def get_o_piece_possessed_not_on_grid(self):
"""Gets the amount of X pieces that the player O still have, but not
put yet on the grid
:return: Amount of pieces that O has, but not on grid
"""
return 9 - self.o_taken - mechanics.get_piece("O", self.grid())
def get_phase(self):
"""Gets the phase number for the current game
:return: A phase number (1, 2, or 3)
"""
return mechanics.get_phase_number(
self.grid(),
self.turn,
self.get_x_piece_possessed_not_on_grid(),
self.get_o_piece_possessed_not_on_grid(),
)
def switch_turn(self):
"""Switches turn between X and O
:return: None
"""
if self.turn == "X":
self.turn = "O"
else:
self.turn = "X"
def toggle_take_mode(self):
"""Toggles take mode
:return: None
"""
if self.take_mode == 0:
self.take_mode = 1
else:
self.take_mode = 0 | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/merels/libraries/game_data.py | game_data.py |
import json
class MerelsStorage:
def __init__(self, topic_name, storage):
"""Instantiate storage field.
The current database has this form:
TOPIC_NAME (UNIQUE)
+----> TURN
+----> X_TAKEN
+----> O_TAKEN
+----> BOARD
+----> HILL_UID
+----> TAKE_MODE
:param name: Name of the storage
"""
self.storage = storage
def update_game(self, topic_name, turn, x_taken, o_taken, board, hill_uid, take_mode):
"""Updates the current status of the game to the database.
:param topic_name: The name of the topic
:param turn: "X" or "O"
:param x_taken: How many X's are taken from the board during the
gameplay by O
:param o_taken: How many O's are taken from the board during the
gameplay by X
:param board: A compact representation of the grid
:param hill_uid: Unique hill id
:param take_mode: Whether the game is in take mode, which "turn" has
to take a piece
:return: None
"""
parameters = (turn, x_taken, o_taken, board, hill_uid, take_mode)
self.storage.put(topic_name, json.dumps(parameters))
def remove_game(self, topic_name):
"""Removes the game from the database by setting it to an empty
string. An empty string marks an empty match.
:param topic_name: The name of the topic
:return: None
"""
self.storage.put(topic_name, "")
def get_game_data(self, topic_name):
"""Gets the game data
:param topic_name: The name of the topic
:return: A tuple containing the data
"""
try:
select = json.loads(self.storage.get(topic_name))
except (json.decoder.JSONDecodeError, KeyError):
select = ""
if select == "":
return None
else:
res = (topic_name, select[0], select[1], select[2], select[3], select[4], select[5])
return res | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/merels/libraries/database.py | database.py |
from collections import Counter
from math import sqrt
from zulip_bots.game_handler import BadMoveException
from . import constants, database, game_data, interface
def is_in_grid(vertical_pos, horizontal_pos):
"""Checks whether the cell actually exists or not
:param vertical_pos: Vertical position of the man, in int
:param horizontal_pos: Horizontal position of the man, in int
:return:
True, if it exists (meaning: in the grid)
False, if it doesn't exist (meaning: out of grid)
"""
return [vertical_pos, horizontal_pos] in constants.ALLOWED_MOVES
def is_empty(vertical_pos, horizontal_pos, grid):
"""Checks whether the current cell is empty
:param vertical_pos: Vertical position of the man, in int
:param horizontal_pos: Horizontal position of the man, in int
:param grid: A 2-dimensional 7x7 list
:return:
True, if it is empty
False, if it is not empty
"""
return grid[vertical_pos][horizontal_pos] == " "
def is_jump(vpos_before, hpos_before, vpos_after, hpos_after):
"""Checks whether the move is considered jumping
:param vpos_before: Vertical cell location before jumping
:param hpos_before: Horizontal cell location before jumping
:param vpos_after: Vertical cell location after jumping
:param hpos_after: Horizontal cell location after jumping
:return:
True, if it is jumping
False, if it is not jumping
"""
distance = sqrt((vpos_after - vpos_before) ** 2 + (hpos_after - hpos_before) ** 2)
# If the man is in outer square, the distance must be 3 or 1
if [vpos_before, hpos_before] in constants.OUTER_SQUARE:
return not (distance == 3 or distance == 1)
# If the man is in middle square, the distance must be 2 or 1
if [vpos_before, hpos_before] in constants.MIDDLE_SQUARE:
return not (distance == 2 or distance == 1)
# If the man is in inner square, the distance must be only 1
if [vpos_before, hpos_before] in constants.INNER_SQUARE:
return not (distance == 1)
def get_hills_numbers(grid):
"""Checks for hills, if it exists, get its relative position based on
constants.py
:param grid: A 7x7 2 dimensional grid
:return: A string, containing the relative position of hills based on
constants.py
"""
relative_hills = ""
for k, hill in enumerate(constants.HILLS):
v1, h1 = hill[0][0], hill[0][1]
v2, h2 = hill[1][0], hill[1][1]
v3, h3 = hill[2][0], hill[2][1]
if all(x == "O" for x in (grid[v1][h1], grid[v2][h2], grid[v3][h3])) or all(
x == "X" for x in (grid[v1][h1], grid[v2][h2], grid[v3][h3])
):
relative_hills += str(k)
return relative_hills
def move_man_legal(v1, h1, v2, h2, grid):
"""Moves a man into a specified cell, assuming it is a legal move
:param v1: Vertical position of cell
:param h1: Horizontal position of cell
:param v2: Vertical position of cell
:param h2: Horizontal version of cell
:param grid: A 2-dimensional 7x7 list
:return: None, since grid is mutable
"""
grid[v2][h2] = grid[v1][h1]
grid[v1][h1] = " "
def put_man_legal(turn, v, h, grid):
"""Puts a man into specified cell, assuming it is a legal move
:param turn: "X" or "O"
:param v: Vertical position of cell
:param h: Horizontal position of cell
:param grid: A 2-dimensional 7x7 grid
:return: None, since grid is mutable
"""
grid[v][h] = turn
def take_man_legal(v, h, grid):
"""Takes an opponent's man from a specified cell.
:param v: Vertical position of the cell
:param h: Horizontal position of the cell
:param grid: A 2-dimensional 7x7 list
:return: None, since grid is mutable
"""
grid[v][h] = " "
def is_legal_move(v1, h1, v2, h2, turn, phase, grid):
"""Determines whether the current move is legal or not
:param v1: Vertical position of man
:param h1: Horizontal position of man
:param v2: Vertical position of man
:param h2: Horizontal position of man
:param turn: "X" or "O"
:param phase: Current phase of the game
:param grid: A 2-dimensional 7x7 list
:return: True if it is legal, False it is not legal
"""
if phase == 1:
return False # Place all the pieces first before moving one
if phase == 3 and get_piece(turn, grid) == 3:
return is_in_grid(v2, h2) and is_empty(v2, h2, grid) and is_own_piece(v1, h1, turn, grid)
return (
is_in_grid(v2, h2)
and is_empty(v2, h2, grid)
and (not is_jump(v1, h1, v2, h2))
and is_own_piece(v1, h1, turn, grid)
)
def is_own_piece(v, h, turn, grid):
"""Check if the player is using the correct piece
:param v: Vertical position of man
:param h: Horizontal position of man
:param turn: "X" or "O"
:param grid: A 2-dimensional 7x7 list
:return: True, if the player is using their own piece, False if otherwise.
"""
return grid[v][h] == turn
def is_legal_put(v, h, grid, phase_number):
"""Determines whether putting the man in specified cell location is legal
or not
:param v: Vertical position of man
:param h: Horizontal position of man
:param grid: A 2-dimensional 7x7 list
:param phase_number: 1, 2, or 3
:return: True if it is legal, False if it is not legal
"""
return is_in_grid(v, h) and is_empty(v, h, grid) and phase_number == 1
def is_legal_take(v, h, turn, grid, take_mode):
"""Determines whether taking a man in that cell is legal or not
:param v: Vertical position of man
:param h: Horizontal position of man
:param turn: "X" or "O"
:param grid: A 2-dimensional 7x7 list
:param take_mode: 1 or 0
:return: True if it is legal, False if it is not legal
"""
return (
is_in_grid(v, h)
and not is_empty(v, h, grid)
and not is_own_piece(v, h, turn, grid)
and take_mode == 1
)
def get_piece(turn, grid):
"""Counts the current piece on the grid
:param turn: "X" or "O"
:param grid: A 2-dimensional 7x7 list
:return: Number of pieces of "turn" on the grid
"""
grid_combined = []
for row in grid:
grid_combined += row
counter = Counter(tuple(grid_combined))
return counter[turn]
def who_won(topic_name, merels_storage):
"""Who won the game? If there was any at that moment
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: "None", if there is no one, "X" if X is winning, "O" if O
is winning
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
if data.get_phase() > 1:
if get_piece("X", data.grid()) <= 2:
return "O"
if get_piece("O", data.grid()) <= 2:
return "X"
return "None"
def get_phase_number(grid, turn, x_pieces_possessed_not_on_grid, o_pieces_possessed_not_on_grid):
"""Updates current game phase
:param grid: A 2-dimensional 7x7 list
:param turn: "X" or "O"
:param x_pieces_possessed_not_on_grid: Amount of man that X currently have,
but not placed yet
:param o_pieces_possessed_not_on_grid: Amount of man that O currently have,
but not placed yet
:return: Phase number. 1 is "placing pieces", 2 is "moving pieces", and 3
is "flying"
"""
if x_pieces_possessed_not_on_grid != 0 or o_pieces_possessed_not_on_grid != 0:
# Placing pieces
return 1
else:
if get_piece("X", grid) <= 3 or get_piece("O", grid) <= 3:
# Flying
return 3
else:
# Moving pieces
return 2
def create_room(topic_name, merels_storage):
"""Creates a game in current topic
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: A response string
"""
merels = database.MerelsStorage(topic_name, merels_storage)
if merels.create_new_game(topic_name):
response = ""
response += f"A room has been created in {topic_name}. Starting game now.\n"
response += display_game(topic_name, merels_storage)
return response
else:
return (
"Failed: Cannot create an already existing game in {}. "
"Please finish the game first.".format(topic_name)
)
def display_game(topic_name, merels_storage):
"""Displays the current layout of the game, with additional info such as
phase number and turn.
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: A response string
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
response = ""
if data.take_mode == 1:
take = "Yes"
else:
take = "No"
response += interface.graph_grid(data.grid()) + "\n"
response += """Phase {}. Take mode: {}.
X taken: {}, O taken: {}.
""".format(
data.get_phase(), take, data.x_taken, data.o_taken
)
return response
def reset_game(topic_name, merels_storage):
"""Resets the game in current topic
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: A response string
"""
merels = database.MerelsStorage(topic_name, merels_storage)
merels.remove_game(topic_name)
return "Game removed.\n" + create_room(topic_name, merels_storage) + "Game reset.\n"
def move_man(topic_name, p1, p2, merels_storage):
"""Moves the current man in topic_name from p1 to p2
:param topic_name: Topic name
:param p1: First cell location
:param p2: Second cell location
:param merels_storage: Merels' storage
:return: A response string
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
# Get the grid
grid = data.grid()
# Check legal move
if is_legal_move(p1[0], p1[1], p2[0], p2[1], data.turn, data.get_phase(), data.grid()):
# Move the man
move_man_legal(p1[0], p1[1], p2[0], p2[1], grid)
# Construct the board back from updated grid
board = interface.construct_board(grid)
# Insert/update the current board
data.board = board
# Update the game data
merels.update_game(
data.topic_name,
data.turn,
data.x_taken,
data.o_taken,
data.board,
data.hill_uid,
data.take_mode,
)
return "Moved a man from ({}, {}) -> ({}, {}) for {}.".format(
p1[0], p1[1], p2[0], p2[1], data.turn
)
else:
raise BadMoveException("Failed: That's not a legal move. Please try again.")
def put_man(topic_name, v, h, merels_storage):
"""Puts a man into the specified cell in topic_name
:param topic_name: Topic name
:param v: Vertical position of cell
:param h: Horizontal position of cell
:param merels_storage: MerelsDatabase object
:return: A response string
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
# Get the grid
grid = data.grid()
# Check legal put
if is_legal_put(v, h, grid, data.get_phase()):
# Put the man
put_man_legal(data.turn, v, h, grid)
# Construct the board back from updated grid
board = interface.construct_board(grid)
# Insert/update form current board
data.board = board
# Update the game data
merels.update_game(
data.topic_name,
data.turn,
data.x_taken,
data.o_taken,
data.board,
data.hill_uid,
data.take_mode,
)
return f"Put a man to ({v}, {h}) for {data.turn}."
else:
raise BadMoveException("Failed: That's not a legal put. Please try again.")
def take_man(topic_name, v, h, merels_storage):
"""Takes a man from the grid
:param topic_name: Topic name
:param v: Vertical position of cell
:param h: Horizontal position of cell
:param merels_storage: Merels' storage
:return: A response string
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
# Get the grid
grid = data.grid()
# Check legal put
if is_legal_take(v, h, data.turn, grid, data.take_mode):
# Take the man
take_man_legal(v, h, grid)
if data.turn == "X":
data.o_taken += 1
else:
data.x_taken += 1
# Construct the board back from updated grid
board = interface.construct_board(grid)
# Insert/update form current board
data.board = board
# Update the game data
merels.update_game(
data.topic_name,
data.turn,
data.x_taken,
data.o_taken,
data.board,
data.hill_uid,
data.take_mode,
)
return f"Taken a man from ({v}, {h}) for {data.turn}."
else:
raise BadMoveException("Failed: That's not a legal take. Please try again.")
def update_hill_uid(topic_name, merels_storage):
"""Updates the hill_uid then store it to the database
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: None
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
data.hill_uid = get_hills_numbers(data.grid())
merels.update_game(
data.topic_name,
data.turn,
data.x_taken,
data.o_taken,
data.board,
data.hill_uid,
data.take_mode,
)
def update_change_turn(topic_name, merels_storage):
"""Changes the turn of player, from X to O and from O to X
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: None
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
data.switch_turn()
merels.update_game(
data.topic_name,
data.turn,
data.x_taken,
data.o_taken,
data.board,
data.hill_uid,
data.take_mode,
)
def update_toggle_take_mode(topic_name, merels_storage):
"""Toggle take_mode from 0 to 1 and from 1 to 0
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: None
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
data.toggle_take_mode()
merels.update_game(
data.topic_name,
data.turn,
data.x_taken,
data.o_taken,
data.board,
data.hill_uid,
data.take_mode,
)
def get_take_status(topic_name, merels_storage):
"""Gets the take status
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: 1 or 0
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
return data.take_mode
def can_take_mode(topic_name, merels_storage):
"""Check if current turn can trigger take mode.
This process can be thought of as seeing the differences between previous
hill_uid and current hill_uid.
Previous hill_uid can be obtained before updating the hill_uid, and current
hill_uid can be obtained after updating the grid.
If the differences and length decreases after, then it is not possible that
he player forms a new hill.
If the differences or length increases, it is possible that the player that
makes the move forms a new hill. This
essentially triggers the take mode, as the player must take one opponent's
piece from the grid.
Essentially, how this works is by checking an updated, but not fully
finished complete database. So the differences between hill_uid can be
seen.
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: True if this turn can trigger take mode, False if otherwise
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
current_hill_uid = data.hill_uid
updated_grid = data.grid()
updated_hill_uid = get_hills_numbers(updated_grid)
if current_hill_uid != updated_hill_uid and len(updated_hill_uid) >= len(current_hill_uid):
return True
else:
return False
def check_moves(turn, grid):
"""Checks whether the player can make any moves from specified grid and turn
:param turn: "X" or "O"
:param grid: A 2-dimensional 7x7 list
:return: True, if there is any, False if otherwise
"""
for hill in constants.HILLS:
for k in range(0, 2):
g1 = grid[hill[k][0]][hill[k][1]]
g2 = grid[hill[k + 1][0]][hill[k + 1][1]]
if (g1 == " " and g2 == turn) or (g2 == " " and g1 == turn):
return True
return False
def can_make_any_move(topic_name, merels_storage):
"""Checks whether the player can actually make a move. If it is phase 1,
don't check it and return True instead
:param topic_name: Topic name
:param merels_storage: Merels' storage
:return: True if the player has a way, False if there isn't
"""
merels = database.MerelsStorage(topic_name, merels_storage)
data = game_data.GameData(merels.get_game_data(topic_name))
if data.get_phase() != 1:
return check_moves(data.turn, data.grid())
return True | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/merels/libraries/mechanics.py | mechanics.py |
from . import constants
def draw_grid(grid):
"""Draws a board from a grid
:param grid: a 2-dimensional 7x7 list
:return: None
"""
print(graph_grid(grid))
def graph_grid(grid):
"""Creates a nice grid display, something like this:
0 1 2 3 4 5 6
0 [ ]---------------[ ]---------------[ ]
| | |
1 | [ ]---------[ ]---------[ ] |
| | | | |
2 | | [ ]---[ ]---[ ] | |
| | | | | |
3 [ ]---[ ]---[ ] [ ]---[ ]---[ ]
| | | | | |
4 | | [ ]---[ ]---[ ] | |
| | | | |
5 | [ ]---------[ ]---------[ ] |
| | |
6 [ ]---------------[ ]---------------[ ]
:param grid: a 2-dimensional 7x7 list.
:return: A nicer display of the grid
"""
return """` 0 1 2 3 4 5 6
0 [{}]---------------[{}]---------------[{}]
| | |
1 | [{}]---------[{}]---------[{}] |
| | | | |
2 | | [{}]---[{}]---[{}] | |
| | | | | |
3 [{}]---[{}]---[{}] [{}]---[{}]---[{}]
| | | | | |
4 | | [{}]---[{}]---[{}] | |
| | | | |
5 | [{}]---------[{}]---------[{}] |
| | |
6 [{}]---------------[{}]---------------[{}]`""".format(
grid[0][0],
grid[0][3],
grid[0][6],
grid[1][1],
grid[1][3],
grid[1][5],
grid[2][2],
grid[2][3],
grid[2][4],
grid[3][0],
grid[3][1],
grid[3][2],
grid[3][4],
grid[3][5],
grid[3][6],
grid[4][2],
grid[4][3],
grid[4][4],
grid[5][1],
grid[5][3],
grid[5][5],
grid[6][0],
grid[6][3],
grid[6][6],
)
def construct_grid(board):
"""Constructs the original grid from the database
:param board: A compact representation of the grid (example:
"NONXONXONXONXONNOXNXNNOX")
:return: A grid
"""
grid = [[" " for _ in range(7)] for _ in range(7)]
for k, cell in enumerate(board):
if cell == "O" or cell == "X":
grid[constants.ALLOWED_MOVES[k][0]][constants.ALLOWED_MOVES[k][1]] = cell
return grid
def construct_board(grid):
"""Constructs a board from a grid
:param grid: A 2-dimensional 7x7 list
:return: A board. Board is a compact representation of the grid
"""
board = ""
for cell_location in constants.ALLOWED_MOVES:
cell_content = grid[cell_location[0]][cell_location[1]]
if cell_content == "X" or cell_content == "O":
board += cell_content
else:
board += "N"
return board | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/merels/libraries/interface.py | interface.py |
import base64
import re
from typing import Any, Dict, Optional
import requests
from zulip_bots.lib import BotHandler
GET_REGEX = re.compile('get "(?P<issue_key>.+)"$')
CREATE_REGEX = re.compile(
'create issue "(?P<summary>.+?)"'
' in project "(?P<project_key>.+?)"'
' with type "(?P<type_name>.+?)"'
'( with description "(?P<description>.+?)")?'
'( assigned to "(?P<assignee>.+?)")?'
'( with priority "(?P<priority_name>.+?)")?'
'( labeled "(?P<labels>.+?)")?'
'( due "(?P<due_date>.+?)")?'
"$"
)
EDIT_REGEX = re.compile(
'edit issue "(?P<issue_key>.+?)"'
'( to use summary "(?P<summary>.+?)")?'
'( to use project "(?P<project_key>.+?)")?'
'( to use type "(?P<type_name>.+?)")?'
'( to use description "(?P<description>.+?)")?'
'( by assigning to "(?P<assignee>.+?)")?'
'( to use priority "(?P<priority_name>.+?)")?'
'( by labeling "(?P<labels>.+?)")?'
'( by making due "(?P<due_date>.+?)")?'
"$"
)
SEARCH_REGEX = re.compile('search "(?P<search_term>.+)"$')
JQL_REGEX = re.compile('jql "(?P<jql_query>.+)"$')
HELP_REGEX = re.compile("help$")
HELP_RESPONSE = """
**get**
`get` takes in an issue key and sends back information about that issue. For example,
you:
> @**Jira Bot** get "BOTS-13"
Jira Bot:
> **Issue *BOTS-13*: Create Jira Bot**
>
> - Type: *Task*
> - Description:
> > Jira Bot would connect to Jira.
> - Creator: *admin*
> - Project: *Bots*
> - Priority: *Medium*
> - Status: *To Do*
---
**search**
`search` takes in a search term and returns issues with matching summaries. For example,
you:
> @**Jira Bot** search "XSS"
Jira Bot:
> **Search results for *"XSS"*:**
>
> - ***BOTS-5:*** Stored XSS **[Published]**
> - ***BOTS-6:*** Reflected XSS **[Draft]**
---
**jql**
`jql` takes in a jql search string and returns matching issues. For example,
you:
> @**Jira Bot** jql "issuetype = Engagement ORDER BY created DESC"
Jira Bot:
> **Search results for *"issuetype = Engagement ORDER BY created DESC"*:**
>
> - ***BOTS-1:*** External Website Test **[In Progress]**
> - ***BOTS-3:*** Network Vulnerability Scan **[Draft]**
---
**create**
`create` creates an issue using its
- summary,
- project,
- type,
- description *(optional)*,
- assignee *(optional)*,
- priority *(optional)*,
- labels *(optional)*, and
- due date *(optional)*
For example, to create an issue with every option,
you:
> @**Jira Bot** create issue "Make an issue" in project "BOTS"' with type \
"Task" with description "This is a description" assigned to "skunkmb" with \
priority "Medium" labeled "issues, testing" due "2017-01-23"
Jira Bot:
> Issue *BOTS-16* is up! https://example.atlassian.net/browse/BOTS-16
---
**edit**
`edit` is like create, but changes an existing issue using its
- summary,
- project *(optional)*,
- type *(optional)*,
- description *(optional)*,
- assignee *(optional)*,
- priority *(optional)*,
- labels *(optional)*, and
- due date *(optional)*.
For example, to change every part of an issue,
you:
> @**Jira Bot** edit issue "BOTS-16" to use summary "Change the summary" \
to use project "NEWBOTS" to use type "Bug" to use description "This is \
a new description" by assigning to "admin" to use priority "Low" by \
labeling "new, labels" by making due "2018-12-5"
Jira Bot:
> Issue *BOTS-16* was edited! https://example.atlassian.net/browse/BOTS-16
"""
class JiraHandler:
def usage(self) -> str:
return """
Jira Bot uses the Jira REST API to interact with Jira. In order to use
Jira Bot, `jira.conf` must be set up. See `doc.md` for more details.
"""
def initialize(self, bot_handler: BotHandler) -> None:
config = bot_handler.get_config_info("jira")
username = config.get("username")
password = config.get("password")
domain = config.get("domain")
if not username:
raise KeyError("No `username` was specified")
if not password:
raise KeyError("No `password` was specified")
if not domain:
raise KeyError("No `domain` was specified")
self.auth = make_jira_auth(username, password)
# Allow users to override the HTTP scheme
if re.match(r"^https?://", domain, re.IGNORECASE):
self.domain_with_protocol = domain
else:
self.domain_with_protocol = "https://" + domain
# Use the front facing URL in output
self.display_url = config.get("display_url")
if not self.display_url:
self.display_url = self.domain_with_protocol
def jql_search(self, jql_query: str) -> str:
UNKNOWN_VAL = "*unknown*"
jira_response = requests.get(
self.domain_with_protocol
+ f"/rest/api/2/search?jql={jql_query}&fields=key,summary,status",
headers={"Authorization": self.auth},
).json()
url = self.display_url + "/browse/"
errors = jira_response.get("errorMessages", [])
results = jira_response.get("total", 0)
if errors:
response = "Oh no! Jira raised an error:\n > " + ", ".join(errors)
else:
response = f"*Found {results} results*\n\n"
for issue in jira_response.get("issues", []):
fields = issue.get("fields", {})
summary = fields.get("summary", UNKNOWN_VAL)
status_name = fields.get("status", {}).get("name", UNKNOWN_VAL)
response += "\n - {}: [{}]({}) **[{}]**".format(
issue["key"], summary, url + issue["key"], status_name
)
return response
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
content = message.get("content")
response = ""
get_match = GET_REGEX.match(content)
create_match = CREATE_REGEX.match(content)
edit_match = EDIT_REGEX.match(content)
search_match = SEARCH_REGEX.match(content)
jql_match = JQL_REGEX.match(content)
help_match = HELP_REGEX.match(content)
if get_match:
UNKNOWN_VAL = "*unknown*"
key = get_match.group("issue_key")
jira_response = requests.get(
self.domain_with_protocol + "/rest/api/2/issue/" + key,
headers={"Authorization": self.auth},
).json()
url = self.display_url + "/browse/" + key
errors = jira_response.get("errorMessages", [])
fields = jira_response.get("fields", {})
creator_name = fields.get("creator", {}).get("name", UNKNOWN_VAL)
description = fields.get("description", UNKNOWN_VAL)
priority_name = fields.get("priority", {}).get("name", UNKNOWN_VAL)
project_name = fields.get("project", {}).get("name", UNKNOWN_VAL)
type_name = fields.get("issuetype", {}).get("name", UNKNOWN_VAL)
status_name = fields.get("status", {}).get("name", UNKNOWN_VAL)
summary = fields.get("summary", UNKNOWN_VAL)
if errors:
response = "Oh no! Jira raised an error:\n > " + ", ".join(errors)
else:
response = (
"**Issue *[{}]({})*: {}**\n\n"
" - Type: *{}*\n"
" - Description:\n"
" > {}\n"
" - Creator: *{}*\n"
" - Project: *{}*\n"
" - Priority: *{}*\n"
" - Status: *{}*\n"
).format(
key,
url,
summary,
type_name,
description,
creator_name,
project_name,
priority_name,
status_name,
)
elif create_match:
jira_response = requests.post(
self.domain_with_protocol + "/rest/api/2/issue",
headers={"Authorization": self.auth},
json=make_create_json(
create_match.group("summary"),
create_match.group("project_key"),
create_match.group("type_name"),
create_match.group("description"),
create_match.group("assignee"),
create_match.group("priority_name"),
create_match.group("labels"),
create_match.group("due_date"),
),
)
jira_response_json = jira_response.json() if jira_response.text else {}
key = jira_response_json.get("key", "")
url = self.display_url + "/browse/" + key
errors = list(jira_response_json.get("errors", {}).values())
if errors:
response = "Oh no! Jira raised an error:\n > " + ", ".join(errors)
else:
response = "Issue *" + key + "* is up! " + url
elif edit_match and check_is_editing_something(edit_match):
key = edit_match.group("issue_key")
jira_response = requests.put(
self.domain_with_protocol + "/rest/api/2/issue/" + key,
headers={"Authorization": self.auth},
json=make_edit_json(
edit_match.group("summary"),
edit_match.group("project_key"),
edit_match.group("type_name"),
edit_match.group("description"),
edit_match.group("assignee"),
edit_match.group("priority_name"),
edit_match.group("labels"),
edit_match.group("due_date"),
),
)
jira_response_json = jira_response.json() if jira_response.text else {}
url = self.display_url + "/browse/" + key
errors = list(jira_response_json.get("errors", {}).values())
if errors:
response = "Oh no! Jira raised an error:\n > " + ", ".join(errors)
else:
response = "Issue *" + key + "* was edited! " + url
elif search_match:
search_term = search_match.group("search_term")
search_results = self.jql_search(f"summary ~ {search_term}")
response = f'**Search results for "{search_term}"**\n\n{search_results}'
elif jql_match:
jql_query = jql_match.group("jql_query")
search_results = self.jql_search(jql_query)
response = f'**Search results for "{jql_query}"**\n\n{search_results}'
elif help_match:
response = HELP_RESPONSE
else:
response = "Sorry, I don't understand that! Send me `help` for instructions."
bot_handler.send_reply(message, response)
def make_jira_auth(username: str, password: str) -> str:
"""Makes an auth header for Jira in the form 'Basic: <encoded credentials>'.
Parameters:
- username: The Jira email address.
- password: The Jira password.
"""
combo = username + ":" + password
encoded = base64.b64encode(combo.encode("utf-8")).decode("utf-8")
return "Basic " + encoded
def make_create_json(
summary: str,
project_key: str,
type_name: str,
description: Optional[str],
assignee: Optional[str],
priority_name: Optional[str],
labels: Optional[str],
due_date: Optional[str],
) -> Any:
"""Makes a JSON string for the Jira REST API editing endpoint based on
fields that could be edited.
Parameters:
- summary: The Jira summary property.
- project_key: The Jira project key property.
- type_name (optional): The Jira type name property.
- description (optional): The Jira description property.
- assignee (optional): The Jira assignee property.
- priority_name (optional): The Jira priority name property.
- labels (optional): The Jira labels property, as a string of labels separated by
comma-spaces.
- due_date (optional): The Jira due date property.
"""
json_fields = {
"summary": summary,
"project": {"key": project_key},
"issuetype": {"name": type_name},
}
if description:
json_fields["description"] = description
if assignee:
json_fields["assignee"] = {"name": assignee}
if priority_name:
json_fields["priority"] = {"name": priority_name}
if labels:
json_fields["labels"] = labels.split(", ")
if due_date:
json_fields["duedate"] = due_date
json = {"fields": json_fields}
return json
def make_edit_json(
summary: Optional[str],
project_key: Optional[str],
type_name: Optional[str],
description: Optional[str],
assignee: Optional[str],
priority_name: Optional[str],
labels: Optional[str],
due_date: Optional[str],
) -> Any:
"""Makes a JSON string for the Jira REST API editing endpoint based on
fields that could be edited.
Parameters:
- summary (optional): The Jira summary property.
- project_key (optional): The Jira project key property.
- type_name (optional): The Jira type name property.
- description (optional): The Jira description property.
- assignee (optional): The Jira assignee property.
- priority_name (optional): The Jira priority name property.
- labels (optional): The Jira labels property, as a string of labels separated by
comma-spaces.
- due_date (optional): The Jira due date property.
"""
json_fields = {}
if summary:
json_fields["summary"] = summary
if project_key:
json_fields["project"] = {"key": project_key}
if type_name:
json_fields["issuetype"] = {"name": type_name}
if description:
json_fields["description"] = description
if assignee:
json_fields["assignee"] = {"name": assignee}
if priority_name:
json_fields["priority"] = {"name": priority_name}
if labels:
json_fields["labels"] = labels.split(", ")
if due_date:
json_fields["duedate"] = due_date
json = {"fields": json_fields}
return json
def check_is_editing_something(match: Any) -> bool:
"""Checks if an editing match is actually going to do editing. It is
possible for an edit regex to match without doing any editing because each
editing field is optional. For example, 'edit issue "BOTS-13"' would pass
but wouldn't preform any actions.
Parameters:
- match: The regex match object.
"""
return bool(
match.group("summary")
or match.group("project_key")
or match.group("type_name")
or match.group("description")
or match.group("assignee")
or match.group("priority_name")
or match.group("labels")
or match.group("due_date")
)
handler_class = JiraHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/jira/jira.py | jira.py |
# Jira Bot
## Setup
To use Jira Bot, first set up `jira.conf`. `jira.conf` requires 3 options:
- username (an email or username that can access your Jira),
- password (the password for that username), and
- domain (a domain like `example.atlassian.net`)
- display_url ([optional] your front facing jira URL if different from domain.
E.g. `https://example-lb.atlassian.net`)
## Usage
### get
`get` takes in an issue key and sends back information about that issue. For example,
you:
> @**Jira Bot** get "BOTS-13"
Jira Bot:
> **Issue *BOTS-13*: Create Jira Bot**
>
> - Type: *Task*
> - Description:
> > Jira Bot would connect to Jira.
> - Creator: *admin*
> - Project: *Bots*
> - Priority: *Medium*
> - Status: *To Do*
### search
`search` takes in a search term and returns issues with matching summaries. For example,
you:
> @**Jira Bot** search "XSS"
Jira Bot:
> **Search results for *"XSS"*:**
>
> - ***BOTS-5:*** Stored XSS **[Published]**
> - ***BOTS-6:*** Reflected XSS **[Draft]**
---
### jql
`jql` takes in a jql search string and returns matching issues. For example,
you:
> @**Jira Bot** jql "issuetype = Engagement ORDER BY created DESC"
Jira Bot:
> **Search results for "issuetype = vulnerability ORDER BY created DESC"**
>
> *Found 53 results*
>
> - ***BOTS-1:*** External Website Test **[In Progress]**
> - ***BOTS-3:*** Network Vulnerability Scan **[Draft]**
---
### create
`create` creates an issue using its
- summary,
- project,
- type,
- description *(optional)*,
- assignee *(optional)*,
- priority *(optional)*,
- labels *(optional)*, and
- due date *(optional)*
For example, to create an issue with every option,
you:
> @**Jira Bot** create issue "Make an issue" in project "BOTS"' with type "Task" with description
> "This is a description" assigned to "skunkmb" with priority "Medium" labeled "issues, testing"
> due "2017-01-23"
Jira Bot:
> Issue *BOTS-16* is up! https://example.atlassian.net/browse/BOTS-16
### edit
`edit` is like create, but changes an existing issue using its
- summary,
- project *(optional)*,
- type *(optional)*,
- description *(optional)*,
- assignee *(optional)*,
- priority *(optional)*,
- labels *(optional)*, and
- due date *(optional)*.
For example, to change every part of an issue,
you:
> @**Jira Bot** edit issue "BOTS-16" to use summary "Change the summary" to use project
> "NEWBOTS" to use type "Bug" to use description "This is a new description" by assigning
> to "admin" to use priority "Low" by labeling "new, labels" by making due "2018-12-5"
Jira Bot:
> Issue *BOTS-16* was edited! https://example.atlassian.net/browse/BOTS-16
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/jira/doc.md | doc.md |
from copy import deepcopy
from functools import reduce
from zulip_bots.game_handler import BadMoveException
class ConnectFourModel:
"""
Object that manages running the Connect
Four logic for the Connect Four Bot
"""
def __init__(self):
self.blank_board = [
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0],
]
self.current_board = self.blank_board
def update_board(self, board):
self.current_board = deepcopy(board)
def get_column(self, col):
# We use this in tests.
return [self.current_board[i][col] for i in range(6)]
def validate_move(self, column_number):
if column_number < 0 or column_number > 6:
return False
row = 0
column = column_number
return self.current_board[row][column] == 0
def available_moves(self):
available_moves = []
row = 0
for column in range(0, 7):
if self.current_board[row][column] == 0:
available_moves.append(column)
return available_moves
def make_move(self, move, player_number, is_computer=False):
if player_number == 1:
token_number = -1
if player_number == 0:
token_number = 1
finding_move = True
row = 5
column = int(move.replace("move ", "")) - 1
while finding_move:
if row < 0:
raise BadMoveException("Make sure your move is in a column with free space.")
if self.current_board[row][column] == 0:
self.current_board[row][column] = token_number
finding_move = False
row -= 1
return deepcopy(self.current_board)
def determine_game_over(self, players):
def get_horizontal_wins(board):
horizontal_sum = 0
for row in range(0, 6):
for column in range(0, 4):
horizontal_sum = (
board[row][column]
+ board[row][column + 1]
+ board[row][column + 2]
+ board[row][column + 3]
)
if horizontal_sum == -4:
return -1
elif horizontal_sum == 4:
return 1
return 0
def get_vertical_wins(board):
vertical_sum = 0
for row in range(0, 3):
for column in range(0, 7):
vertical_sum = (
board[row][column]
+ board[row + 1][column]
+ board[row + 2][column]
+ board[row + 3][column]
)
if vertical_sum == -4:
return -1
elif vertical_sum == 4:
return 1
return 0
def get_diagonal_wins(board):
major_diagonal_sum = 0
minor_diagonal_sum = 0
# Major Diagonl Sum
for row in range(0, 3):
for column in range(0, 4):
major_diagonal_sum = (
board[row][column]
+ board[row + 1][column + 1]
+ board[row + 2][column + 2]
+ board[row + 3][column + 3]
)
if major_diagonal_sum == -4:
return -1
elif major_diagonal_sum == 4:
return 1
# Minor Diagonal Sum
for row in range(3, 6):
for column in range(0, 4):
minor_diagonal_sum = (
board[row][column]
+ board[row - 1][column + 1]
+ board[row - 2][column + 2]
+ board[row - 3][column + 3]
)
if minor_diagonal_sum == -4:
return -1
elif minor_diagonal_sum == 4:
return 1
return 0
first_player, second_player = players[0], players[1]
# If all tokens in top row are filled (its a draw), product != 0
top_row_multiple = reduce(lambda x, y: x * y, self.current_board[0])
if top_row_multiple != 0:
return "draw"
winner = (
get_horizontal_wins(self.current_board)
+ get_vertical_wins(self.current_board)
+ get_diagonal_wins(self.current_board)
)
if winner == 1:
return first_player
elif winner == -1:
return second_player
return "" | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/connect_four/controller.py | controller.py |
from typing import Any
from zulip_bots.bots.connect_four.controller import ConnectFourModel
from zulip_bots.game_handler import GameAdapter
class ConnectFourMessageHandler:
tokens = [":blue_circle:", ":red_circle:"]
def parse_board(self, board: Any) -> str:
# Header for the top of the board
board_str = ":one: :two: :three: :four: :five: :six: :seven:"
for row in range(0, 6):
board_str += "\n\n"
for column in range(0, 7):
if board[row][column] == 0:
board_str += ":white_circle: "
elif board[row][column] == 1:
board_str += self.tokens[0] + " "
elif board[row][column] == -1:
board_str += self.tokens[1] + " "
return board_str
def get_player_color(self, turn: int) -> str:
return self.tokens[turn]
def alert_move_message(self, original_player: str, move_info: str) -> str:
column_number = move_info.replace("move ", "")
return original_player + " moved in column " + column_number
def game_start_message(self) -> str:
return "Type `move <column-number>` or `<column-number>` to place a token.\n\
The first player to get 4 in a row wins!\n Good Luck!"
class ConnectFourBotHandler(GameAdapter):
"""
Bot that uses the Game Adapter class
to allow users to play other users
or the comptuer in a game of Connect
Four
"""
def __init__(self) -> None:
game_name = "Connect Four"
bot_name = "connect_four"
move_help_message = (
"* To make your move during a game, type\n"
"```move <column-number>``` or ```<column-number>```"
)
move_regex = "(move ([1-7])$)|(([1-7])$)"
model = ConnectFourModel
gameMessageHandler = ConnectFourMessageHandler
rules = """Try to get four pieces in row, Diagonals count too!"""
super().__init__(
game_name,
bot_name,
move_help_message,
move_regex,
model,
gameMessageHandler,
rules,
max_players=2,
)
handler_class = ConnectFourBotHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/connect_four/connect_four.py | connect_four.py |
from typing import Any, Dict, List
import requests
from zulip_bots.lib import BotHandler
supported_commands = [
("help", "Get the bot usage information."),
("list-commands", "Get information about the commands supported by the bot."),
("get-all-boards", "Get all the boards under the configured account."),
("get-all-cards <board_id>", "Get all the cards in the given board."),
("get-all-checklists <card_id>", "Get all the checklists in the given card."),
("get-all-lists <board_id>", "Get all the lists in the given board."),
]
INVALID_ARGUMENTS_ERROR_MESSAGE = "Invalid Arguments."
RESPONSE_ERROR_MESSAGE = "Invalid Response. Please check configuration and parameters."
class TrelloHandler:
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("trello")
self.api_key = self.config_info["api_key"]
self.access_token = self.config_info["access_token"]
self.user_name = self.config_info["user_name"]
self.auth_params = {"key": self.api_key, "token": self.access_token}
self.check_access_token(bot_handler)
def check_access_token(self, bot_handler: BotHandler) -> None:
test_query_response = requests.get(
f"https://api.trello.com/1/members/{self.user_name}/", params=self.auth_params
)
if test_query_response.text == "invalid key":
bot_handler.quit("Invalid Credentials. Please see doc.md to find out how to get them.")
def usage(self) -> str:
return """
This interactive bot can be used to interact with Trello.
Use `list-commands` to get information about the supported commands.
"""
def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> None:
content = message["content"].strip().split()
if content == []:
bot_handler.send_reply(message, "Empty Query")
return
content[0] = content[0].lower()
if content == ["help"]:
bot_handler.send_reply(message, self.usage())
return
if content == ["list-commands"]:
bot_reply = self.get_all_supported_commands()
elif content == ["get-all-boards"]:
bot_reply = self.get_all_boards()
else:
if content[0] == "get-all-cards":
bot_reply = self.get_all_cards(content)
elif content[0] == "get-all-checklists":
bot_reply = self.get_all_checklists(content)
elif content[0] == "get-all-lists":
bot_reply = self.get_all_lists(content)
else:
bot_reply = "Command not supported"
bot_handler.send_reply(message, bot_reply)
def get_all_supported_commands(self) -> str:
bot_response = "**Commands:** \n"
for index, (command, desc) in enumerate(supported_commands):
bot_response += f"{index + 1}. **{command}**: {desc}\n"
return bot_response
def get_all_boards(self) -> str:
get_board_ids_url = f"https://api.trello.com/1/members/{self.user_name}/"
board_ids_response = requests.get(get_board_ids_url, params=self.auth_params)
try:
boards = board_ids_response.json()["idBoards"]
bot_response = "**Boards:**\n" + self.get_board_descs(boards)
except (KeyError, ValueError, TypeError):
return RESPONSE_ERROR_MESSAGE
return bot_response
def get_board_descs(self, boards: List[str]) -> str:
bot_response = [] # type: List[str]
get_board_desc_url = "https://api.trello.com/1/boards/{}/"
for index, board in enumerate(boards):
board_desc_response = requests.get(
get_board_desc_url.format(board), params=self.auth_params
)
board_data = board_desc_response.json()
bot_response += [
"{_count}.[{name}]({url}) (`{id}`)".format(_count=index + 1, **board_data)
]
return "\n".join(bot_response)
def get_all_cards(self, content: List[str]) -> str:
if len(content) != 2:
return INVALID_ARGUMENTS_ERROR_MESSAGE
board_id = content[1]
get_cards_url = f"https://api.trello.com/1/boards/{board_id}/cards"
cards_response = requests.get(get_cards_url, params=self.auth_params)
try:
cards = cards_response.json()
bot_response = ["**Cards:**"]
for index, card in enumerate(cards):
bot_response += [
"{_count}. [{name}]({url}) (`{id}`)".format(_count=index + 1, **card)
]
except (KeyError, ValueError, TypeError):
return RESPONSE_ERROR_MESSAGE
return "\n".join(bot_response)
def get_all_checklists(self, content: List[str]) -> str:
if len(content) != 2:
return INVALID_ARGUMENTS_ERROR_MESSAGE
card_id = content[1]
get_checklists_url = f"https://api.trello.com/1/cards/{card_id}/checklists/"
checklists_response = requests.get(get_checklists_url, params=self.auth_params)
try:
checklists = checklists_response.json()
bot_response = ["**Checklists:**"]
for index, checklist in enumerate(checklists):
bot_response += ["{}. `{}`:".format(index + 1, checklist["name"])]
if "checkItems" in checklist:
for item in checklist["checkItems"]:
bot_response += [
" * [{}] {}".format(
"X" if item["state"] == "complete" else "-", item["name"]
)
]
except (KeyError, ValueError, TypeError):
return RESPONSE_ERROR_MESSAGE
return "\n".join(bot_response)
def get_all_lists(self, content: List[str]) -> str:
if len(content) != 2:
return INVALID_ARGUMENTS_ERROR_MESSAGE
board_id = content[1]
get_lists_url = f"https://api.trello.com/1/boards/{board_id}/lists"
lists_response = requests.get(get_lists_url, params=self.auth_params)
try:
lists = lists_response.json()
bot_response = ["**Lists:**"]
for index, _list in enumerate(lists):
bot_response += ["{}. {}".format(index + 1, _list["name"])]
if "cards" in _list:
for card in _list["cards"]:
bot_response += [" * {}".format(card["name"])]
except (KeyError, ValueError, TypeError):
return RESPONSE_ERROR_MESSAGE
return "\n".join(bot_response)
handler_class = TrelloHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/trello/trello.py | trello.py |
# Trello bot
The Trello bot is a Zulip bot that enables interaction with Trello using the
[Trello API](https://developers.trello.com).
To use the Trello bot, you can simply call it with `@<botname>` followed
by a command, like so:
```
@Trello help
```
## Setup
Before usage, you will need to configure the bot by putting the value of the `<api_key>`,
`<access_token>`, and `<user_name>` in the config file.
To do this, follow the given steps:
1. Go to [this]( https://trello.com/app-key) link after logging in at
[Trello]( https://trello.com/).
2. Generate an `access_token` and note it down. Continue to get your
`api_key`.
3. Go to your profile page in Trello and note down your `username`.
4. Open up `zulip_bots/bots/trello/trello.conf` in an editor and
change the values of the `<api_key>`, `<access_token>`, and `<user_name>`
attributes to the corresponding noted values.
## Developer Notes
Be sure to add the additional commands and their descriptions to the `supported_commands`
list in `trello.py` so that they can be displayed with the other available commands using
`@<botname> list-commands`. Also modify the `test_list_commands_command` in
`test_trello.py`.
## Usage
`@Trello list-commands` - This command gives a list of all available commands along with
short descriptions.
Example:

| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/trello/doc.md | doc.md |
import logging
import string
from typing import Dict
import html2text
import requests
from zulip_bots.lib import BotHandler
class DefineHandler:
"""
This plugin define a word that the user inputs. It
looks for messages starting with '@mention-bot'.
"""
DEFINITION_API_URL = "https://owlbot.info/api/v2/dictionary/{}?format=json"
REQUEST_ERROR_MESSAGE = "Could not load definition."
EMPTY_WORD_REQUEST_ERROR_MESSAGE = "Please enter a word to define."
PHRASE_ERROR_MESSAGE = "Definitions for phrases are not available."
SYMBOLS_PRESENT_ERROR_MESSAGE = "Definitions of words with symbols are not possible."
def usage(self) -> str:
return """
This plugin will allow users to define a word. Users should preface
messages with @mention-bot.
"""
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
original_content = message["content"].strip()
bot_response = self.get_bot_define_response(original_content)
bot_handler.send_reply(message, bot_response)
def get_bot_define_response(self, original_content: str) -> str:
split_content = original_content.split(" ")
# If there are more than one word (a phrase)
if len(split_content) > 1:
return DefineHandler.PHRASE_ERROR_MESSAGE
to_define = split_content[0].strip()
to_define_lower = to_define.lower()
# Check for presence of non-letters
non_letters = set(to_define_lower) - set(string.ascii_lowercase)
if len(non_letters):
return self.SYMBOLS_PRESENT_ERROR_MESSAGE
# No word was entered.
if not to_define_lower:
return self.EMPTY_WORD_REQUEST_ERROR_MESSAGE
else:
response = f"**{to_define}**:\n"
try:
# Use OwlBot API to fetch definition.
api_result = requests.get(self.DEFINITION_API_URL.format(to_define_lower))
# Convert API result from string to JSON format.
definitions = api_result.json()
# Could not fetch definitions for the given word.
if not definitions:
response += self.REQUEST_ERROR_MESSAGE
else: # Definitions available.
# Show definitions line by line.
for d in definitions:
example = d["example"] if d["example"] else "*No example available.*"
response += "\n" + "* (**{}**) {}\n {}".format(
d["type"], d["definition"], html2text.html2text(example)
)
except Exception:
response += self.REQUEST_ERROR_MESSAGE
logging.exception("")
return response
handler_class = DefineHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/define/define.py | define.py |
# DefineBot
* This is a bot that defines a word that the user inputs. Whenever the user
inputs a message starting with '@define', the bot defines the word
that follows.
* The definitions are brought to the website using an API. The bot posts the
definition of the word to the stream from which the user inputs the message.
If the user inputs a word that does not exist or a word that is incorrect or
is not in the dictionary, the definition is not displayed.
* For example, if the user says "@define crash", all the meanings of crash
appear, each in a separate line.

* If the user enters a wrong word, like "@define cresh" or "@define crish",
then an error message saying no definition is available is displayed.

| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/define/doc.md | doc.md |
About EncryptBot:
EncryptBot Allows for quick ROT13 encryption in the middle of a chat.
What It Does:
The bot encrypts any message sent to it on any stream it is subscribed to with ROT13.
How It Works:
The bot will Use ROT13(A -> N, B -> O... and vice-versa) in a python
implementation to provide quick and easy encryption.
How to Use:
-Send the message you want to encrypt, add @encrypt to the beginning.
-The Encrypted message will be sent back to the stream the original
message was posted in to the topic <sender-email>'s encrypted text.
-Messages can be decrypted by sending them to EncryptBot in the same way.
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/encrypt/doc.md | doc.md |
import json
import logging
from typing import Dict
import apiai
from zulip_bots.lib import BotHandler
help_message = """DialogFlow bot
This bot will interact with dialogflow bots.
Simply send this bot a message, and it will respond depending on the configured bot's behaviour.
"""
def get_bot_result(message_content: str, config: Dict[str, str], sender_id: str) -> str:
if message_content.strip() == "" or message_content.strip() == "help":
return config["bot_info"]
ai = apiai.ApiAI(config["key"])
try:
request = ai.text_request()
request.session_id = sender_id
request.query = message_content
response = request.getresponse()
res_str = response.read().decode("utf8", "ignore")
res_json = json.loads(res_str)
if res_json["status"]["errorType"] != "success" and "result" not in res_json.keys():
return "Error {}: {}.".format(
res_json["status"]["code"], res_json["status"]["errorDetails"]
)
if res_json["result"]["fulfillment"]["speech"] == "":
if "alternateResult" in res_json.keys():
if res_json["alternateResult"]["fulfillment"]["speech"] != "":
return res_json["alternateResult"]["fulfillment"]["speech"]
return "Error. No result."
return res_json["result"]["fulfillment"]["speech"]
except Exception as e:
logging.exception(str(e))
return f"Error. {str(e)}."
class DialogFlowHandler:
"""
This plugin allows users to easily add their own
DialogFlow bots to zulip
"""
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("dialogflow")
def usage(self) -> str:
return """
This plugin will allow users to easily add their own
DialogFlow bots to zulip
"""
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
result = get_bot_result(message["content"], self.config_info, message["sender_id"])
bot_handler.send_reply(message, result)
handler_class = DialogFlowHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/dialogflow/dialogflow.py | dialogflow.py |
# DialogFlow bot
This bot allows users to easily add their own DialogFlow bots to zulip.
## Setup
To add your DialogFlow bot:
Add the V1 Client access token from your agent's settings in the DialogFlow console to
`dialogflow.conf`, and write a short sentence describing what your bot does in the same file
as `bot_info`.
## Usage
Run this bot as described
[here](https://zulip.com/api/running-bots#running-a-bot).
Mention the bot in order to say things to it.
For example: `@weather What is the weather today?`
## Limitations
When creating your DialogFlow bot, please consider these things:
- Empty input will not be sent to the bot.
- Only text can be sent to, and recieved from the bot.
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/dialogflow/doc.md | doc.md |
import copy
import re
from typing import Dict, Optional
import chess
import chess.engine
from zulip_bots.lib import BotHandler
START_REGEX = re.compile("start with other user$")
START_COMPUTER_REGEX = re.compile("start as (?P<user_color>white|black) with computer")
MOVE_REGEX = re.compile("do (?P<move_san>.+)$")
RESIGN_REGEX = re.compile("resign$")
class ChessHandler:
def usage(self) -> str:
return (
"Chess Bot is a bot that allows you to play chess against either "
"another user or the computer. Use `start with other user` or "
"`start as <color> with computer` to start a game.\n\n"
"In order to play against a computer, `chess.conf` must be set "
"with the key `stockfish_location` set to the location of the "
"Stockfish program on this computer."
)
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("chess")
try:
self.engine = chess.engine.SimpleEngine.popen_uci(
self.config_info["stockfish_location"]
)
except FileNotFoundError:
# It is helpful to allow for fake Stockfish locations if the bot
# runner is testing or knows they won't be using an engine.
print("That Stockfish doesn't exist. Continuing.")
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
content = message["content"]
if content == "":
bot_handler.send_reply(message, self.usage())
return
start_regex_match = START_REGEX.match(content)
start_computer_regex_match = START_COMPUTER_REGEX.match(content)
move_regex_match = MOVE_REGEX.match(content)
resign_regex_match = RESIGN_REGEX.match(content)
is_with_computer = False
last_fen = chess.Board().fen()
if bot_handler.storage.contains("is_with_computer"):
is_with_computer = (
# `bot_handler`'s `storage` only accepts `str` values.
bot_handler.storage.get("is_with_computer")
== str(True)
)
if bot_handler.storage.contains("last_fen"):
last_fen = bot_handler.storage.get("last_fen")
if start_regex_match:
self.start(message, bot_handler)
elif start_computer_regex_match:
self.start_computer(
message, bot_handler, start_computer_regex_match.group("user_color") == "white"
)
elif move_regex_match:
if is_with_computer:
self.move_computer(
message, bot_handler, last_fen, move_regex_match.group("move_san")
)
else:
self.move(message, bot_handler, last_fen, move_regex_match.group("move_san"))
elif resign_regex_match:
self.resign(message, bot_handler, last_fen)
def start(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
"""Starts a game with another user, with the current user as white.
Replies to the bot handler.
Parameters:
- message: The Zulip Bots message object.
- bot_handler: The Zulip Bots bot handler object.
"""
new_board = chess.Board()
bot_handler.send_reply(message, make_start_reponse(new_board))
# `bot_handler`'s `storage` only accepts `str` values.
bot_handler.storage.put("is_with_computer", str(False))
bot_handler.storage.put("last_fen", new_board.fen())
def start_computer(
self, message: Dict[str, str], bot_handler: BotHandler, is_white_user: bool
) -> None:
"""Starts a game with the computer. Replies to the bot handler.
Parameters:
- message: The Zulip Bots message object.
- bot_handler: The Zulip Bots bot handler object.
- is_white_user: Whether or not the player wants to be
white. If false, the user is black. If the
user is white, they will get to make the
first move; if they are black the computer
will make the first move.
"""
new_board = chess.Board()
if is_white_user:
bot_handler.send_reply(message, make_start_computer_reponse(new_board))
# `bot_handler`'s `storage` only accepts `str` values.
bot_handler.storage.put("is_with_computer", str(True))
bot_handler.storage.put("last_fen", new_board.fen())
else:
self.move_computer_first(
message,
bot_handler,
new_board.fen(),
)
def validate_board(
self, message: Dict[str, str], bot_handler: BotHandler, fen: str
) -> Optional[chess.Board]:
"""Validates a board based on its FEN string. Replies to the bot
handler if there is an error with the board.
Parameters:
- message: The Zulip Bots message object.
- bot_handler: The Zulip Bots bot handler object.
- fen: The FEN string of the board.
Returns: `None` if the board didn't pass, or the board object itself
if it did.
"""
try:
last_board = chess.Board(fen)
except ValueError:
bot_handler.send_reply(message, make_copied_wrong_response())
return None
return last_board
def validate_move(
self,
message: Dict[str, str],
bot_handler: BotHandler,
last_board: chess.Board,
move_san: str,
is_computer: object,
) -> Optional[chess.Move]:
"""Validates a move based on its SAN string and the current board.
Replies to the bot handler if there is an error with the move.
Parameters:
- message: The Zulip Bots message object.
- bot_handler: The Zulip Bots bot handler object.
- last_board: The board object before the move.
- move_san: The SAN of the move.
- is_computer: Whether or not the user is playing against a
computer (used in the response if the move is not
legal).
Returns: `False` if the move didn't pass, or the move object itself if
it did.
"""
try:
move = last_board.parse_san(move_san)
except ValueError:
bot_handler.send_reply(message, make_not_legal_response(last_board, move_san))
return None
if move not in last_board.legal_moves:
bot_handler.send_reply(message, make_not_legal_response(last_board, move_san))
return None
return move
def check_game_over(
self, message: Dict[str, str], bot_handler: BotHandler, new_board: chess.Board
) -> bool:
"""Checks if a game is over due to
- checkmate,
- stalemate,
- insufficient material,
- 50 moves without a capture or pawn move, or
- 3-fold repetition.
Replies to the bot handler if it is game over.
Parameters:
- message: The Zulip Bots message object.
- bot_handler: The Zulip Bots bot handler object.
- new_board: The board object.
Returns: True if it is game over, false if it's not.
"""
# This assumes that the players will claim a draw after 3-fold
# repetition or 50 moves go by without a capture or pawn move.
# According to the official rules, the game is only guaranteed to
# be over if it's *5*-fold or *75* moves, but if either player
# wants the game to be a draw, after 3 or 75 it a draw. For now,
# just assume that the players would want the draw.
if new_board.is_game_over(claim_draw=True):
game_over_output = ""
if new_board.is_checkmate():
game_over_output = make_loss_response(new_board, "was checkmated")
elif new_board.is_stalemate():
game_over_output = make_draw_response("stalemate")
elif new_board.is_insufficient_material():
game_over_output = make_draw_response("insufficient material")
elif new_board.can_claim_fifty_moves():
game_over_output = make_draw_response("50 moves without a capture or pawn move")
elif new_board.can_claim_threefold_repetition():
game_over_output = make_draw_response("3-fold repetition")
bot_handler.send_reply(message, game_over_output)
return True
return False
def move(
self, message: Dict[str, str], bot_handler: BotHandler, last_fen: str, move_san: str
) -> None:
"""Makes a move for a user in a game with another user. Replies to
the bot handler.
Parameters:
- message: The Zulip Bots message object.
- bot_handler: The Zulip Bots bot handler object.
- last_fen: The FEN string of the board before the move.
- move_san: The SAN of the move to make.
"""
last_board = self.validate_board(message, bot_handler, last_fen)
if not last_board:
return
move = self.validate_move(message, bot_handler, last_board, move_san, False)
if not move:
return
new_board = copy.copy(last_board)
new_board.push(move)
if self.check_game_over(message, bot_handler, new_board):
return
bot_handler.send_reply(message, make_move_reponse(last_board, new_board, move))
bot_handler.storage.put("last_fen", new_board.fen())
def move_computer(
self, message: Dict[str, str], bot_handler: BotHandler, last_fen: str, move_san: str
) -> None:
"""Preforms a move for a user in a game with the computer and then
makes the computer's move. Replies to the bot handler. Unlike `move`,
replies only once to the bot handler every two moves (only after the
computer moves) instead of after every move. Doesn't require a call in
order to make the computer move. To make the computer move without the
user going first, use `move_computer_first`.
Parameters:
- message: The Zulip Bots message object.
- bot_handler: The Zulip Bots bot handler object.
- last_fen: The FEN string of the board before the user's move.
- move_san: The SAN of the user's move to make.
"""
last_board = self.validate_board(message, bot_handler, last_fen)
if not last_board:
return
move = self.validate_move(message, bot_handler, last_board, move_san, True)
if not move:
return
new_board = copy.copy(last_board)
new_board.push(move)
if self.check_game_over(message, bot_handler, new_board):
return
computer_move = calculate_computer_move(new_board, self.engine)
if not computer_move:
bot_handler.send_reply(message, make_engine_failed_response())
return
new_board_after_computer_move = copy.copy(new_board)
new_board_after_computer_move.push(computer_move)
if self.check_game_over(message, bot_handler, new_board_after_computer_move):
return
bot_handler.send_reply(
message, make_move_reponse(new_board, new_board_after_computer_move, computer_move)
)
bot_handler.storage.put("last_fen", new_board_after_computer_move.fen())
def move_computer_first(
self, message: Dict[str, str], bot_handler: BotHandler, last_fen: str
) -> None:
"""Preforms a move for the computer without having the user go first in
a game with the computer. Replies to the bot handler. Like
`move_computer`, but doesn't have the user move first. This is usually
only useful at the beginning of a game.
Parameters:
- message: The Zulip Bots message object.
- bot_handler: The Zulip Bots bot handler object.
- last_fen: The FEN string of the board before the computer's
move.
"""
last_board = self.validate_board(message, bot_handler, last_fen)
if not last_board:
return
computer_move = calculate_computer_move(last_board, self.engine)
if not computer_move:
bot_handler.send_reply(message, make_engine_failed_response())
return
new_board_after_computer_move = copy.copy(last_board)
new_board_after_computer_move.push(computer_move)
if self.check_game_over(message, bot_handler, new_board_after_computer_move):
return
bot_handler.send_reply(
message, make_move_reponse(last_board, new_board_after_computer_move, computer_move)
)
bot_handler.storage.put("last_fen", new_board_after_computer_move.fen())
# `bot_handler`'s `storage` only accepts `str` values.
bot_handler.storage.put("is_with_computer", str(True))
def resign(self, message: Dict[str, str], bot_handler: BotHandler, last_fen: str) -> None:
"""Resigns the game for the current player.
Parameters:
- message: The Zulip Bots message object.
- bot_handler: The Zulip Bots bot handler object.
- last_fen: The FEN string of the board.
"""
last_board = self.validate_board(message, bot_handler, last_fen)
if not last_board:
return
bot_handler.send_reply(message, make_loss_response(last_board, "resigned"))
handler_class = ChessHandler
def calculate_computer_move(
board: chess.Board, engine: chess.engine.SimpleEngine
) -> Optional[chess.Move]:
"""Calculates the computer's move.
Parameters:
- board: The board object before the move.
- engine: The UCI engine object.
Returns: The computer's move object.
"""
result = engine.play(board, chess.engine.Limit(time=3.0))
return result.move
def make_draw_response(reason: str) -> str:
"""Makes a response string for a draw.
Parameters:
- reason: The reason for the draw, in the form of a noun, e.g.,
'stalemate' or 'insufficient material'.
Returns: The draw response string.
"""
return f"It's a draw because of {reason}!"
def make_loss_response(board: chess.Board, reason: str) -> str:
"""Makes a response string for a loss (or win).
Parameters:
- board: The board object at the end of the game.
- reason: The reason for the loss, in the form of a predicate, e.g.,
'was checkmated'.
Returns: The loss response string.
"""
return ("*{}* {}. **{}** wins!\n\n" "{}").format(
"White" if board.turn else "Black",
reason,
"Black" if board.turn else "White",
make_str(board, board.turn),
)
def make_not_legal_response(board: chess.Board, move_san: str) -> str:
"""Makes a response string for a not-legal move.
Parameters:
- board: The board object before the move.
- move_san: The SAN of the not-legal move.
Returns: The not-legal-move response string.
"""
return ("Sorry, the move *{}* isn't legal.\n\n" "{}" "\n\n\n" "{}").format(
move_san, make_str(board, board.turn), make_footer()
)
def make_copied_wrong_response() -> str:
"""Makes a response string for a FEN string that was copied wrong.
Returns: The copied-wrong response string.
"""
return (
"Sorry, it seems like you copied down the response wrong.\n\n"
"Please try to copy the response again from the last message!"
)
def make_start_reponse(board: chess.Board) -> str:
"""Makes a response string for the first response of a game with another
user.
Parameters:
- board: The board object to start the game with (which most-likely
should be general opening chess position).
Returns: The starting response string.
"""
return (
"New game! The board looks like this:\n\n"
"{}"
"\n\n\n"
"Now it's **{}**'s turn."
"\n\n\n"
"{}"
).format(make_str(board, True), "white" if board.turn else "black", make_footer())
def make_start_computer_reponse(board: chess.Board) -> str:
"""Makes a response string for the first response of a game with a
computer, when the user is playing as white. If the user is playing as
black, use `ChessHandler.move_computer_first`.
Parameters:
- board: The board object to start the game with (which most-likely
should be general opening chess position).
Returns: The starting response string.
"""
return (
"New game with computer! The board looks like this:\n\n"
"{}"
"\n\n\n"
"Now it's **{}**'s turn."
"\n\n\n"
"{}"
).format(make_str(board, True), "white" if board.turn else "black", make_footer())
def make_move_reponse(last_board: chess.Board, new_board: chess.Board, move: chess.Move) -> str:
"""Makes a response string for after a move is made.
Parameters:
- last_board: The board object before the move.
- new_board: The board object after the move.
- move: The move object.
Returns: The move response string.
"""
return (
"The board was like this:\n\n"
"{}"
"\n\n\n"
"Then *{}* moved *{}*:\n\n"
"{}"
"\n\n\n"
"Now it's **{}**'s turn."
"\n\n\n"
"{}"
).format(
make_str(last_board, new_board.turn),
"white" if last_board.turn else "black",
last_board.san(move),
make_str(new_board, new_board.turn),
"white" if new_board.turn else "black",
make_footer(),
)
def make_engine_failed_response() -> str:
"""Makes a response string for engine failure.
Returns: The engine failure response string.
"""
return "The computer failed to make a move."
def make_footer() -> str:
"""Makes a footer to be appended to the bottom of other, actionable
responses.
"""
return (
"To make your next move, respond to Chess Bot with\n\n"
"```do <your move>```\n\n"
"*Remember to @-mention Chess Bot at the beginning of your "
"response.*"
)
def make_str(board: chess.Board, is_white_on_bottom: bool) -> str:
"""Converts a board object into a string to be used in Markdown. Backticks
are added around the string to preserve formatting.
Parameters:
- board: The board object.
- is_white_on_bottom: Whether or not white should be on the bottom
side in the string. If false, black will be on
the bottom.
Returns: The string made from the board.
"""
default_str = board.__str__()
replaced_str = replace_with_unicode(default_str)
replaced_and_guided_str = guide_with_numbers(replaced_str)
properly_flipped_str = (
replaced_and_guided_str if is_white_on_bottom else replaced_and_guided_str[::-1]
)
trimmed_str = trim_whitespace_before_newline(properly_flipped_str)
monospaced_str = f"```\n{trimmed_str}\n```"
return monospaced_str
def guide_with_numbers(board_str: str) -> str:
"""Adds numbers and letters on the side of a string without them made out
of a board.
Parameters:
- board_str: The string from the board object.
Returns: The string with the numbers and letters.
"""
# Spaces and newlines would mess up the loop because they add extra indexes
# between pieces. Newlines are added later by the loop and spaces are added
# back in at the end.
board_without_whitespace_str = board_str.replace(" ", "").replace("\n", "")
# The first number, 8, needs to be added first because it comes before a
# newline. From then on, numbers are inserted at newlines.
row_list = list("8" + board_without_whitespace_str)
for i, char in enumerate(row_list):
# `(i + 1) % 10 == 0` if it is the end of a row, i.e., the 10th column
# since lists are 0-indexed.
if (i + 1) % 10 == 0:
# Since `i + 1` is always a multiple of 10 (because index 0, 10,
# 20, etc. is the other row letter and 1-8, 11-18, 21-28, etc. are
# the squares), `(i + 1) // 10` is the inverted row number (1 when
# it should be 8, 2 when it should be 7, etc.), so therefore
# `9 - (i + 1) // 10` is the actual row number.
row_num = 9 - (i + 1) // 10
# The 3 separate components are split into only 2 elements so that
# the newline isn't counted by the loop. If they were split into 3,
# or combined into just 1 string, the counter would become off
# because it would be counting what is really 2 rows as 3 or 1.
row_list[i:i] = [str(row_num) + "\n", str(row_num - 1)]
# 1 is appended to the end because it isn't created in the loop, and lines
# that begin with spaces have their spaces removed for aesthetics.
row_str = (" ".join(row_list) + " 1").replace("\n ", "\n")
# a, b, c, d, e, f, g, and h are easy to add in.
row_and_col_str = " a b c d e f g h \n" + row_str + "\n a b c d e f g h "
return row_and_col_str
def replace_with_unicode(board_str: str) -> str:
"""Replaces the default characters in a board object's string output with
Unicode chess characters, e.g., '♖' instead of 'R.'
Parameters:
- board_str: The string from the board object.
Returns: The string with the replaced characters.
"""
replaced_str = board_str
replaced_str = replaced_str.replace("P", "♙")
replaced_str = replaced_str.replace("N", "♘")
replaced_str = replaced_str.replace("B", "♗")
replaced_str = replaced_str.replace("R", "♖")
replaced_str = replaced_str.replace("Q", "♕")
replaced_str = replaced_str.replace("K", "♔")
replaced_str = replaced_str.replace("p", "♟")
replaced_str = replaced_str.replace("n", "♞")
replaced_str = replaced_str.replace("b", "♝")
replaced_str = replaced_str.replace("r", "♜")
replaced_str = replaced_str.replace("q", "♛")
replaced_str = replaced_str.replace("k", "♚")
replaced_str = replaced_str.replace(".", "·")
return replaced_str
def trim_whitespace_before_newline(str_to_trim: str) -> str:
"""Removes any spaces before a newline in a string.
Parameters:
- str_to_trim: The string to trim.
Returns: The trimmed string.
"""
return re.sub(r"\s+$", "", str_to_trim, flags=re.M) | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/chessbot/chessbot.py | chessbot.py |
## Starting a Game
You can start a game with another user by typing
```
start with other user
```
or you can start a game with a computer with
```
start as <white or black> with computer
```
## Playing
After starting the game, you can make your move by typing
```
do <your move>
```
using [Standard Algebraic Chess Notation](https://goo.gl/rehi8n). For example,
`do e4` to move a pawn to *e4* or `do Nf3` to move a night to *f3* or `do O-O`
to castle.
## Ending the game
The bot will detect if a game is over. You can end one early by resigning
with the
```
resign
```
command.
(Or you could just stop responding.)
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/chessbot/doc.md | doc.md |
import logging
import re
from typing import Any, Dict, List, Optional
import requests
from zulip_bots.lib import BotHandler
API_BASE_URL = "https://beta.idonethis.com/api/v2"
api_key = ""
default_team = ""
class AuthenticationException(Exception):
pass
class TeamNotFoundException(Exception):
def __init__(self, team: str) -> None:
self.team = team
class UnknownCommandSyntax(Exception):
def __init__(self, detail: str) -> None:
self.detail = detail
class UnspecifiedProblemException(Exception):
pass
def make_API_request(
endpoint: str,
method: str = "GET",
body: Optional[Dict[str, str]] = None,
params: Optional[Dict[str, str]] = None,
) -> Any:
headers = {"Authorization": "Token " + api_key}
if method == "GET":
r = requests.get(API_BASE_URL + endpoint, headers=headers, params=params)
elif method == "POST":
r = requests.post(API_BASE_URL + endpoint, headers=headers, params=params, json=body)
if r.status_code == 200:
return r.json()
elif (
r.status_code == 401
and "error" in r.json()
and r.json()["error"] == "Invalid API Authentication"
):
logging.error("Error authenticating, please check key " + str(r.url))
raise AuthenticationException()
else:
logging.error("Error make API request, code " + str(r.status_code) + ". json: " + r.json())
raise UnspecifiedProblemException()
def api_noop() -> None:
make_API_request("/noop")
def api_list_team() -> List[Dict[str, str]]:
return make_API_request("/teams")
def api_show_team(hash_id: str) -> Dict[str, str]:
return make_API_request(f"/teams/{hash_id}")
# NOTE: This function is not currently used
def api_show_users(hash_id: str) -> Any:
return make_API_request(f"/teams/{hash_id}/members")
def api_list_entries(team_id: Optional[str] = None) -> List[Dict[str, Any]]:
if team_id:
return make_API_request("/entries", params=dict(team_id=team_id))
else:
return make_API_request("/entries")
def api_create_entry(body: str, team_id: str) -> Dict[str, Any]:
return make_API_request("/entries", "POST", {"body": body, "team_id": team_id})
def list_teams() -> str:
response = ["Teams:"] + [" * " + team["name"] for team in api_list_team()]
return "\n".join(response)
def get_team_hash(team_name: str) -> str:
for team in api_list_team():
if team["name"].lower() == team_name.lower() or team["hash_id"] == team_name:
return team["hash_id"]
raise TeamNotFoundException(team_name)
def team_info(team_name: str) -> str:
data = api_show_team(get_team_hash(team_name))
return "\n".join(["Team Name: {name}", "ID: `{hash_id}`", "Created at: {created_at}"]).format(
**data
)
def entries_list(team_name: str) -> str:
if team_name:
data = api_list_entries(get_team_hash(team_name))
response = f"Entries for {team_name}:"
else:
data = api_list_entries()
response = "Entries for all teams:"
for entry in data:
response += "\n".join(
[
"",
" * {body_formatted}",
" * Created at: {created_at}",
" * Status: {status}",
" * User: {username}",
" * Team: {teamname}",
" * ID: {hash_id}",
]
).format(username=entry["user"]["full_name"], teamname=entry["team"]["name"], **entry)
return response
def create_entry(message: str) -> str:
SINGLE_WORD_REGEX = re.compile("--team=([a-zA-Z0-9_]*)")
MULTIWORD_REGEX = re.compile('"--team=([^"]*)"')
team = ""
new_message = ""
single_word_match = SINGLE_WORD_REGEX.search(message)
multiword_match = MULTIWORD_REGEX.search(message)
if multiword_match is not None:
team = multiword_match.group(1)
new_message = MULTIWORD_REGEX.sub("", message).strip()
elif single_word_match is not None:
team = single_word_match.group(1)
new_message = SINGLE_WORD_REGEX.sub("", message).strip()
elif default_team:
team = default_team
new_message = message
else:
raise UnknownCommandSyntax(
"""I don't know which team you meant for me to create an entry under.
Either set a default team or pass the `--team` flag.
More information in my help"""
)
team_id = get_team_hash(team)
data = api_create_entry(new_message, team_id)
return "Great work :thumbs_up:. New entry `{}` created!".format(data["body_formatted"])
class IDoneThisHandler:
def initialize(self, bot_handler: BotHandler) -> None:
global api_key, default_team
self.config_info = bot_handler.get_config_info("idonethis")
if "api_key" in self.config_info:
api_key = self.config_info["api_key"]
else:
logging.error("An API key must be specified for this bot to run.")
logging.error(
"Have a look at the Setup section of my documenation for more information."
)
bot_handler.quit()
if "default_team" in self.config_info:
default_team = self.config_info["default_team"]
else:
logging.error(
"Cannot find default team. Users will need to manually specify a team each time an entry is created."
)
try:
api_noop()
except AuthenticationException:
logging.error(
"Authentication exception with idonethis. Can you check that your API keys are correct? "
)
bot_handler.quit()
except UnspecifiedProblemException:
logging.error("Problem connecting to idonethis. Please check connection")
bot_handler.quit()
def usage(self) -> str:
default_team_message = ""
if default_team:
default_team_message = "The default team is currently set as `" + default_team + "`."
else:
default_team_message = "There is currently no default team set up :frowning:."
return (
"""
This bot allows for interaction with idonethis, a collaboration tool to increase a team's productivity.
Below are some of the commands you can use, and what they do.
`<team>` can either be the name or ID of a team.
* `@mention help` view this help message
* `@mention list teams`
List all the teams
* `@mention team info <team>`
Show information about one `<team>`
* `@mention list entries`
List entries from any team
* `@mention list entries <team>`
List all entries from `<team>`
* `@mention new entry` or `@mention i did`
Create a new entry. Optionally supply `--team=<team>` for teams with no spaces or `"--team=<team>"`
for teams with spaces. For example `@mention i did "--team=product team" something` will create a
new entry `something` for the product team.
"""
+ default_team_message
)
def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> None:
bot_handler.send_reply(message, self.get_response(message))
def get_response(self, message: Dict[str, Any]) -> str:
message_content = message["content"].strip().split()
reply = ""
try:
command = " ".join(message_content[:2])
if command in ["teams list", "list teams"]:
reply = list_teams()
elif command in ["teams info", "team info"]:
if len(message_content) > 2:
reply = team_info(" ".join(message_content[2:]))
else:
raise UnknownCommandSyntax(
"You must specify the team in which you request information from."
)
elif command in ["entries list", "list entries"]:
reply = entries_list(" ".join(message_content[2:]))
elif command in ["entries create", "create entry", "new entry", "i did"]:
reply = create_entry(" ".join(message_content[2:]))
elif command in ["help"]:
reply = self.usage()
else:
raise UnknownCommandSyntax("I can't understand the command you sent me :confused: ")
except TeamNotFoundException as e:
reply = (
"Sorry, it doesn't seem as if I can find a team named `" + e.team + "` :frowning:."
)
except AuthenticationException:
reply = "I can't currently authenticate with idonethis. "
reply += "Can you check that your API key is correct? For more information see my documentation."
except UnknownCommandSyntax as e:
reply = (
"Sorry, I don't understand what your trying to say. Use `@mention help` to see my help. "
+ e.detail
)
except Exception as e: # catches UnspecifiedProblemException, and other problems
reply = "Oh dear, I'm having problems processing your request right now. Perhaps you could try again later :grinning:"
logging.error("Exception caught: " + str(e))
return reply
handler_class = IDoneThisHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/idonethis/idonethis.py | idonethis.py |
# idonethis bot
The idonethis bot is a Zulip bot which allows interaction with [idonethis](https://idonethis.com/)
through Zulip. It can peform actions such as viewing teams, list entries and creating entries.
To use the bot simply @-mention the bot followed by a specific command. See the usage section
below for a list of available commands.
## Setup
Before proceeding further, ensure you have an idonethis account.
1. Go to [your idonethis settings](https://beta.idonethis.com/u/settings), scroll down
and copy your API token.
2. Open up `zulip_bots/bots/idonethis/idonethis.conf` in your favorite editor, and change
`api_key` to your API token.
3. Optionally, change the `default_team` value to your default team for creating new messages.
If this is not specified, a team will be required to be manually specified every time an entry is created.
Run this bot as described [here](https://zulip.com/api/running-bots#running-a-bot).
## Usage
`<team>` can either be the name or ID of a team.
* `@mention help` view this help message.

* `@mention teams list` or `@mention list teams`
List all the teams.

* `@mention team info <team>`.
Show information about one `<team>`.

* `@mention entries list` or `@mention list entries`.
List entries from any team

* `@mention entries list <team>` or `@mention list entries <team>`
List all entries from `<team>`.

* `@mention entries create` or `@mention new entry` or `@mention create entry`
or `@mention new entry` or `@mention i did`
Create a new entry. Optionally supply `--team=<team>` for teams with no spaces or `"--team=<team>"`
for teams with spaces. For example `@mention i did "--team=product team" something` will create a
new entry `something` for the product team.


| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/idonethis/doc.md | doc.md |
import logging
from typing import Any, Dict, List, Optional, Tuple
import requests
from requests.exceptions import ConnectionError
from zulip_bots.lib import BotHandler
USERS_LIST_URL = "https://api.flock.co/v1/roster.listContacts"
SEND_MESSAGE_URL = "https://api.flock.co/v1/chat.sendMessage"
help_message = """
You can send messages to any Flock user associated with your account from Zulip.
*Syntax*: **@botname to: message** where `to` is **firstName** of recipient.
"""
# Matches the recipient name provided by user with list of users in his contacts.
# If matches, returns the matched User's ID
def find_recipient_id(users: List[Any], recipient_name: str) -> str:
for user in users:
if recipient_name == user["firstName"]:
return user["id"]
# Make request to given flock URL and return a two-element tuple
# whose left-hand value contains JSON body of response (or None if request failed)
# and whose right-hand value contains an error message (or None if request succeeded)
def make_flock_request(url: str, params: Dict[str, str]) -> Tuple[Any, str]:
try:
res = requests.get(url, params=params)
return (res.json(), None)
except ConnectionError as e:
logging.exception(str(e))
error = "Uh-Oh, couldn't process the request \
right now.\nPlease try again later"
return (None, error)
# Returns two-element tuple whose left-hand value contains recipient
# user's ID (or None if it was not found) and right-hand value contains
# an error message (or None if recipient user's ID was found)
def get_recipient_id(
recipient_name: str, config: Dict[str, str]
) -> Tuple[Optional[str], Optional[str]]:
token = config["token"]
payload = {"token": token}
users, error = make_flock_request(USERS_LIST_URL, payload)
if users is None:
return (None, error)
recipient_id = find_recipient_id(users, recipient_name)
if recipient_id is None:
error = "No user found. Make sure you typed it correctly."
return (None, error)
else:
return (recipient_id, None)
# This handles the message sending work.
def get_flock_response(content: str, config: Dict[str, str]) -> str:
token = config["token"]
content_pieces = content.split(":")
recipient_name = content_pieces[0].strip()
message = content_pieces[1].strip()
recipient_id, error = get_recipient_id(recipient_name, config)
if recipient_id is None:
return error
if len(str(recipient_id)) > 30:
return "Found user is invalid."
payload = {"to": recipient_id, "text": message, "token": token}
res, error = make_flock_request(SEND_MESSAGE_URL, payload)
if res is None:
return error
if "uid" in res:
return "Message sent."
else:
return "Message sending failed :slightly_frowning_face:. Please try again."
def get_flock_bot_response(content: str, config: Dict[str, str]) -> None:
content = content.strip()
if content == "" or content == "help":
return help_message
else:
result = get_flock_response(content, config)
return result
class FlockHandler:
"""
This is flock bot. Now you can send messages to any of your
flock user without having to leave Zulip.
"""
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("flock")
def usage(self) -> str:
return """Hello from Flock Bot. You can send messages to any Flock user
right from Zulip."""
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
response = get_flock_bot_response(message["content"], self.config_info)
bot_handler.send_reply(message, response)
handler_class = FlockHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/flock/flock.py | flock.py |
# Flock Bot
With [Flock](https://flock.com/) bot, you can send messages to any of your
flock contact without having to leave Zulip.
Sending messages to a user is quite easy, syntax is:
`@botname recipient_name: hello`
where `recipient_name` is name of recipient and `hello` is the sample message.
## Configuration
1. Before running Flock bot, you'll need a `token`. In order to get `token`,
Go to [Flock apps](https://dev.flock.com/apps) and create an app.
After successful installation, you'll get an `token` in response from servers.
1. Once you have `token`, you should supply it in `flock.conf` file.
## Usage
Run this bot as described in
[here](https://zulip.com/api/running-bots#running-a-bot).
You can use this bot in one easy step:
`@botname recipient_firstName: message`
For help, do `@botname help`.
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/flock/doc.md | doc.md |
import copy
from typing import Any, Dict, List, Tuple
from zulip_bots.game_handler import BadMoveException, GameAdapter
class GameOfFifteenModel:
final_board = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
initial_board = [[8, 7, 6], [5, 4, 3], [2, 1, 0]]
def __init__(self, board: Any = None) -> None:
if board is not None:
self.current_board = board
else:
self.current_board = copy.deepcopy(self.initial_board)
def get_coordinates(self, board: List[List[int]]) -> Dict[int, Tuple[int, int]]:
return {
board[0][0]: (0, 0),
board[0][1]: (0, 1),
board[0][2]: (0, 2),
board[1][0]: (1, 0),
board[1][1]: (1, 1),
board[1][2]: (1, 2),
board[2][0]: (2, 0),
board[2][1]: (2, 1),
board[2][2]: (2, 2),
}
def determine_game_over(self, players: List[str]) -> str:
if self.won(self.current_board):
return "current turn"
return ""
def won(self, board: Any) -> bool:
for i in range(3):
for j in range(3):
if board[i][j] != self.final_board[i][j]:
return False
return True
def validate_move(self, tile: int) -> bool:
if tile < 1 or tile > 8:
return False
return True
def update_board(self, board):
self.current_board = copy.deepcopy(board)
def make_move(self, move: str, player_number: int, computer_move: bool = False) -> Any:
board = self.current_board
move = move.strip()
move = move.split(" ")
if "" in move:
raise BadMoveException("You should enter space separated digits.")
moves = len(move)
for m in range(1, moves):
tile = int(move[m])
coordinates = self.get_coordinates(board)
if tile not in coordinates:
raise BadMoveException("You can only move tiles which exist in the board.")
i, j = coordinates[tile]
if (j - 1) > -1 and board[i][j - 1] == 0:
board[i][j - 1] = tile
board[i][j] = 0
elif (i - 1) > -1 and board[i - 1][j] == 0:
board[i - 1][j] = tile
board[i][j] = 0
elif (j + 1) < 3 and board[i][j + 1] == 0:
board[i][j + 1] = tile
board[i][j] = 0
elif (i + 1) < 3 and board[i + 1][j] == 0:
board[i + 1][j] = tile
board[i][j] = 0
else:
raise BadMoveException(
"You can only move tiles which are adjacent to :grey_question:."
)
if m == moves - 1:
return board
class GameOfFifteenMessageHandler:
tiles = {
"0": ":grey_question:",
"1": ":one:",
"2": ":two:",
"3": ":three:",
"4": ":four:",
"5": ":five:",
"6": ":six:",
"7": ":seven:",
"8": ":eight:",
}
def parse_board(self, board: Any) -> str:
# Header for the top of the board
board_str = ""
for row in range(3):
board_str += "\n\n"
for column in range(3):
board_str += self.tiles[str(board[row][column])]
return board_str
def alert_move_message(self, original_player: str, move_info: str) -> str:
tile = move_info.replace("move ", "")
return original_player + " moved " + tile
def game_start_message(self) -> str:
return (
"Welcome to Game of Fifteen!"
"To make a move, type @-mention `move <tile1> <tile2> ...`"
)
class GameOfFifteenBotHandler(GameAdapter):
"""
Bot that uses the Game Adapter class
to allow users to play Game of Fifteen
"""
def __init__(self) -> None:
game_name = "Game of Fifteen"
bot_name = "Game of Fifteen"
move_help_message = (
"* To make your move during a game, type\n```move <tile1> <tile2> ...```"
)
move_regex = r"move [\d{1}\s]+$"
model = GameOfFifteenModel
gameMessageHandler = GameOfFifteenMessageHandler
rules = """Arrange the board’s tiles from smallest to largest, left to right,
top to bottom, and tiles adjacent to :grey_question: can only be moved.
Final configuration will have :grey_question: in top left."""
super().__init__(
game_name,
bot_name,
move_help_message,
move_regex,
model,
gameMessageHandler,
rules,
min_players=1,
max_players=1,
)
handler_class = GameOfFifteenBotHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/game_of_fifteen/game_of_fifteen.py | game_of_fifteen.py |
# Game of Fifteen bot
This bot is designed to let you play a [game of fifteen](https://en.wikipedia.org/wiki/15_puzzle).
The goal of the game is to arrange all numbers from smallest to largest,
starting with the grey question mark in the upper left corner, and then
moving through each row till one reaches the end.
## Usage
To start a new game, simply type:
```
@game_of_fifteen
```
`move <tile1> <tile2>` - This command is used to pick which number to
switch with the grey question mark. Only pieces adjacent to the
grey question mark may be moved.
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/game_of_fifteen/doc.md | doc.md |
import logging
from typing import Dict, Optional
import requests
from zulip_bots.lib import BotHandler
# See readme.md for instructions on running this code.
class StackOverflowHandler:
"""
This plugin facilitates searching Stack Overflow for a
specific query and returns the top 3 questions from the
search. It looks for messages starting with '@mention-bot'
In this example, we write all Stack Overflow searches into
the same stream that it was called from.
"""
META = {
"name": "StackOverflow",
"description": "Searches Stack Overflow for a query and returns the top 3 articles.",
}
def usage(self) -> str:
return """
This plugin will allow users to directly search
Stack Overflow for a specific query and get the top 3
articles that are returned from the search. Users
should preface query with "@mention-bot".
@mention-bot <search query>"""
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
bot_response = self.get_bot_stackoverflow_response(message, bot_handler)
bot_handler.send_reply(message, bot_response)
def get_bot_stackoverflow_response(
self, message: Dict[str, str], bot_handler: BotHandler
) -> Optional[str]:
"""This function returns the URLs of the requested topic."""
help_text = "Please enter your query after @mention-bot to search StackOverflow"
# Checking if the link exists.
query = message["content"]
if query == "" or query == "help":
return help_text
query_stack_url = "http://api.stackexchange.com/2.2/search/advanced"
query_stack_params = dict(order="desc", sort="relevance", site="stackoverflow", title=query)
try:
data = requests.get(query_stack_url, params=query_stack_params)
except requests.exceptions.RequestException:
logging.error("broken link")
return (
"Uh-Oh ! Sorry ,couldn't process the request right now.:slightly_frowning_face:\n"
"Please try again later."
)
# Checking if the bot accessed the link.
if data.status_code != 200:
logging.error("Page not found.")
return (
"Uh-Oh ! Sorry ,couldn't process the request right now.:slightly_frowning_face:\n"
"Please try again later."
)
new_content = "For search term:" + query + "\n"
# Checking if there is content for the searched term
if len(data.json()["items"]) == 0:
new_content = (
"I am sorry. The search term you provided is not found :slightly_frowning_face:"
)
else:
for i in range(min(3, len(data.json()["items"]))):
search_string = data.json()["items"][i]["title"]
link = data.json()["items"][i]["link"]
new_content += str(i + 1) + " : " + "[" + search_string + "]" + "(" + link + ")\n"
return new_content
handler_class = StackOverflowHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/stack_overflow/stack_overflow.py | stack_overflow.py |
# StackOverflow Bot
The StackOverflow bot is a Zulip bot that will search Stackoverflow
for a provided set of keywords or a question, and fetch a link to the associated
query. The link is returned to the same stream
it was @mentioned in
The Stackoverflow bot uses the
[StackExchange API](http://api.stackexchange.com/docs)
to obtain the search results it returns
Using the StackOverflow bot is as simple as mentioning @\<stackoverflow-bot-name\>,
followed by the query:
```
@<stackoverflow-bot-name> <query>
```
## Setup
Beyond the typical obtaining of the zuliprc file, no extra setup is required to use the StackOverflow Bot
## Usage
1. ```@<stackoverflow-bot-name> <query>``` -
fetches the link to the appropriate StackOverflow questions.
* For example, `@<stackoverflow-bot-name> rest api`
will return the links having questions related to rest api.
<br>
2. If there are no questions related to the query,
the bot will respond with an error message:
`I am sorry. The search query you provided is does not have any related results.`
<br>
3. If no query is provided, the bot will return the help text:
```Please enter your message after @mention-bot```
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/stack_overflow/doc.md | doc.md |
import logging
import re
from typing import Any, Dict, List
import simple_salesforce
from zulip_bots.bots.salesforce.utils import commands, default_query, link_query, object_types
from zulip_bots.lib import BotHandler
base_help_text = """Salesforce bot
This bot can do simple salesforce query requests
**All commands must be @-mentioned to the bot.**
Commands:
{}
Arguments:
**-limit <num>**: the maximum number of entries sent (default: 5)
**-show**: show all the properties of each entry (default: false)
This bot can also show details about any Salesforce links sent to it.
Supported Object types:
These are the types of Salesforce object supported by this bot.
The bot cannot show the details of any other object types.
{}"""
login_url = "https://login.salesforce.com/"
def get_help_text() -> str:
command_text = ""
for command in commands:
if "template" in command.keys() and "description" in command.keys():
command_text += "**{}**: {}\n".format(
"{} [arguments]".format(command["template"]), command["description"]
)
object_type_text = ""
for object_type in object_types.values():
object_type_text += "{}\n".format(object_type["table"])
return base_help_text.format(command_text, object_type_text)
def format_result(
result: Dict[str, Any],
exclude_keys: List[str] = [],
force_keys: List[str] = [],
rank_output: bool = False,
show_all_keys: bool = False,
) -> str:
exclude_keys += ["Name", "attributes", "Id"]
output = ""
if result["totalSize"] == 0:
return "No records found."
if result["totalSize"] == 1:
record = result["records"][0]
output += "**[{}]({}{})**\n".format(record["Name"], login_url, record["Id"])
for key, value in record.items():
if key not in exclude_keys:
output += f">**{key}**: {value}\n"
else:
for i, record in enumerate(result["records"]):
if rank_output:
output += f"{i + 1}) "
output += "**[{}]({}{})**\n".format(record["Name"], login_url, record["Id"])
added_keys = False
for key, value in record.items():
if key in force_keys or (show_all_keys and key not in exclude_keys):
added_keys = True
output += f">**{key}**: {value}\n"
if added_keys:
output += "\n"
return output
def query_salesforce(
arg: str, salesforce: simple_salesforce.Salesforce, command: Dict[str, Any]
) -> str:
arg = arg.strip()
qarg = arg.split(" -", 1)[0]
split_args = [] # type: List[str]
raw_arg = ""
if len(arg.split(" -", 1)) > 1:
raw_arg = " -" + arg.split(" -", 1)[1]
split_args = raw_arg.split(" -")
limit_num = 5
re_limit = re.compile(r"-limit \d+")
limit = re_limit.search(raw_arg)
if limit:
limit_num = int(limit.group().rsplit(" ", 1)[1])
logging.info(f"Searching with limit {limit_num}")
query = default_query
if "query" in command.keys():
query = command["query"]
object_type = object_types[command["object"]]
res = salesforce.query(
query.format(object_type["fields"], object_type["table"], qarg, limit_num)
)
exclude_keys = [] # type: List[str]
if "exclude_keys" in command.keys():
exclude_keys = command["exclude_keys"]
force_keys = [] # type: List[str]
if "force_keys" in command.keys():
force_keys = command["force_keys"]
rank_output = False
if "rank_output" in command.keys():
rank_output = command["rank_output"]
show_all_keys = "show" in split_args
if "show_all_keys" in command.keys():
show_all_keys = command["show_all_keys"] or "show" in split_args
return format_result(
res,
exclude_keys=exclude_keys,
force_keys=force_keys,
rank_output=rank_output,
show_all_keys=show_all_keys,
)
def get_salesforce_link_details(link: str, sf: Any) -> str:
re_id = re.compile("/[A-Za-z0-9]{18}")
re_id_res = re_id.search(link)
if re_id_res is None:
return "Invalid salesforce link"
id = re_id_res.group().strip("/")
for object_type in object_types.values():
res = sf.query(link_query.format(object_type["fields"], object_type["table"], id))
if res["totalSize"] == 1:
return format_result(res)
return "No object found. Make sure it is of the supported types. Type `help` for more info."
class SalesforceHandler:
def usage(self) -> str:
return """
This is a Salesforce bot, which can search for Contacts,
Accounts and Opportunities. And can be configured for any
other object types.
It will also show details of any Salesforce links posted.
@-mention the bot with 'help' to see available commands.
"""
def get_salesforce_response(self, content: str) -> str:
content = content.strip()
if content == "" or content == "help":
return get_help_text()
if content.startswith("http") and "force" in content:
return get_salesforce_link_details(content, self.sf)
for command in commands:
for command_keyword in command["commands"]:
if content.startswith(command_keyword):
args = content.replace(command_keyword, "").strip()
if args is not None and args != "":
if "callback" in command.keys():
return command["callback"](args, self.sf, command)
else:
return query_salesforce(args, self.sf, command)
else:
return "Usage: {} [arguments]".format(command["template"])
return get_help_text()
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("salesforce")
try:
self.sf = simple_salesforce.Salesforce(
username=self.config_info["username"],
password=self.config_info["password"],
security_token=self.config_info["security_token"],
)
except simple_salesforce.exceptions.SalesforceAuthenticationFailed as err:
bot_handler.quit(f"Failed to log in to Salesforce. {err.code} {err.message}")
def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> None:
try:
bot_response = self.get_salesforce_response(message["content"])
bot_handler.send_reply(message, bot_response)
except Exception as e:
bot_handler.send_reply(message, f"Error. {e}.", bot_response)
handler_class = SalesforceHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/salesforce/salesforce.py | salesforce.py |
# Salesforce bot
The Salesforce bot can get records from your Salesforce database.
It can also show details about any Salesforce links that you post.
## Setup
1. Create a user in Salesforce that the bot can use to access Salesforce.
Make sure it has the appropriate permissions to access records.
2. In `salesforce.conf` paste the Salesforce `username`, `password` and
`security_token`.
3. Run the bot as explained [here](https://zulip.com/api/running-bots#running-a-bot)
## Examples
### Standard query

### Custom query

### Link details

## Optional Configuration (Advanced)
The bot has been designed to be able to configure custom commands and objects.
If you wanted to find a custom object type, or an object type not included with the bot,
like `Event`, you can add these by adding to the Commands and Object Types in `utils.py`.
A Command is a phrase that the User asks the bot. For example `find contact bob`. To make a Command,
the corresponding object type must be made.
Object types are Salesforce objects, like `Event`, and are used to tell the bot which fields of the object the bot
should ask for and display.
To show details about a link posted, only the Object Type for the object needs to be present.
Please read the
[SOQL reference](https://goo.gl/6VwBV3)
to make custom queries, and the [simple_salesforce documentation](https://pypi.python.org/pypi/simple-salesforce)
to make custom callbacks.
### Commands
For example: "find contact tim"
In `utils.py`, the commands are stored in the list `commands`.
Parameter | Required? | Type | Description | Default
--------- | --------- | ---- | ----------- | -------
commands | [x] | list[str] | What the user should start their command with | `None`
object | [x] | str | The Salesforce object type in `object_types` | `None`
query | [ ] | str | The SOQL query to access this object* | `'SELECT {} FROM {} WHERE Name LIKE %\'{}\'% LIMIT {}'`
description | [x] | str | What does the command do? | `None`
template | [x] | str | Example of the command | `None`
rank_output | [ ] | boolean | Should the output be ranked? (1., 2., 3. etc.) | `False`
force_keys | [ ] | list[str] | Values which should always be shown in the output | `[]`
callback | [ ] | callable** | Custom handling behaviour | `None`
**Note**: *`query` must have `LIMIT {}` at the end, and the 4 parameters are `fields`, `table` (from `object_types`),
`args` (the search term), `limit` (the maximum number of terms)
**`callback` must be a function which accepts `args: str`(arguments passed in by the user, including search term),
`sf: simple_salesforce.api.Salesforce` (the Salesforce handler object, `self.sf`), `command: Dict[str, Any]`
(the command used from `commands`)
### Object Types
In `utils.py` the object types are stored in the dictionary `object_types`.
The name of each object type corresponds to the `object` referenced in `commands`.
Parameter | Required? | Type | Description
--------- | --------- | ---- | -----------
fields* | [x] | str | The Salesforce fields to fetch from the database.
name | [x] | str | The API name of the object**.
**Note**: * This must contain Name and Id, however Id is not displayed.
** Found in the salesforce object manager.
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/salesforce/doc.md | doc.md |
import logging
from typing import Dict
import requests
from requests.exceptions import ConnectionError
from zulip_bots.lib import BotHandler
help_message = """
You can add datapoints towards your beeminder goals \
following the syntax shown below :smile:.\n \
\n**@mention-botname daystamp, value, comment**\
\n* `daystamp`**:** *yyyymmdd* \
[**NOTE:** Optional field, default is *current daystamp*],\
\n* `value`**:** Enter a value [**NOTE:** Required field, can be any number],\
\n* `comment`**:** Add a comment [**NOTE:** Optional field, default is *None*]\
"""
def get_beeminder_response(message_content: str, config_info: Dict[str, str]) -> str:
username = config_info["username"]
goalname = config_info["goalname"]
auth_token = config_info["auth_token"]
message_content = message_content.strip()
if message_content == "" or message_content == "help":
return help_message
url = "https://www.beeminder.com/api/v1/users/{}/goals/{}/datapoints.json".format(
username, goalname
)
message_pieces = message_content.split(",")
for i in range(len(message_pieces)):
message_pieces[i] = message_pieces[i].strip()
if len(message_pieces) == 1:
payload = {"value": message_pieces[0], "auth_token": auth_token}
elif len(message_pieces) == 2:
if message_pieces[1].isdigit():
payload = {
"daystamp": message_pieces[0],
"value": message_pieces[1],
"auth_token": auth_token,
}
else:
payload = {
"value": message_pieces[0],
"comment": message_pieces[1],
"auth_token": auth_token,
}
elif len(message_pieces) == 3:
payload = {
"daystamp": message_pieces[0],
"value": message_pieces[1],
"comment": message_pieces[2],
"auth_token": auth_token,
}
elif len(message_pieces) > 3:
return "Make sure you follow the syntax.\n You can take a look \
at syntax by: @mention-botname help"
try:
r = requests.post(url, json=payload)
if r.status_code != 200:
if r.status_code == 401: # Handles case of invalid key and missing key
return "Error. Check your key!"
else:
return "Error occured : {}".format(
r.status_code
) # Occures in case of unprocessable entity
else:
datapoint_link = f"https://www.beeminder.com/{username}/{goalname}"
return "[Datapoint]({}) created.".format(
datapoint_link
) # Handles the case of successful datapoint creation
except ConnectionError as e:
logging.exception(str(e))
return "Uh-Oh, couldn't process the request \
right now.\nPlease try again later"
class BeeminderHandler:
"""
This plugin allows users to easily add datapoints
towards their beeminder goals via zulip
"""
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("beeminder")
# Check for valid auth_token
auth_token = self.config_info["auth_token"]
try:
r = requests.get(
"https://www.beeminder.com/api/v1/users/me.json", params={"auth_token": auth_token}
)
if r.status_code == 401:
bot_handler.quit("Invalid key!")
except ConnectionError as e:
logging.exception(str(e))
def usage(self) -> str:
return "This plugin allows users to add datapoints towards their Beeminder goals"
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
response = get_beeminder_response(message["content"], self.config_info)
bot_handler.send_reply(message, response)
handler_class = BeeminderHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/beeminder/beeminder.py | beeminder.py |
# Beeminder bot
The Beeminder bot can help you adding datapoints towards
your Beeminder goal from Zulip.
To use the Beeminder bot, you can simply call it with `@beeminder`
followed by a daystamp, value and an optional comment.
Syntax is like:
```
@beeminder daystamp, value, comment
```
**NOTE** : **Commas** between inputs are a must, otherwise,
you'll get an error.
## Setup and Configuration
Before running Beeminder bot you will need three things as follows :
1. **auth_token**
- Go to your [Beeminder](https://www.beeminder.com/) **account settings**.
Under **APPS & API** section you will find your **auth token**.
2. **username**
- Your Beeminder username.
3. **Goalname**
- The name of your Beeminder goal for which you want to
add datapoints from [Zulip](https://zulip.com/)
Once you have above information, you should supply
them in `beeminder.conf` file.
Run this bot as described in
[here](https://zulip.com/api/running-bots#running-a-bot).
## Usage
You can give command to add datapoint in 4 ways:
1. `@beeminder daystamp, value, comment`
- Example usage: `@beeminder 20180125, 15, Adding datapoint`.
- This will add a datapoint to your Beeminder goal having
**daystamp**: `20180125`, **value**: `15` with
**comment**: `Adding datapoint`.
2. `@beeminder daystamp, value`
- Example usage: `@beeminder 20180125, 15`.
- This will add a datapoint in your Beeminder goal having
**daystamp**: `20180125`, **value**: `15` and **comment**: `None`.
3. `@beeminder value, comment`
- Example usage: `@beeminder 15, Adding datapoint`.
- This will add a datapoint in your Beeminder goal having
**daystamp**: `current daystamp`, **value**: `15` and **comment**: `Adding datapoint`.
4. `@beeminder value`
- Example usage: `@beeminder 15`.
- This will add a datapoint in your Beeminder goal having
**daystamp**: `current daystamp`, **value**: `15` and **comment**: `None`.
5. `@beeminder ` or `@beeminder help` will fetch you the `help message`.
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/beeminder/doc.md | doc.md |
from typing import Any, Dict
import requests
from zulip_bots.lib import BotHandler
api_url = "http://api.openweathermap.org/data/2.5/weather"
class WeatherHandler:
def initialize(self, bot_handler: BotHandler) -> None:
self.api_key = bot_handler.get_config_info("weather")["key"]
self.response_pattern = "Weather in {}, {}:\n{:.2f} F / {:.2f} C\n{}"
self.check_api_key(bot_handler)
def check_api_key(self, bot_handler: BotHandler) -> None:
api_params = dict(q="nyc", APPID=self.api_key)
test_response = requests.get(api_url, params=api_params)
try:
test_response_data = test_response.json()
if test_response_data["cod"] == 401:
bot_handler.quit("API Key not valid. Please see doc.md to find out how to get it.")
except KeyError:
pass
def usage(self) -> str:
return """
This plugin will give info about weather in a specified city
"""
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
help_content = """
This bot returns weather info for specified city.
You specify city in the following format:
city, state/country
state and country parameter is optional(useful when there are many cities with the same name)
For example:
@**Weather Bot** Portland
@**Weather Bot** Portland, Me
""".strip()
if (message["content"] == "help") or (message["content"] == ""):
response = help_content
else:
api_params = dict(q=message["content"], APPID=self.api_key)
r = requests.get(api_url, params=api_params)
if r.json()["cod"] == "404":
response = "Sorry, city not found"
else:
response = format_response(r, message["content"], self.response_pattern)
bot_handler.send_reply(message, response)
def format_response(text: Any, city: str, response_pattern: str) -> str:
j = text.json()
city = j["name"]
country = j["sys"]["country"]
fahrenheit = to_fahrenheit(j["main"]["temp"])
celsius = to_celsius(j["main"]["temp"])
description = j["weather"][0]["description"].title()
return response_pattern.format(city, country, fahrenheit, celsius, description)
def to_celsius(temp_kelvin: float) -> float:
return int(temp_kelvin) - 273.15
def to_fahrenheit(temp_kelvin: float) -> float:
return int(temp_kelvin) * (9.0 / 5.0) - 459.67
handler_class = WeatherHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/weather/weather.py | weather.py |
# WeatherBot
* This is a bot that sends weather information to a selected stream on
request.
* Weather information is brought to the website using an
OpenWeatherMap API. The bot posts the weather information to the
stream from which the user inputs the message. If the user inputs a
city that does not exist, the bot displays a "Sorry, city not found"
message.
* Before using this bot, you have to generate an OpenWeatherMap API
key and replace the dummy value in weather.conf.


| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/weather/doc.md | doc.md |
import logging
from typing import Dict, Union
import requests
from requests.exceptions import ConnectionError, HTTPError
from zulip_bots.custom_exceptions import ConfigValidationError
from zulip_bots.lib import BotHandler
GIPHY_TRANSLATE_API = "http://api.giphy.com/v1/gifs/translate"
GIPHY_RANDOM_API = "http://api.giphy.com/v1/gifs/random"
class GiphyHandler:
"""
This plugin posts a GIF in response to the keywords provided by the user.
Images are provided by Giphy, through the public API.
The bot looks for messages starting with @mention of the bot
and responds with a message with the GIF based on provided keywords.
It also responds to private messages.
"""
def usage(self) -> str:
return """
This plugin allows users to post GIFs provided by Giphy.
Users should preface keywords with the Giphy-bot @mention.
The bot responds also to private messages.
"""
@staticmethod
def validate_config(config_info: Dict[str, str]) -> None:
query = {"s": "Hello", "api_key": config_info["key"]}
try:
data = requests.get(GIPHY_TRANSLATE_API, params=query)
data.raise_for_status()
except ConnectionError as e:
raise ConfigValidationError(str(e))
except HTTPError as e:
error_message = str(e)
if data.status_code == 403:
error_message += (
"This is likely due to an invalid key.\n"
"Follow the instructions in doc.md for setting an API key."
)
raise ConfigValidationError(error_message)
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("giphy")
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
bot_response = get_bot_giphy_response(message, bot_handler, self.config_info)
bot_handler.send_reply(message, bot_response)
class GiphyNoResultException(Exception):
pass
def get_url_gif_giphy(keyword: str, api_key: str) -> Union[int, str]:
# Return a URL for a Giphy GIF based on keywords given.
# In case of error, e.g. failure to fetch a GIF URL, it will
# return a number.
query = {"api_key": api_key}
if len(keyword) > 0:
query["s"] = keyword
url = GIPHY_TRANSLATE_API
else:
url = GIPHY_RANDOM_API
try:
data = requests.get(url, params=query)
except requests.exceptions.ConnectionError: # Usually triggered by bad connection.
logging.exception("Bad connection")
raise
data.raise_for_status()
try:
gif_url = data.json()["data"]["images"]["original"]["url"]
except (TypeError, KeyError): # Usually triggered by no result in Giphy.
raise GiphyNoResultException()
return gif_url
def get_bot_giphy_response(
message: Dict[str, str], bot_handler: BotHandler, config_info: Dict[str, str]
) -> str:
# Each exception has a specific reply should "gif_url" return a number.
# The bot will post the appropriate message for the error.
keyword = message["content"]
try:
gif_url = get_url_gif_giphy(keyword, config_info["key"])
except requests.exceptions.ConnectionError:
return (
"Uh oh, sorry :slightly_frowning_face:, I "
"cannot process your request right now. But, "
"let's try again later! :grin:"
)
except GiphyNoResultException:
return 'Sorry, I don\'t have a GIF for "%s"! ' ":astonished:" % (keyword,)
return (
"[Click to enlarge](%s)"
"[](/static/images/interactive-bot/giphy/powered-by-giphy.png)" % (gif_url,)
)
handler_class = GiphyHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/giphy/giphy.py | giphy.py |
# GIPHY bot
The GIPHY bot is a Zulip bot that can fetch a GIF associated with
a given keyword from [GIPHY](https://giphy.com/).
To use the GIPHY bot, you can simply call it with `@Giphy` followed
by a keyword, like so:
```
@Giphy hello
```
## Setup
Before you can proceed further, you'll need to go to the
[GIPHY Developers](https://developers.giphy.com/), and get a
GIPHY API key.
1. Click on the **Create an App** button on the top right corner.
2. Click on **Create an App** under the **Your Apps** section.
3. Enter a name and a description for your app and click on
**Create New App**.
4. And you're done! You should now have a GIPHY API key.
5. Open up `zulip_bots/bots/giphy/giphy.conf` in an editor and
and change the value of the `key` attribute to the API key
you generated above.
Run this bot as described in [here](https://zulip.com/api/running-bots#running-a-bot).
## Usage
1. `@Giphy <keyword` - This command will fetch a GIF associated
with the given keyword. Example usage: `@Giphy hello`:

2. If a GIF can't be found for a given keyword, the bot will
respond with an error message:

3. If there's a connection error, the bot will respond with an
error message:

| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/giphy/doc.md | doc.md |
import logging
from typing import Dict, List
import requests
from bs4 import BeautifulSoup
from zulip_bots.lib import BotHandler
def google_search(keywords: str) -> List[Dict[str, str]]:
query = {"q": keywords}
# Gets the page
page = requests.get("http://www.google.com/search", params=query)
# Parses the page into BeautifulSoup
soup = BeautifulSoup(page.text, "lxml")
# Gets all search URLs
anchors = soup.find(id="search").findAll("a")
results = []
for a in anchors:
try:
# Tries to get the href property of the URL
link = a["href"]
except KeyError:
continue
# Link must start with '/url?', as these are the search result links
if not link.startswith("/url?"):
continue
# Makes sure a hidden 'cached' result isn't displayed
if a.text.strip() == "Cached" and "webcache.googleusercontent.com" in a["href"]:
continue
# a.text: The name of the page
result = {"url": f"https://www.google.com{link}", "name": a.text}
results.append(result)
return results
def get_google_result(search_keywords: str) -> str:
help_message = "To use this bot, start messages with @mentioned-bot, \
followed by what you want to search for. If \
found, Zulip will return the first search result \
on Google.\
\
An example message that could be sent is:\
'@mentioned-bot zulip' or \
'@mentioned-bot how to create a chatbot'."
search_keywords = search_keywords.strip()
if search_keywords == "help":
return help_message
elif search_keywords == "" or search_keywords is None:
return help_message
else:
try:
results = google_search(search_keywords)
if len(results) == 0:
return "Found no results."
return "Found Result: [{}]({})".format(results[0]["name"], results[0]["url"])
except Exception as e:
logging.exception(str(e))
return f"Error: Search failed. {e}."
class GoogleSearchHandler:
"""
This plugin allows users to enter a search
term in Zulip and get the top URL sent back
to the context (stream or private) in which
it was called. It looks for messages starting
with @mentioned-bot.
"""
def usage(self) -> str:
return """
This plugin will allow users to search
for a given search term on Google from
Zulip. Use '@mentioned-bot help' to get
more information on the bot usage. Users
should preface messages with
@mentioned-bot.
"""
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
original_content = message["content"]
result = get_google_result(original_content)
bot_handler.send_reply(message, result)
handler_class = GoogleSearchHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/google_search/google_search.py | google_search.py |
# Google Search bot
This bot allows users to do Google search queries and have the bot
respond with the first search result. It is by default set to the
highest safe-search setting.
## Usage
Run this bot as described
[here](https://zulip.com/api/running-bots#running-a-bot).
Use this bot with the following command
`@mentioned-bot <search terms>`
This will return the first link found by Google for `<search terms>`
and print the resulting URL.
If no `<search terms>` are entered, a help message is printed instead.
If there was an error in the process of running the search (socket
errors, Google search function failed, or general failures), an error
message is returned.
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/google_search/doc.md | doc.md |
import logging
import re
from typing import Any, Dict, Tuple, Union
import requests
from zulip_bots.lib import BotHandler
class GithubHandler:
"""
This bot provides details on github issues and pull requests when they're
referenced in the chat.
"""
GITHUB_ISSUE_URL_TEMPLATE = "https://api.github.com/repos/{owner}/{repo}/issues/{id}"
HANDLE_MESSAGE_REGEX = re.compile(r"(?:([\w-]+)\/)?([\w-]+)?#(\d+)")
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("github_detail", optional=True)
self.owner = self.config_info.get("owner", False)
self.repo = self.config_info.get("repo", False)
def usage(self) -> str:
return (
"This plugin displays details on github issues and pull requests. "
"To reference an issue or pull request usename mention the bot then "
"anytime in the message type its id, for example:\n"
"@**Github detail** #3212 zulip#3212 zulip/zulip#3212\n"
"The default owner is {} and the default repo is {}.".format(self.owner, self.repo)
)
def format_message(self, details: Dict[str, Any]) -> str:
number = details["number"]
title = details["title"]
link = details["html_url"]
author = details["user"]["login"]
owner = details["owner"]
repo = details["repo"]
description = details["body"]
status = details["state"].title()
message_string = (
f"**[{owner}/{repo}#{number}]",
f"({link}) - {title}**\n",
"Created by **[{author}](https://github.com/{author})**\n".format(author=author),
"Status - **{status}**\n```quote\n{description}\n```".format(
status=status, description=description
),
)
return "".join(message_string)
def get_details_from_github(
self, owner: str, repo: str, number: str
) -> Union[None, Dict[str, Union[str, int, bool]]]:
# Gets the details of an issues or pull request
try:
r = requests.get(
self.GITHUB_ISSUE_URL_TEMPLATE.format(owner=owner, repo=repo, id=number)
)
except requests.exceptions.RequestException as e:
logging.exception(str(e))
return None
if r.status_code != requests.codes.ok:
return None
return r.json()
def get_owner_and_repo(self, issue_pr: Any) -> Tuple[str, str]:
owner = issue_pr.group(1)
repo = issue_pr.group(2)
if owner is None:
owner = self.owner
if repo is None:
repo = self.repo
return (owner, repo)
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
# Send help message
if message["content"] == "help":
bot_handler.send_reply(message, self.usage())
return
# Capture owner, repo, id
issue_prs = list(re.finditer(self.HANDLE_MESSAGE_REGEX, message["content"]))
bot_messages = []
if len(issue_prs) > 5:
# We limit to 5 requests to prevent denial-of-service
bot_message = "Please ask for <=5 links in any one request"
bot_handler.send_reply(message, bot_message)
return
for issue_pr in issue_prs:
owner, repo = self.get_owner_and_repo(issue_pr)
if owner and repo:
details = self.get_details_from_github(owner, repo, issue_pr.group(3))
if details is not None:
details["owner"] = owner
details["repo"] = repo
bot_messages.append(self.format_message(details))
else:
bot_messages.append(
"Failed to find issue/pr: {owner}/{repo}#{id}".format(
owner=owner, repo=repo, id=issue_pr.group(3)
)
)
else:
bot_messages.append("Failed to detect owner and repository name.")
if len(bot_messages) == 0:
bot_messages.append("Failed to find any issue or PR.")
bot_message = "\n".join(bot_messages)
bot_handler.send_reply(message, bot_message)
handler_class = GithubHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/github_detail/github_detail.py | github_detail.py |
This bot links and details issues and pull requests.
To use it @-mention the bot then type an id:
Ids can be specified in three different forms:
- Id only: `#2000`
- Repository and id: `zulip#2000`
- Owner, repository and id `zulip/zulip#2000`
The id can occur at any time in the message. You
can also mention multiple ids in a single message. For example:
`@**GitHub Detail Bot** find me #5176 and zulip/zulip#4534 .`
You can configure a default owner and repository.
The configuration file should be located at `api/bots/github_detail/github_detail.conf`.
It should look like this:
```ini
[github_detail]
owner = <repository owner>
repo = <repository name>
```
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/github_detail/doc.md | doc.md |
from typing import Any, Dict, List
import requests
from zulip_bots.lib import BotHandler
class BaremetricsHandler:
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("baremetrics")
self.api_key = self.config_info["api_key"]
self.auth_header = {"Authorization": "Bearer " + self.api_key}
self.commands = [
"help",
"list-commands",
"account-info",
"list-sources",
"list-plans <source_id>",
"list-customers <source_id>",
"list-subscriptions <source_id>",
"create-plan <source_id> <oid> <name> <currency> <amount> <interval> <interval_count>",
]
self.descriptions = [
"Display bot info",
"Display the list of available commands",
"Display the account info",
"List the sources",
"List the plans for the source",
"List the customers in the source",
"List the subscriptions in the source",
"Create a plan in the given source",
]
self.check_api_key(bot_handler)
def check_api_key(self, bot_handler: BotHandler) -> None:
url = "https://api.baremetrics.com/v1/account"
test_query_response = requests.get(url, headers=self.auth_header)
test_query_data = test_query_response.json()
try:
if test_query_data["error"] == "Unauthorized. Token not found (001)":
bot_handler.quit("API Key not valid. Please see doc.md to find out how to get it.")
except KeyError:
pass
def usage(self) -> str:
return """
This bot gives updates about customer behavior, financial performance, and analytics
for an organization using the Baremetrics Api.\n
Enter `list-commands` to show the list of available commands.
Version 1.0
"""
def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> None:
content = message["content"].strip().split()
if content == []:
bot_handler.send_reply(message, "No Command Specified")
return
content[0] = content[0].lower()
if content == ["help"]:
bot_handler.send_reply(message, self.usage())
return
if content == ["list-commands"]:
response = "**Available Commands:** \n"
for command, description in zip(self.commands, self.descriptions):
response += f" - {command} : {description}\n"
bot_handler.send_reply(message, response)
return
response = self.generate_response(content)
bot_handler.send_reply(message, response)
def generate_response(self, commands: List[str]) -> str:
try:
instruction = commands[0]
if instruction == "account-info":
return self.get_account_info()
if instruction == "list-sources":
return self.get_sources()
try:
if instruction == "list-plans":
return self.get_plans(commands[1])
if instruction == "list-customers":
return self.get_customers(commands[1])
if instruction == "list-subscriptions":
return self.get_subscriptions(commands[1])
if instruction == "create-plan":
if len(commands) == 8:
return self.create_plan(commands[1:])
else:
return "Invalid number of arguments."
except IndexError:
return "Missing Params."
except KeyError:
return "Invalid Response From API."
return "Invalid Command."
def get_account_info(self) -> str:
url = "https://api.baremetrics.com/v1/account"
account_response = requests.get(url, headers=self.auth_header)
account_data = account_response.json()
account_data = account_data["account"]
template = [
"**Your account information:**",
"Id: {id}",
"Company: {company}",
"Default Currency: {currency}",
]
return "\n".join(template).format(
currency=account_data["default_currency"]["name"], **account_data
)
def get_sources(self) -> str:
url = "https://api.baremetrics.com/v1/sources"
sources_response = requests.get(url, headers=self.auth_header)
sources_data = sources_response.json()
sources_data = sources_data["sources"]
response = "**Listing sources:** \n"
for index, source in enumerate(sources_data):
response += (
"{_count}.ID: {id}\n" "Provider: {provider}\n" "Provider ID: {provider_id}\n\n"
).format(_count=index + 1, **source)
return response
def get_plans(self, source_id: str) -> str:
url = f"https://api.baremetrics.com/v1/{source_id}/plans"
plans_response = requests.get(url, headers=self.auth_header)
plans_data = plans_response.json()
plans_data = plans_data["plans"]
template = "\n".join(
[
"{_count}.Name: {name}",
"Active: {active}",
"Interval: {interval}",
"Interval Count: {interval_count}",
"Amounts:",
]
)
response = ["**Listing plans:**"]
for index, plan in enumerate(plans_data):
response += (
[template.format(_count=index + 1, **plan)]
+ [" - {amount} {currency}".format(**amount) for amount in plan["amounts"]]
+ [""]
)
return "\n".join(response)
def get_customers(self, source_id: str) -> str:
url = f"https://api.baremetrics.com/v1/{source_id}/customers"
customers_response = requests.get(url, headers=self.auth_header)
customers_data = customers_response.json()
customers_data = customers_data["customers"]
# FIXME BUG here? mismatch of name and display name?
template = "\n".join(
[
"{_count}.Name: {display_name}",
"Display Name: {name}",
"OID: {oid}",
"Active: {is_active}",
"Email: {email}",
"Notes: {notes}",
"Current Plans:",
]
)
response = ["**Listing customers:**"]
for index, customer in enumerate(customers_data):
response += (
[template.format(_count=index + 1, **customer)]
+ [" - {name}".format(**plan) for plan in customer["current_plans"]]
+ [""]
)
return "\n".join(response)
def get_subscriptions(self, source_id: str) -> str:
url = f"https://api.baremetrics.com/v1/{source_id}/subscriptions"
subscriptions_response = requests.get(url, headers=self.auth_header)
subscriptions_data = subscriptions_response.json()
subscriptions_data = subscriptions_data["subscriptions"]
template = "\n".join(
[
"{_count}.Customer Name: {name}",
"Customer Display Name: {display_name}",
"Customer OID: {oid}",
"Customer Email: {email}",
"Active: {_active}",
"Plan Name: {_plan_name}",
"Plan Amounts:",
]
)
response = ["**Listing subscriptions:**"]
for index, subscription in enumerate(subscriptions_data):
response += (
[
template.format(
_count=index + 1,
_active=subscription["active"],
_plan_name=subscription["plan"]["name"],
**subscription["customer"],
)
]
+ [
" - {amount} {symbol}".format(**amount)
for amount in subscription["plan"]["amounts"]
]
+ [""]
)
return "\n".join(response)
def create_plan(self, parameters: List[str]) -> str:
data_header = {
"oid": parameters[1],
"name": parameters[2],
"currency": parameters[3],
"amount": int(parameters[4]),
"interval": parameters[5],
"interval_count": int(parameters[6]),
} # type: Any
url = f"https://api.baremetrics.com/v1/{parameters[0]}/plans"
create_plan_response = requests.post(url, data=data_header, headers=self.auth_header)
if "error" not in create_plan_response.json():
return "Plan Created."
else:
return "Invalid Arguments Error."
handler_class = BaremetricsHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/baremetrics/baremetrics.py | baremetrics.py |
# Baremetrics bot
The Baremetrics bot is a Zulip bot that gives updates about customer behavior, financial performance, and
analytics for an organization using the [Baremetrics](https://baremetrics.com/) API.
To use the Baremetrics bot, you can simply call it with `@<botname>` followed
by a command, like so:
```
@Baremetrics help
```
## Setup
Before usage, you will need to configure the bot by putting the value of the `<api_key>` in the config file.
To do this, follow the given steps:
1. Login at [Baremetrics Console](https://app.baremetrics.com/settings/api).
2. Note the `Live API Key`.
3. Open up `zulip_bots/bots/baremetrics/baremetrics.conf` in an editor and
change the value of the `<api_key>` attribute to the noted `Live API Key`.
## Developer Notes
Be sure to add the command and its description to their respective lists (named `commands` and `descriptions`)
so that it can be displayed with the other available commands using `@<botname> list-commands`. Also modify
the `test_list_commands_command` in `test_baremetrics.py`.
## Links
- [Baremetrics](https://baremetrics.com/)
- [Baremetrics Developer API](https://developers.baremetrics.com/reference)
- [Baremetrics Dashboard](https://app.baremetrics.com/setup)
## Usage
`@Baremetrics list-commands` - This command gives a list of all available commands along with short
short descriptions.
Example:

| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/baremetrics/doc.md | doc.md |
from typing import Any, Dict, List
import requests
from zulip_bots.lib import BotHandler
class MentionHandler:
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("mention")
self.access_token = self.config_info["access_token"]
self.account_id = ""
self.check_access_token(bot_handler)
def check_access_token(self, bot_handler: BotHandler) -> None:
test_query_header = {
"Authorization": "Bearer " + self.access_token,
"Accept-Version": "1.15",
}
test_query_response = requests.get(
"https://api.mention.net/api/accounts/me", headers=test_query_header
)
try:
test_query_data = test_query_response.json()
if (
test_query_data["error"] == "invalid_grant"
and test_query_data["error_description"] == "The access token provided is invalid."
):
bot_handler.quit(
"Access Token Invalid. Please see doc.md to find out how to get it."
)
except KeyError:
pass
def usage(self) -> str:
return """
This is a Mention API Bot which will find mentions
of the given keyword throughout the web.
Version 1.00
"""
def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> None:
message["content"] = message["content"].strip()
if message["content"].lower() == "help":
bot_handler.send_reply(message, self.usage())
return
if message["content"] == "":
bot_handler.send_reply(message, "Empty Mention Query")
return
keyword = message["content"]
content = self.generate_response(keyword)
bot_handler.send_reply(message, content)
def get_account_id(self) -> str:
get_ac_id_header = {
"Authorization": "Bearer " + self.access_token,
"Accept-Version": "1.15",
}
response = requests.get("https://api.mention.net/api/accounts/me", headers=get_ac_id_header)
data_json = response.json()
account_id = data_json["account"]["id"]
return account_id
def get_alert_id(self, keyword: str) -> str:
create_alert_header = {
"Authorization": "Bearer " + self.access_token,
"Content-Type": "application/json",
"Accept-Version": "1.15",
}
create_alert_data = {
"name": keyword,
"query": {"type": "basic", "included_keywords": [keyword]},
"languages": ["en"],
"sources": ["web"],
} # type: Any
response = requests.post(
"https://api.mention.net/api/accounts/" + self.account_id + "/alerts",
data=create_alert_data,
headers=create_alert_header,
)
data_json = response.json()
alert_id = data_json["alert"]["id"]
return alert_id
def get_mentions(self, alert_id: str) -> List[Any]:
get_mentions_header = {
"Authorization": "Bearer " + self.access_token,
"Accept-Version": "1.15",
}
response = requests.get(
"https://api.mention.net/api/accounts/"
+ self.account_id
+ "/alerts/"
+ alert_id
+ "/mentions",
headers=get_mentions_header,
)
data_json = response.json()
mentions = data_json["mentions"]
return mentions
def generate_response(self, keyword: str) -> str:
if self.account_id == "":
self.account_id = self.get_account_id()
try:
alert_id = self.get_alert_id(keyword)
except (TypeError, KeyError):
# Usually triggered by invalid token or json parse error when account quote is finished.
raise MentionNoResponseException()
try:
mentions = self.get_mentions(alert_id)
except (TypeError, KeyError):
# Usually triggered by no response or json parse error when account quota is finished.
raise MentionNoResponseException()
reply = "The most recent mentions of `" + keyword + "` on the web are: \n"
for mention in mentions:
reply += "[{title}]({id})\n".format(title=mention["title"], id=mention["original_url"])
return reply
handler_class = MentionHandler
class MentionNoResponseException(Exception):
pass | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/mention/mention.py | mention.py |
# Mention bot
The Mention bot is a Zulip bot that can fetch Mentions associated with
a given keyword from the web using [Mention](https://mention.com/en/).
To use the Mention bot, you can simply call it with `@<botname>` followed
by a keyword, like so:
```
@Mention Apple
```
## Setup
Before you can proceed further, you'll need to go to the
[Mention Dev](https://dev.mention.com/login), and get a
Mention API Access Token.
1. Login.
2. Enter the **App Name**, **Description**, **Website**, and **Redirect uris**. In this version, there
is no actual use of the Redirect Uri and Website.
3. After accepting the agreement, click on **Create New App**.
4. And you're done! You should now have an Access Token.
5. Open up `zulip_bots/bots/mention/mention.conf` in an editor and
change the value of the `<access_token>` attribute to the Access Token
you generated above.
## Usage
`@Mention <keyword>` - This command will fetch the most recent 20
mentions of the keyword on the web (Limitations of a free account).
Example:

| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/mention/doc.md | doc.md |
import logging
from typing import Dict
import requests
from zulip_bots.lib import BotHandler
# See readme.md for instructions on running this code.
class WikipediaHandler:
"""
This plugin facilitates searching Wikipedia for a
specific key term and returns the top 3 articles from the
search. It looks for messages starting with '@mention-bot'
In this example, we write all Wikipedia searches into
the same stream that it was called from, but this code
could be adapted to write Wikipedia searches to some
kind of external issue tracker as well.
"""
META = {
"name": "Wikipedia",
"description": "Searches Wikipedia for a term and returns the top 3 articles.",
}
def usage(self) -> str:
return """
This plugin will allow users to directly search
Wikipedia for a specific key term and get the top 3
articles that is returned from the search. Users
should preface searches with "@mention-bot".
@mention-bot <name of article>"""
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
bot_response = self.get_bot_wiki_response(message, bot_handler)
bot_handler.send_reply(message, bot_response)
def get_bot_wiki_response(self, message: Dict[str, str], bot_handler: BotHandler) -> str:
"""This function returns the URLs of the requested topic."""
help_text = "Please enter your search term after {}"
# Checking if the link exists.
query = message["content"]
if query == "":
return help_text.format(bot_handler.identity().mention)
query_wiki_url = "https://en.wikipedia.org/w/api.php"
query_wiki_params = dict(action="query", list="search", srsearch=query, format="json")
try:
data = requests.get(query_wiki_url, params=query_wiki_params)
except requests.exceptions.RequestException:
logging.error("broken link")
return (
"Uh-Oh ! Sorry ,couldn't process the request right now.:slightly_frowning_face:\n"
"Please try again later."
)
# Checking if the bot accessed the link.
if data.status_code != 200:
logging.error("Page not found.")
return (
"Uh-Oh ! Sorry ,couldn't process the request right now.:slightly_frowning_face:\n"
"Please try again later."
)
new_content = "For search term:" + query + "\n"
# Checking if there is content for the searched term
if len(data.json()["query"]["search"]) == 0:
new_content = (
"I am sorry. The search term you provided is not found :slightly_frowning_face:"
)
else:
for i in range(min(3, len(data.json()["query"]["search"]))):
search_string = data.json()["query"]["search"][i]["title"].replace(" ", "_")
url = "https://en.wikipedia.org/wiki/" + search_string
new_content += (
str(i + 1)
+ ":"
+ "["
+ search_string
+ "]"
+ "("
+ url.replace('"', "%22")
+ ")\n"
)
return new_content
handler_class = WikipediaHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/wikipedia/wikipedia.py | wikipedia.py |
# Wikipedia Bot
The Wikipedia bot is a Zulip bot that will search Wikipedia
for a provided keyword, and fetch a link to the associated
Wikipedia article. The link is returned to the same stream
it was @mentioned in
The Wikipedia bot uses the
[MediaWiki API](https://www.mediawiki.org/wiki/API:Main_page)
to obtain the search results it returns
Using the Wikipedia bot is as simple as mentioning @\<wikipedia-bot-name\>,
followed by the keyword:
```
@<wikipedia-bot-name> <keyword>
```
## Setup
Beyond the typical obtaining of the zuliprc file, no extra setup is required to use the Wikipedia Bot
## Usage
1. ```@<wikipedia-bot-name> <keyword>``` -
fetches the link to the appropriate Wikipedia article.
* For example, `@<wikipedia-bot-name> Zulip`
will return the link `https://en.wikipedia.org/wiki/Zulip`
<br>
2. If the keyword does not return an article link,
the bot will respond with an error message:
`I am sorry. The search term you provided is not found`
<br>
3. If no keyword is provided, the bot will return the help text:
```Please enter your message after @mention-bot```
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/wikipedia/doc.md | doc.md |
# File Uploader Bot
This bot allows the user to upload a file with a given path to the Zulip server.
## Usage
Use this bot with any of the following commands:
- `@uploader <local_file_path>` : Upload a file, where `<local_file_path>` is the path to the file
- `@uploader help` : Display help message
### Usage examples
The following command will upload the file `/tmp/image.png` to the Zulip server:
```
@**uploader** /tmp/image.png
```
Here's an example response:
> [image.png](https://server.zulipchat.com/user_uploads/3787/RgoZReSsfMjlQSzvVxjIgAQy/image.png)
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/file_uploader/doc.md | doc.md |
import re
from typing import Any, Dict, List, Tuple
from dropbox import Dropbox
from zulip_bots.lib import BotHandler
URL = "[{name}](https://www.dropbox.com/home{path})"
class DropboxHandler:
"""
This bot allows you to easily share, search and upload files
between zulip and your dropbox account.
"""
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("dropbox_share")
self.ACCESS_TOKEN = self.config_info.get("access_token")
self.client = Dropbox(self.ACCESS_TOKEN)
def usage(self) -> str:
return get_help()
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
command = message["content"]
if command == "":
command = "help"
msg = dbx_command(self.client, command)
bot_handler.send_reply(message, msg)
def get_help() -> str:
return """
Example commands:
```
@mention-bot usage: see usage examples
@mention-bot mkdir: create a folder
@mention-bot ls: list a folder
@mention-bot write: write text
@mention-bot rm: remove a file or folder
@mention-bot read: read a file
@mention-bot search: search a file/folder
@mention-bot share: get a shareable link for the file/folder
```
"""
def get_usage_examples() -> str:
return """
Usage:
```
@dropbox ls - Shows files/folders in the root folder.
@dropbox mkdir foo - Make folder named foo.
@dropbox ls foo/boo - Shows the files/folders in foo/boo folder.
@dropbox write test hello world - Write "hello world" to the file 'test'.
@dropbox rm test - Remove the file/folder test.
@dropbox read foo - Read the contents of file/folder foo.
@dropbox share foo - Get shareable link for the file/folder foo.
@dropbox search boo - Search for boo in root folder and get at max 20 results.
@dropbox search boo --mr 10 - Search for boo and get at max 10 results.
@dropbox search boo --fd foo - Search for boo in folder foo.
```
"""
REGEXES = dict(
command="(ls|mkdir|read|rm|write|search|usage|help)",
path=r"(\S+)",
optional_path=r"(\S*)",
some_text="(.+?)",
folder=r"?(?:--fd (\S+))?",
max_results=r"?(?:--mr (\d+))?",
)
def get_commands() -> Dict[str, Tuple[Any, List[str]]]:
return {
"help": (dbx_help, ["command"]),
"ls": (dbx_ls, ["optional_path"]),
"mkdir": (dbx_mkdir, ["path"]),
"rm": (dbx_rm, ["path"]),
"write": (dbx_write, ["path", "some_text"]),
"read": (dbx_read, ["path"]),
"search": (dbx_search, ["some_text", "folder", "max_results"]),
"share": (dbx_share, ["path"]),
"usage": (dbx_usage, []),
}
def dbx_command(client: Any, cmd: str) -> str:
cmd = cmd.strip()
if cmd == "help":
return get_help()
cmd_name = cmd.split()[0]
cmd_args = cmd[len(cmd_name) :].strip()
commands = get_commands()
if cmd_name not in commands:
return "ERROR: unrecognized command\n" + get_help()
f, arg_names = commands[cmd_name]
partial_regexes = [REGEXES[a] for a in arg_names]
regex = " ".join(partial_regexes)
regex += "$"
m = re.match(regex, cmd_args)
if m:
return f(client, *m.groups())
else:
return "ERROR: " + syntax_help(cmd_name)
def syntax_help(cmd_name: str) -> str:
commands = get_commands()
f, arg_names = commands[cmd_name]
arg_syntax = " ".join("<" + a + ">" for a in arg_names)
if arg_syntax:
cmd = cmd_name + " " + arg_syntax
else:
cmd = cmd_name
return f"syntax: {cmd}"
def dbx_help(client: Any, cmd_name: str) -> str:
return syntax_help(cmd_name)
def dbx_usage(client: Any) -> str:
return get_usage_examples()
def dbx_mkdir(client: Any, fn: str) -> str:
fn = "/" + fn # foo/boo -> /foo/boo
try:
result = client.files_create_folder(fn)
msg = "CREATED FOLDER: " + URL.format(name=result.name, path=result.path_lower)
except Exception:
msg = (
"Please provide a correct folder path and name.\n"
"Usage: `mkdir <foldername>` to create a folder."
)
return msg
def dbx_ls(client: Any, fn: str) -> str:
if fn != "":
fn = "/" + fn
try:
result = client.files_list_folder(fn)
files_list = [] # type: List[str]
for meta in result.entries:
files_list += [" - " + URL.format(name=meta.name, path=meta.path_lower)]
msg = "\n".join(files_list)
if msg == "":
msg = "`No files available`"
except Exception:
msg = (
"Please provide a correct folder path\n"
"Usage: `ls <foldername>` to list folders in directory\n"
"or simply `ls` for listing folders in the root directory"
)
return msg
def dbx_rm(client: Any, fn: str) -> str:
fn = "/" + fn
try:
result = client.files_delete(fn)
msg = "DELETED File/Folder : " + URL.format(name=result.name, path=result.path_lower)
except Exception:
msg = (
"Please provide a correct folder path and name.\n"
"Usage: `rm <foldername>` to delete a folder in root directory."
)
return msg
def dbx_write(client: Any, fn: str, content: str) -> str:
fn = "/" + fn
try:
result = client.files_upload(content.encode(), fn)
msg = "Written to file: " + URL.format(name=result.name, path=result.path_lower)
except Exception:
msg = "Incorrect file path or file already exists.\nUsage: `write <filename> CONTENT`"
return msg
def dbx_read(client: Any, fn: str) -> str:
fn = "/" + fn
try:
result = client.files_download(fn)
msg = f"**{result[0].name}** :\n{result[1].text}"
except Exception:
msg = (
"Please provide a correct file path\nUsage: `read <filename>` to read content of a file"
)
return msg
def dbx_search(client: Any, query: str, folder: str, max_results: str) -> str:
if folder is None:
folder = ""
else:
folder = "/" + folder
if max_results is None:
max_results = "20"
try:
result = client.files_search(folder, query, max_results=int(max_results))
msg_list = []
count = 0
for entry in result.matches:
file_info = entry.metadata
count += 1
msg_list += [" - " + URL.format(name=file_info.name, path=file_info.path_lower)]
msg = "\n".join(msg_list)
except Exception:
msg = (
"Usage: `search <foldername> query --mr 10 --fd <folderName>`\n"
"Note:`--mr <int>` is optional and is used to specify maximun results.\n"
" `--fd <folderName>` to search in specific folder."
)
if msg == "":
msg = (
"No files/folders found matching your query.\n"
"For file name searching, the last token is used for prefix matching"
" (i.e. “bat c” matches “bat cave” but not “batman car”)."
)
return msg
def dbx_share(client: Any, fn: str):
fn = "/" + fn
try:
result = client.sharing_create_shared_link(fn)
msg = result.url
except Exception:
msg = "Please provide a correct file name.\nUsage: `share <filename>`"
return msg
handler_class = DropboxHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/dropbox_share/dropbox_share.py | dropbox_share.py |
# Dropbox Bot
This bot links your [dropbox](https://www.dropbox.com) account to [zulip](https://chat.zulip.org).
## Usage
- Create a dropbox app from [here](https://www.dropbox.com/developers/apps).
- Click the `generate` button under the **Generate access token** section.
- Copy the Access Token and paste it in a file named `dropbox_share.conf` as shown:
```
[dropbox_share]
ACCESS_TOKEN=<your_access_token>
```
- Follow the instructions as described in [here](https://zulip.com/api/running-bots#running-a-bot).
- Run the bot: `zulip-run-bot dropbox_share -b <Path/to/dropbox_share.conf> -c <Path/to/zuliprc>`
Use this bot with any of the following commands:
- `@dropbox mkdir` : Create a folder
- `@dropbox ls` : List contents of a folder
- `@dropbox write` : Save text to a file
- `@dropbox rm` : Remove a file/folder
- `@dropbox help` : See help text
- `@dropbox read`: Read contents of a file
- `@dropbox share`: Get a shareable link for a file/folder
- `@dropbox search`: Search for matching file/folder names
where `dropbox` may be the name of the bot you registered in the zulip system.
### Usage examples
- `dropbox ls -` Shows files/folders in the root folder.
- `dropbox mkdir foo` - Make folder named foo.
- `dropbox ls foo/boo` - Shows the files/folders in foo/boo folder.
- `dropbox write test hello world` - Write "hello world" to the file 'test'.
- `dropbox rm test` - Remove the file/folder test.
- `dropbox read foo` - Read the contents of file/folder foo.
- `dropbox share foo` - Get shareable link for the file/folder foo.
- `dropbox search boo` - Search for boo in root folder and get at max 20 results.
- `dropbox search boo --mr 10` - Search for boo and get at max 10 results.
- `dropbox search boo --fd foo` - Search for boo in folder foo.
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/dropbox_share/doc.md | doc.md |
import re
from typing import Any, Dict
import requests
from zulip_bots.lib import BotHandler
class LinkShortenerHandler:
"""A Zulip bot that will shorten URLs ("links") in a conversation using the
goo.gl URL shortener.
"""
def usage(self) -> str:
return (
"Mention the link shortener bot in a conversation and then enter "
"any URLs you want to shorten in the body of the message. \n\n"
"`key` must be set in `link_shortener.conf`."
)
def initialize(self, bot_handler: BotHandler) -> None:
self.config_info = bot_handler.get_config_info("link_shortener")
self.check_api_key(bot_handler)
def check_api_key(self, bot_handler: BotHandler) -> None:
test_request_data = self.call_link_shorten_service("www.youtube.com/watch") # type: Any
try:
if self.is_invalid_token_error(test_request_data):
bot_handler.quit(
"Invalid key. Follow the instructions in doc.md for setting API key."
)
except KeyError:
pass
def is_invalid_token_error(self, response_json: Any) -> bool:
return (
response_json["status_code"] == 500
and response_json["status_txt"] == "INVALID_ARG_ACCESS_TOKEN"
)
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
REGEX_STR = (
r"("
r"(?:http|https):\/\/" # This allows for the HTTP or HTTPS
# protocol.
r'[^"<>\{\}|\^~[\]` ]+' # This allows for any character except
# for certain non-URL-safe ones.
r")"
)
HELP_STR = (
"Mention the link shortener bot in a conversation and "
"then enter any URLs you want to shorten in the body of "
"the message."
)
content = message["content"]
if content.strip() == "help":
bot_handler.send_reply(message, HELP_STR)
return
link_matches = re.findall(REGEX_STR, content)
shortened_links = [self.shorten_link(link) for link in link_matches]
link_pairs = [
(link_match + ": " + shortened_link)
for link_match, shortened_link in zip(link_matches, shortened_links)
if shortened_link != ""
]
final_response = "\n".join(link_pairs)
if final_response == "":
bot_handler.send_reply(message, "No links found. " + HELP_STR)
return
bot_handler.send_reply(message, final_response)
def shorten_link(self, long_url: str) -> str:
"""Shortens a link using goo.gl Link Shortener and returns it, or
returns an empty string if something goes wrong.
Parameters:
long_url (str): The original URL to shorten.
"""
response_json = self.call_link_shorten_service(long_url)
if response_json["status_code"] == 200 and self.has_shorten_url(response_json):
shorten_url = self.get_shorten_url(response_json)
else:
shorten_url = ""
return shorten_url
def call_link_shorten_service(self, long_url: str) -> Any:
response = requests.get(
"https://api-ssl.bitly.com/v3/shorten",
params={"access_token": self.config_info["key"], "longUrl": long_url},
)
return response.json()
def has_shorten_url(self, response_json: Any) -> bool:
return "data" in response_json and "url" in response_json["data"]
def get_shorten_url(self, response_json: Any) -> str:
return response_json["data"]["url"]
handler_class = LinkShortenerHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/link_shortener/link_shortener.py | link_shortener.py |
# Link Shortener Bot
Link Shortener Bot is a Zulip bot that will shorten URLs ("links") in a
conversation. It uses the [bitly URL shortener API] to shorten its links.
Use [this](https://dev.bitly.com/get_started.html) to get your API Key.
Links can be anywhere in the message, for example,
> @**Link Shortener Bot** @**Joe Smith** See
> https://github.com/zulip/python-zulip-api/tree/master/zulip_bots/zulip_bots/bots
> for a list of all Zulip bots.
and LS Bot would respond
> https://github.com/zulip/python-zulip-api/tree/master/zulip_bots/zulip_bots/bots:
> **https://bit.ly/2FF3QHu**
[bitly URL shortener API]: https://bitly.com/
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/link_shortener/doc.md | doc.md |
import re
from typing import Any, Dict
import requests
from zulip_bots.lib import BotHandler
class FrontHandler:
FRONT_API = "https://api2.frontapp.com/conversations/{}"
COMMANDS = [
("archive", "Archive a conversation."),
("delete", "Delete a conversation."),
("spam", "Mark a conversation as spam."),
("open", "Restore a conversation."),
("comment <text>", "Leave a comment."),
]
CNV_ID_REGEXP = "cnv_(?P<id>[0-9a-z]+)"
COMMENT_PREFIX = "comment "
def usage(self) -> str:
return """
Front Bot uses the Front REST API to interact with Front. In order to use
Front Bot, `front.conf` must be set up. See `doc.md` for more details.
"""
def initialize(self, bot_handler: BotHandler) -> None:
config = bot_handler.get_config_info("front")
api_key = config.get("api_key")
if not api_key:
raise KeyError("No API key specified.")
self.auth = "Bearer " + api_key
def help(self, bot_handler: BotHandler) -> str:
response = ""
for command, description in self.COMMANDS:
response += f"`{command}` {description}\n"
return response
def archive(self, bot_handler: BotHandler) -> str:
response = requests.patch(
self.FRONT_API.format(self.conversation_id),
headers={"Authorization": self.auth},
json={"status": "archived"},
)
if response.status_code not in (200, 204):
return "Something went wrong."
return "Conversation was archived."
def delete(self, bot_handler: BotHandler) -> str:
response = requests.patch(
self.FRONT_API.format(self.conversation_id),
headers={"Authorization": self.auth},
json={"status": "deleted"},
)
if response.status_code not in (200, 204):
return "Something went wrong."
return "Conversation was deleted."
def spam(self, bot_handler: BotHandler) -> str:
response = requests.patch(
self.FRONT_API.format(self.conversation_id),
headers={"Authorization": self.auth},
json={"status": "spam"},
)
if response.status_code not in (200, 204):
return "Something went wrong."
return "Conversation was marked as spam."
def restore(self, bot_handler: BotHandler) -> str:
response = requests.patch(
self.FRONT_API.format(self.conversation_id),
headers={"Authorization": self.auth},
json={"status": "open"},
)
if response.status_code not in (200, 204):
return "Something went wrong."
return "Conversation was restored."
def comment(self, bot_handler: BotHandler, **kwargs: Any) -> str:
response = requests.post(
self.FRONT_API.format(self.conversation_id) + "/comments",
headers={"Authorization": self.auth},
json=kwargs,
)
if response.status_code not in (200, 201):
return "Something went wrong."
return "Comment was sent."
def handle_message(self, message: Dict[str, str], bot_handler: BotHandler) -> None:
command = message["content"]
result = re.search(self.CNV_ID_REGEXP, message["subject"])
if not result:
bot_handler.send_reply(
message,
"No coversation ID found. Please make "
"sure that the name of the topic "
"contains a valid coversation ID.",
)
return None
self.conversation_id = result.group()
if command == "help":
bot_handler.send_reply(message, self.help(bot_handler))
elif command == "archive":
bot_handler.send_reply(message, self.archive(bot_handler))
elif command == "delete":
bot_handler.send_reply(message, self.delete(bot_handler))
elif command == "spam":
bot_handler.send_reply(message, self.spam(bot_handler))
elif command == "open":
bot_handler.send_reply(message, self.restore(bot_handler))
elif command.startswith(self.COMMENT_PREFIX):
kwargs = {
"author_id": "alt:email:" + message["sender_email"],
"body": command[len(self.COMMENT_PREFIX) :],
}
bot_handler.send_reply(message, self.comment(bot_handler, **kwargs))
else:
bot_handler.send_reply(message, "Unknown command. Use `help` for instructions.")
handler_class = FrontHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/front/front.py | front.py |
import copy
import random
from typing import Any, List, Tuple
from zulip_bots.game_handler import BadMoveException, GameAdapter
# -------------------------------------
State = List[List[str]]
class TicTacToeModel:
smarter = True
# If smarter is True, the computer will do some extra thinking - it'll be harder for the user.
triplets = [
[(0, 0), (0, 1), (0, 2)], # Row 1
[(1, 0), (1, 1), (1, 2)], # Row 2
[(2, 0), (2, 1), (2, 2)], # Row 3
[(0, 0), (1, 0), (2, 0)], # Column 1
[(0, 1), (1, 1), (2, 1)], # Column 2
[(0, 2), (1, 2), (2, 2)], # Column 3
[(0, 0), (1, 1), (2, 2)], # Diagonal 1
[(0, 2), (1, 1), (2, 0)], # Diagonal 2
]
initial_board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
def __init__(self, board: Any = None) -> None:
if board is not None:
self.current_board = board
else:
self.current_board = copy.deepcopy(self.initial_board)
def get_value(self, board: Any, position: Tuple[int, int]) -> int:
return board[position[0]][position[1]]
def determine_game_over(self, players: List[str]) -> str:
if self.contains_winning_move(self.current_board):
return "current turn"
if self.board_is_full(self.current_board):
return "draw"
return ""
def board_is_full(self, board: Any) -> bool:
"""Determines if the board is full or not."""
for row in board:
for element in row:
if element == 0:
return False
return True
# Used for current board & trial computer board
def contains_winning_move(self, board: Any) -> bool:
"""Returns true if all coordinates in a triplet have the same value in them (x or o) and no coordinates
in the triplet are blank."""
for triplet in self.triplets:
if (
self.get_value(board, triplet[0])
== self.get_value(board, triplet[1])
== self.get_value(board, triplet[2])
!= 0
):
return True
return False
def get_locations_of_char(self, board: Any, char: int) -> List[List[int]]:
"""Gets the locations of the board that have char in them."""
locations = []
for row in range(3):
for col in range(3):
if board[row][col] == char:
locations.append([row, col])
return locations
def two_blanks(self, triplet: List[Tuple[int, int]], board: Any) -> List[Tuple[int, int]]:
"""Determines which rows/columns/diagonals have two blank spaces and an 2 already in them. It's more advantageous
for the computer to move there. This is used when the computer makes its move."""
o_found = False
for position in triplet:
if self.get_value(board, position) == 2:
o_found = True
break
blanks_list = []
if o_found:
for position in triplet:
if self.get_value(board, position) == 0:
blanks_list.append(position)
if len(blanks_list) == 2:
return blanks_list
return []
def computer_move(self, board: Any, player_number: Any) -> Any:
"""The computer's logic for making its move."""
my_board = copy.deepcopy(board) # First the board is copied; used later on
blank_locations = self.get_locations_of_char(my_board, 0)
# Gets the locations that already have x's
x_locations = self.get_locations_of_char(board, 1)
# List of the coordinates of the corners of the board
corner_locations = [[0, 0], [0, 2], [2, 0], [2, 2]]
# List of the coordinates of the edge spaces of the board
edge_locations = [[1, 0], [0, 1], [1, 2], [2, 1]]
# If no empty spaces are left, the computer can't move anyway, so it just returns the board.
if blank_locations == []:
return board
# This is special logic only used on the first move.
if len(x_locations) == 1:
# If the user played first in the corner or edge,
# the computer should move in the center.
if x_locations[0] in corner_locations or x_locations[0] in edge_locations:
board[1][1] = 2
# If user played first in the center, the computer should move in the corner. It doesn't matter which corner.
else:
location = random.choice(corner_locations)
row = location[0]
col = location[1]
board[row][col] = 2
return board
# This logic is used on all other moves.
# First I'll check if the computer can win in the next move. If so, that's where the computer will play.
# The check is done by replacing the blank locations with o's and seeing if the computer would win in each case.
for row, col in blank_locations:
my_board[row][col] = 2
if self.contains_winning_move(my_board):
board[row][col] = 2
return board
else:
my_board[row][col] = 0 # Revert if not winning
# If the computer can't immediately win, it wants to make sure the user can't win in their next move, so it
# checks to see if the user needs to be blocked.
# The check is done by replacing the blank locations with x's and seeing if the user would win in each case.
for row, col in blank_locations:
my_board[row][col] = 1
if self.contains_winning_move(my_board):
board[row][col] = 2
return board
else:
my_board[row][col] = 0 # Revert if not winning
# Assuming nobody will win in their next move, now I'll find the best place for the computer to win.
for row, col in blank_locations:
if (
1 not in my_board[row]
and my_board[0][col] != 1
and my_board[1][col] != 1
and my_board[2][col] != 1
):
board[row][col] = 2
return board
# If no move has been made, choose a random blank location. If smarter is True, the computer will choose a
# random blank location from a set of better locations to play. These locations are determined by seeing if
# there are two blanks and an 2 in each row, column, and diagonal (done in two_blanks).
# If smarter is False, all blank locations can be chosen.
if self.smarter:
blanks = [] # type: Any
for triplet in self.triplets:
result = self.two_blanks(triplet, board)
if result:
blanks = blanks + result
blank_set = set(blanks)
blank_list = list(blank_set)
if blank_list == []:
location = random.choice(blank_locations)
else:
location = random.choice(blank_list)
row = location[0]
col = location[1]
board[row][col] = 2
return board
else:
location = random.choice(blank_locations)
row = location[0]
col = location[1]
board[row][col] = 2
return board
def is_valid_move(self, move: str) -> bool:
"""Checks the validity of the coordinate input passed in to make sure it's not out-of-bounds (ex. 5, 5)"""
try:
split_move = move.split(",")
row = split_move[0].strip()
col = split_move[1].strip()
valid = False
if row in ("1", "2", "3") and col in ("1", "2", "3"):
valid = True
except IndexError:
valid = False
return valid
def make_move(self, move: str, player_number: int, computer_move: bool = False) -> Any:
if computer_move:
return self.computer_move(self.current_board, player_number + 1)
move_coords_str = coords_from_command(move)
if not self.is_valid_move(move_coords_str):
raise BadMoveException("Make sure your move is from 0-9")
board = self.current_board
move_coords = move_coords_str.split(",")
# Subtraction must be done to convert to the right indices,
# since computers start numbering at 0.
row = (int(move_coords[1])) - 1
column = (int(move_coords[0])) - 1
if board[row][column] != 0:
raise BadMoveException("Make sure your space hasn't already been filled.")
board[row][column] = player_number + 1
return board
class TicTacToeMessageHandler:
tokens = [":x:", ":o:"]
def parse_row(self, row: Tuple[int, int], row_num: int) -> str:
"""Takes the row passed in as a list and returns it as a string."""
row_chars = []
num_symbols = [
":one:",
":two:",
":three:",
":four:",
":five:",
":six:",
":seven:",
":eight:",
":nine:",
]
for i, e in enumerate(row):
if e == 0:
row_chars.append(num_symbols[row_num * 3 + i])
else:
row_chars.append(self.get_player_color(e - 1))
row_string = " ".join(row_chars)
return row_string + "\n\n"
def parse_board(self, board: Any) -> str:
"""Takes the board as a nested list and returns a nice version for the user."""
return "".join(self.parse_row(r, r_num) for r_num, r in enumerate(board))
def get_player_color(self, turn: int) -> str:
return self.tokens[turn]
def alert_move_message(self, original_player: str, move_info: str) -> str:
move_info = move_info.replace("move ", "")
return f"{original_player} put a token at {move_info}"
def game_start_message(self) -> str:
return (
"Welcome to tic-tac-toe!" "To make a move, type @-mention `move <number>` or `<number>`"
)
class ticTacToeHandler(GameAdapter):
"""
You can play tic-tac-toe! Make sure your message starts with
"@mention-bot".
"""
META = {
"name": "TicTacToe",
"description": "Lets you play Tic-tac-toe against a computer.",
}
def usage(self) -> str:
return """
You can play tic-tac-toe now! Make sure your
message starts with @mention-bot.
"""
def __init__(self) -> None:
game_name = "Tic Tac Toe"
bot_name = "tictactoe"
move_help_message = "* To move during a game, type\n`move <number>` or `<number>`"
move_regex = r"(move (\d)$)|((\d)$)"
model = TicTacToeModel
gameMessageHandler = TicTacToeMessageHandler
rules = """Try to get three in horizontal or vertical or diagonal row to win the game."""
super().__init__(
game_name,
bot_name,
move_help_message,
move_regex,
model,
gameMessageHandler,
rules,
supports_computer=True,
)
def coords_from_command(cmd: str) -> str:
# This function translates the input command into a TicTacToeGame move.
# It should return two indices, each one of (1,2,3), separated by a comma, eg. "3,2"
"""As there are various ways to input a coordinate (with/without parentheses, with/without spaces, etc.) the
input is stripped to just the numbers before being used in the program."""
cmd_num = int(cmd.replace("move ", "")) - 1
cmd = f"{(cmd_num % 3) + 1},{(cmd_num // 3) + 1}"
return cmd
handler_class = ticTacToeHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/tictactoe/tictactoe.py | tictactoe.py |
# Tic-Tac-Toe Bot
This bot allows you to play tic-tac-toe in a private message with the bot.
Multiple games can simultaneously be played by different users, each playing
against the computer.
The bot only responds to messages starting with @mention of the bot(botname).
## Setup
This bot does not require any special setup. Just run it according to the
instructions in [this guide](https://zulip.com/api/running-bots#running-a-bot).
## Commands
* `@mention-botname new` - start a new game (but not if you are already
playing a game.) You must type this first to start playing!
* `@mention-botname help` - return a help message.
* `@mention-botname quit` - quit the current game.
* `@mention-botname <coordinate>` - make a move at the entered coordinate.
For example, `@mention-botname 1,1` . After this, the bot will make its
move, or declare the game over if the user or bot has won.
Coordinates are entered in a (row, column) format. Numbering is from top to
bottom and left to right.
Here are the coordinates of each position. When entering coordinates, parentheses
and spaces are optional.
(1, 1) | (1, 2) | (1, 3)
(2, 1) | (2, 2) | (2, 3)
(3, 1) | (3, 2) | (3, 3)
Invalid commands will result in an "I don't understand" response from the bot,
with a suggestion to type `@mention-botname help`.
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/tictactoe/doc.md | doc.md |
import json
import re
from typing import Any, Dict, Tuple
from zulip_bots.lib import BotHandler
QUESTION = "How should we handle this?"
ANSWERS = {
"1": "known issue",
"2": "ignore",
"3": "in process",
"4": "escalate",
}
class InvalidAnswerException(Exception):
pass
class IncidentHandler:
def usage(self) -> str:
return """
This plugin lets folks reports incidents and
triage them. It is intended to be sample code.
In the real world you'd modify this code to talk
to some kind of issue tracking system. But the
glue code here should be pretty portable.
"""
def handle_message(self, message: Dict[str, Any], bot_handler: BotHandler) -> None:
query = message["content"]
if query.startswith("new "):
start_new_incident(query, message, bot_handler)
elif query.startswith("answer "):
try:
(ticket_id, answer) = parse_answer(query)
except InvalidAnswerException:
bot_response = "Invalid answer format"
bot_handler.send_reply(message, bot_response)
return
bot_response = f"Incident {ticket_id}\n status = {answer}"
bot_handler.send_reply(message, bot_response)
else:
bot_response = 'type "new <description>" for a new incident'
bot_handler.send_reply(message, bot_response)
def start_new_incident(query: str, message: Dict[str, Any], bot_handler: BotHandler) -> None:
# Here is where we would enter the incident in some sort of backend
# system. We just simulate everything by having an incident id that
# we generate here.
incident = query[len("new ") :]
ticket_id = generate_ticket_id(bot_handler.storage)
bot_response = format_incident_for_markdown(ticket_id, incident)
widget_content = format_incident_for_widget(ticket_id, incident)
bot_handler.send_reply(message, bot_response, widget_content)
def parse_answer(query: str) -> Tuple[str, str]:
m = re.match(r"answer\s+(TICKET....)\s+(.)", query)
if not m:
raise InvalidAnswerException()
ticket_id = m.group(1)
# In a real world system, we'd validate the ticket_id against
# a backend system. (You could use Zulip itself to store incident
# data, if you want something really lite, but there are plenty
# of systems that specialize in incident management.)
answer = m.group(2).upper()
if answer not in "1234":
raise InvalidAnswerException()
return (ticket_id, ANSWERS[answer])
def generate_ticket_id(storage: Any) -> str:
try:
incident_num = storage.get("ticket_id")
except (KeyError):
incident_num = 0
incident_num += 1
incident_num = incident_num % (1000)
storage.put("ticket_id", incident_num)
ticket_id = "TICKET%04d" % (incident_num,)
return ticket_id
def format_incident_for_widget(ticket_id: str, incident: Dict[str, Any]) -> str:
widget_type = "zform"
heading = ticket_id + ": " + incident
def get_choice(code: str) -> Dict[str, str]:
answer = ANSWERS[code]
reply = "answer " + ticket_id + " " + code
return dict(
type="multiple_choice",
short_name=code,
long_name=answer,
reply=reply,
)
choices = [get_choice(code) for code in "1234"]
extra_data = dict(
type="choices",
heading=heading,
choices=choices,
)
widget_content = dict(
widget_type=widget_type,
extra_data=extra_data,
)
payload = json.dumps(widget_content)
return payload
def format_incident_for_markdown(ticket_id: str, incident: Dict[str, Any]) -> str:
answer_list = "\n".join(
"* **{code}** {answer}".format(
code=code,
answer=ANSWERS[code],
)
for code in "1234"
)
how_to_respond = f"""**reply**: answer {ticket_id} <code>"""
content = """
Incident: {incident}
Q: {question}
{answer_list}
{how_to_respond}""".format(
question=QUESTION,
answer_list=answer_list,
how_to_respond=how_to_respond,
incident=incident,
)
return content
handler_class = IncidentHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/incident/incident.py | incident.py |
import requests
class GoogleTranslateHandler:
"""
This bot will translate any messages sent to it using google translate.
Before using it, make sure you set up google api keys, and enable google
cloud translate from the google cloud console.
"""
def usage(self):
return """
This plugin allows users translate messages
Users should @-mention the bot with the format
@-mention "<text_to_translate>" <target-language> <source-language(optional)>
"""
def initialize(self, bot_handler):
self.config_info = bot_handler.get_config_info("googletranslate")
# Retrieving the supported languages also serves as a check whether
# the bot is properly connected to the Google Translate API.
try:
self.supported_languages = get_supported_languages(self.config_info["key"])
except TranslateError as e:
bot_handler.quit(str(e))
def handle_message(self, message, bot_handler):
bot_response = get_translate_bot_response(
message["content"],
self.config_info,
message["sender_full_name"],
self.supported_languages,
)
bot_handler.send_reply(message, bot_response)
api_url = "https://translation.googleapis.com/language/translate/v2"
help_text = """
Google translate bot
Please format your message like:
`@-mention "<text_to_translate>" <target-language> <source-language(optional)>`
Visit [here](https://cloud.google.com/translate/docs/languages) for all languages
"""
language_not_found_text = "{} language not found. Visit [here](https://cloud.google.com/translate/docs/languages) for all languages"
def get_supported_languages(key):
parameters = {"key": key, "target": "en"}
response = requests.get(api_url + "/languages", params=parameters)
if response.status_code == requests.codes.ok:
languages = response.json()["data"]["languages"]
return {lang["name"].lower(): lang["language"].lower() for lang in languages}
raise TranslateError(response.json()["error"]["message"])
class TranslateError(Exception):
pass
def translate(text_to_translate, key, dest, src):
parameters = {"q": text_to_translate, "target": dest, "key": key}
if src != "":
parameters.update({"source": src})
response = requests.post(api_url, params=parameters)
if response.status_code == requests.codes.ok:
return response.json()["data"]["translations"][0]["translatedText"]
raise TranslateError(response.json()["error"]["message"])
def get_code_for_language(language, all_languages):
if language.lower() not in all_languages.values():
if language.lower() not in all_languages.keys():
return ""
language = all_languages[language.lower()]
return language
def get_translate_bot_response(message_content, config_file, author, all_languages):
message_content = message_content.strip()
if message_content == "help" or message_content is None or not message_content.startswith('"'):
return help_text
split_text = message_content.rsplit('" ', 1)
if len(split_text) == 1:
return help_text
split_text += split_text.pop(1).split(" ")
if len(split_text) == 2:
# There is no source language
split_text.append("")
if len(split_text) != 3:
return help_text
(text_to_translate, target_language, source_language) = split_text
text_to_translate = text_to_translate[1:]
target_language = get_code_for_language(target_language, all_languages)
if target_language == "":
return language_not_found_text.format("Target")
if source_language != "":
source_language = get_code_for_language(source_language, all_languages)
if source_language == "":
return language_not_found_text.format("Source")
try:
translated_text = translate(
text_to_translate, config_file["key"], target_language, source_language
)
except requests.exceptions.ConnectionError as conn_err:
return f"Could not connect to Google Translate. {conn_err}."
except TranslateError as tr_err:
return f"Translate Error. {tr_err}."
except Exception as err:
return f"Error. {err}."
return f"{translated_text} (from {author})"
handler_class = GoogleTranslateHandler | zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/google_translate/google_translate.py | google_translate.py |
# Google Translate bot
The Google Translate bot uses Google Translate to translate
any text sent to it.
## Setup
This bot requires a google cloud API key. Create one
[here](https://support.google.com/cloud/answer/6158862?hl=en)
You should add this key to `googletranslate.conf`.
To run this bot, use:
`zulip-run-bots googletranslate -c <zuliprc file>
--bot-config-file <path to googletranslate.conf>`
## Usage
To use this bot, @-mention it like this:
`@-mention "<text>" <target language> <source language(Optional)>`
`text` must be in quotation marks, and `source language`
is optional.
If `source language` is not given, it will automatically detect your language.
| zulip-bots | /zulip_bots-0.8.2-py3-none-any.whl/zulip_bots/bots/google_translate/doc.md | doc.md |
```
zulip-botserver --config-file <path to botserverrc> --hostname <address> --port <port>
```
Example: `zulip-botserver --config-file ~/botserverrc`
This program loads the bot configurations from the
config file (`botserverrc`, here) and loads the bot modules.
It then starts the server and fetches the requests to the
above loaded modules and returns the success/failure result.
The `--hostname` and `--port` arguments are optional, and default to
127.0.0.1 and 5002 respectively.
The format for a configuration file is:
[helloworld]
key=value
[email protected]
site=http://localhost
token=abcd1234
Is passed `--use-env-vars` instead of `--config-file`, the
configuration can instead be provided via the `ZULIP_BOTSERVER_CONFIG`
environment variable. This should be a JSON-formatted dictionary of
bot names to dictionary of their configuration; for example:
ZULIP_BOTSERVER_CONFIG='{"helloworld":{"email":"[email protected]","key":"value","site":"http://localhost","token":"abcd1234"}}' \
zulip-botserver --use-env-vars
| zulip-botserver | /zulip_botserver-0.8.2.tar.gz/zulip_botserver-0.8.2/README.md | README.md |
import configparser
import json
import logging
import os
import sys
from collections import OrderedDict
from configparser import MissingSectionHeaderError, NoOptionError
from importlib import import_module
from types import ModuleType
from typing import Any, Dict, List, Optional
from flask import Flask, request
from werkzeug.exceptions import BadRequest, Unauthorized
from zulip import Client
from zulip_bots import lib
from zulip_bots.finder import import_module_from_source, import_module_from_zulip_bot_registry
from zulip_botserver.input_parameters import parse_args
def read_config_section(parser: configparser.ConfigParser, section: str) -> Dict[str, str]:
section_info = {
"email": parser.get(section, "email"),
"key": parser.get(section, "key"),
"site": parser.get(section, "site"),
"token": parser.get(section, "token"),
}
return section_info
def read_config_from_env_vars(bot_name: Optional[str] = None) -> Dict[str, Dict[str, str]]:
bots_config = {} # type: Dict[str, Dict[str, str]]
json_config = os.environ.get("ZULIP_BOTSERVER_CONFIG")
if json_config is None:
raise OSError(
"Could not read environment variable 'ZULIP_BOTSERVER_CONFIG': Variable not set."
)
# Load JSON-formatted environment variable; use OrderedDict to
# preserve ordering on Python 3.6 and below.
env_config = json.loads(json_config, object_pairs_hook=OrderedDict)
if bot_name is not None:
if bot_name in env_config:
bots_config[bot_name] = env_config[bot_name]
else:
# If the bot name provided via the command line does not
# exist in the configuration provided via the environment
# variable, use the first bot in the environment variable,
# with name updated to match, along with a warning.
first_bot_name = list(env_config.keys())[0]
bots_config[bot_name] = env_config[first_bot_name]
logging.warning(
"First bot name in the config list was changed from '{}' to '{}'".format(
first_bot_name, bot_name
)
)
else:
bots_config = dict(env_config)
return bots_config
def read_config_file(
config_file_path: str, bot_name: Optional[str] = None
) -> Dict[str, Dict[str, str]]:
parser = parse_config_file(config_file_path)
bots_config = {} # type: Dict[str, Dict[str, str]]
if bot_name is None:
bots_config = {
section: read_config_section(parser, section) for section in parser.sections()
}
return bots_config
logging.warning("Single bot mode is enabled")
if len(parser.sections()) == 0:
sys.exit(
"Error: Your Botserver config file `{0}` does not contain any sections!\n"
"You need to write the name of the bot you want to run in the "
"section header of `{0}`.".format(config_file_path)
)
if bot_name in parser.sections():
bot_section = bot_name
bots_config[bot_name] = read_config_section(parser, bot_name)
ignored_sections = [section for section in parser.sections() if section != bot_name]
else:
bot_section = parser.sections()[0]
bots_config[bot_name] = read_config_section(parser, bot_section)
logging.warning(
"First bot name in the config list was changed from '{}' to '{}'".format(
bot_section, bot_name
)
)
ignored_sections = parser.sections()[1:]
if len(ignored_sections) > 0:
logging.warning(f"Sections except the '{bot_section}' will be ignored")
return bots_config
def parse_config_file(config_file_path: str) -> configparser.ConfigParser:
config_file_path = os.path.abspath(os.path.expanduser(config_file_path))
if not os.path.isfile(config_file_path):
raise OSError(f"Could not read config file {config_file_path}: File not found.")
parser = configparser.ConfigParser()
parser.read(config_file_path)
return parser
def load_lib_modules(available_bots: List[str]) -> Dict[str, ModuleType]:
bots_lib_module = {}
for bot in available_bots:
try:
if bot.endswith(".py") and os.path.isfile(bot):
lib_module = import_module_from_source(bot, "custom_bot_module")
else:
module_name = "zulip_bots.bots.{bot}.{bot}".format(bot=bot)
lib_module = import_module(module_name)
bots_lib_module[bot] = lib_module
except ImportError:
_, bots_lib_module[bot] = import_module_from_zulip_bot_registry(bot)
if bots_lib_module[bot] is None:
error_message = (
f'Error: Bot "{bot}" doesn\'t exist. Please make sure '
"you have set up the botserverrc file correctly.\n"
)
if bot == "api":
error_message += (
"Did you forget to specify the bot you want to run with -b <botname> ?"
)
sys.exit(error_message)
return bots_lib_module
def load_bot_handlers(
available_bots: List[str],
bot_lib_modules: Dict[str, ModuleType],
bots_config: Dict[str, Dict[str, str]],
third_party_bot_conf: Optional[configparser.ConfigParser] = None,
) -> Dict[str, lib.ExternalBotHandler]:
bot_handlers = {}
for bot in available_bots:
client = Client(
email=bots_config[bot]["email"],
api_key=bots_config[bot]["key"],
site=bots_config[bot]["site"],
)
bot_dir = os.path.join(os.path.dirname(os.path.abspath(bot_lib_modules[bot].__file__)))
bot_handler = lib.ExternalBotHandler(
client, bot_dir, bot_details={}, bot_config_parser=third_party_bot_conf
)
bot_handlers[bot] = bot_handler
return bot_handlers
def init_message_handlers(
available_bots: List[str],
bots_lib_modules: Dict[str, Any],
bot_handlers: Dict[str, lib.ExternalBotHandler],
) -> Dict[str, Any]:
message_handlers = {}
for bot in available_bots:
bot_lib_module = bots_lib_modules[bot]
bot_handler = bot_handlers[bot]
message_handler = lib.prepare_message_handler(bot, bot_handler, bot_lib_module)
message_handlers[bot] = message_handler
return message_handlers
app = Flask(__name__)
bots_config = {} # type: Dict[str, Dict[str, str]]
@app.route("/", methods=["POST"])
def handle_bot() -> str:
event = request.get_json(force=True)
assert event is not None
for bot_name, config in bots_config.items():
if config["email"] == event["bot_email"]:
bot = bot_name
bot_config = config
break
else:
raise BadRequest(
"Cannot find a bot with email {} in the Botserver "
"configuration file. Do the emails in your botserverrc "
"match the bot emails on the server?".format(event["bot_email"])
)
if bot_config["token"] != event["token"]:
raise Unauthorized(
"Request token does not match token found for bot {} in the "
"Botserver configuration file. Do the outgoing webhooks in "
"Zulip point to the right Botserver?".format(event["bot_email"])
)
app.config.get("BOTS_LIB_MODULES", {})[bot]
bot_handler = app.config.get("BOT_HANDLERS", {})[bot]
message_handler = app.config.get("MESSAGE_HANDLERS", {})[bot]
is_mentioned = event["trigger"] == "mention"
is_private_message = event["trigger"] == "private_message"
message = event["message"]
message["full_content"] = message["content"]
# Strip at-mention botname from the message
if is_mentioned:
# message['content'] will be None when the bot's @-mention is not at the beginning.
# In that case, the message shall not be handled.
message["content"] = lib.extract_query_without_mention(message=message, client=bot_handler)
if message["content"] is None:
return json.dumps(dict(response_not_required=True))
if is_private_message or is_mentioned:
message_handler.handle_message(message=message, bot_handler=bot_handler)
return json.dumps(dict(response_not_required=True))
def main() -> None:
options = parse_args()
global bots_config
if options.use_env_vars:
bots_config = read_config_from_env_vars(options.bot_name)
elif options.config_file:
try:
bots_config = read_config_file(options.config_file, options.bot_name)
except MissingSectionHeaderError:
sys.exit(
"Error: Your Botserver config file `{0}` contains an empty section header!\n"
"You need to write the names of the bots you want to run in the "
"section headers of `{0}`.".format(options.config_file)
)
except NoOptionError as e:
sys.exit(
"Error: Your Botserver config file `{0}` has a missing option `{1}` in section `{2}`!\n"
"You need to add option `{1}` with appropriate value in section `{2}` of `{0}`".format(
options.config_file, e.option, e.section
)
)
available_bots = list(bots_config.keys())
bots_lib_modules = load_lib_modules(available_bots)
third_party_bot_conf = (
parse_config_file(options.bot_config_file) if options.bot_config_file is not None else None
)
bot_handlers = load_bot_handlers(
available_bots, bots_lib_modules, bots_config, third_party_bot_conf
)
message_handlers = init_message_handlers(available_bots, bots_lib_modules, bot_handlers)
app.config["BOTS_LIB_MODULES"] = bots_lib_modules
app.config["BOT_HANDLERS"] = bot_handlers
app.config["MESSAGE_HANDLERS"] = message_handlers
app.run(host=options.hostname, port=int(options.port), debug=True)
if __name__ == "__main__":
main() | zulip-botserver | /zulip_botserver-0.8.2.tar.gz/zulip_botserver-0.8.2/zulip_botserver/server.py | server.py |
import platform
import subprocess
from typing_extensions import Literal
# PLATFORM DETECTION
SupportedPlatforms = Literal["Linux", "MacOS", "WSL"]
AllPlatforms = Literal[SupportedPlatforms, "unsupported"]
raw_platform = platform.system()
PLATFORM: AllPlatforms
if raw_platform == "Linux":
PLATFORM = "WSL" if "microsoft" in platform.release().lower() else "Linux"
elif raw_platform == "Darwin":
PLATFORM = "MacOS"
else:
PLATFORM = "unsupported"
# PLATFORM DEPENDENT HELPERS
MOUSE_SELECTION_KEY = "Fn + Alt" if PLATFORM == "MacOS" else "Shift"
def notify(title: str, text: str) -> str:
command_list = None
if PLATFORM == "MacOS":
command_list = [
"osascript",
"-e",
"on run(argv)",
"-e",
"return display notification item 1 of argv with title "
'item 2 of argv sound name "ZT_NOTIFICATION_SOUND"',
"-e",
"end",
"--",
text,
title,
]
elif PLATFORM == "Linux":
command_list = ["notify-send", "--", title, text]
if command_list is not None:
try:
subprocess.run(
command_list, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
except FileNotFoundError:
# This likely means the notification command could not be found
return command_list[0]
return ""
def successful_GUI_return_code() -> int:
"""
Returns success retrn code for GUI commands, which are OS specific.
"""
# WSL uses GUI return code as 1. Refer below link to know more:
# https://stackoverflow.com/questions/52423031/
# why-does-opening-an-explorer-window-and-selecting-a-file-through-pythons-subpro/
# 52423798#52423798
if PLATFORM == "WSL":
return 1
return 0
def normalized_file_path(path: str) -> str:
"""
Returns file paths which are normalized as per platform.
"""
# Convert Unix path to Windows path for WSL
if PLATFORM == "WSL":
return path.replace("/", "\\")
return path | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/platform_code.py | platform_code.py |
from typing import Any, Dict, List, Optional, Union
from typing_extensions import Literal, TypedDict
# These are documented in the zulip package (python-zulip-api repo)
from zulip import EditPropagateMode # one/all/later
from zulip import EmojiType # [unicode/realm/zulip_extra + _emoji]
from zulip import MessageFlag # superset of below, may only be changed indirectly
from zulip import ModifiableMessageFlag # directly modifiable read/starred/collapsed
RESOLVED_TOPIC_PREFIX = "✔ "
class PrivateComposition(TypedDict):
type: Literal["private"]
content: str
to: List[int] # User ids
class StreamComposition(TypedDict):
type: Literal["stream"]
content: str
to: str # stream name # TODO: Migrate to using int (stream id)
subject: str # TODO: Migrate to using topic
Composition = Union[PrivateComposition, StreamComposition]
class Message(TypedDict, total=False):
id: int
sender_id: int
content: str
timestamp: int
client: str
subject: str # Only for stream msgs.
# NOTE: new in Zulip 3.0 / ZFL 1, replacing `subject_links`
# NOTE: API response format of `topic_links` changed in Zulip 4.0 / ZFL 46
topic_links: List[Any]
# NOTE: `subject_links` in Zulip 2.1; deprecated from Zulip 3.0 / ZFL 1
subject_links: List[str]
is_me_message: bool
reactions: List[Dict[str, Any]]
submessages: List[Dict[str, Any]]
flags: List[MessageFlag]
sender_full_name: str
sender_email: str
sender_realm_str: str
display_recipient: Any
type: str
stream_id: int # Only for stream msgs.
avatar_url: str
content_type: str
match_content: str # If keyword search specified in narrow params.
match_subject: str # If keyword search specified in narrow params.
# Unused/Unsupported fields
# NOTE: Deprecated; a server implementation detail not useful in a client.
# recipient_id: int
# NOTE: Removed from Zulip 3.1 / ZFL 26; unused before that.
# sender_short_name: str
# Elements and types taken from https://zulip.com/api/get-events
class Subscription(TypedDict):
stream_id: int
name: str
description: str
rendered_description: str
date_created: int # NOTE: new in Zulip 4.0 / ZFL 30
invite_only: bool
subscribers: List[int]
desktop_notifications: Optional[bool]
email_notifications: Optional[bool]
wildcard_mentions_notify: Optional[bool]
push_notifications: Optional[bool]
audible_notifications: Optional[bool]
pin_to_top: bool
email_address: str
is_muted: bool # NOTE: new in Zulip 2.1 (in_home_view still present)
in_home_view: bool # TODO: Migrate to is_muted (note inversion)
is_announcement_only: bool # Deprecated in Zulip 3.0 -> stream_post_policy
stream_post_policy: int # NOTE: new in Zulip 3.0 / ZFL 1
is_web_public: bool
role: int # NOTE: new in Zulip 4.0 / ZFL 31
color: str
message_retention_days: Optional[int] # NOTE: new in Zulip 3.0 / ZFL 17
history_public_to_subscribers: bool
first_message_id: Optional[int]
stream_weekly_traffic: Optional[int]
class RealmUser(TypedDict):
user_id: int
full_name: str
email: str
# Present in most cases, but these only in /users/me from Zulip 3.0 (ZFL 10):
timezone: str
date_joined: str
avatar_url: str # Absent depending on server/capability-field (Zulip 3.0/ZFL 18+)
avatar_version: int # NOTE: new in Zulip 3.0 [(ZFL 6) (ZFL 10)]
is_bot: bool
# These are only meaningfully (or literally) present for bots (ie. is_bot==True)
bot_type: Optional[int]
bot_owner_id: int # NOTE: new in Zulip 3.0 (ZFL 1) - None for old bots
bot_owner: str # (before ZFL 1; containing email field of owner instead)
is_billing_admin: bool # NOTE: new in Zulip 5.0 (ZFL 73)
# If role is present, prefer it to the other is_* fields below
role: int # NOTE: new in Zulip 4.0 (ZFL 59)
is_owner: bool # NOTE: new in Zulip 3.0 [/users/* (ZFL 8); /register (ZFL 11)]
is_admin: bool
is_guest: bool # NOTE: added /users/me ZFL 10; other changes before that
# To support in future:
# profile_data: Dict # NOTE: Only if requested
# is_active: bool # NOTE: Dependent upon realm_users vs realm_non_active_users
# delivery_email: str # NOTE: Only available if admin, and email visibility limited
# Occasionally present or deprecated fields
# is_moderator: bool # NOTE: new in Zulip 4.0 (ZFL 60) - ONLY IN REGISTER RESPONSE
# is_cross_realm_bot: bool # NOTE: Only for cross-realm bots
# max_message_id: int # NOTE: DEPRECATED & only for /users/me
class MessageEvent(TypedDict):
type: Literal["message"]
message: Message
flags: List[MessageFlag]
class UpdateMessageEvent(TypedDict):
type: Literal["update_message"]
message_id: int
# FIXME: These groups of types are not always present
# A: Content needs re-rendering
rendered_content: str
# B: Subject of these message ids needs updating?
message_ids: List[int]
orig_subject: str
subject: str
propagate_mode: EditPropagateMode
stream_id: int
class ReactionEvent(TypedDict):
type: Literal["reaction"]
op: str
user: Dict[str, Any] # 'email', 'user_id', 'full_name'
reaction_type: EmojiType
emoji_code: str
emoji_name: str
message_id: int
class SubscriptionEvent(TypedDict):
type: Literal["subscription"]
op: str
property: str
user_id: int # Present when a streams subscribers are updated.
user_ids: List[int] # NOTE: replaces 'user_id' in ZFL 35
stream_id: int
stream_ids: List[int] # NOTE: replaces 'stream_id' in ZFL 35 for peer*
value: bool
message_ids: List[int] # Present when subject of msg(s) is updated
class TypingEvent(TypedDict):
type: Literal["typing"]
sender: Dict[str, Any] # 'email', ...
op: str
class UpdateMessageFlagsEvent(TypedDict):
type: Literal["update_message_flags"]
messages: List[int]
operation: str # NOTE: deprecated in Zulip 4.0 / ZFL 32 -> 'op'
op: str
flag: ModifiableMessageFlag
all: bool
class UpdateDisplaySettings(TypedDict):
type: Literal["update_display_settings"]
setting_name: str
setting: bool
class RealmEmojiData(TypedDict):
id: str
name: str
source_url: str
deactivated: bool
# Previous versions had an author object with an id field.
author_id: int # NOTE: new in Zulip 3.0 / ZFL 7.
class UpdateRealmEmojiEvent(TypedDict):
type: Literal["realm_emoji"]
realm_emoji: Dict[str, RealmEmojiData]
# This is specifically only those supported by ZT
SupportedUserSettings = Literal["send_private_typing_notifications"]
class UpdateUserSettingsEvent(TypedDict):
type: Literal["user_settings"]
op: Literal["update"]
property: SupportedUserSettings
value: Any
# This is specifically only those supported by ZT
SupportedGlobalNotificationSettings = Literal["pm_content_in_desktop_notifications"]
class UpdateGlobalNotificationsEvent(TypedDict):
type: Literal["update_global_notifications"]
notification_name: SupportedGlobalNotificationSettings
setting: Any
Event = Union[
MessageEvent,
UpdateMessageEvent,
ReactionEvent,
SubscriptionEvent,
TypingEvent,
UpdateMessageFlagsEvent,
UpdateDisplaySettings,
UpdateRealmEmojiEvent,
UpdateUserSettingsEvent,
UpdateGlobalNotificationsEvent,
] | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/api_types.py | api_types.py |
import os
import subprocess
import time
from collections import OrderedDict, defaultdict
from contextlib import contextmanager
from functools import partial, wraps
from itertools import chain, combinations
from re import ASCII, MULTILINE, findall, match
from tempfile import NamedTemporaryFile
from threading import Thread
from typing import (
Any,
Callable,
DefaultDict,
Dict,
FrozenSet,
Iterable,
Iterator,
List,
Optional,
Set,
Tuple,
TypeVar,
Union,
)
from urllib.parse import unquote
import requests
from typing_extensions import TypedDict
from zulipterminal.api_types import Composition, EmojiType, Message
from zulipterminal.config.keys import primary_key_for_command
from zulipterminal.config.regexes import (
REGEX_COLOR_3_DIGIT,
REGEX_COLOR_6_DIGIT,
REGEX_QUOTED_FENCE_LENGTH,
)
from zulipterminal.config.ui_mappings import StreamAccessType
from zulipterminal.platform_code import (
PLATFORM,
normalized_file_path,
successful_GUI_return_code,
)
class StreamData(TypedDict):
name: str
id: int
color: str
stream_access_type: StreamAccessType
description: str
class EmojiData(TypedDict):
code: str
aliases: List[str]
type: EmojiType
NamedEmojiData = Dict[str, EmojiData]
class TidiedUserInfo(TypedDict):
full_name: str
email: str
date_joined: str
timezone: str
role: Optional[int]
last_active: str
is_bot: bool
# Below fields are only meaningful if is_bot == True
bot_type: Optional[int]
bot_owner_name: str
class Index(TypedDict):
pointer: Dict[str, Union[int, Set[None]]] # narrow_str, message_id
# Various sets of downloaded message ids (all, starred, ...)
all_msg_ids: Set[int]
starred_msg_ids: Set[int]
mentioned_msg_ids: Set[int]
private_msg_ids: Set[int]
private_msg_ids_by_user_ids: Dict[FrozenSet[int], Set[int]]
stream_msg_ids_by_stream_id: Dict[int, Set[int]]
topic_msg_ids: Dict[int, Dict[str, Set[int]]]
# Extra cached information
edited_messages: Set[int] # {message_id, ...}
topics: Dict[int, List[str]] # {topic names, ...}
search: Set[int] # {message_id, ...}
# Downloaded message data by message id
messages: Dict[int, Message]
initial_index = Index(
pointer=defaultdict(set),
all_msg_ids=set(),
starred_msg_ids=set(),
mentioned_msg_ids=set(),
private_msg_ids=set(),
private_msg_ids_by_user_ids=defaultdict(set),
stream_msg_ids_by_stream_id=defaultdict(set),
topic_msg_ids=defaultdict(dict),
edited_messages=set(),
topics=defaultdict(list),
search=set(),
# mypy bug: https://github.com/python/mypy/issues/7217
messages=defaultdict(lambda: Message()),
)
class UnreadCounts(TypedDict):
all_msg: int
all_pms: int
all_mentions: int
unread_topics: Dict[Tuple[int, str], int] # stream_id, topic
unread_pms: Dict[int, int] # sender_id
unread_huddles: Dict[FrozenSet[int], int] # Group pms
streams: Dict[int, int] # stream_id
def asynch(func: Callable[..., None]) -> Callable[..., None]:
"""
Decorator for executing a function in a separate :class:`threading.Thread`.
"""
@wraps(func)
def wrapper(*args: Any, **kwargs: Any) -> Any:
# If calling when pytest is running simply return the function
# to avoid running in asynch mode.
if os.environ.get("PYTEST_CURRENT_TEST"):
return func(*args, **kwargs)
thread = Thread(target=func, args=args, kwargs=kwargs)
thread.daemon = True
return thread.start()
return wrapper
def _set_count_in_model(
new_count: int, changed_messages: List[Message], unread_counts: UnreadCounts
) -> None:
"""
This function doesn't explicitly set counts in model,
but updates `unread_counts` (which can update the model
if it's passed in, but is not tied to it).
"""
# broader unread counts (for all_*) are updated
# later conditionally in _set_count_in_view.
KeyT = TypeVar("KeyT")
def update_unreads(unreads: Dict[KeyT, int], key: KeyT) -> None:
if key in unreads:
unreads[key] += new_count
if unreads[key] == 0:
unreads.pop(key)
elif new_count == 1:
unreads[key] = new_count
for message in changed_messages:
if message["type"] == "stream":
stream_id = message["stream_id"]
update_unreads(
unread_counts["unread_topics"], (stream_id, message["subject"])
)
update_unreads(unread_counts["streams"], stream_id)
# self-pm has only one display_recipient
# 1-1 pms have 2 display_recipient
elif len(message["display_recipient"]) <= 2:
update_unreads(unread_counts["unread_pms"], message["sender_id"])
else: # If it's a group pm
update_unreads(
unread_counts["unread_huddles"],
frozenset(
recipient["id"] for recipient in message["display_recipient"]
),
)
def _set_count_in_view(
controller: Any,
new_count: int,
changed_messages: List[Message],
unread_counts: UnreadCounts,
) -> None:
"""
This function for the most part contains the logic for setting the
count in the UI buttons. The later buttons (all_msg, all_pms)
additionally set the current count in the model and make use of the
same in the UI.
"""
stream_buttons_list = controller.view.stream_w.streams_btn_list
is_open_topic_view = controller.view.left_panel.is_in_topic_view
if is_open_topic_view:
topic_buttons_list = controller.view.topic_w.topics_btn_list
toggled_stream_id = controller.view.topic_w.stream_button.stream_id
user_buttons_list = controller.view.user_w.users_btn_list
all_msg = controller.view.home_button
all_pm = controller.view.pm_button
all_mentioned = controller.view.mentioned_button
for message in changed_messages:
user_id = message["sender_id"]
# If we sent this message, don't increase the count
if user_id == controller.model.user_id:
continue
msg_type = message["type"]
add_to_counts = True
if {"mentioned", "wildcard_mentioned"} & set(message["flags"]):
unread_counts["all_mentions"] += new_count
all_mentioned.update_count(unread_counts["all_mentions"])
if msg_type == "stream":
stream_id = message["stream_id"]
msg_topic = message["subject"]
if controller.model.is_muted_stream(stream_id):
add_to_counts = False # if muted, don't add to eg. all_msg
else:
for stream_button in stream_buttons_list:
if stream_button.stream_id == stream_id:
stream_button.update_count(stream_button.count + new_count)
break
# FIXME: Update unread_counts['unread_topics']?
if controller.model.is_muted_topic(stream_id, msg_topic):
add_to_counts = False
if is_open_topic_view and stream_id == toggled_stream_id:
# If topic_view is open for incoming messages's stream,
# We update the respective TopicButton count accordingly.
for topic_button in topic_buttons_list:
if topic_button.topic_name == msg_topic:
topic_button.update_count(topic_button.count + new_count)
else:
for user_button in user_buttons_list:
if user_button.user_id == user_id:
user_button.update_count(user_button.count + new_count)
break
unread_counts["all_pms"] += new_count
all_pm.update_count(unread_counts["all_pms"])
if add_to_counts:
unread_counts["all_msg"] += new_count
all_msg.update_count(unread_counts["all_msg"])
def set_count(id_list: List[int], controller: Any, new_count: int) -> None:
# This method applies new_count for 'new message' (1) or 'read' (-1)
# (we could ensure this in a different way by a different type)
assert new_count == 1 or new_count == -1
messages = controller.model.index["messages"]
unread_counts: UnreadCounts = controller.model.unread_counts
changed_messages = [messages[id] for id in id_list]
_set_count_in_model(new_count, changed_messages, unread_counts)
# if view is not yet loaded. Usually the case when first message is read.
while not hasattr(controller, "view"):
time.sleep(0.1)
_set_count_in_view(controller, new_count, changed_messages, unread_counts)
while not hasattr(controller, "loop"):
time.sleep(0.1)
controller.update_screen()
def index_messages(messages: List[Message], model: Any, index: Index) -> Index:
"""
STRUCTURE OF INDEX
{
'pointer': {
'[]': 30 # str(ZulipModel.narrow)
'[["stream", "verona"]]': 32,
...
}
'topic_msg_ids': {
123: { # stream_id
'topic name': {
51234, # message id
56454,
...
}
},
'private_msg_ids_by_user_ids': {
(3, 7): { # user_ids frozenset
51234,
56454,
...
},
(1, 2, 3, 4): { # multiple recipients
12345,
32553,
}
},
'topics': {
123: [ # stread_id
'Denmark2', # topic name
'Verona2',
....
]
},
'all_msg_ids': {
14231,
23423,
...
},
'private_msg_ids': {
22334,
23423,
...
},
'mentioned_msg_ids': {
14423,
33234,
...
},
'stream_msg_ids_by_stream_id': {
123: {
53434,
36435,
...
}
234: {
23423,
23423,
...
}
},
'edited_messages':{
51234,
23423,
...
},
'search': {
13242,
23423,
23423,
...
},
'messages': {
# all the messages mapped to their id
# for easy retrieval of message from id
45645: { # PRIVATE
'id': 4290,
'timestamp': 1521817473,
'content': 'Hi @**Cordelia Lear**',
'sender_full_name': 'Iago',
'flags': [],
'sender_email': '[email protected]',
'subject': '',
'subject_links': [],
'sender_id': 73,
'type': 'private',
'reactions': [],
'display_recipient': [
{
'email': '[email protected]',
'id': 70,
'full_name': 'Zoe',
}, {
'email': '[email protected]',
'id': 71,
'full_name': 'Cordelia Lear',
}, {
'email': '[email protected]',
'id': 72,
'full_name': 'King Hamlet',
}, {
'email': '[email protected]',
'id': 73,
'full_name': 'Iago',
}
]
},
45645: { # STREAM
'timestamp': 1521863062,
'sender_id': 72,
'sender_full_name': 'King Hamlet',
'content': 'https://github.com/zulip/zulip-terminal',
'type': 'stream',
'sender_email': '[email protected]',
'id': 4298,
'display_recipient': 'Verona',
'flags': [],
'reactions': [],
'subject': 'Verona2',
'stream_id': 32,
},
},
}
"""
narrow = model.narrow
for msg in messages:
if "edit_history" in msg.keys():
index["edited_messages"].add(msg["id"])
index["messages"][msg["id"]] = msg
if not narrow:
index["all_msg_ids"].add(msg["id"])
elif model.is_search_narrow():
index["search"].add(msg["id"])
continue
if len(narrow) == 1:
if narrow[0][1] == "starred":
if "starred" in msg["flags"]:
index["starred_msg_ids"].add(msg["id"])
if narrow[0][1] == "mentioned":
if {"mentioned", "wildcard_mentioned"} & set(msg["flags"]):
index["mentioned_msg_ids"].add(msg["id"])
if msg["type"] == "private":
index["private_msg_ids"].add(msg["id"])
recipients = frozenset(
{recipient["id"] for recipient in msg["display_recipient"]}
)
if narrow[0][0] == "pm_with":
narrow_emails = [
model.user_dict[email]["user_id"]
for email in narrow[0][1].split(", ")
] + [model.user_id]
if recipients == frozenset(narrow_emails):
index["private_msg_ids_by_user_ids"][recipients].add(msg["id"])
if msg["type"] == "stream" and msg["stream_id"] == model.stream_id:
index["stream_msg_ids_by_stream_id"][msg["stream_id"]].add(msg["id"])
if (
msg["type"] == "stream"
and len(narrow) == 2
and narrow[1][1] == msg["subject"]
):
topics_in_stream = index["topic_msg_ids"][msg["stream_id"]]
if not topics_in_stream.get(msg["subject"]):
topics_in_stream[msg["subject"]] = set()
topics_in_stream[msg["subject"]].add(msg["id"])
return index
def classify_unread_counts(model: Any) -> UnreadCounts:
# TODO: support group pms
unread_msg_counts = model.initial_data["unread_msgs"]
unread_counts = UnreadCounts(
all_msg=0,
all_pms=0,
all_mentions=0,
unread_topics=dict(),
unread_pms=dict(),
unread_huddles=dict(),
streams=defaultdict(int),
)
mentions_count = len(unread_msg_counts["mentions"])
unread_counts["all_mentions"] += mentions_count
for pm in unread_msg_counts["pms"]:
count = len(pm["unread_message_ids"])
unread_counts["unread_pms"][pm["sender_id"]] = count
unread_counts["all_msg"] += count
unread_counts["all_pms"] += count
for stream in unread_msg_counts["streams"]:
count = len(stream["unread_message_ids"])
stream_id = stream["stream_id"]
# unsubscribed streams may be in raw unreads, but are not tracked
if not model.is_user_subscribed_to_stream(stream_id):
continue
if model.is_muted_topic(stream_id, stream["topic"]):
continue
stream_topic = (stream_id, stream["topic"])
unread_counts["unread_topics"][stream_topic] = count
if not unread_counts["streams"].get(stream_id):
unread_counts["streams"][stream_id] = count
else:
unread_counts["streams"][stream_id] += count
if stream_id not in model.muted_streams:
unread_counts["all_msg"] += count
# store unread count of group pms in `unread_huddles`
for group_pm in unread_msg_counts["huddles"]:
count = len(group_pm["unread_message_ids"])
user_ids = group_pm["user_ids_string"].split(",")
user_ids = frozenset(map(int, user_ids))
unread_counts["unread_huddles"][user_ids] = count
unread_counts["all_msg"] += count
unread_counts["all_pms"] += count
return unread_counts
def match_user(user: Any, text: str) -> bool:
"""
Matches if the user full name, last name or email matches
with `text` or not.
"""
full_name = user["full_name"].lower()
keywords = full_name.split()
# adding full_name helps in further narrowing down the right user.
keywords.append(full_name)
keywords.append(user["email"].lower())
for keyword in keywords:
if keyword.startswith(text.lower()):
return True
return False
def match_user_name_and_email(user: Any, text: str) -> bool:
"""
Matches if the user's full name, last name, email or a combination
in the form of "name <email>" matches with `text`.
"""
full_name = user["full_name"].lower()
email = user["email"].lower()
keywords = full_name.split()
keywords.append(full_name)
keywords.append(email)
keywords.append(f"{full_name} <{email}>")
for keyword in keywords:
if keyword.startswith(text.lower()):
return True
return False
def match_emoji(emoji: str, text: str) -> bool:
"""
True if the emoji matches with `text` (case insensitive),
False otherwise.
"""
return emoji.lower().startswith(text.lower())
def match_topics(topic_names: List[str], search_text: str) -> List[str]:
return [
name for name in topic_names if name.lower().startswith(search_text.lower())
]
DataT = TypeVar("DataT")
def match_stream(
data: List[Tuple[DataT, str]], search_text: str, pinned_streams: List[StreamData]
) -> Tuple[List[DataT], List[str]]:
"""
Returns a list of DataT (streams) and a list of their corresponding names
whose words match with the 'text' in the following order:
* 1st-word startswith match > 2nd-word startswith match > ... (pinned)
* 1st-word startswith match > 2nd-word startswith match > ... (unpinned)
Note: This function expects `data` to be sorted, in a non-decreasing
order, and ordered by their pinning status.
"""
pinned_stream_names = [stream["name"] for stream in pinned_streams]
# Assert that the data is sorted, in a non-decreasing order, and ordered by
# their pinning status.
assert data == sorted(
sorted(data, key=lambda data: data[1].lower()),
key=lambda data: data[1] in pinned_stream_names,
reverse=True,
)
delimiters = "-_/"
trans = str.maketrans(delimiters, len(delimiters) * " ")
stream_splits = [
((datum, [stream_name] + stream_name.translate(trans).split()[1:]))
for datum, stream_name in data
]
matches: "OrderedDict[str, DefaultDict[int, List[Tuple[DataT, str]]]]" = (
OrderedDict(
[
("pinned", defaultdict(list)),
("unpinned", defaultdict(list)),
]
)
)
for datum, splits in stream_splits:
stream_name = splits[0]
kind = "pinned" if stream_name in pinned_stream_names else "unpinned"
for match_position, word in enumerate(splits):
if word.lower().startswith(search_text.lower()):
matches[kind][match_position].append((datum, stream_name))
ordered_matches = []
ordered_names = []
for matched_data in matches.values():
if not matched_data:
continue
for match_position in range(max(matched_data.keys()) + 1):
for datum, name in matched_data.get(match_position, []):
if datum not in ordered_matches:
ordered_matches.append(datum)
ordered_names.append(name)
return ordered_matches, ordered_names
def match_group(group_name: str, text: str) -> bool:
"""
True if any group name matches with `text` (case insensitive),
False otherwise.
"""
return group_name.lower().startswith(text.lower())
def format_string(names: List[str], wrapping_text: str) -> List[str]:
"""
Wrap a list of names using the wrapping characters for typeahead
"""
return [wrapping_text.format(name) for name in names]
def powerset(
iterable: Iterable[Any], map_func: Callable[[Any], Any] = set
) -> List[Any]:
"""
>> powerset([1,2,3])
returns: [set(), {1}, {2}, {3}, {1, 2}, {1, 3}, {2, 3}, {1, 2, 3}]"
"""
s = list(iterable)
powerset = chain.from_iterable(combinations(s, r) for r in range(len(s) + 1))
return list(map(map_func, list(powerset)))
def canonicalize_color(color: str) -> str:
"""
Given a color of the format '#xxxxxx' or '#xxx', produces one of the
format '#xxx'. Always produces lowercase hex digits.
"""
if match(REGEX_COLOR_6_DIGIT, color, ASCII) is not None:
# '#xxxxxx' color, stored by current zulip server
return (color[:2] + color[3] + color[5]).lower()
elif match(REGEX_COLOR_3_DIGIT, color, ASCII) is not None:
# '#xxx' color, which may be stored by the zulip server <= 2.0.0
# Potentially later versions too
return color.lower()
else:
raise ValueError(f'Unknown format for color "{color}"')
def display_error_if_present(response: Dict[str, Any], controller: Any) -> None:
if response["result"] == "error" and hasattr(controller, "view"):
controller.report_error([response["msg"]])
def check_narrow_and_notify(
outer_narrow: List[Any], inner_narrow: List[Any], controller: Any
) -> None:
current_narrow = controller.model.narrow
if (
current_narrow != []
and current_narrow != outer_narrow
and current_narrow != inner_narrow
):
key = primary_key_for_command("NARROW_MESSAGE_RECIPIENT")
controller.report_success(
[
f"Message is sent outside of current narrow. Press [{key}] to narrow to conversation."
],
duration=6,
)
def notify_if_message_sent_outside_narrow(
message: Composition, controller: Any
) -> None:
current_narrow = controller.model.narrow
if message["type"] == "stream":
stream_narrow = [["stream", message["to"]]]
topic_narrow = stream_narrow + [["topic", message["subject"]]]
check_narrow_and_notify(stream_narrow, topic_narrow, controller)
elif message["type"] == "private":
pm_narrow = [["is", "private"]]
recipient_emails = [
controller.model.user_id_email_dict[user_id] for user_id in message["to"]
]
pm_with_narrow = [["pm_with", ", ".join(recipient_emails)]]
check_narrow_and_notify(pm_narrow, pm_with_narrow, controller)
def hash_util_decode(string: str) -> str:
"""
Returns a decoded string given a hash_util_encode() [present in
zulip/zulip's zerver/lib/url_encoding.py] encoded string.
"""
# Acknowledge custom string replacements in zulip/zulip's
# zerver/lib/url_encoding.py before unquote.
return unquote(string.replace(".", "%"))
def get_unused_fence(content: str) -> str:
"""
Generates fence for quoted-message based on regex pattern
of continuous back-ticks. Referred and translated from
zulip/static/shared/js/fenced_code.js.
"""
max_length_fence = 3
matches = findall(REGEX_QUOTED_FENCE_LENGTH, content, flags=MULTILINE)
if len(matches) != 0:
max_length_fence = max(max_length_fence, len(max(matches, key=len)) + 1)
return "`" * max_length_fence
@contextmanager
def suppress_output() -> Iterator[None]:
"""
Context manager to redirect stdout and stderr to /dev/null.
Adapted from https://stackoverflow.com/a/2323563
"""
stdout = os.dup(1)
stderr = os.dup(2)
os.close(1)
os.close(2)
os.open(os.devnull, os.O_RDWR)
try:
yield
finally:
os.dup2(stdout, 1)
os.dup2(stderr, 2)
@asynch
def process_media(controller: Any, link: str) -> None:
"""
Helper to process media links.
"""
if not link:
controller.report_error("The media link is empty")
return
show_download_status = partial(
controller.view.set_footer_text, "Downloading your media..."
)
media_path = download_media(controller, link, show_download_status)
tool = ""
# TODO: Add support for other platforms as well.
if PLATFORM == "WSL":
tool = "explorer.exe"
# Modifying path to backward slashes instead of forward slashes
media_path = media_path.replace("/", "\\")
elif PLATFORM == "Linux":
tool = "xdg-open"
elif PLATFORM == "MacOS":
tool = "open"
else:
controller.report_error("Media not supported for this platform")
return
controller.show_media_confirmation_popup(open_media, tool, media_path)
def download_media(
controller: Any, url: str, show_download_status: Callable[..., None]
) -> str:
"""
Helper to download media from given link. Returns the path to downloaded media.
"""
media_name = url.split("/")[-1]
client = controller.client
auth = requests.auth.HTTPBasicAuth(client.email, client.api_key)
with requests.get(url, auth=auth, stream=True) as response:
response.raise_for_status()
local_path = ""
with NamedTemporaryFile(
mode="wb", delete=False, prefix="zt-", suffix=f"-{media_name}"
) as file:
local_path = file.name
for chunk in response.iter_content(chunk_size=8192):
if chunk: # Filter out keep-alive new chunks.
file.write(chunk)
show_download_status()
controller.report_success([" Downloaded ", ("bold", media_name)])
return normalized_file_path(local_path)
return ""
@asynch
def open_media(controller: Any, tool: str, media_path: str) -> None:
"""
Helper to open a media file given its path and tool.
"""
error = []
command = [tool, media_path]
try:
process = subprocess.run(
command, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL
)
exit_status = process.returncode
if exit_status != successful_GUI_return_code():
error = [
" The tool ",
("footer_contrast", tool),
" did not run successfully" ". Exited with ",
("footer_contrast", str(exit_status)),
]
except FileNotFoundError:
error = [" The tool ", ("footer_contrast", tool), " could not be found"]
if error:
controller.report_error(error) | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/helper.py | helper.py |
import itertools
import os
import signal
import sys
import time
import webbrowser
from collections import OrderedDict
from functools import partial
from platform import platform
from types import TracebackType
from typing import Any, Dict, List, Optional, Tuple, Type, Union
import pyperclip
import urwid
import zulip
from typing_extensions import Literal
from zulipterminal.api_types import Composition, Message
from zulipterminal.config.themes import ThemeSpec
from zulipterminal.helper import asynch, suppress_output
from zulipterminal.model import Model
from zulipterminal.platform_code import PLATFORM
from zulipterminal.ui import Screen, View
from zulipterminal.ui_tools.utils import create_msg_box_list
from zulipterminal.ui_tools.views import (
AboutView,
EditHistoryView,
EditModeView,
EmojiPickerView,
FullRawMsgView,
FullRenderedMsgView,
HelpView,
MarkdownHelpView,
MsgInfoView,
NoticeView,
PopUpConfirmationView,
StreamInfoView,
StreamMembersView,
UserInfoView,
)
from zulipterminal.version import ZT_VERSION
ExceptionInfo = Tuple[Type[BaseException], BaseException, TracebackType]
class Controller:
"""
A class responsible for setting up the model and view and running
the application.
"""
def __init__(
self,
*,
config_file: str,
maximum_footlinks: int,
theme_name: str,
theme: ThemeSpec,
color_depth: int,
debug_path: Optional[str],
in_explore_mode: bool,
autohide: bool,
notify: bool,
) -> None:
self.theme_name = theme_name
self.theme = theme
self.color_depth = color_depth
self.in_explore_mode = in_explore_mode
self.autohide = autohide
self.notify_enabled = notify
self.maximum_footlinks = maximum_footlinks
self.debug_path = debug_path
self._editor: Optional[Any] = None
self.active_conversation_info: Dict[str, Any] = {}
self.is_typing_notification_in_progress = False
self.show_loading()
client_identifier = f"ZulipTerminal/{ZT_VERSION} {platform()}"
self.client = zulip.Client(config_file=config_file, client=client_identifier)
self.model = Model(self)
self.view = View(self)
# Start polling for events after view is rendered.
self.model.poll_for_events()
screen = Screen()
screen.set_terminal_properties(colors=self.color_depth)
self.loop = urwid.MainLoop(self.view, self.theme, screen=screen)
# urwid pipe for concurrent screen update handling
self._update_pipe = self.loop.watch_pipe(self._draw_screen)
# data and urwid pipe for inter-thread exception handling
self._exception_info: Optional[ExceptionInfo] = None
self._critical_exception = False
self._exception_pipe = self.loop.watch_pipe(self._raise_exception)
# Register new ^C handler
signal.signal(signal.SIGINT, self.exit_handler)
def raise_exception_in_main_thread(
self, exc_info: ExceptionInfo, *, critical: bool
) -> None:
"""
Sets an exception from another thread, which is cleanly handled
from within the Controller thread via _raise_exception
"""
# Exceptions shouldn't occur before the pipe is set
assert hasattr(self, "_exception_pipe")
if isinstance(exc_info, tuple):
self._exception_info = exc_info
self._critical_exception = critical
else:
self._exception_info = (
RuntimeError,
f"Invalid cross-thread exception info '{exc_info}'",
None,
)
self._critical_exception = True
os.write(self._exception_pipe, b"1")
def is_in_editor_mode(self) -> bool:
return self._editor is not None
def enter_editor_mode_with(self, editor: Any) -> None:
assert self._editor is None, "Already in editor mode"
self._editor = editor
def exit_editor_mode(self) -> None:
self._editor = None
def current_editor(self) -> Any:
assert self._editor is not None, "Current editor is None"
return self._editor
@asynch
def show_loading(self) -> None:
def spinning_cursor() -> Any:
while True:
yield from "|/-\\"
spinner = spinning_cursor()
sys.stdout.write("\033[92mWelcome to Zulip.\033[0m\n")
while not hasattr(self, "view"):
next_spinner = "Loading " + next(spinner)
sys.stdout.write(next_spinner)
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write("\b" * len(next_spinner))
self.capture_stdout()
def capture_stdout(self) -> None:
if hasattr(self, "_stdout"):
return
self._stdout = sys.stdout
if self.debug_path is not None:
# buffering=1 avoids need for flush=True with print() debugging
sys.stdout = open(self.debug_path, "a", buffering=1)
else:
# Redirect stdout (print does nothing)
sys.stdout = open(os.devnull, "a")
def restore_stdout(self) -> None:
if not hasattr(self, "_stdout"):
return
sys.stdout.flush()
sys.stdout.close()
sys.stdout = self._stdout
sys.stdout.write("\n")
del self._stdout
def update_screen(self) -> None:
# Update should not happen until pipe is set
assert hasattr(self, "_update_pipe")
# Write something to update pipe to trigger draw_screen
os.write(self._update_pipe, b"1")
def _draw_screen(self, *args: Any, **kwargs: Any) -> Literal[True]:
self.loop.draw_screen()
return True # Always retain pipe
def maximum_popup_dimensions(self) -> Tuple[int, int]:
"""
Returns 3/4th of the screen estate's columns if columns are greater
than 100 (MAX_LINEAR_SCALING_WIDTH) else scales accordingly untill
popup width becomes full width at 80 (MIN_SUPPORTED_POPUP_WIDTH) below
which popup width remains full width.
The screen estate's rows are always scaled by 3/4th to get the
popup rows.
"""
MIN_SUPPORTED_POPUP_WIDTH = 80
MAX_LINEAR_SCALING_WIDTH = 100
def clamp(n: int, minn: int, maxn: int) -> int:
return max(min(maxn, n), minn)
max_cols, max_rows = self.loop.screen.get_cols_rows()
min_width = MIN_SUPPORTED_POPUP_WIDTH
max_width = MAX_LINEAR_SCALING_WIDTH
# Scale Width
width = clamp(max_cols, min_width, max_width)
scaling = 1 - ((width - min_width) / (4 * (max_width - min_width)))
max_popup_cols = int(scaling * max_cols)
# Scale Height
max_popup_rows = 3 * max_rows // 4
return max_popup_cols, max_popup_rows
def show_pop_up(self, to_show: Any, style: str) -> None:
border_lines = dict(
tlcorner="▛",
tline="▀",
trcorner="▜",
rline="▐",
lline="▌",
blcorner="▙",
bline="▄",
brcorner="▟",
)
text = urwid.Text(to_show.title, align="center")
title_map = urwid.AttrMap(urwid.Filler(text), style)
title_box_adapter = urwid.BoxAdapter(title_map, height=1)
title_box = urwid.LineBox(
title_box_adapter,
tlcorner="▄",
tline="▄",
trcorner="▄",
rline="",
lline="",
blcorner="",
bline="",
brcorner="",
)
title = urwid.AttrMap(title_box, "popup_border")
content = urwid.LineBox(to_show, **border_lines)
self.loop.widget = urwid.Overlay(
urwid.AttrMap(urwid.Frame(header=title, body=content), "popup_border"),
self.view,
align="center",
valign="middle",
# +2 to both of the following, due to LineBox
# +2 to height, due to title enhancement
width=to_show.width + 2,
height=to_show.height + 4,
)
def is_any_popup_open(self) -> bool:
return isinstance(self.loop.widget, urwid.Overlay)
def exit_popup(self) -> None:
self.loop.widget = self.view
def show_help(self) -> None:
help_view = HelpView(self, "Help Menu (up/down scrolls)")
self.show_pop_up(help_view, "area:help")
def show_markdown_help(self) -> None:
markdown_view = MarkdownHelpView(self, "Markdown Help Menu (up/down scrolls)")
self.show_pop_up(markdown_view, "area:help")
def show_topic_edit_mode(self, button: Any) -> None:
self.show_pop_up(EditModeView(self, button), "area:msg")
def show_msg_info(
self,
msg: Message,
topic_links: "OrderedDict[str, Tuple[str, int, bool]]",
message_links: "OrderedDict[str, Tuple[str, int, bool]]",
time_mentions: List[Tuple[str, str]],
) -> None:
msg_info_view = MsgInfoView(
self,
msg,
"Message Information (up/down scrolls)",
topic_links,
message_links,
time_mentions,
)
self.show_pop_up(msg_info_view, "area:msg")
def show_emoji_picker(self, message: Message) -> None:
all_emoji_units = [
(emoji_name, emoji["code"], emoji["aliases"])
for emoji_name, emoji in self.model.active_emoji_data.items()
]
emoji_picker_view = EmojiPickerView(
self, "Add/Remove Emojis", all_emoji_units, message, self.view
)
self.show_pop_up(emoji_picker_view, "area:msg")
def show_stream_info(self, stream_id: int) -> None:
show_stream_view = StreamInfoView(self, stream_id)
self.show_pop_up(show_stream_view, "area:stream")
def show_stream_members(self, stream_id: int) -> None:
stream_members_view = StreamMembersView(self, stream_id)
self.show_pop_up(stream_members_view, "area:stream")
def popup_with_message(self, text: str, width: int) -> None:
self.show_pop_up(NoticeView(self, text, width, "NOTICE"), "area:error")
def show_about(self) -> None:
self.show_pop_up(
AboutView(
self,
"About",
zt_version=ZT_VERSION,
server_version=self.model.server_version,
server_feature_level=self.model.server_feature_level,
theme_name=self.theme_name,
color_depth=self.color_depth,
notify_enabled=self.notify_enabled,
autohide_enabled=self.autohide,
maximum_footlinks=self.maximum_footlinks,
),
"area:help",
)
def show_user_info(self, user_id: int) -> None:
self.show_pop_up(
UserInfoView(self, user_id, "User Information (up/down scrolls)"),
"area:user",
)
def show_full_rendered_message(
self,
message: Message,
topic_links: "OrderedDict[str, Tuple[str, int, bool]]",
message_links: "OrderedDict[str, Tuple[str, int, bool]]",
time_mentions: List[Tuple[str, str]],
) -> None:
self.show_pop_up(
FullRenderedMsgView(
self,
message,
topic_links,
message_links,
time_mentions,
"Full rendered message (up/down scrolls)",
),
"area:msg",
)
def show_full_raw_message(
self,
message: Message,
topic_links: "OrderedDict[str, Tuple[str, int, bool]]",
message_links: "OrderedDict[str, Tuple[str, int, bool]]",
time_mentions: List[Tuple[str, str]],
) -> None:
self.show_pop_up(
FullRawMsgView(
self,
message,
topic_links,
message_links,
time_mentions,
"Full raw message (up/down scrolls)",
),
"area:msg",
)
def show_edit_history(
self,
message: Message,
topic_links: "OrderedDict[str, Tuple[str, int, bool]]",
message_links: "OrderedDict[str, Tuple[str, int, bool]]",
time_mentions: List[Tuple[str, str]],
) -> None:
self.show_pop_up(
EditHistoryView(
self,
message,
topic_links,
message_links,
time_mentions,
"Edit History (up/down scrolls)",
),
"area:msg",
)
def open_in_browser(self, url: str) -> None:
"""
Opens any provided URL in a graphical browser, if found, else
prints an appropriate error message.
"""
# Don't try to open web browser if running without a GUI
# TODO: Explore and eventually support opening links in text-browsers.
if (
PLATFORM == "Linux"
and not os.environ.get("DISPLAY")
and os.environ.get("TERM")
):
self.report_error(
[
"No DISPLAY environment variable specified. This could "
"likely mean the ZT host is running without a GUI."
]
)
return
try:
# Checks for a runnable browser in the system and returns
# its browser controller, if found, else reports an error
browser_controller = webbrowser.get()
# Suppress stdout and stderr when opening browser
with suppress_output():
browser_controller.open(url)
self.report_success(
[
f"The link was successfully opened using {browser_controller.name}"
]
)
except webbrowser.Error as e:
# Set a footer text if no runnable browser is located
self.report_error([f"ERROR: {e}"])
@asynch
def show_typing_notification(self) -> None:
self.is_typing_notification_in_progress = True
dots = itertools.cycle(["", ".", "..", "..."])
# Until conversation becomes "inactive" like when a `stop` event is sent
while self.active_conversation_info:
sender_name = self.active_conversation_info["sender_name"]
self.view.set_footer_text(
[
("footer_contrast", " " + sender_name + " "),
" is typing" + next(dots),
]
)
time.sleep(0.45)
self.is_typing_notification_in_progress = False
self.view.set_footer_text()
def report_error(
self,
text: List[Union[str, Tuple[Literal["footer_contrast"], str]]],
duration: int = 3,
) -> None:
"""
Helper to show an error message in footer
"""
self.view.set_footer_text(text, "task:error", duration)
def report_success(
self,
text: List[Union[str, Tuple[Literal["footer_contrast"], str]]],
duration: int = 3,
) -> None:
"""
Helper to show a success message in footer
"""
self.view.set_footer_text(text, "task:success", duration)
def report_warning(
self,
text: List[Union[str, Tuple[Literal["footer_contrast"], str]]],
duration: int = 3,
) -> None:
"""
Helper to show a warning message in footer
"""
self.view.set_footer_text(text, "task:warning", duration)
def show_media_confirmation_popup(
self, func: Any, tool: str, media_path: str
) -> None:
callback = partial(func, self, tool, media_path)
question = urwid.Text(
[
"Your requested media has been downloaded to:\n",
("bold", media_path),
"\n\nDo you want the application to open it with ",
("bold", tool),
"?",
]
)
self.loop.widget = PopUpConfirmationView(
self, question, callback, location="center"
)
def search_messages(self, text: str) -> None:
# Search for a text in messages
self.model.index["search"].clear()
self.model.set_search_narrow(text)
self.model.get_messages(num_after=0, num_before=30, anchor=10000000000)
msg_id_list = self.model.get_message_ids_in_current_narrow()
w_list = create_msg_box_list(self.model, msg_id_list)
self.view.message_view.log.clear()
self.view.message_view.log.extend(w_list)
focus_position = 0
if 0 <= focus_position < len(w_list):
self.view.message_view.set_focus(focus_position)
def save_draft_confirmation_popup(self, draft: Composition) -> None:
question = urwid.Text(
"Save this message as a draft? (This will overwrite the existing draft.)"
)
save_draft = partial(self.model.save_draft, draft)
self.loop.widget = PopUpConfirmationView(self, question, save_draft)
def stream_muting_confirmation_popup(
self, stream_id: int, stream_name: str
) -> None:
currently_muted = self.model.is_muted_stream(stream_id)
type_of_action = "unmuting" if currently_muted else "muting"
question = urwid.Text(
("bold", f"Confirm {type_of_action} of stream '{stream_name}' ?"),
"center",
)
mute_this_stream = partial(self.model.toggle_stream_muted_status, stream_id)
self.loop.widget = PopUpConfirmationView(self, question, mute_this_stream)
def copy_to_clipboard(self, text: str, text_category: str) -> None:
try:
pyperclip.copy(text)
clipboard_text = pyperclip.paste()
if clipboard_text == text:
self.report_success([f"{text_category} copied successfully"])
else:
self.report_warning(
[f"{text_category} copied, but the clipboard text does not match"]
)
except pyperclip.PyperclipException:
body = [
"Zulip terminal uses 'pyperclip', for copying texts to your clipboard,"
" which could not find a copy/paste mechanism for your system. :("
"\nThis error should only appear on Linux. You can fix this by"
" installing any ONE of the copy/paste mechanisms below:\n",
("msg_bold", "- xclip\n- xsel"),
"\n\nvia something like:\n",
("msg_code", "apt-get install xclip [Recommended]\n"),
("msg_code", "apt-get install xsel"),
]
self.show_pop_up(
NoticeView(self, body, 60, "UTILITY PACKAGE MISSING"), "area:error"
)
def _narrow_to(self, anchor: Optional[int], **narrow: Any) -> None:
already_narrowed = self.model.set_narrow(**narrow)
if already_narrowed and anchor is None:
return
msg_id_list = self.model.get_message_ids_in_current_narrow()
# If no messages are found in the current narrow
# OR, given anchor is not present in msg_id_list
# then, get more messages.
if len(msg_id_list) == 0 or (anchor is not None and anchor not in msg_id_list):
self.model.get_messages(num_before=30, num_after=10, anchor=anchor)
msg_id_list = self.model.get_message_ids_in_current_narrow()
w_list = create_msg_box_list(self.model, msg_id_list, focus_msg_id=anchor)
focus_position = self.model.get_focus_in_current_narrow()
if focus_position == set(): # No available focus; set to end
focus_position = len(w_list) - 1
assert not isinstance(focus_position, set)
self.view.message_view.log.clear()
if 0 <= focus_position < len(w_list):
self.view.message_view.log.extend(w_list, focus_position)
else:
self.view.message_view.log.extend(w_list)
def narrow_to_stream(
self, *, stream_name: str, contextual_message_id: Optional[int] = None
) -> None:
self._narrow_to(anchor=contextual_message_id, stream=stream_name)
def narrow_to_topic(
self,
*,
stream_name: str,
topic_name: str,
contextual_message_id: Optional[int] = None,
) -> None:
self._narrow_to(
anchor=contextual_message_id,
stream=stream_name,
topic=topic_name,
)
def narrow_to_user(
self,
*,
recipient_emails: List[str],
contextual_message_id: Optional[int] = None,
) -> None:
self._narrow_to(
anchor=contextual_message_id,
pm_with=", ".join(recipient_emails),
)
def narrow_to_all_messages(
self, *, contextual_message_id: Optional[int] = None
) -> None:
self._narrow_to(anchor=contextual_message_id)
def narrow_to_all_pm(self, *, contextual_message_id: Optional[int] = None) -> None:
self._narrow_to(anchor=contextual_message_id, pms=True)
def narrow_to_all_starred(self) -> None:
# NOTE: Should we allow maintaining anchor focus here?
# (nothing currently requires narrowing around a message id)
self._narrow_to(anchor=None, starred=True)
def narrow_to_all_mentions(self) -> None:
# NOTE: Should we allow maintaining anchor focus here?
# (nothing currently requires narrowing around a message id)
self._narrow_to(anchor=None, mentioned=True)
def deregister_client(self) -> None:
queue_id = self.model.queue_id
self.client.deregister(queue_id, 1.0)
def exit_handler(self, signum: int, frame: Any) -> None:
self.deregister_client()
sys.exit(0)
def _raise_exception(self, *args: Any, **kwargs: Any) -> Literal[True]:
if self._exception_info is not None:
exc = self._exception_info
if self._critical_exception:
raise exc[0].with_traceback(exc[1], exc[2])
else:
import traceback
exception_logfile = "zulip-terminal-thread-exceptions.log"
with open(exception_logfile, "a") as logfile:
traceback.print_exception(*exc, file=logfile)
message = (
"An exception occurred:"
+ "\n\n"
+ "".join(traceback.format_exception_only(exc[0], exc[1]))
+ "\n"
+ "The application should continue functioning, but you "
+ "may notice inconsistent behavior in this session."
+ "\n\n"
+ "Please report this to us either in"
+ "\n"
+ "* the #zulip-terminal stream"
+ "\n"
+ " (https://chat.zulip.org/#narrow/stream/"
+ "206-zulip-terminal in the webapp)"
+ "\n"
+ "* an issue at "
+ "https://github.com/zulip/zulip-terminal/issues"
+ "\n\n"
+ "Details of the exception can be found in "
+ exception_logfile
)
self.popup_with_message(message, width=80)
self._exception_info = None
return True # If don't raise, retain pipe
def main(self) -> None:
try:
# TODO: Enable resuming? (in which case, remove ^Z below)
disabled_keys = {
"susp": "undefined", # Disable ^Z - no suspending
"stop": "undefined", # Disable ^S - enabling shortcut key use
"quit": "undefined", # Disable ^\, ^4
}
old_signal_list = self.loop.screen.tty_signal_keys(**disabled_keys)
self.loop.run()
except Exception:
self.restore_stdout()
self.loop.screen.tty_signal_keys(*old_signal_list)
raise
finally:
self.restore_stdout()
self.loop.screen.tty_signal_keys(*old_signal_list) | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/core.py | core.py |
import urllib.parse
from zulipterminal.api_types import Message
def hash_util_encode(string: str) -> str:
"""
Hide URI-encoding by replacing '%' with '.'
urllib.quote is equivalent to encodeURIComponent in JavaScript.
Referred from zerver/lib/url_encoding.py
"""
# `safe` has a default value of "/", but we want those encoded, too.
return urllib.parse.quote(string, safe=b"").replace(".", "%2E").replace("%", ".")
def encode_stream(stream_id: int, stream_name: str) -> str:
"""
Encodes stream_name with stream_id and replacing any occurence
of whitespace to '-'. This is the format of message representation
in webapp. Referred from zerver/lib/url_encoding.py.
"""
stream_name = stream_name.replace(" ", "-")
return str(stream_id) + "-" + hash_util_encode(stream_name)
def near_stream_message_url(server_url: str, message: Message) -> str:
"""
Returns the complete encoded URL of a message from #narrow/stream.
Referred from zerver/lib/url_encoding.py.
"""
message_id = str(message["id"])
stream_id = message["stream_id"]
stream_name = message["display_recipient"]
topic_name = message["subject"]
encoded_stream = encode_stream(stream_id, stream_name)
encoded_topic = hash_util_encode(topic_name)
parts = [
server_url,
"#narrow",
"stream",
encoded_stream,
"topic",
encoded_topic,
"near",
message_id,
]
full_url = "/".join(parts)
return full_url
def near_pm_message_url(server_url: str, message: Message) -> str:
"""
Returns the complete encoded URL of a message from #narrow/pm-with.
Referred from zerver/lib/url_encoding.py.
"""
message_id = str(message["id"])
str_user_ids = [str(recipient["id"]) for recipient in message["display_recipient"]]
pm_str = ",".join(str_user_ids) + "-pm"
parts = [
server_url,
"#narrow",
"pm-with",
pm_str,
"near",
message_id,
]
full_url = "/".join(parts)
return full_url
def near_message_url(server_url: str, message: Message) -> str:
"""
Returns the correct encoded URL of a message, if
it is present in stream/pm-with accordingly.
Referred from zerver/lib/url_encoding.py.
"""
if message["type"] == "stream":
url = near_stream_message_url(server_url, message)
else:
url = near_pm_message_url(server_url, message)
return url | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/server_url.py | server_url.py |
import random
import re
import time
from typing import Any, List, Optional
import urwid
from zulipterminal.config.keys import commands_for_random_tips, is_command_key
from zulipterminal.config.symbols import (
APPLICATION_TITLE_BAR_LINE,
AUTOHIDE_TAB_LEFT_ARROW,
AUTOHIDE_TAB_RIGHT_ARROW,
COLUMN_TITLE_BAR_LINE,
)
from zulipterminal.config.ui_sizes import LEFT_WIDTH, RIGHT_WIDTH, TAB_WIDTH
from zulipterminal.helper import asynch
from zulipterminal.platform_code import MOUSE_SELECTION_KEY, PLATFORM
from zulipterminal.ui_tools.boxes import SearchBox, WriteBox
from zulipterminal.ui_tools.views import (
LeftColumnView,
MiddleColumnView,
RightColumnView,
TabView,
)
from zulipterminal.urwid_types import urwid_Box
class View(urwid.WidgetWrap):
"""
A class responsible for providing the application's interface.
"""
def __init__(self, controller: Any) -> None:
self.controller = controller
self.palette = controller.theme
self.model = controller.model
self.users = self.model.users
self.pinned_streams = self.model.pinned_streams
self.unpinned_streams = self.model.unpinned_streams
self.write_box = WriteBox(self)
self.search_box = SearchBox(self.controller)
self.message_view: Any = None
self.displaying_selection_hint = False
super().__init__(self.main_window())
def left_column_view(self) -> Any:
tab = TabView(
f"{AUTOHIDE_TAB_LEFT_ARROW} STREAMS & TOPICS {AUTOHIDE_TAB_LEFT_ARROW}"
)
panel = LeftColumnView(self)
return panel, tab
def middle_column_view(self) -> Any:
self.middle_column = MiddleColumnView(
self, self.model, self.write_box, self.search_box
)
return urwid.LineBox(
self.middle_column,
title="Messages",
title_attr="column_title",
tline=COLUMN_TITLE_BAR_LINE,
bline="",
trcorner="│",
tlcorner="│",
)
def right_column_view(self) -> Any:
tab = TabView(f"{AUTOHIDE_TAB_RIGHT_ARROW} USERS {AUTOHIDE_TAB_RIGHT_ARROW}")
self.users_view = RightColumnView(self)
panel = urwid.LineBox(
self.users_view,
title="Users",
title_attr="column_title",
tlcorner=COLUMN_TITLE_BAR_LINE,
tline=COLUMN_TITLE_BAR_LINE,
trcorner=COLUMN_TITLE_BAR_LINE,
lline="",
blcorner="─",
rline="",
bline="",
brcorner="",
)
return panel, tab
def get_random_help(self) -> List[Any]:
# Get random allowed hotkey (ie. eligible for being displayed as a tip)
allowed_commands = commands_for_random_tips()
if not allowed_commands:
return ["Help(?): "]
random_command = random.choice(allowed_commands)
return [
"Help(?): ",
("footer_contrast", " " + ", ".join(random_command["keys"]) + " "),
" " + random_command["help_text"],
]
@asynch
def set_footer_text(
self,
text_list: Optional[List[Any]] = None,
style: str = "footer",
duration: Optional[float] = None,
) -> None:
# Avoid updating repeatedly (then pausing and showing default text)
# This is simple, though doesn't avoid starting one thread for each call
if text_list == self._w.footer.text:
return
if text_list is None:
text = self.get_random_help()
else:
text = text_list
self.frame.footer.set_text(text)
self.frame.footer.set_attr_map({None: style})
self.controller.update_screen()
if duration is not None:
assert duration > 0
time.sleep(duration)
self.set_footer_text()
@asynch
def set_typeahead_footer(
self, suggestions: List[str], state: Optional[int], is_truncated: bool
) -> None:
if suggestions:
# Wrap by space.
footer_text: List[Any] = [" " + s + " " for s in suggestions]
if state is not None:
footer_text[state] = ("footer_contrast", footer_text[state])
if is_truncated:
footer_text += [" [more] "]
footer_text.insert(0, [" "]) # Add leading space.
else:
footer_text = [" [No matches found]"]
self.set_footer_text(footer_text)
def footer_view(self) -> Any:
text_header = self.get_random_help()
return urwid.AttrWrap(urwid.Text(text_header), "footer")
def main_window(self) -> Any:
self.left_panel, self.left_tab = self.left_column_view()
self.center_panel = self.middle_column_view()
self.right_panel, self.right_tab = self.right_column_view()
if self.controller.autohide:
body = [
(TAB_WIDTH, self.left_tab),
("weight", 10, self.center_panel),
(TAB_WIDTH, self.right_tab),
]
else:
body = [
(LEFT_WIDTH, self.left_panel),
("weight", 10, self.center_panel),
(RIGHT_WIDTH, self.right_panel),
]
self.body = urwid.Columns(body, focus_column=0)
# NOTE: message_view is None, but middle_column_view is called above
# and sets it.
assert self.message_view is not None
# NOTE: set_focus_changed_callback is actually called before the
# focus is set, so the message is not read yet, it will be read when
# the focus is changed again either vertically or horizontally.
self.body._contents.set_focus_changed_callback(self.message_view.read_message)
title_text = " {full_name} ({email}) - {server_name} ({url}) ".format(
full_name=self.model.user_full_name,
email=self.model.user_email,
server_name=self.model.server_name,
url=self.model.server_url,
)
title_bar = urwid.Columns(
[
urwid.Divider(div_char=APPLICATION_TITLE_BAR_LINE),
(len(title_text), urwid.Text([title_text])),
urwid.Divider(div_char=APPLICATION_TITLE_BAR_LINE),
]
)
self.frame = urwid.Frame(
self.body, title_bar, focus_part="body", footer=self.footer_view()
)
# Show left panel on startup in autohide mode
self.show_left_panel(visible=True)
return self.frame
def show_left_panel(self, *, visible: bool) -> None:
if not self.controller.autohide:
return
if visible:
self.frame.body = urwid.Overlay(
urwid.Columns(
[(LEFT_WIDTH, self.left_panel), (1, urwid.SolidFill("▏"))]
),
self.body,
align="left",
width=LEFT_WIDTH + 1,
valign="top",
height=("relative", 100),
)
else:
self.frame.body = self.body
# FIXME: This can be avoided after fixing the "sacrificing 1st
# unread msg" issue and setting focus_column=1 when initializing.
self.body.focus_position = 1
def show_right_panel(self, *, visible: bool) -> None:
if not self.controller.autohide:
return
if visible:
self.frame.body = urwid.Overlay(
urwid.Columns(
[(1, urwid.SolidFill("▕")), (RIGHT_WIDTH, self.right_panel)]
),
self.body,
align="right",
width=RIGHT_WIDTH + 1,
valign="top",
height=("relative", 100),
)
else:
self.frame.body = self.body
# FIXME: This can be avoided after fixing the "sacrificing 1st
# unread msg" issue and setting focus_column=1 when initializing.
self.body.focus_position = 1
def keypress(self, size: urwid_Box, key: str) -> Optional[str]:
self.model.new_user_input = True
if self.controller.is_in_editor_mode():
return self.controller.current_editor().keypress((size[1],), key)
# Redirect commands to message_view.
elif (
is_command_key("SEARCH_MESSAGES", key)
or is_command_key("NEXT_UNREAD_TOPIC", key)
or is_command_key("NEXT_UNREAD_PM", key)
or is_command_key("STREAM_MESSAGE", key)
or is_command_key("PRIVATE_MESSAGE", key)
):
self.show_left_panel(visible=False)
self.show_right_panel(visible=False)
self.body.focus_col = 1
self.middle_column.keypress(size, key)
return key
elif is_command_key("ALL_PM", key):
self.pm_button.activate(key)
elif is_command_key("ALL_STARRED", key):
self.starred_button.activate(key)
elif is_command_key("ALL_MENTIONS", key):
self.mentioned_button.activate(key)
elif is_command_key("SEARCH_PEOPLE", key):
# Start User Search if not in editor_mode
self.show_left_panel(visible=False)
self.show_right_panel(visible=True)
self.body.focus_position = 2
self.users_view.keypress(size, key)
return key
elif is_command_key("SEARCH_STREAMS", key) or is_command_key(
"SEARCH_TOPICS", key
):
# jump stream search
self.show_right_panel(visible=False)
self.show_left_panel(visible=True)
self.body.focus_position = 0
self.left_panel.keypress(size, key)
return key
elif is_command_key("OPEN_DRAFT", key):
saved_draft = self.model.session_draft_message()
if saved_draft:
self.show_left_panel(visible=False)
self.show_right_panel(visible=False)
if saved_draft["type"] == "stream":
stream_id = self.model.stream_id_from_name(saved_draft["to"])
self.write_box.stream_box_view(
caption=saved_draft["to"],
title=saved_draft["subject"],
stream_id=stream_id,
)
elif saved_draft["type"] == "private":
recipient_user_ids = saved_draft["to"]
self.write_box.private_box_view(
recipient_user_ids=recipient_user_ids,
)
content = saved_draft["content"]
self.write_box.msg_write_box.edit_text = content
self.write_box.msg_write_box.edit_pos = len(content)
self.body.focus_col = 1
self.middle_column.set_focus("footer")
else:
self.controller.report_error(
["No draft message was saved in this session."]
)
return key
elif is_command_key("ABOUT", key):
self.controller.show_about()
return key
elif is_command_key("HELP", key):
# Show help menu
self.controller.show_help()
return key
elif is_command_key("MARKDOWN_HELP", key):
self.controller.show_markdown_help()
return key
return super().keypress(size, key)
def mouse_event(
self, size: urwid_Box, event: str, button: int, col: int, row: int, focus: bool
) -> bool:
if event == "mouse drag":
self.model.controller.view.set_footer_text(
[
"Try pressing ",
("footer_contrast", f" {MOUSE_SELECTION_KEY} "),
" and dragging to select text.",
],
"task:warning",
)
self.displaying_selection_hint = True
elif event == "mouse release" and self.displaying_selection_hint:
self.model.controller.view.set_footer_text()
self.displaying_selection_hint = False
return super().mouse_event(size, event, button, col, row, focus)
class Screen(urwid.raw_display.Screen):
def write(self, data: Any) -> None:
if PLATFORM == "WSL":
# replace urwid's SI/SO, which produce artifacts under WSL.
# https://github.com/urwid/urwid/issues/264#issuecomment-358633735
# Above link describes the change.
data = re.sub("[\x0e\x0f]", "", data)
super().write(data) | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/ui.py | ui.py |
import json
import time
from collections import OrderedDict, defaultdict
from concurrent.futures import Future, ThreadPoolExecutor, wait
from copy import deepcopy
from datetime import datetime
from typing import (
Any,
Callable,
DefaultDict,
Dict,
FrozenSet,
Iterable,
List,
Optional,
Set,
Tuple,
Union,
cast,
)
from urllib.parse import urlparse
import zulip
from bs4 import BeautifulSoup
from typing_extensions import Literal, TypedDict
from zulipterminal import unicode_emojis
from zulipterminal.api_types import (
Composition,
EditPropagateMode,
Event,
PrivateComposition,
RealmEmojiData,
RealmUser,
StreamComposition,
Subscription,
)
from zulipterminal.config.keys import primary_key_for_command
from zulipterminal.config.symbols import STREAM_TOPIC_SEPARATOR
from zulipterminal.config.ui_mappings import ROLE_BY_ID, StreamAccessType
from zulipterminal.helper import (
Message,
NamedEmojiData,
StreamData,
TidiedUserInfo,
asynch,
canonicalize_color,
classify_unread_counts,
display_error_if_present,
index_messages,
initial_index,
notify_if_message_sent_outside_narrow,
set_count,
)
from zulipterminal.platform_code import notify
from zulipterminal.ui_tools.utils import create_msg_box_list
OFFLINE_THRESHOLD_SECS = 140
# Adapted from zerver/models.py
# These fields have migrated to the API inside the Realm object
# in ZFL 53. To allow backporting to earlier server versions, we
# define these hard-coded parameters.
MAX_STREAM_NAME_LENGTH = 60
MAX_TOPIC_NAME_LENGTH = 60
MAX_MESSAGE_LENGTH = 10000
class ServerConnectionFailure(Exception):
pass
def sort_streams(streams: List[StreamData]) -> None:
"""
Used for sorting model.pinned_streams and model.unpinned_streams.
"""
streams.sort(key=lambda s: s["name"].lower())
class UserSettings(TypedDict):
send_private_typing_notifications: bool
twenty_four_hour_time: bool
pm_content_in_desktop_notifications: bool
class Model:
"""
A class responsible for storing the data to be displayed.
"""
def __init__(self, controller: Any) -> None:
self.controller = controller
self.client = controller.client
self.narrow: List[Any] = []
self._have_last_message: Dict[str, bool] = {}
self.stream_id: Optional[int] = None
self.recipients: FrozenSet[Any] = frozenset()
self.index = initial_index
self.user_id = -1
self.user_email = ""
self.user_full_name = ""
self.server_url = "{uri.scheme}://{uri.netloc}/".format(
uri=urlparse(self.client.base_url)
)
self.server_name = ""
self._notified_user_of_notification_failure = False
# Events fetched once at startup
self.initial_data_to_fetch: List[str] = [
"realm",
"presence",
"subscription",
"message",
"starred_messages",
"update_message_flags",
"muted_topics",
"realm_user", # Enables cross_realm_bots
"realm_user_groups",
"update_global_notifications",
"update_display_settings",
"user_settings",
"realm_emoji",
# zulip_version and zulip_feature_level are always returned in
# POST /register from Feature level 3.
"zulip_version",
]
# Events desired with their corresponding callback
self.event_actions: "OrderedDict[str, Callable[[Event], None]]" = OrderedDict(
[
("message", self._handle_message_event),
("update_message", self._handle_update_message_event),
("reaction", self._handle_reaction_event),
("subscription", self._handle_subscription_event),
("typing", self._handle_typing_event),
("update_message_flags", self._handle_update_message_flags_event),
(
"update_global_notifications",
self._handle_update_global_notifications_event,
),
("update_display_settings", self._handle_update_display_settings_event),
("user_settings", self._handle_user_settings_event),
("realm_emoji", self._handle_update_emoji_event),
]
)
self.initial_data: Dict[str, Any] = {}
# Register to the queue before initializing further so that we don't
# lose any updates while messages are being fetched.
self._fetch_initial_data()
self._all_users_by_id: Dict[int, RealmUser] = {}
self._cross_realm_bots_by_id: Dict[int, RealmUser] = {}
self.server_version = self.initial_data["zulip_version"]
self.server_feature_level = self.initial_data.get("zulip_feature_level")
self.users = self.get_all_users()
self.stream_dict: Dict[int, Any] = {}
self.muted_streams: Set[int] = set()
self.pinned_streams: List[StreamData] = []
self.unpinned_streams: List[StreamData] = []
self.visual_notified_streams: Set[int] = set()
self._subscribe_to_streams(self.initial_data["subscriptions"])
# NOTE: The date_created field of stream has been added in feature
# level 30, server version 4. For consistency we add this field
# on server iterations even before this with value of None.
if self.server_feature_level is None or self.server_feature_level < 30:
for stream in self.stream_dict.values():
stream["date_created"] = None
self.normalize_and_cache_message_retention_text()
# NOTE: The expected response has been upgraded from
# [stream_name, topic] to [stream_name, topic, date_muted] in
# feature level 1, server version 3.0.
muted_topics = self.initial_data["muted_topics"]
assert set(map(len, muted_topics)) in (set(), {2}, {3})
self._muted_topics: Dict[Tuple[str, str], Optional[int]] = {
(stream_name, topic): (
None if self.server_feature_level is None else date_muted[0]
)
for stream_name, topic, *date_muted in muted_topics
}
groups = self.initial_data["realm_user_groups"]
self.user_group_by_id: Dict[int, Dict[str, Any]] = {}
self.user_group_names = self._group_info_from_realm_user_groups(groups)
self.unread_counts = classify_unread_counts(self)
self._draft: Optional[Composition] = None
self._store_content_length_restrictions()
self.active_emoji_data, self.all_emoji_names = self.generate_all_emoji_data(
self.initial_data["realm_emoji"]
)
# "user_settings" only present in ZFl 89+ (v5.0)
user_settings = self.initial_data.get("user_settings", None)
# TODO: Support multiple settings locations via settings migration #1108
self._user_settings = UserSettings(
send_private_typing_notifications=(
True
if user_settings is None
else user_settings["send_private_typing_notifications"]
), # ZFL 105, Zulip 5.0
twenty_four_hour_time=self.initial_data["twenty_four_hour_time"],
pm_content_in_desktop_notifications=self.initial_data[
"pm_content_in_desktop_notifications"
],
)
self.new_user_input = True
self._start_presence_updates()
def user_settings(self) -> UserSettings:
return deepcopy(self._user_settings)
def message_retention_days_response(self, days: int, org_default: bool) -> str:
suffix = " [Organization default]" if org_default else ""
return ("Indefinite" if (days == -1 or days is None) else str(days)) + suffix
def normalize_and_cache_message_retention_text(self) -> None:
# NOTE: The "message_retention_days" field was added in server v3.0, ZFL 17.
# For consistency, we add this field on server iterations even before this
# assigning it the value of "realm_message_retention_days" from /register.
# The server defines two special values for this field:
# • None: Inherits organization-level setting i.e. realm_message_retention_days
# • -1: Messages in this stream are stored indefinitely
# We store the abstracted message retention text for each stream mapped to its
# sream_id in model.cached_retention_text. This will be displayed in the UI.
self.cached_retention_text: Dict[int, str] = {}
realm_message_retention_days = self.initial_data["realm_message_retention_days"]
if self.server_feature_level is None or self.server_feature_level < 17:
for stream in self.stream_dict.values():
stream["message_retention_days"] = None
for stream in self.stream_dict.values():
message_retention_days = stream["message_retention_days"]
is_organization_default = message_retention_days is None
final_msg_retention_days = (
realm_message_retention_days
if is_organization_default
else message_retention_days
)
message_retention_response = self.message_retention_days_response(
final_msg_retention_days, is_organization_default
)
self.cached_retention_text[stream["stream_id"]] = message_retention_response
def get_focus_in_current_narrow(self) -> Union[int, Set[None]]:
"""
Returns the focus in the current narrow.
For no existing focus this returns {}, otherwise the message ID.
"""
return self.index["pointer"][repr(self.narrow)]
def set_focus_in_current_narrow(self, focus_message: int) -> None:
self.index["pointer"][repr(self.narrow)] = focus_message
def is_search_narrow(self) -> bool:
"""
Checks if the current narrow is a result of a previous search for
a messages in a different narrow.
"""
return "search" in [subnarrow[0] for subnarrow in self.narrow]
def set_narrow(
self,
*,
stream: Optional[str] = None,
topic: Optional[str] = None,
pms: bool = False,
pm_with: Optional[str] = None,
starred: bool = False,
mentioned: bool = False,
) -> bool:
selected_params = {k for k, v in locals().items() if k != "self" and v}
valid_narrows: Dict[FrozenSet[str], List[Any]] = {
frozenset(): [],
frozenset(["stream"]): [["stream", stream]],
frozenset(["stream", "topic"]): [["stream", stream], ["topic", topic]],
frozenset(["pms"]): [["is", "private"]],
frozenset(["pm_with"]): [["pm_with", pm_with]],
frozenset(["starred"]): [["is", "starred"]],
frozenset(["mentioned"]): [["is", "mentioned"]],
}
for narrow_param, narrow in valid_narrows.items():
if narrow_param == selected_params:
new_narrow = narrow
break
else:
raise RuntimeError("Model.set_narrow parameters used incorrectly.")
if new_narrow != self.narrow:
self.narrow = new_narrow
if pm_with is not None and new_narrow[0][0] == "pm_with":
users = pm_with.split(", ")
self.recipients = frozenset(
[self.user_dict[user]["user_id"] for user in users] + [self.user_id]
)
else:
self.recipients = frozenset()
if stream is not None:
# FIXME?: Set up a mapping for this if we plan to use it a lot
self.stream_id = self.stream_id_from_name(stream)
else:
self.stream_id = None
return False
else:
return True
def set_search_narrow(self, search_query: str) -> None:
self.unset_search_narrow()
self.narrow.append(["search", search_query])
def unset_search_narrow(self) -> None:
# If current narrow is a result of a previous started search,
# we pop the ['search', 'text'] term in the narrow, before
# setting a new narrow.
if self.is_search_narrow():
self.narrow = [item for item in self.narrow if item[0] != "search"]
def get_message_ids_in_current_narrow(self) -> Set[int]:
narrow = self.narrow
index = self.index
if narrow == []:
ids = index["all_msg_ids"]
elif self.is_search_narrow(): # Check searches first
ids = index["search"]
elif narrow[0][0] == "stream":
assert self.stream_id is not None
stream_id = self.stream_id
if len(narrow) == 1:
ids = index["stream_msg_ids_by_stream_id"][stream_id]
elif len(narrow) == 2:
topic = narrow[1][1]
ids = index["topic_msg_ids"][stream_id].get(topic, set())
elif narrow[0][1] == "private":
ids = index["private_msg_ids"]
elif narrow[0][0] == "pm_with":
recipients = self.recipients
ids = index["private_msg_ids_by_user_ids"].get(recipients, set())
elif narrow[0][1] == "starred":
ids = index["starred_msg_ids"]
elif narrow[0][1] == "mentioned":
ids = index["mentioned_msg_ids"]
return ids.copy()
def current_narrow_contains_message(self, message: Message) -> bool:
"""
Determine if a message conceptually belongs to a narrow
FIXME?: stars are not handled right now
"""
return (
# all messages contains all messages
not self.narrow
# mentions
or (
self.narrow[0][1] == "mentioned"
and bool({"mentioned", "wildcard_mentioned"} & set(message["flags"]))
)
# All-PMs
# FIXME Buggy condition?
or (self.narrow[0][1] == message["type"] and len(self.narrow) == 1)
# stream or stream+topic
or (
self.narrow[0][0] == "stream"
and message["type"] == "stream"
and message["display_recipient"] == self.narrow[0][1]
and (
len(self.narrow) == 1 # stream
or (
len(self.narrow) == 2 # stream+topic
and self.narrow[1][1] == message["subject"]
)
)
)
# PM-with
or (
self.narrow[0][0] == "pm_with"
and message["type"] == "private"
and len(self.narrow) == 1
and self.recipients
== frozenset([user["id"] for user in message["display_recipient"]])
)
)
def _notify_server_of_presence(self) -> Dict[str, Any]:
response = self.client.update_presence(
request={
# TODO: Determine `status` from terminal tab focus.
"status": "active" if self.new_user_input else "idle",
"new_user_input": self.new_user_input,
}
)
self.new_user_input = False
return response
@asynch
def _start_presence_updates(self) -> None:
"""
Call `_notify_server_of_presence` every minute (version 1a).
Use 'response' to update user list (version 1b).
"""
# FIXME: Version 2: call endpoint with ping_only=True only when
# needed, and rely on presence events to update
while True:
response = self._notify_server_of_presence()
if response["result"] == "success":
self.initial_data["presences"] = response["presences"]
self.users = self.get_all_users()
if hasattr(self.controller, "view"):
view = self.controller.view
view.users_view.update_user_list(user_list=self.users)
view.middle_column.update_message_list_status_markers()
time.sleep(60)
@asynch
def toggle_message_reaction(
self, message: Message, reaction_to_toggle: str
) -> None:
# Check if reaction_to_toggle is a valid original/alias
assert reaction_to_toggle in self.all_emoji_names
for emoji_name, emoji_data in self.active_emoji_data.items():
if (
reaction_to_toggle == emoji_name
or reaction_to_toggle in emoji_data["aliases"]
):
# Found the emoji to toggle. Store its code/type and dont check further
emoji_code = emoji_data["code"]
emoji_type = emoji_data["type"]
break
reaction_to_toggle_spec = dict(
emoji_name=reaction_to_toggle,
emoji_code=emoji_code,
reaction_type=emoji_type,
message_id=str(message["id"]),
)
has_user_reacted = self.has_user_reacted_to_message(
message, emoji_code=emoji_code
)
if has_user_reacted:
response = self.client.remove_reaction(reaction_to_toggle_spec)
else:
response = self.client.add_reaction(reaction_to_toggle_spec)
display_error_if_present(response, self.controller)
def has_user_reacted_to_message(self, message: Message, *, emoji_code: str) -> bool:
for reaction in message["reactions"]:
if reaction["emoji_code"] != emoji_code:
continue
# The reaction.user_id field was added in Zulip v3.0, ZFL 2 so we need to
# check both the reaction.user.{user_id/id} fields too for pre v3 support.
user = reaction.get("user", {})
has_user_reacted = (
user.get("user_id", None) == self.user_id
or user.get("id", None) == self.user_id
or reaction.get("user_id", None) == self.user_id
)
if has_user_reacted:
return True
return False
def session_draft_message(self) -> Optional[Composition]:
return deepcopy(self._draft)
def save_draft(self, draft: Composition) -> None:
self._draft = deepcopy(draft)
self.controller.report_success(["Saved message as draft"])
@asynch
def toggle_message_star_status(self, message: Message) -> None:
base_request = dict(flag="starred", messages=[message["id"]])
if "starred" in message["flags"]:
request = dict(base_request, op="remove")
else:
request = dict(base_request, op="add")
response = self.client.update_message_flags(request)
display_error_if_present(response, self.controller)
@asynch
def mark_message_ids_as_read(self, id_list: List[int]) -> None:
if not id_list:
return
response = self.client.update_message_flags(
{
"messages": id_list,
"flag": "read",
"op": "add",
}
)
display_error_if_present(response, self.controller)
@asynch
def send_typing_status_by_user_ids(
self, recipient_user_ids: List[int], *, status: Literal["start", "stop"]
) -> None:
if not self.user_settings()["send_private_typing_notifications"]:
return
if recipient_user_ids:
request = {"to": recipient_user_ids, "op": status}
response = self.client.set_typing_status(request)
display_error_if_present(response, self.controller)
else:
raise RuntimeError("Empty recipient list.")
def send_private_message(self, recipients: List[int], content: str) -> bool:
if recipients:
composition = PrivateComposition(
type="private",
to=recipients,
content=content,
)
response = self.client.send_message(composition)
display_error_if_present(response, self.controller)
message_was_sent = response["result"] == "success"
if message_was_sent:
notify_if_message_sent_outside_narrow(composition, self.controller)
return message_was_sent
else:
raise RuntimeError("Empty recipients list.")
def send_stream_message(self, stream: str, topic: str, content: str) -> bool:
composition = StreamComposition(
type="stream",
to=stream,
subject=topic,
content=content,
)
response = self.client.send_message(composition)
display_error_if_present(response, self.controller)
message_was_sent = response["result"] == "success"
if message_was_sent:
notify_if_message_sent_outside_narrow(composition, self.controller)
return message_was_sent
def update_private_message(self, msg_id: int, content: str) -> bool:
request = {
"message_id": msg_id,
"content": content,
}
response = self.client.update_message(request)
display_error_if_present(response, self.controller)
return response["result"] == "success"
def update_stream_message(
self,
topic: str,
message_id: int,
propagate_mode: EditPropagateMode,
content: Optional[str] = None,
) -> bool:
request = {
"message_id": message_id,
"propagate_mode": propagate_mode,
"topic": topic,
}
if content is not None:
request["content"] = content
response = self.client.update_message(request)
display_error_if_present(response, self.controller)
if response["result"] == "success":
message = self.index["messages"][message_id]
stream_name = message.get("display_recipient", None)
old_topic = message.get("subject", None)
new_topic = request["topic"]
stream_name_markup = (
"footer_contrast",
f" {stream_name} {STREAM_TOPIC_SEPARATOR} ",
)
old_topic_markup = ("footer_contrast", f" {old_topic} ")
new_topic_markup = ("footer_contrast", f" {new_topic} ")
if old_topic != new_topic:
if propagate_mode == "change_one":
messages_changed = "one message's"
elif propagate_mode == "change_all":
messages_changed = "all messages'"
else: # propagate_mode == "change_later":
messages_changed = "some messages'"
self.controller.report_success(
[
f"You changed {messages_changed} topic from ",
stream_name_markup,
old_topic_markup,
" to ",
stream_name_markup,
new_topic_markup,
" .",
],
duration=6,
)
return response["result"] == "success"
def generate_all_emoji_data(
self, custom_emoji: Dict[str, RealmEmojiData]
) -> Tuple[NamedEmojiData, List[str]]:
unicode_emoji_data = unicode_emojis.EMOJI_DATA
for name, data in unicode_emoji_data.items():
data["type"] = "unicode_emoji"
typed_unicode_emoji_data = cast(NamedEmojiData, unicode_emoji_data)
custom_emoji_data: NamedEmojiData = {
emoji["name"]: {
"code": emoji_code,
"aliases": [],
"type": "realm_emoji",
}
for emoji_code, emoji in custom_emoji.items()
if not emoji["deactivated"]
}
zulip_extra_emoji: NamedEmojiData = {
"zulip": {"code": "zulip", "aliases": [], "type": "zulip_extra_emoji"}
}
all_emoji_data = {
**typed_unicode_emoji_data,
**custom_emoji_data,
**zulip_extra_emoji,
}
all_emoji_names = []
for emoji_name, emoji_data in all_emoji_data.items():
all_emoji_names.append(emoji_name)
all_emoji_names.extend(emoji_data["aliases"])
all_emoji_names = sorted(all_emoji_names)
active_emoji_data = OrderedDict(sorted(all_emoji_data.items()))
return active_emoji_data, all_emoji_names
def get_messages(
self, *, num_after: int, num_before: int, anchor: Optional[int]
) -> str:
# anchor value may be specific message (int) or next unread (None)
first_anchor = anchor is None
anchor_value = anchor if anchor is not None else 0
request = {
"anchor": anchor_value,
"num_before": num_before,
"num_after": num_after,
"apply_markdown": True,
"use_first_unread_anchor": first_anchor,
"client_gravatar": True,
"narrow": json.dumps(self.narrow),
}
response = self.client.get_messages(message_filters=request)
if response["result"] == "success":
response["messages"] = [
self.modernize_message_response(msg) for msg in response["messages"]
]
self.index = index_messages(response["messages"], self, self.index)
narrow_str = repr(self.narrow)
if first_anchor and response["anchor"] != 10000000000000000:
self.index["pointer"][narrow_str] = response["anchor"]
if "found_newest" in response:
just_found_last_msg = response["found_newest"]
else:
# Older versions of the server does not contain the
# 'found_newest' flag. Instead, we use this logic:
query_range = num_after + num_before + 1
just_found_last_msg = len(response["messages"]) < query_range
had_last_msg = self._have_last_message.get(narrow_str, False)
self._have_last_message[narrow_str] = had_last_msg or just_found_last_msg
return ""
display_error_if_present(response, self.controller)
return response["msg"]
def _store_content_length_restrictions(self) -> None:
"""
Stores content length restriction fields for compose box in
Model, if received from server, else use pre-defined values.
These fields were added in server version 4.0, ZFL 53.
"""
self.max_stream_name_length = self.initial_data.get(
"max_stream_name_length", MAX_STREAM_NAME_LENGTH
)
self.max_topic_length = self.initial_data.get(
"max_topic_length", MAX_TOPIC_NAME_LENGTH
)
self.max_message_length = self.initial_data.get(
"max_message_length", MAX_MESSAGE_LENGTH
)
@staticmethod
def modernize_message_response(message: Message) -> Message:
"""
Converts received message into the modern message response format.
This provides a good single place to handle support for older server
releases params, and making them compatible with recent releases.
TODO: This could be extended for other message params in future.
"""
# (1) `subject_links` param is changed to `topic_links` from
# feature level 1, server version 3.0
if "subject_links" in message:
message["topic_links"] = message.pop("subject_links")
# (2) Modernize `topic_links` old response (List[str]) to new response
# (List[Dict[str, str]])
if "topic_links" in message:
topic_links = [
{"url": link, "text": ""}
for link in message["topic_links"]
if type(link) == str
]
if topic_links:
message["topic_links"] = topic_links
return message
def fetch_message_history(
self, message_id: int
) -> List[Dict[str, Union[int, str]]]:
"""
Fetches message edit history for a message using its ID.
"""
response = self.client.get_message_history(message_id)
if response["result"] == "success":
return response["message_history"]
display_error_if_present(response, self.controller)
return list()
def fetch_raw_message_content(self, message_id: int) -> Optional[str]:
"""
Fetches raw message content of a message using its ID.
"""
response = self.client.get_raw_message(message_id)
if response["result"] == "success":
return response["raw_content"]
display_error_if_present(response, self.controller)
return None
def _fetch_topics_in_streams(self, stream_list: Iterable[int]) -> str:
"""
Fetch all topics with specified stream_id's and
index their names (Version 1)
"""
# FIXME: Version 2: Fetch last 'n' recent topics for each stream.
for stream_id in stream_list:
response = self.client.get_stream_topics(stream_id)
if response["result"] == "success":
self.index["topics"][stream_id] = [
topic["name"] for topic in response["topics"]
]
else:
display_error_if_present(response, self.controller)
return response["msg"]
return ""
def topics_in_stream(self, stream_id: int) -> List[str]:
"""
Returns a list of topic names for stream_id from the index.
"""
if not self.index["topics"][stream_id]:
self._fetch_topics_in_streams([stream_id])
return list(self.index["topics"][stream_id])
@staticmethod
def exception_safe_result(future: "Future[str]") -> str:
try:
return future.result()
except zulip.ZulipError as e:
return str(e)
def is_muted_stream(self, stream_id: int) -> bool:
return stream_id in self.muted_streams
def is_muted_topic(self, stream_id: int, topic: str) -> bool:
"""
Returns True if topic is muted via muted_topics.
"""
stream_name = self.stream_dict[stream_id]["name"]
topic_to_search = (stream_name, topic)
return topic_to_search in self._muted_topics.keys()
def _fetch_initial_data(self) -> None:
# Thread Processes to reduce start time.
# NOTE: Exceptions do not work well with threads
with ThreadPoolExecutor(max_workers=1) as executor:
futures: Dict[str, Future[str]] = {
"get_messages": executor.submit(
self.get_messages, num_after=10, num_before=30, anchor=None
),
"register": executor.submit(
self._register_desired_events, fetch_data=True
),
}
# Wait for threads to complete
wait(futures.values())
results: Dict[str, str] = {
name: self.exception_safe_result(future) for name, future in futures.items()
}
if not any(results.values()):
self.user_id = self.initial_data["user_id"]
self.user_email = self.initial_data["email"]
self.user_full_name = self.initial_data["full_name"]
self.server_name = self.initial_data["realm_name"]
else:
failures: DefaultDict[str, List[str]] = defaultdict(list)
for name, result in results.items():
if result:
failures[result].append(name)
failure_text = [
"{} ({})".format(error, ", ".join(sorted(calls)))
for error, calls in failures.items()
]
raise ServerConnectionFailure(", ".join(failure_text))
def get_other_subscribers_in_stream(
self, stream_id: Optional[int] = None, stream_name: Optional[str] = None
) -> List[int]:
assert stream_id is not None or stream_name is not None
if stream_id:
assert self.is_user_subscribed_to_stream(stream_id)
return [
sub
for sub in self.stream_dict[stream_id]["subscribers"]
if sub != self.user_id
]
else:
return [
sub
for _, stream in self.stream_dict.items()
for sub in stream["subscribers"]
if stream["name"] == stream_name
if sub != self.user_id
]
def get_user_info(self, user_id: int) -> Optional[TidiedUserInfo]:
api_user_data: Optional[RealmUser] = self._all_users_by_id.get(user_id, None)
if not api_user_data:
return None
# TODO: Add custom fields later as an enhancement
user_info: TidiedUserInfo = dict(
full_name=api_user_data.get("full_name", "(No name)"),
email=api_user_data.get("email", ""),
date_joined=api_user_data.get("date_joined", ""),
timezone=api_user_data.get("timezone", ""),
is_bot=api_user_data.get("is_bot", False),
# Role `None` for triggering servers < Zulip 4.1 (ZFL 59)
role=api_user_data.get("role", None),
bot_type=api_user_data.get("bot_type", None),
bot_owner_name="", # Can be non-empty only if is_bot == True
last_active="",
)
if user_info["role"] is None:
# Default role is member
user_info["role"] = 400
# Ensure backwards compatibility for role parameters (e.g., `is_admin`)
for role_id, role in ROLE_BY_ID.items():
if api_user_data.get(role["bool"], None):
user_info["role"] = role_id
break
bot_owner: Optional[Union[RealmUser, Dict[str, Any]]] = None
if api_user_data.get("bot_owner_id", None):
bot_owner = self._all_users_by_id.get(api_user_data["bot_owner_id"], None)
# Ensure backwards compatibility for `bot_owner` (which is email of owner)
elif api_user_data.get("bot_owner", None):
bot_owner = self.user_dict.get(api_user_data["bot_owner"], None)
user_info["bot_owner_name"] = bot_owner["full_name"] if bot_owner else ""
if self.initial_data["presences"].get(user_info["email"], None):
timestamp = self.initial_data["presences"][user_info["email"]][
"aggregated"
]["timestamp"]
# Take 24h vs AM/PM format into consideration
user_info["last_active"] = self.formatted_local_time(
timestamp, show_seconds=True
)
return user_info
def get_all_users(self) -> List[Dict[str, Any]]:
# Dict which stores the active/idle status of users (by email)
presences = self.initial_data["presences"]
# Construct a dict of each user in the realm to look up by email
# and a user-id to email mapping
self.user_dict: Dict[str, Dict[str, Any]] = dict()
self.user_id_email_dict: Dict[int, str] = dict()
for user in self.initial_data["realm_users"]:
if self.user_id == user["user_id"]:
self._all_users_by_id[self.user_id] = user
current_user = {
"full_name": user["full_name"],
"email": user["email"],
"user_id": user["user_id"],
"status": "active",
}
continue
email = user["email"]
if email in presences: # presences currently subset of all users
"""
* Aggregate our information on a user's presence across their
* clients.
*
* For an explanation of the Zulip presence model this helps
* implement, see the subsystem doc:
https://zulip.readthedocs.io/en/latest/subsystems/presence.html
*
* This logic should match `status_from_timestamp` in the web
* app's
* `static/js/presence.js`.
*
* Out of the ClientPresence objects found in `presence`, we
* consider only those with a timestamp newer than
* OFFLINE_THRESHOLD_SECS; then of
* those, return the one that has the greatest UserStatus, where
* `active` > `idle` > `offline`.
*
* If there are several ClientPresence objects with the greatest
* UserStatus, an arbitrary one is chosen.
"""
aggregate_status = "offline"
for client in presences[email].items():
client_name = client[0]
status = client[1]["status"]
timestamp = client[1]["timestamp"]
if client_name == "aggregated":
continue
elif (time.time() - timestamp) < OFFLINE_THRESHOLD_SECS:
if status == "active":
aggregate_status = "active"
if status == "idle":
if aggregate_status != "active":
aggregate_status = status
if status == "offline":
if (
aggregate_status != "active"
and aggregate_status != "idle"
):
aggregate_status = status
status = aggregate_status
else:
# Set status of users not in the `presence` list
# as 'inactive'. They will not be displayed in the
# user's list by default (only in the search list).
status = "inactive"
self.user_dict[email] = {
"full_name": user["full_name"],
"email": email,
"user_id": user["user_id"],
"status": status,
}
self._all_users_by_id[user["user_id"]] = user
self.user_id_email_dict[user["user_id"]] = email
# Add internal (cross-realm) bots to dicts
for bot in self.initial_data["cross_realm_bots"]:
email = bot["email"]
self.user_dict[email] = {
"full_name": bot["full_name"],
"email": email,
"user_id": bot["user_id"],
"status": "inactive",
}
self._cross_realm_bots_by_id[bot["user_id"]] = bot
self._all_users_by_id[bot["user_id"]] = bot
self.user_id_email_dict[bot["user_id"]] = email
# Generate filtered lists for active & idle users
active = [
properties
for properties in self.user_dict.values()
if properties["status"] == "active"
]
idle = [
properties
for properties in self.user_dict.values()
if properties["status"] == "idle"
]
offline = [
properties
for properties in self.user_dict.values()
if properties["status"] == "offline"
]
inactive = [
properties
for properties in self.user_dict.values()
if properties["status"] == "inactive"
]
# Construct user_list from sorted components of each list
user_list = sorted(active, key=lambda u: u["full_name"].casefold())
user_list += sorted(idle, key=lambda u: u["full_name"].casefold())
user_list += sorted(offline, key=lambda u: u["full_name"].casefold())
user_list += sorted(inactive, key=lambda u: u["full_name"].casefold())
# Add current user to the top of the list
user_list.insert(0, current_user)
self.user_dict[current_user["email"]] = current_user
self.user_id_email_dict[self.user_id] = current_user["email"]
return user_list
def user_name_from_id(self, user_id: int) -> str:
"""
Returns user's full name given their ID.
"""
user_email = self.user_id_email_dict.get(user_id)
if not user_email:
raise RuntimeError("Invalid user ID.")
return self.user_dict[user_email]["full_name"]
def _subscribe_to_streams(self, subscriptions: List[Subscription]) -> None:
def make_reduced_stream_data(stream: Subscription) -> StreamData:
# stream_id has been changed to id.
return StreamData(
{
"name": stream["name"],
"id": stream["stream_id"],
"color": stream["color"],
"stream_access_type": self.stream_access_type(stream["stream_id"]),
"description": stream["description"],
}
)
new_pinned_streams = []
new_unpinned_streams = []
new_muted_streams = set()
new_visual_notified_streams = set()
for subscription in subscriptions:
# Canonicalize color formats, since zulip server versions may use
# different formats
subscription["color"] = canonicalize_color(subscription["color"])
self.stream_dict[subscription["stream_id"]] = subscription
streamData = make_reduced_stream_data(subscription)
if subscription["pin_to_top"]:
new_pinned_streams.append(streamData)
else:
new_unpinned_streams.append(streamData)
if not subscription["in_home_view"]:
new_muted_streams.add(subscription["stream_id"])
if subscription["desktop_notifications"]:
new_visual_notified_streams.add(subscription["stream_id"])
if new_pinned_streams:
self.pinned_streams.extend(new_pinned_streams)
sort_streams(self.pinned_streams)
if new_unpinned_streams:
self.unpinned_streams.extend(new_unpinned_streams)
sort_streams(self.unpinned_streams)
self.muted_streams = self.muted_streams.union(new_muted_streams)
self.visual_notified_streams = self.visual_notified_streams.union(
new_visual_notified_streams
)
def _group_info_from_realm_user_groups(
self, groups: List[Dict[str, Any]]
) -> List[str]:
"""
Stores group information in the model and returns a list of
group_names which helps in group typeahead. (Eg: @*terminal*)
"""
for sub_group in groups:
self.user_group_by_id[sub_group["id"]] = {
key: sub_group[key] for key in sub_group if key != "id"
}
user_group_names = [
self.user_group_by_id[group_id]["name"]
for group_id in self.user_group_by_id
]
# Sort groups for typeahead to work alphabetically (case-insensitive)
user_group_names.sort(key=str.lower)
return user_group_names
def toggle_stream_muted_status(self, stream_id: int) -> None:
request = [
{
"stream_id": stream_id,
"property": "is_muted",
"value": not self.is_muted_stream(stream_id)
# True for muting and False for unmuting.
}
]
response = self.client.update_subscription_settings(request)
display_error_if_present(response, self.controller)
def stream_id_from_name(self, stream_name: str) -> int:
for stream_id, stream in self.stream_dict.items():
if stream["name"] == stream_name:
return stream_id
raise RuntimeError("Invalid stream name.")
def stream_access_type(self, stream_id: int) -> StreamAccessType:
if stream_id not in self.stream_dict:
raise RuntimeError("Invalid stream id.")
stream = self.stream_dict[stream_id]
if stream.get("is_web_public", False):
return "web-public"
if stream["invite_only"]:
return "private"
return "public"
def is_pinned_stream(self, stream_id: int) -> bool:
return stream_id in [stream["id"] for stream in self.pinned_streams]
def toggle_stream_pinned_status(self, stream_id: int) -> bool:
request = [
{
"stream_id": stream_id,
"property": "pin_to_top",
"value": not self.is_pinned_stream(stream_id),
}
]
response = self.client.update_subscription_settings(request)
return response["result"] == "success"
def is_visual_notifications_enabled(self, stream_id: int) -> bool:
"""
Returns true if the stream had "desktop_notifications" enabled
"""
return stream_id in self.visual_notified_streams
def toggle_stream_visual_notifications(self, stream_id: int) -> None:
request = [
{
"stream_id": stream_id,
"property": "desktop_notifications",
"value": not self.is_visual_notifications_enabled(stream_id),
}
]
response = self.client.update_subscription_settings(request)
display_error_if_present(response, self.controller)
def is_user_subscribed_to_stream(self, stream_id: int) -> bool:
return stream_id in self.stream_dict
def _handle_subscription_event(self, event: Event) -> None:
"""
Handle changes in subscription (eg. muting/unmuting,
pinning/unpinning streams)
"""
assert event["type"] == "subscription"
def get_stream_by_id(streams: List[StreamData], stream_id: int) -> StreamData:
for stream in streams:
if stream["id"] == stream_id:
return stream
raise RuntimeError("Invalid stream id.")
if event["op"] == "update":
if hasattr(self.controller, "view"):
if event.get("property", None) == "in_home_view":
stream_id = event["stream_id"]
# FIXME: Does this always contain the stream_id?
stream_button = self.controller.view.stream_id_to_button[stream_id]
unread_count = self.unread_counts["streams"][stream_id]
if event["value"]: # Unmuting streams
self.muted_streams.remove(stream_id)
self.unread_counts["all_msg"] += unread_count
stream_button.mark_unmuted(unread_count)
else: # Muting streams
self.muted_streams.add(stream_id)
self.unread_counts["all_msg"] -= unread_count
stream_button.mark_muted()
self.controller.update_screen()
elif event.get("property", None) == "pin_to_top":
stream_id = event["stream_id"]
# FIXME: Does this always contain the stream_id?
stream_button = self.controller.view.stream_id_to_button[stream_id]
if event["value"]:
stream = get_stream_by_id(self.unpinned_streams, stream_id)
if stream:
self.unpinned_streams.remove(stream)
self.pinned_streams.append(stream)
else:
stream = get_stream_by_id(self.pinned_streams, stream_id)
if stream:
self.pinned_streams.remove(stream)
self.unpinned_streams.append(stream)
sort_streams(self.unpinned_streams)
sort_streams(self.pinned_streams)
self.controller.view.left_panel.update_stream_view()
self.controller.update_screen()
elif event.get("property", None) == "desktop_notifications":
stream_id = event["stream_id"]
if event["value"]:
self.visual_notified_streams.add(stream_id)
else:
self.visual_notified_streams.discard(stream_id)
elif event["op"] in ("peer_add", "peer_remove"):
# NOTE: ZFL 35 commit was not atomic with API change
# (ZFL >=35 can use new plural style)
if "stream_ids" not in event or "user_ids" not in event:
stream_ids = [event["stream_id"]]
user_ids = [event["user_id"]]
else:
stream_ids = event["stream_ids"]
user_ids = event["user_ids"]
for stream_id in stream_ids:
if self.is_user_subscribed_to_stream(stream_id):
subscribers = self.stream_dict[stream_id]["subscribers"]
if event["op"] == "peer_add":
subscribers.extend(user_ids)
else:
for user_id in user_ids:
subscribers.remove(user_id)
def _handle_typing_event(self, event: Event) -> None:
"""
Handle typing notifications (in private messages)
"""
assert event["type"] == "typing"
if not hasattr(self.controller, "view"):
return
narrow = self.narrow
controller = self.controller
active_conversation_info = controller.active_conversation_info
sender_email = event["sender"]["email"]
sender_id = event["sender"]["user_id"]
# If the user is in pm narrow with the person typing
# and the person typing isn't the user themselves
if (
len(narrow) == 1
and narrow[0][0] == "pm_with"
and sender_email in narrow[0][1].split(",")
and sender_id != self.user_id
):
if event["op"] == "start":
sender_name = self.user_dict[sender_email]["full_name"]
active_conversation_info["sender_name"] = sender_name
if not controller.is_typing_notification_in_progress:
controller.show_typing_notification()
elif event["op"] == "stop":
controller.active_conversation_info = {}
else:
raise RuntimeError("Unknown typing event operation")
def is_valid_private_recipient(
self,
recipient_email: str,
recipient_name: str,
) -> bool:
return (
recipient_email in self.user_dict
and self.user_dict[recipient_email]["full_name"] == recipient_name
)
def is_valid_stream(self, stream_name: str) -> bool:
for stream in self.stream_dict.values():
if stream["name"] == stream_name:
return True
return False
def notify_user(self, message: Message) -> str:
"""
return value signifies if notification failed, if it should occur
"""
# Check if notifications are enabled by the user.
# It is disabled by default.
if not self.controller.notify_enabled:
return ""
if message["sender_id"] == self.user_id:
return ""
recipient = ""
content = message["content"]
hidden_content = False
if message["type"] == "private":
recipient = "you"
if len(message["display_recipient"]) > 2:
extra_targets = [recipient] + [
recip["full_name"]
for recip in message["display_recipient"]
if recip["id"] not in (self.user_id, message["sender_id"])
]
recipient = ", ".join(extra_targets)
if not self.user_settings()["pm_content_in_desktop_notifications"]:
content = f"New private message from {message['sender_full_name']}"
hidden_content = True
elif message["type"] == "stream":
stream_id = message["stream_id"]
if {"mentioned", "wildcard_mentioned"}.intersection(
set(message["flags"])
) or self.is_visual_notifications_enabled(stream_id):
recipient = "{display_recipient} -> {subject}".format(**message)
if recipient:
if hidden_content:
text = content
else:
soup = BeautifulSoup(content, "lxml")
for spoiler_tag in soup.find_all(
"div", attrs={"class": "spoiler-block"}
):
header = spoiler_tag.find("div", attrs={"class": "spoiler-header"})
header.contents = [ele for ele in header.contents if ele != "\n"]
empty_header = len(header.contents) == 0
header.unwrap()
to_hide = spoiler_tag.find(
"div", attrs={"class": "spoiler-content"}
)
to_hide.string = "(...)" if empty_header else " (...)"
spoiler_tag.unwrap()
text = soup.text
return notify(
f"{self.server_name}:\n"
f"{message['sender_full_name']} (to {recipient})",
text,
)
return ""
def _handle_message_event(self, event: Event) -> None:
"""
Handle new messages (eg. add message to the end of the view)
"""
assert event["type"] == "message"
message = self.modernize_message_response(event["message"])
# sometimes `flags` are missing in `event` so initialize
# an empty list of flags in that case.
message["flags"] = event.get("flags", [])
# We need to update the topic order in index, unconditionally.
if message["type"] == "stream":
# NOTE: The subsequent helper only updates the topic index based
# on the message event not the UI (the UI is updated in a
# consecutive block independently). However, it is critical to keep
# the topics index synchronized as it used whenever the topics list
# view is reconstructed later.
self._update_topic_index(message["stream_id"], message["subject"])
# If the topic view is toggled for incoming message's
# recipient stream, then we re-arrange topic buttons
# with most recent at the top.
if hasattr(self.controller, "view"):
view = self.controller.view
if view.left_panel.is_in_topic_view_with_stream_id(
message["stream_id"]
):
view.topic_w.update_topics_list(
message["stream_id"], message["subject"], message["sender_id"]
)
self.controller.update_screen()
# We can notify user regardless of whether UI is rendered or not,
# but depend upon the UI to indicate failures.
failed_command = self.notify_user(message)
if (
failed_command
and hasattr(self.controller, "view")
and not self._notified_user_of_notification_failure
):
notice_template = (
"You have enabled notifications, but your notification "
"command '{}' could not be found."
"\n\n"
"The application will continue attempting to run this command "
"in this session, but will not notify you again."
"\n\n"
"Press '{}' to close this window."
)
notice = notice_template.format(
failed_command, primary_key_for_command("GO_BACK")
)
self.controller.popup_with_message(notice, width=50)
self.controller.update_screen()
self._notified_user_of_notification_failure = True
# Index messages before calling set_count.
self.index = index_messages([message], self, self.index)
if "read" not in message["flags"]:
set_count([message["id"]], self.controller, 1)
if hasattr(self.controller, "view") and self._have_last_message.get(
repr(self.narrow), False
):
msg_log = self.controller.view.message_view.log
if msg_log:
last_message = msg_log[-1].original_widget.message
else:
last_message = None
msg_w_list = create_msg_box_list(
self, [message["id"]], last_message=last_message
)
if not msg_w_list:
return
else:
msg_w = msg_w_list[0]
if self.current_narrow_contains_message(message):
msg_log.append(msg_w)
self.controller.update_screen()
def _update_topic_index(self, stream_id: int, topic_name: str) -> None:
"""
Update topic order in index based on incoming message.
Helper method called by _handle_message_event
"""
topic_list = self.topics_in_stream(stream_id)
for topic_iterator, topic in enumerate(topic_list):
if topic == topic_name:
topic_list.insert(0, topic_list.pop(topic_iterator))
break
else:
# No previous topics with same topic names are found
# hence, it must be a new topic.
topic_list.insert(0, topic_name)
# Update the index.
self.index["topics"][stream_id] = topic_list
def _handle_update_message_event(self, event: Event) -> None:
"""
Handle updated (edited) messages (changed content/subject)
"""
assert event["type"] == "update_message"
# Update edited message status from single message id
# NOTE: If all messages in topic have topic edited,
# they are not all marked as edited, as per server optimization
message_id = event["message_id"]
indexed_message = self.index["messages"].get(message_id, None)
if indexed_message:
self.index["edited_messages"].add(message_id)
# Update the rendered content, if the message is indexed
if "rendered_content" in event and indexed_message:
indexed_message["content"] = event["rendered_content"]
self.index["messages"][message_id] = indexed_message
self._update_rendered_view(message_id)
# NOTE: This is independent of messages being indexed
# Previous assertion:
# * 'subject' is not present in update event if
# the event didn't have a 'subject' update.
if "subject" in event:
new_subject = event["subject"]
stream_id = event["stream_id"]
old_subject = event["orig_subject"]
msg_ids_by_topic = self.index["topic_msg_ids"][stream_id]
# Remove each message_id from the old topic's `topic_msg_ids` set
# if it exists, and update & re-render the message if it is indexed.
for msg_id in event["message_ids"]:
# Ensure that the new topic is not the same as the old one
# (no-op topic edit).
if new_subject != old_subject:
# Remove the msg_id from the relevant `topic_msg_ids` set,
# if that topic's set has already been initiated.
if old_subject in msg_ids_by_topic:
msg_ids_by_topic[old_subject].discard(msg_id)
# Add the msg_id to the new topic's set, if the set has
# already been initiated.
if new_subject in msg_ids_by_topic:
msg_ids_by_topic[new_subject].add(msg_id)
# Update and re-render indexed messages.
indexed_msg = self.index["messages"].get(msg_id)
if indexed_msg:
indexed_msg["subject"] = new_subject
self._update_rendered_view(msg_id)
# If topic view is open, reload list else reset cache.
if stream_id in self.index["topics"]:
if hasattr(self.controller, "view"):
view = self.controller.view
if view.left_panel.is_in_topic_view_with_stream_id(stream_id):
self._fetch_topics_in_streams([stream_id])
view.left_panel.show_topic_view(view.topic_w.stream_button)
self.controller.update_screen()
else:
self.index["topics"][stream_id] = []
def _handle_reaction_event(self, event: Event) -> None:
"""
Handle change to reactions on a message
"""
assert event["type"] == "reaction"
message_id = event["message_id"]
# If the message is indexed
if message_id in self.index["messages"]:
message = self.index["messages"][message_id]
if event["op"] == "add":
message["reactions"].append(
{
"user": event["user"],
"reaction_type": event["reaction_type"],
"emoji_code": event["emoji_code"],
"emoji_name": event["emoji_name"],
}
)
else:
emoji_code = event["emoji_code"]
for reaction in message["reactions"]:
# Since Who reacted is not displayed,
# remove the first one encountered
if reaction["emoji_code"] == emoji_code:
message["reactions"].remove(reaction)
self.index["messages"][message_id] = message
self._update_rendered_view(message_id)
def _handle_update_message_flags_event(self, event: Event) -> None:
"""
Handle change to message flags (eg. starred, read)
"""
assert event["type"] == "update_message_flags"
if self.server_feature_level is None or self.server_feature_level < 32:
operation = event["operation"]
else:
operation = event["op"]
if event["all"]: # FIXME Should handle eventually
return
flag_to_change = event["flag"]
if flag_to_change not in {"starred", "read"}:
return
if flag_to_change == "read" and operation == "remove":
return
indexed_message_ids = set(self.index["messages"])
message_ids_to_mark = set(event["messages"])
for message_id in message_ids_to_mark & indexed_message_ids:
msg = self.index["messages"][message_id]
if operation == "add":
if flag_to_change not in msg["flags"]:
msg["flags"].append(flag_to_change)
if flag_to_change == "starred":
self.index["starred_msg_ids"].add(message_id)
elif operation == "remove":
if flag_to_change in msg["flags"]:
msg["flags"].remove(flag_to_change)
if (
message_id in self.index["starred_msg_ids"]
and flag_to_change == "starred"
):
self.index["starred_msg_ids"].remove(message_id)
else:
raise RuntimeError(event, msg["flags"])
self.index["messages"][message_id] = msg
self._update_rendered_view(message_id)
if operation == "add" and flag_to_change == "read":
set_count(
list(message_ids_to_mark & indexed_message_ids), self.controller, -1
)
if flag_to_change == "starred" and operation in ["add", "remove"]:
# update starred count in view
len_ids = len(message_ids_to_mark)
count = -len_ids if operation == "remove" else len_ids
self.controller.view.starred_button.update_count(
self.controller.view.starred_button.count + count
)
self.controller.update_screen()
def formatted_local_time(
self, timestamp: int, *, show_seconds: bool, show_year: bool = False
) -> str:
local_time = datetime.fromtimestamp(timestamp)
use_24h_format = self.user_settings()["twenty_four_hour_time"]
format_codes = (
"%a %b %d "
f"{'%Y ' if show_year else ''}"
f"{'%H:' if use_24h_format else '%I:'}"
"%M"
f"{':%S' if show_seconds else ''}"
f"{'' if use_24h_format else ' %p'}"
)
return local_time.strftime(format_codes)
def _handle_update_emoji_event(self, event: Event) -> None:
"""
Handle update of emoji
"""
# Here, the event contains information of all realm emojis added
# by the users in the organisation along with a boolean value
# representing the active state of each emoji.
assert event["type"] == "realm_emoji"
self.active_emoji_data, self.all_emoji_names = self.generate_all_emoji_data(
event["realm_emoji"]
)
def _update_rendered_view(self, msg_id: int) -> None:
"""
Helper method called by various _handle_* methods
"""
# Update new content in the rendered view
view = self.controller.view
for msg_w in view.message_view.log:
msg_box = msg_w.original_widget
if msg_box.message["id"] == msg_id:
# Remove the message if it no longer belongs in the current
# narrow.
if (
len(self.narrow) == 2
and msg_box.message["subject"] != self.narrow[1][1]
):
view.message_view.log.remove(msg_w)
# Change narrow if there are no messages left in the
# current narrow.
if not view.message_view.log:
msg_w_list = create_msg_box_list(
self, [msg_id], last_message=msg_box.last_message
)
if msg_w_list:
# FIXME Still depends on widget
widget = msg_w_list[0].original_widget
self.controller.narrow_to_topic(
stream_name=widget.stream_name,
topic_name=widget.topic_name,
contextual_message_id=widget.message["id"],
)
self.controller.update_screen()
return
msg_w_list = create_msg_box_list(
self, [msg_id], last_message=msg_box.last_message
)
if not msg_w_list:
return
else:
new_msg_w = msg_w_list[0]
msg_pos = view.message_view.log.index(msg_w)
view.message_view.log[msg_pos] = new_msg_w
# If this is not the last message in the view
# update the next message's last_message too.
if len(view.message_view.log) != (msg_pos + 1):
next_msg_w = view.message_view.log[msg_pos + 1]
msg_w_list = create_msg_box_list(
self,
[next_msg_w.original_widget.message["id"]],
last_message=new_msg_w.original_widget.message,
)
view.message_view.log[msg_pos + 1] = msg_w_list[0]
self.controller.update_screen()
return
def _handle_user_settings_event(self, event: Event) -> None:
"""
Event when user settings have changed - from ZFL 89, v5.0
(previously "update_display_settings" and "update_global_notifications")
"""
assert event["type"] == "user_settings"
if event["op"] == "update": # Should always be the case
# Only update settings after initialization
if event["property"] in self._user_settings.keys():
setting = event["property"]
self._user_settings[setting] = event["value"]
def _handle_update_global_notifications_event(self, event: Event) -> None:
assert event["type"] == "update_global_notifications"
to_update = event["notification_name"]
if to_update == "pm_content_in_desktop_notifications":
self._user_settings[to_update] = event["setting"]
def _handle_update_display_settings_event(self, event: Event) -> None:
"""
Handle change to user display setting (Eg: Time format)
"""
assert event["type"] == "update_display_settings"
view = self.controller.view
if event["setting_name"] == "twenty_four_hour_time":
self._user_settings["twenty_four_hour_time"] = event["setting"]
for msg_w in view.message_view.log:
msg_box = msg_w.original_widget
msg_id = msg_box.message["id"]
last_msg = msg_box.last_message
msg_pos = view.message_view.log.index(msg_w)
msg_w_list = create_msg_box_list(self, [msg_id], last_message=last_msg)
view.message_view.log[msg_pos] = msg_w_list[0]
self.controller.update_screen()
def _register_desired_events(self, *, fetch_data: bool = False) -> str:
fetch_types = None if not fetch_data else self.initial_data_to_fetch
event_types = list(self.event_actions)
try:
response = self.client.register(
event_types=event_types,
fetch_event_types=fetch_types,
client_gravatar=True,
apply_markdown=True,
include_subscribers=True,
)
except zulip.ZulipError as e:
return str(e)
if response["result"] == "success":
if fetch_data:
# FIXME: Improve methods to avoid updating `realm_users` on
# every cycle. Add support for `realm_users` events too.
self.initial_data.update(response)
self.max_message_id = response["max_message_id"]
self.queue_id = response["queue_id"]
self.last_event_id = response["last_event_id"]
return ""
return response["msg"]
@asynch
def poll_for_events(self) -> None:
reregister_timeout = 10
queue_id = self.queue_id
last_event_id = self.last_event_id
while True:
if queue_id is None:
while True:
if not self._register_desired_events():
queue_id = self.queue_id
last_event_id = self.last_event_id
break
time.sleep(reregister_timeout)
response = self.client.get_events(
queue_id=queue_id, last_event_id=last_event_id
)
if "error" in response["result"]:
if response["msg"].startswith("Bad event queue id:"):
# Our event queue went away, probably because
# we were asleep or the server restarted
# abnormally. We may have missed some
# events while the network was down or
# something, but there's not really anything
# we can do about it other than resuming
# getting new ones.
#
# Reset queue_id to register a new event queue.
queue_id = None
time.sleep(1)
continue
for event in response["events"]:
last_event_id = max(last_event_id, int(event["id"]))
if event["type"] in self.event_actions:
try:
self.event_actions[event["type"]](event)
except Exception:
import sys
self.controller.raise_exception_in_main_thread(
sys.exc_info(), critical=False
) | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/model.py | model.py |
from enum import Enum
from typing import Any
from pygments.style import Style
from pygments.token import (
Comment,
Error,
Escape,
Generic,
Keyword,
Literal,
Name,
Number,
Operator,
Punctuation,
String,
Text,
Whitespace,
)
# fmt: off
# NOTE: The 24bit color codes use 256 color which can be
# enhanced to be truly 24bit.
# NOTE: The 256code format can be moved to h0-255 to
# make use of the complete range instead of only 216 colors.
class DefaultColor(Enum):
# color = 16code 256code 24code
DEFAULT = 'default default default'
BLACK = 'black g19 g19'
DARK_RED = 'dark_red #a00 #a00'
DARK_GREEN = 'dark_green #080 #080'
BROWN = 'brown #880 #880'
DARK_BLUE = 'dark_blue #24a #24a'
DARK_MAGENTA = 'dark_magenta h90 h90' # #870087
DARK_CYAN = 'dark_cyan #088 #088'
DARK_GRAY = 'dark_gray #666 #666'
LIGHT_RED = 'light_red #f00 #f00'
LIGHT_GREEN = 'light_green #0f0 #0f0'
YELLOW = 'yellow #ff0 #ff0'
LIGHT_BLUE = 'light_blue #28d #28d'
LIGHT_MAGENTA = 'light_magenta #c8f #c8f'
LIGHT_CYAN = 'light_cyan h152 h152' # #afd7d7
LIGHT_GRAY = 'light_gray #ccc #ccc'
WHITE = 'white #fff #fff'
# fmt: on
def color_properties(colors: Any, *prop: str) -> Any:
"""
Adds properties(Bold, Italics, etc...) to Enum Colors in theme files.
Useage: color_properties(Color, 'BOLD', 'ITALICS', 'STRIKETHROUGH')
NOTE: color_properties(Color, BOLD, ITALICS) would result in only
Color.WHITE and Color.WHITE__BOLD_ITALICS
but not Color.WHITE__BOLD or Color.WHITE__ITALICS.
One would also have to do color_properties(Color, BOLD)
and color_properties(Color, ITALICS) for the others to work
>>> This function can be later extended to achieve all combinations
with one call to the function.
"""
prop_n = "_".join([p.upper() for p in prop])
prop_v = " , ".join([p.lower() for p in prop])
updated_colors: Any = Enum( # type: ignore # Ref: python/mypy#529, #535 and #5317
"Color",
{
**{c.name: c.value for c in colors},
**{c.name + f"__{prop_n}": c.value + f" , {prop_v}" for c in colors},
},
)
return updated_colors
DefaultBoldColor = color_properties(DefaultColor, "BOLD")
# fmt: off
class Term16Style(Style):
"""
This style is a 16 color syntax style made for use in all ZT themes.
"var" bypasses pygments style format checking.
"_" is used in place of space and changed later below.
"""
background_color = "dark gray"
styles = {
Text: "var:light_gray",
Escape: "var:light_cyan",
Error: "var:dark_red",
Whitespace: "var:light_gray",
Keyword: "var:light_blue,_bold",
Name: "var:brown",
Name.Class: "var:yellow",
Name.Function: "var:light_green",
Literal: "var:light_green",
String: "var:dark_green",
String.Escape: "var:light_gray",
String.Doc: "var:light_gray",
Number: "var:light_red",
Operator: "var:light_cyan",
Punctuation: "var:light_gray,_bold",
Comment: "var:light_gray",
Generic: "var:light_gray",
}
# fmt:on
term16 = Term16Style()
for style, code in term16.styles.items():
term16.styles[style] = code[4:].replace("_", " ") | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/config/color.py | color.py |
from collections import OrderedDict
from typing import List
from typing_extensions import TypedDict
from urwid.command_map import (
CURSOR_DOWN,
CURSOR_LEFT,
CURSOR_MAX_RIGHT,
CURSOR_PAGE_DOWN,
CURSOR_PAGE_UP,
CURSOR_RIGHT,
CURSOR_UP,
command_map,
)
class KeyBinding(TypedDict, total=False):
keys: List[str]
help_text: str
excluded_from_random_tips: bool
key_category: str
# fmt: off
KEY_BINDINGS: 'OrderedDict[str, KeyBinding]' = OrderedDict([
# Key that is displayed in the UI is determined by the method
# primary_key_for_command. (Currently the first key in the list)
('HELP', {
'keys': ['?'],
'help_text': 'Show/hide help menu',
'excluded_from_random_tips': True,
'key_category': 'general',
}),
('MARKDOWN_HELP', {
'keys': ['meta m'],
'help_text': 'Show/hide markdown help menu',
'key_category': 'general',
}),
('ABOUT', {
'keys': ['meta ?'],
'help_text': 'Show/hide about menu',
'key_category': 'general',
}),
('GO_BACK', {
'keys': ['esc'],
'help_text': 'Go Back',
'excluded_from_random_tips': False,
'key_category': 'general',
}),
('OPEN_DRAFT', {
'keys': ['d'],
'help_text': 'Open draft message saved in this session',
'key_category': 'general',
}),
('GO_UP', {
'keys': ['up', 'k'],
'help_text': 'Go up / Previous message',
'key_category': 'navigation',
}),
('GO_DOWN', {
'keys': ['down', 'j'],
'help_text': 'Go down / Next message',
'key_category': 'navigation',
}),
('GO_LEFT', {
'keys': ['left', 'h'],
'help_text': 'Go left',
'key_category': 'navigation',
}),
('GO_RIGHT', {
'keys': ['right', 'l'],
'help_text': 'Go right',
'key_category': 'navigation',
}),
('SCROLL_UP', {
'keys': ['page up', 'K'],
'help_text': 'Scroll up',
'key_category': 'navigation',
}),
('SCROLL_DOWN', {
'keys': ['page down', 'J'],
'help_text': 'Scroll down',
'key_category': 'navigation',
}),
('GO_TO_BOTTOM', {
'keys': ['end', 'G'],
'help_text': 'Go to bottom / Last message',
'key_category': 'navigation',
}),
('REPLY_MESSAGE', {
'keys': ['r', 'enter'],
'help_text': 'Reply to the current message',
'key_category': 'msg_actions',
}),
('MENTION_REPLY', {
'keys': ['@'],
'help_text': 'Reply mentioning the sender of the current message',
'key_category': 'msg_actions',
}),
('QUOTE_REPLY', {
'keys': ['>'],
'help_text': 'Reply quoting the current message text',
'key_category': 'msg_actions',
}),
('REPLY_AUTHOR', {
'keys': ['R'],
'help_text': 'Reply privately to the sender of the current message',
'key_category': 'msg_actions',
}),
('EDIT_MESSAGE', {
'keys': ['e'],
'help_text': "Edit message's content or topic",
'key_category': 'msg_actions'
}),
('STREAM_MESSAGE', {
'keys': ['c'],
'help_text': 'New message to a stream',
'key_category': 'msg_actions',
}),
('PRIVATE_MESSAGE', {
'keys': ['x'],
'help_text': 'New message to a person or group of people',
'key_category': 'msg_actions',
}),
('CYCLE_COMPOSE_FOCUS', {
'keys': ['tab'],
'help_text': 'Cycle through recipient and content boxes',
'key_category': 'msg_compose',
}),
('SEND_MESSAGE', {
'keys': ['ctrl d', 'meta enter'],
'help_text': 'Send a message',
'key_category': 'msg_compose',
}),
('SAVE_AS_DRAFT', {
'keys': ['meta s'],
'help_text': 'Save current message as a draft',
'key_category': 'msg_compose',
}),
('AUTOCOMPLETE', {
'keys': ['ctrl f'],
'help_text': ('Autocomplete @mentions, #stream_names, :emoji:'
' and topics'),
'key_category': 'msg_compose',
}),
('AUTOCOMPLETE_REVERSE', {
'keys': ['ctrl r'],
'help_text': 'Cycle through autocomplete suggestions in reverse',
'key_category': 'msg_compose',
}),
('ADD_REACTION', {
'keys': [':'],
'help_text': 'Show/hide Emoji picker popup for current message',
'key_category': 'msg_actions',
}),
('STREAM_NARROW', {
'keys': ['s'],
'help_text': 'Narrow to the stream of the current message',
'key_category': 'msg_actions',
}),
('TOPIC_NARROW', {
'keys': ['S'],
'help_text': 'Narrow to the topic of the current message',
'key_category': 'msg_actions',
}),
('NARROW_MESSAGE_RECIPIENT', {
'keys': ['meta .'],
'help_text': 'Narrow to compose box message recipient',
'key_category': 'msg_compose',
}),
('TOGGLE_NARROW', {
'keys': ['z'],
'help_text':
'Narrow to a topic/private-chat, or stream/all-private-messages',
'key_category': 'msg_actions',
}),
('TOGGLE_TOPIC', {
'keys': ['t'],
'help_text': 'Toggle topics in a stream',
'key_category': 'stream_list',
}),
('ALL_MESSAGES', {
'keys': ['a', 'esc'],
'help_text': 'Narrow to all messages',
'key_category': 'navigation',
}),
('ALL_PM', {
'keys': ['P'],
'help_text': 'Narrow to all private messages',
'key_category': 'navigation',
}),
('ALL_STARRED', {
'keys': ['f'],
'help_text': 'Narrow to all starred messages',
'key_category': 'navigation',
}),
('ALL_MENTIONS', {
'keys': ['#'],
'help_text': "Narrow to messages in which you're mentioned",
'key_category': 'navigation',
}),
('NEXT_UNREAD_TOPIC', {
'keys': ['n'],
'help_text': 'Next unread topic',
'key_category': 'navigation',
}),
('NEXT_UNREAD_PM', {
'keys': ['p'],
'help_text': 'Next unread private message',
'key_category': 'navigation',
}),
('SEARCH_PEOPLE', {
'keys': ['w'],
'help_text': 'Search Users',
'key_category': 'searching',
}),
('SEARCH_MESSAGES', {
'keys': ['/'],
'help_text': 'Search Messages',
'key_category': 'searching',
}),
('SEARCH_STREAMS', {
'keys': ['q'],
'help_text': 'Search Streams',
'key_category': 'searching',
}),
('SEARCH_TOPICS', {
'keys': ['q'],
'help_text': 'Search topics in a stream',
'key_category': 'searching',
}),
('SEARCH_EMOJIS', {
'keys': ['p'],
'help_text': 'Search emojis from Emoji-picker popup',
'excluded_from_random_tips': True,
'key_category': 'searching',
}),
('TOGGLE_MUTE_STREAM', {
'keys': ['m'],
'help_text': 'Mute/unmute Streams',
'key_category': 'stream_list',
}),
('ENTER', {
'keys': ['enter'],
'help_text': 'Perform current action',
'key_category': 'navigation',
}),
('THUMBS_UP', {
'keys': ['+'],
'help_text': 'Add/remove thumbs-up reaction to the current message',
'key_category': 'msg_actions',
}),
('TOGGLE_STAR_STATUS', {
'keys': ['ctrl s', '*'],
'help_text': 'Add/remove star status of the current message',
'key_category': 'msg_actions',
}),
('MSG_INFO', {
'keys': ['i'],
'help_text': 'Show/hide message information',
'key_category': 'msg_actions',
}),
('EDIT_HISTORY', {
'keys': ['e'],
'help_text': 'Show/hide edit history (from message information)',
'excluded_from_random_tips': True,
'key_category': 'msg_actions',
}),
('VIEW_IN_BROWSER', {
'keys': ['v'],
'help_text':
'View current message in browser (from message information)',
'excluded_from_random_tips': True,
'key_category': 'msg_actions',
}),
('STREAM_DESC', {
'keys': ['i'],
'help_text': 'Show/hide stream information & modify settings',
'key_category': 'stream_list',
}),
('STREAM_MEMBERS', {
'keys': ['m'],
'help_text': 'Show/hide stream members (from stream information)',
'excluded_from_random_tips': True,
'key_category': 'stream_list',
}),
('COPY_STREAM_EMAIL', {
'keys': ['c'],
'help_text':
'Copy stream email to clipboard (from stream information)',
'excluded_from_random_tips': True,
'key_category': 'stream_list',
}),
('REDRAW', {
'keys': ['ctrl l'],
'help_text': 'Redraw screen',
'key_category': 'general',
}),
('QUIT', {
'keys': ['ctrl c'],
'help_text': 'Quit',
'key_category': 'general',
}),
('USER_INFO', {
'keys': ['i'],
'help_text': 'View user information (From Users list)',
'key_category': 'general',
}),
('BEGINNING_OF_LINE', {
'keys': ['ctrl a'],
'help_text': 'Jump to the beginning of line',
'key_category': 'msg_compose',
}),
('END_OF_LINE', {
'keys': ['ctrl e'],
'help_text': 'Jump to the end of line',
'key_category': 'msg_compose',
}),
('ONE_WORD_BACKWARD', {
'keys': ['meta b'],
'help_text': 'Jump backward one word',
'key_category': 'msg_compose',
}),
('ONE_WORD_FORWARD', {
'keys': ['meta f'],
'help_text': 'Jump forward one word',
'key_category': 'msg_compose',
}),
('DELETE_LAST_CHARACTER', {
'keys': ['ctrl h'],
'help_text': 'Delete previous character (to left)',
'key_category': 'msg_compose',
}),
('TRANSPOSE_CHARACTERS', {
'keys': ['ctrl t'],
'help_text': 'Transpose characters',
'key_category': 'msg_compose',
}),
('CUT_TO_END_OF_LINE', {
'keys': ['ctrl k'],
'help_text': 'Cut forwards to the end of the line',
'key_category': 'msg_compose',
}),
('CUT_TO_START_OF_LINE', {
'keys': ['ctrl u'],
'help_text': 'Cut backwards to the start of the line',
'key_category': 'msg_compose',
}),
('CUT_TO_END_OF_WORD', {
'keys': ['meta d'],
'help_text': 'Cut forwards to the end of the current word',
'key_category': 'msg_compose',
}),
('CUT_TO_START_OF_WORD', {
'keys': ['ctrl w'],
'help_text': 'Cut backwards to the start of the current word',
'key_category': 'msg_compose',
}),
('PASTE_LAST_CUT', {
'keys': ['ctrl y'],
'help_text': 'Paste last cut section',
'key_category': 'msg_compose',
}),
('UNDO_LAST_ACTION', {
'keys': ['ctrl _'],
'help_text': 'Undo last action',
'key_category': 'msg_compose',
}),
('PREV_LINE', {
'keys': ['up', 'ctrl p'],
'help_text': 'Jump to the previous line',
'key_category': 'msg_compose',
}),
('NEXT_LINE', {
'keys': ['down', 'ctrl n'],
'help_text': 'Jump to the next line',
'key_category': 'msg_compose',
}),
('CLEAR_MESSAGE', {
'keys': ['ctrl l'],
'help_text': 'Clear compose box',
'key_category': 'msg_compose',
}),
('FULL_RENDERED_MESSAGE', {
'keys': ['f'],
'help_text': 'Show/hide full rendered message (from message information)',
'key_category': 'msg_actions',
}),
('FULL_RAW_MESSAGE', {
'keys': ['r'],
'help_text': 'Show/hide full raw message (from message information)',
'key_category': 'msg_actions',
}),
])
# fmt: on
HELP_CATEGORIES = OrderedDict(
[
("general", "General"),
("navigation", "Navigation"),
("searching", "Searching"),
("msg_actions", "Message actions"),
("stream_list", "Stream list actions"),
("msg_compose", "Composing a Message"),
]
)
ZT_TO_URWID_CMD_MAPPING = {
"GO_UP": CURSOR_UP,
"GO_DOWN": CURSOR_DOWN,
"GO_LEFT": CURSOR_LEFT,
"GO_RIGHT": CURSOR_RIGHT,
"SCROLL_UP": CURSOR_PAGE_UP,
"SCROLL_DOWN": CURSOR_PAGE_DOWN,
"GO_TO_BOTTOM": CURSOR_MAX_RIGHT,
}
class InvalidCommand(Exception):
pass
def is_command_key(command: str, key: str) -> bool:
"""
Returns the mapped binding for a key if mapped
or the key otherwise.
"""
try:
return key in KEY_BINDINGS[command]["keys"]
except KeyError as exception:
raise InvalidCommand(command)
def keys_for_command(command: str) -> List[str]:
"""
Returns the actual keys for a given mapped command
"""
try:
return list(KEY_BINDINGS[command]["keys"])
except KeyError as exception:
raise InvalidCommand(command)
def primary_key_for_command(command: str) -> str:
"""
Primary Key is the key that will be displayed eg. in the UI
"""
return keys_for_command(command).pop(0)
def commands_for_random_tips() -> List[KeyBinding]:
"""
Return list of commands which may be displayed as a random tip
"""
return [
key_binding
for key_binding in KEY_BINDINGS.values()
if not key_binding.get("excluded_from_random_tips", False)
]
# Refer urwid/command_map.py
# Adds alternate keys for standard urwid navigational commands.
for zt_cmd, urwid_cmd in ZT_TO_URWID_CMD_MAPPING.items():
for key in keys_for_command(zt_cmd):
command_map[key] = urwid_cmd | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/config/keys.py | keys.py |
from typing import Any, Dict, List, Optional, Tuple, Union
from pygments.token import STANDARD_TYPES
from zulipterminal.config.color import term16
from zulipterminal.themes import gruvbox_dark, gruvbox_light, zt_blue, zt_dark, zt_light
StyleSpec = Union[
Tuple[Optional[str], str, str],
Tuple[Optional[str], str, str, Optional[str]],
Tuple[Optional[str], str, str, Optional[str], str, str],
]
ThemeSpec = List[StyleSpec]
# fmt: off
# The keys in REQUIRED_STYLES specify what styles are necessary for a theme to
# be complete, while the values are those used to style each element in
# monochrome (1-bit) mode - independently of the specified theme
REQUIRED_STYLES = {
# style name : monochrome style
None : '',
'selected' : 'standout',
'msg_selected' : 'standout',
'header' : 'bold',
'general_narrow' : 'standout',
'general_bar' : '',
'name' : '',
'unread' : 'strikethrough',
'user_active' : 'bold',
'user_idle' : '',
'user_offline' : '',
'user_inactive' : '',
'title' : 'bold',
'column_title' : 'bold',
'time' : '',
'bar' : 'standout',
'msg_emoji' : 'bold',
'reaction' : 'bold',
'reaction_mine' : 'standout',
'msg_heading' : 'bold',
'msg_math' : 'standout',
'msg_mention' : 'bold',
'msg_link' : '',
'msg_link_index' : 'bold',
'msg_quote' : 'underline',
'msg_code' : 'bold',
'msg_bold' : 'bold',
'msg_time' : 'bold',
'footer' : 'standout',
'footer_contrast' : 'standout',
'starred' : 'bold',
'unread_count' : 'bold',
'starred_count' : '',
'table_head' : 'bold',
'filter_results' : 'bold',
'edit_topic' : 'standout',
'edit_tag' : 'standout',
'edit_author' : 'bold',
'edit_time' : 'bold',
'current_user' : '',
'muted' : 'bold',
'popup_border' : 'bold',
'popup_category' : 'bold',
'popup_contrast' : 'standout',
'popup_important' : 'bold',
'widget_disabled' : 'strikethrough',
'area:help' : 'standout',
'area:msg' : 'standout',
'area:stream' : 'standout',
'area:error' : 'standout',
'area:user' : 'standout',
'search_error' : 'standout',
'task:success' : 'standout',
'task:error' : 'standout',
'task:warning' : 'standout',
}
REQUIRED_META = {
'pygments': {
'styles' : None,
'background' : None,
'overrides' : None,
}
}
# fmt: on
# This is the main list of themes
THEMES: Dict[str, Any] = {
"gruvbox_dark": gruvbox_dark,
"gruvbox_light": gruvbox_light,
"zt_dark": zt_dark,
"zt_light": zt_light,
"zt_blue": zt_blue,
}
# These are older aliases to some of the above, for compatibility
# NOTE: Do not add to this section, and only modify if a theme name changes
THEME_ALIASES = {
"default": "zt_dark",
"gruvbox": "gruvbox_dark",
"light": "zt_light",
"blue": "zt_blue",
}
# These are urwid color names with underscores instead of spaces
valid_16_color_codes = [
"default",
"black",
"dark_red",
"dark_green",
"brown",
"dark_blue",
"dark_magenta",
"dark_cyan",
"dark_gray",
"light_red",
"light_green",
"yellow",
"light_blue",
"light_magenta",
"light_cyan",
"light_gray",
"white",
]
class InvalidThemeColorCode(Exception):
pass
def all_themes() -> List[str]:
return list(THEMES.keys())
def aliased_themes() -> Dict[str, str]:
return dict(THEME_ALIASES)
def complete_and_incomplete_themes() -> Tuple[List[str], List[str]]:
complete = {
name
for name, theme in THEMES.items()
if set(theme.STYLES) == set(REQUIRED_STYLES)
if set(theme.META) == set(REQUIRED_META)
for meta, conf in theme.META.items()
if set(conf) == set(REQUIRED_META.get(meta, {}))
}
incomplete = list(set(THEMES) - complete)
return sorted(list(complete)), sorted(incomplete)
def generate_theme(theme_name: str, color_depth: int) -> ThemeSpec:
theme_styles = THEMES[theme_name].STYLES
validate_colors(theme_name, color_depth)
urwid_theme = parse_themefile(theme_styles, color_depth)
try:
theme_meta = THEMES[theme_name].META
add_pygments_style(theme_meta, urwid_theme)
except AttributeError:
pass
return urwid_theme
def validate_colors(theme_name: str, color_depth: int) -> None:
"""
This function validates color-codes for a given theme, given colors are in `Color`.
If any color is not in accordance with urwid default 16-color codes then the
function raises InvalidThemeColorCode with the invalid colors.
"""
theme_colors = THEMES[theme_name].Color
failure_text = []
if color_depth == 16:
for color in theme_colors:
color_16code = color.value.split()[0]
if color_16code not in valid_16_color_codes:
invalid_16_color_code = str(color.name)
failure_text.append(f"- {invalid_16_color_code} = {color_16code}")
if failure_text == []:
return
else:
text = "\n".join(
[f"Invalid 16-color codes in theme '{theme_name}':"] + failure_text
)
raise InvalidThemeColorCode(text)
def parse_themefile(
theme_styles: Dict[Optional[str], Tuple[Any, Any]], color_depth: int
) -> ThemeSpec:
urwid_theme = []
for style_name, (fg, bg) in theme_styles.items():
fg_code16, fg_code256, fg_code24, *fg_props = fg.value.split()
bg_code16, bg_code256, bg_code24, *bg_props = bg.value.split()
new_style: StyleSpec
if color_depth == 1:
new_style = (style_name, "", "", REQUIRED_STYLES[style_name])
elif color_depth == 16:
fg = " ".join([fg_code16] + fg_props).replace("_", " ")
bg = " ".join([bg_code16] + bg_props).replace("_", " ")
new_style = (style_name, fg, bg)
elif color_depth == 256:
fg = " ".join([fg_code256] + fg_props).lower()
bg = " ".join([bg_code256] + bg_props).lower()
new_style = (style_name, "", "", "", fg, bg)
elif color_depth == 2**24:
fg = " ".join([fg_code24] + fg_props).lower()
bg = " ".join([bg_code24] + bg_props).lower()
new_style = (style_name, "", "", "", fg, bg)
urwid_theme.append(new_style)
return urwid_theme
def add_pygments_style(theme_meta: Dict[str, Any], urwid_theme: ThemeSpec) -> None:
"""
This function adds pygments styles for use in syntax
highlighting of code blocks and inline code.
pygments["styles"]:
one of those available in pygments/styles.
pygments["background"]:
used to set a different background for codeblocks instead of the
one used in the syntax style, if it doesn't match with
the overall zt theme.
The default is available as Eg: MaterialStyle.background_color
pygments["overrides"]:
used to override certain pygments styles to match to urwid format.
It can also be used to customize the syntax style.
"""
pygments = theme_meta["pygments"]
pygments_styles = pygments["styles"]
pygments_bg = pygments["background"]
pygments_overrides = pygments["overrides"]
term16_styles = term16.styles
term16_bg = term16.background_color
for token, css_class in STANDARD_TYPES.items():
if css_class in pygments_overrides:
pygments_styles[token] = pygments_overrides[css_class]
# Inherit parent pygments style if not defined.
# Eg: Use `String` if `String.Double` is not present.
if pygments_styles[token] == "":
try:
t = [k for k, v in STANDARD_TYPES.items() if v == css_class[0]]
pygments_styles[token] = pygments_styles[t[0]]
except IndexError:
pass
if term16_styles[token] == "":
try:
t = [k for k, v in STANDARD_TYPES.items() if v == css_class[0]]
term16_styles[token] = term16_styles[t[0]]
except IndexError:
pass
new_style = (
f"pygments:{css_class}",
term16_styles[token],
term16_bg,
"bold", # Mono style
pygments_styles[token],
pygments_bg,
)
urwid_theme.append(new_style) | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/config/themes.py | themes.py |
from typing import List
from typing_extensions import TypedDict
class MarkdownElements(TypedDict):
name: str
raw_text: str
html_element: str
MARKDOWN_ELEMENTS: List[MarkdownElements] = [
{
# BOLD TEXT
"name": "Bold text",
"raw_text": "**bold**",
"html_element": "<strong>bold</strong>",
},
{
# EMOJI
"name": "Emoji",
"raw_text": ":heart:",
"html_element": '<span class="emoji">:heart:</span>',
},
{
# MESSAGE LINKS
"name": "Message links",
"raw_text": "[Zulip website]\n(https://zulip.org)",
"html_element": '<a href="https://zulip.org">Zulip website</a>',
},
{
# BULLET LISTS
"name": "Bullet lists",
"raw_text": "* Milk\n* Tea\n * Green tea\n * Black tea\n"
" * Oolong tea\n* Coffee",
"html_element": "<ul><li>Milk</li><li>Tea<ul><li>Green tea</li>"
"<li>Black tea</li><li>Oolong tea</li></ul>"
"</li><li>Coffee</li>",
},
{
# NUMBERED LISTS
"name": "Numbered lists",
"raw_text": "1. Milk\n2. Tea\n3. Coffee",
"html_element": "<ol><li>Milk</li><li>Tea</li><li>Coffee</li></ol>",
},
{
# USER MENTIONS
"name": "User mentions",
"raw_text": "@**King Hamlet**",
"html_element": '<span class="user-mention">@King Hamlet</span>',
},
{
# USER SILENT MENTIONS
"name": "User silent mentions",
"raw_text": "@_**King Hamlet**",
"html_element": '<span class="user-mention silent">King Hamlet</span>',
},
{
# NOTIFY ALL RECIPIENTS
"name": "Notify all recipients",
"raw_text": "@**all**",
"html_element": '<span class="user-mention">@all</span>',
},
{
# LINK TO A STREAM
"name": "Link to a stream",
"raw_text": "#**announce**",
"html_element": '<a class="stream" data-stream-id="6" '
'href="/#narrow/stream/6-announce">#announce</a>',
},
{
# STATUS MESSAGE
"name": "Status message",
"raw_text": "/me is busy writing code.",
"html_element": "<strong>{user}</strong> is busy writing code.",
},
{
# INLINE CODE
"name": "Inline code",
"raw_text": "Some inline `code`",
"html_element": "Some inline <code>code</code>",
},
{
# CODE BLOCK
"name": "Code block",
"raw_text": "```\ndef zulip():\n print 'Zulip'\n```",
"html_element": '<div class="codehilite"><pre><span></span><code>\n'
"def zulip():\n print 'Zulip'</code></pre></div>",
},
{
# QUOTED TEXT
"name": "Quoted text",
"raw_text": ">Quoted",
"html_element": "<blockquote>░ Quoted</blockquote>",
},
{
# QUOTED BLOCK
"name": "Quoted block",
"raw_text": "```quote\nQuoted block\n```",
"html_element": "<blockquote>\n░ Quoted block</blockquote>",
},
{
# TABLE RENDERING
"name": "Table rendering",
"raw_text": "|Name|Id|\n|--|--:|\n|Robert|1|\n|Mary|100|",
"html_element": (
"<table>"
"<thead>"
'<tr><th align="left">Name</th><th align="right">Id</th></tr>'
"</thead>"
"<tbody>"
'<tr><td align="left">Robert</td><td align="right">1</td></tr>'
'<tr><td align="left">Mary</td><td align="right">100</td></tr>'
"</tbody>"
"</table>"
),
},
] | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/config/markdown_examples.py | markdown_examples.py |
import argparse
import configparser
import logging
import os
import stat
import sys
import traceback
from os import path, remove
from typing import Any, Dict, List, Optional, Tuple
import requests
from urwid import display_common, set_encoding
from zulipterminal.config.themes import (
InvalidThemeColorCode,
aliased_themes,
all_themes,
complete_and_incomplete_themes,
generate_theme,
)
from zulipterminal.core import Controller
from zulipterminal.model import ServerConnectionFailure
from zulipterminal.version import ZT_VERSION
TRACEBACK_LOG_FILENAME = "zulip-terminal-tracebacks.log"
API_CALL_LOG_FILENAME = "zulip-terminal-API-requests.log"
ZULIPRC_CONFIG = "in zuliprc file"
NO_CONFIG = "with no config"
# Create a logger for this application
zt_logger = logging.getLogger(__name__)
zt_logger.setLevel(logging.DEBUG)
zt_logfile_handler = logging.FileHandler(
TRACEBACK_LOG_FILENAME,
delay=True, # Don't open the file until there's a logging event
)
zt_logger.addHandler(zt_logfile_handler)
# Route requests details (API calls) to separate file
requests_logger = logging.getLogger("urllib3")
requests_logger.setLevel(logging.DEBUG)
# These should be the defaults without config file or command-line overrides
DEFAULT_SETTINGS = {
"theme": "zt_dark",
"autohide": "no_autohide",
"notify": "disabled",
"footlinks": "enabled",
"color-depth": "256",
"maximum-footlinks": "3",
}
def in_color(color: str, text: str) -> str:
color_for_str = {
"red": "1",
"green": "2",
"yellow": "3",
"blue": "4",
"purple": "5",
"cyan": "6",
}
# We can use 3 instead of 9 if high-contrast is eg. less compatible?
return f"\033[9{color_for_str[color]}m{text}\033[0m"
def exit_with_error(
error_message: str, *, helper_text: str = "", error_code: int = 1
) -> None:
print(in_color("red", error_message))
if helper_text:
print(helper_text)
sys.exit(error_code)
def parse_args(argv: List[str]) -> argparse.Namespace:
description = """
Starts Zulip-Terminal.
"""
formatter_class = argparse.RawDescriptionHelpFormatter
parser = argparse.ArgumentParser(
description=description, formatter_class=formatter_class
)
parser.add_argument(
"-v",
"--version",
action="store_true",
default=False,
help="show zulip-terminal version and exit",
)
parser.add_argument(
"--config-file",
"-c",
action="store",
help="config file downloaded from your zulip "
"organization (default: ~/zuliprc)",
)
parser.add_argument(
"--theme",
"-t",
help=f"choose color theme (default: {DEFAULT_SETTINGS['theme']})",
)
parser.add_argument(
"--list-themes",
action="store_true",
help="list all the color themes and exit",
)
parser.add_argument(
"--color-depth",
choices=["1", "16", "256", "24bit"],
help=f"force the color depth (default: {DEFAULT_SETTINGS['color-depth']})",
)
parser.add_argument(
"-e",
"--explore",
action="store_true",
help="do not mark messages as read in the session",
)
notify_group = parser.add_mutually_exclusive_group()
notify_group.add_argument(
"--notify",
dest="notify",
default=None,
action="store_const",
const="enabled",
help="enable desktop notifications",
)
notify_group.add_argument(
"--no-notify",
dest="notify",
default=None,
action="store_const",
const="disabled",
help="disable desktop notifications",
)
autohide_group = parser.add_mutually_exclusive_group()
autohide_group.add_argument(
"--autohide",
dest="autohide",
default=None,
action="store_const",
const="autohide",
help="autohide list of users and streams",
)
autohide_group.add_argument(
"--no-autohide",
dest="autohide",
default=None,
action="store_const",
const="no_autohide",
help="don't autohide list of users and streams",
)
parser.add_argument(
"-d",
"--debug",
action="store_true",
help="enable debug mode",
)
parser.add_argument(
"--profile",
dest="profile",
action="store_true",
default=False,
help="profile runtime",
)
return parser.parse_args(argv)
def styled_input(label: str) -> str:
return input(in_color("blue", label))
def get_login_id(realm_url: str) -> str:
res_json = requests.get(url=f"{realm_url}/api/v1/server_settings").json()
require_email_format_usernames = res_json["require_email_format_usernames"]
email_auth_enabled = res_json["email_auth_enabled"]
if not require_email_format_usernames and email_auth_enabled:
label = "Email or Username: "
elif not require_email_format_usernames:
label = "Username: "
else:
# TODO: Validate Email address
label = "Email: "
return styled_input(label)
def get_api_key(realm_url: str) -> Tuple[requests.Response, str]:
from getpass import getpass
login_id = get_login_id(realm_url)
password = getpass(in_color("blue", "Password: "))
response = requests.post(
url=f"{realm_url}/api/v1/fetch_api_key",
data={
"username": login_id,
"password": password,
},
)
return response, login_id
def fetch_zuliprc(zuliprc_path: str) -> None:
print(
f"{in_color('red', f'zuliprc file was not found at {zuliprc_path}')}"
f"\nPlease enter your credentials to login into your Zulip organization."
f"\n"
f"\nNOTE: The {in_color('blue', 'Zulip URL')}"
f" is where you would go in a web browser to log in to Zulip."
f"\nIt often looks like one of the following:"
f"\n {in_color('green', 'your-org.zulipchat.com')} (Zulip cloud)"
f"\n {in_color('green', 'zulip.your-org.com')} (self-hosted servers)"
f"\n {in_color('green', 'chat.zulip.org')} (the Zulip community server)"
)
realm_url = styled_input("Zulip URL: ")
if realm_url.startswith("localhost"):
realm_url = f"http://{realm_url}"
elif not realm_url.startswith("http"):
realm_url = f"https://{realm_url}"
# Remove trailing "/"s from realm_url to simplify the below logic
# for adding "/api"
realm_url = realm_url.rstrip("/")
res, login_id = get_api_key(realm_url)
while res.status_code != 200:
print(in_color("red", "\nIncorrect Email(or Username) or Password!\n"))
res, login_id = get_api_key(realm_url)
save_zuliprc_failure = _write_zuliprc(
zuliprc_path,
login_id=login_id,
api_key=str(res.json()["api_key"]),
server_url=realm_url,
)
if not save_zuliprc_failure:
print(f"Generated API key saved at {zuliprc_path}")
else:
exit_with_error(save_zuliprc_failure)
def _write_zuliprc(
to_path: str, *, login_id: str, api_key: str, server_url: str
) -> str:
"""
Writes a zuliprc file, returning a non-empty error string on failure
Only creates new private files; errors if file already exists
"""
try:
with open(
os.open(to_path, os.O_CREAT | os.O_WRONLY | os.O_EXCL, 0o600), "w"
) as f:
f.write(f"[api]\nemail={login_id}\nkey={api_key}\nsite={server_url}")
return ""
except FileExistsError as ex:
return f"zuliprc already exists at {to_path}"
except OSError as ex:
return f"{ex.__class__.__name__}: zuliprc could not be created at {to_path}"
def parse_zuliprc(zuliprc_str: str) -> Dict[str, Any]:
zuliprc_path = path.expanduser(zuliprc_str)
while not path.exists(zuliprc_path):
try:
fetch_zuliprc(zuliprc_path)
# Invalid user inputs (e.g. pressing arrow keys) may cause ValueError
except (OSError, ValueError):
# Remove zuliprc file if created.
if path.exists(zuliprc_path):
remove(zuliprc_path)
print(in_color("red", "\nInvalid Credentials, Please try again!\n"))
except EOFError:
# Assume that the user pressed Ctrl+D and continue the loop
print("\n")
mode = os.stat(zuliprc_path).st_mode
is_readable_by_group_or_others = mode & (stat.S_IRWXG | stat.S_IRWXO)
if is_readable_by_group_or_others:
print(
in_color(
"red",
"ERROR: Please ensure your zuliprc is NOT publicly accessible:\n"
" {0}\n"
"(it currently has permissions '{1}')\n"
"This can often be achieved with a command such as:\n"
" chmod og-rwx {0}\n"
"Consider regenerating the [api] part of your zuliprc to ensure "
"your account is secure.".format(zuliprc_path, stat.filemode(mode)),
)
)
sys.exit(1)
zuliprc = configparser.ConfigParser()
try:
res = zuliprc.read(zuliprc_path)
if len(res) == 0:
exit_with_error(f"Could not access zuliprc file at {zuliprc_path}")
except configparser.MissingSectionHeaderError:
exit_with_error(f"Failed to parse zuliprc file at {zuliprc_path}")
# Initialize with default settings
NO_CONFIG = "with no config"
settings = {
setting: (default, NO_CONFIG) for setting, default in DEFAULT_SETTINGS.items()
}
if "zterm" in zuliprc:
config = zuliprc["zterm"]
for conf in config:
settings[conf] = (config[conf], ZULIPRC_CONFIG)
return settings
def list_themes() -> str:
available_themes = all_themes()
text = "The following themes are available:\n"
for theme in available_themes:
suffix = ""
if theme == DEFAULT_SETTINGS["theme"]:
suffix += "[default theme]"
text += f" {theme} {suffix}\n"
return text + (
"Specify theme in zuliprc file or override "
"using -t/--theme options on command line."
)
def main(options: Optional[List[str]] = None) -> None:
"""
Launch Zulip Terminal.
"""
argv = options if options is not None else sys.argv[1:]
args = parse_args(argv)
set_encoding("utf-8")
if args.debug:
debug_path: Optional[str] = "debug.log"
assert isinstance(debug_path, str)
print(
"NOTE: Debug mode enabled:"
f"\n API calls will be logged to {in_color('blue', API_CALL_LOG_FILENAME)}"
f"\n Standard output being logged to {in_color('blue', debug_path)}"
)
requests_logfile_handler = logging.FileHandler(API_CALL_LOG_FILENAME)
requests_logger.addHandler(requests_logfile_handler)
else:
debug_path = None
requests_logger.addHandler(logging.NullHandler())
if args.profile:
import cProfile
prof = cProfile.Profile()
prof.enable()
if args.version:
print(f"Zulip Terminal {ZT_VERSION}")
sys.exit(0)
if args.list_themes:
print(list_themes())
sys.exit(0)
if args.config_file:
zuliprc_path = args.config_file
else:
zuliprc_path = "~/zuliprc"
try:
zterm = parse_zuliprc(zuliprc_path)
if args.autohide:
zterm["autohide"] = (args.autohide, "on command line")
if args.theme:
theme_to_use = (args.theme, "on command line")
else:
theme_to_use = zterm["theme"]
if (
zterm["footlinks"][1] == ZULIPRC_CONFIG
and zterm["maximum-footlinks"][1] == ZULIPRC_CONFIG
):
exit_with_error(
"Footlinks property is not allowed alongside maximum-footlinks"
)
if (
zterm["maximum-footlinks"][1] == ZULIPRC_CONFIG
and int(zterm["maximum-footlinks"][0]) < 0
):
exit_with_error("Minimum value allowed for maximum-footlinks is 0")
if zterm["footlinks"][1] == ZULIPRC_CONFIG:
if zterm["footlinks"][0] == DEFAULT_SETTINGS["footlinks"]:
maximum_footlinks = 3
else:
maximum_footlinks = 0
else:
maximum_footlinks = int(zterm["maximum-footlinks"][0])
available_themes = all_themes()
theme_aliases = aliased_themes()
is_valid_theme = (
theme_to_use[0] in available_themes or theme_to_use[0] in theme_aliases
)
if not is_valid_theme:
exit_with_error(
"Invalid theme '{}' was specified {}.".format(*theme_to_use),
helper_text=list_themes(),
)
if theme_to_use[0] not in available_themes:
# theme must be an alias, as it is valid
real_theme_name = theme_aliases[theme_to_use[0]]
theme_to_use = (
real_theme_name,
"{} (by alias '{}')".format(theme_to_use[1], theme_to_use[0]),
)
if args.color_depth:
zterm["color-depth"] = (args.color_depth, "on command line")
color_depth_str = zterm["color-depth"][0]
if color_depth_str == "24bit":
color_depth = 2**24
else:
color_depth = int(color_depth_str)
if args.notify:
zterm["notify"] = (args.notify, "on command line")
print("Loading with:")
print(" theme '{}' specified {}.".format(*theme_to_use))
complete, incomplete = complete_and_incomplete_themes()
if theme_to_use[0] in incomplete:
if complete:
incomplete_theme_warning = (
" WARNING: Incomplete theme; results may vary!\n"
" (you could try: {})".format(", ".join(complete))
)
else:
incomplete_theme_warning = (
" WARNING: Incomplete theme; results may vary!\n"
" (all themes are incomplete)"
)
print(in_color("yellow", incomplete_theme_warning))
print(" autohide setting '{}' specified {}.".format(*zterm["autohide"]))
if zterm["footlinks"][1] == ZULIPRC_CONFIG:
print(
" maximum footlinks value '{}' specified {} from footlinks.".format(
maximum_footlinks, zterm["footlinks"][1]
)
)
else:
print(
" maximum footlinks value '{}' specified {}.".format(
*zterm["maximum-footlinks"]
)
)
print(" color depth setting '{}' specified {}.".format(*zterm["color-depth"]))
print(" notify setting '{}' specified {}.".format(*zterm["notify"]))
# For binary settings
# Specify setting in order True, False
valid_settings = {
"autohide": ["autohide", "no_autohide"],
"notify": ["enabled", "disabled"],
"color-depth": ["1", "16", "256", "24bit"],
}
boolean_settings: Dict[str, bool] = dict()
for setting, valid_values in valid_settings.items():
if zterm[setting][0] not in valid_values:
helper_text = (
["Valid values are:"]
+ [f" {option}" for option in valid_values]
+ [f"Specify the {setting} option in zuliprc file."]
)
exit_with_error(
"Invalid {} setting '{}' was specified {}.".format(
setting, *zterm[setting]
),
helper_text="\n".join(helper_text),
)
if setting == "color-depth":
break
boolean_settings[setting] = zterm[setting][0] == valid_values[0]
theme_data = generate_theme(theme_to_use[0], color_depth)
Controller(
config_file=zuliprc_path,
maximum_footlinks=maximum_footlinks,
theme_name=theme_to_use[0],
theme=theme_data,
color_depth=color_depth,
in_explore_mode=args.explore,
**boolean_settings,
debug_path=debug_path,
).main()
except ServerConnectionFailure as e:
# Acts as separator between logs
zt_logger.info(f"\n\n{e}\n\n")
zt_logger.exception(e)
exit_with_error(f"\nError connecting to Zulip server: {e}.")
except InvalidThemeColorCode as e:
# Acts as separator between logs
zt_logger.info(f"\n\n{e}\n\n")
zt_logger.exception(e)
exit_with_error(f"\n{e}")
except (display_common.AttrSpecError, display_common.ScreenError) as e:
# NOTE: Strictly this is not necessarily just a theme error
# FIXME: Add test for this - once loading takes place after UI setup
# Acts as separator between logs
zt_logger.info(f"\n\n{e}\n\n")
zt_logger.exception(e)
exit_with_error(f"\nPossible theme error: {e}.")
except Exception as e:
zt_logger.info("\n\n{e}\n\n")
zt_logger.exception(e)
if args.debug:
sys.stdout.flush()
traceback.print_exc(file=sys.stderr)
run_debugger = input("Run Debugger? (y/n): ")
if run_debugger in ["y", "Y", "yes"]:
# Open PUDB Debugger
import pudb
pudb.post_mortem()
if hasattr(e, "extra_info"):
print(in_color("red", f"\n{e.extra_info}"), file=sys.stderr) # type: ignore
print(
in_color(
"red",
"\nZulip Terminal has crashed!"
f"\nPlease refer to {TRACEBACK_LOG_FILENAME}"
" for full log of the error.",
),
file=sys.stderr,
)
print(
"You can ask for help at:"
"\nhttps://chat.zulip.org/#narrow/stream/206-zulip-terminal",
file=sys.stderr,
)
print("\nThanks for using the Zulip-Terminal interface.\n")
sys.stderr.flush()
finally:
if args.profile:
prof.disable()
import tempfile
with tempfile.NamedTemporaryFile(
prefix="zulip_term_profile.", suffix=".dat", delete=False
) as profile_file:
profile_path = profile_file.name
# Dump stats only after temporary file is closed (for Win NT+ case)
prof.dump_stats(profile_path)
print(
"Profile data saved to {0}.\n"
"You can visualize it using e.g. `snakeviz {0}`".format(profile_path)
)
sys.exit(1)
if __name__ == "__main__":
main() | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/cli/run.py | run.py |
from pygments.styles.zenburn import ZenburnStyle
from zulipterminal.config.color import DefaultBoldColor as Color
# fmt: off
STYLES = {
# style_name : foreground background
None : (Color.BLACK, Color.LIGHT_BLUE),
'selected' : (Color.BLACK, Color.LIGHT_GRAY),
'msg_selected' : (Color.BLACK, Color.LIGHT_GRAY),
'header' : (Color.BLACK, Color.DARK_BLUE),
'general_narrow' : (Color.WHITE, Color.DARK_BLUE),
'general_bar' : (Color.DARK_BLUE, Color.LIGHT_BLUE),
'name' : (Color.DARK_RED, Color.LIGHT_BLUE),
'unread' : (Color.LIGHT_GRAY, Color.LIGHT_BLUE),
'user_active' : (Color.LIGHT_GREEN__BOLD, Color.LIGHT_BLUE),
'user_idle' : (Color.DARK_GRAY, Color.LIGHT_BLUE),
'user_offline' : (Color.BLACK, Color.LIGHT_BLUE),
'user_inactive' : (Color.BLACK, Color.LIGHT_BLUE),
'title' : (Color.WHITE__BOLD, Color.DARK_BLUE),
'column_title' : (Color.BLACK__BOLD, Color.LIGHT_BLUE),
'time' : (Color.DARK_BLUE, Color.LIGHT_BLUE),
'bar' : (Color.WHITE, Color.DARK_BLUE),
'msg_emoji' : (Color.DARK_MAGENTA, Color.LIGHT_BLUE),
'reaction' : (Color.DARK_MAGENTA__BOLD, Color.LIGHT_BLUE),
'reaction_mine' : (Color.LIGHT_BLUE, Color.DARK_MAGENTA),
'msg_heading' : (Color.WHITE__BOLD, Color.BLACK),
'msg_math' : (Color.LIGHT_GRAY, Color.DARK_GRAY),
'msg_mention' : (Color.LIGHT_RED__BOLD, Color.LIGHT_BLUE),
'msg_link' : (Color.DARK_BLUE, Color.LIGHT_GRAY),
'msg_link_index' : (Color.DARK_BLUE__BOLD, Color.LIGHT_GRAY),
'msg_quote' : (Color.BROWN, Color.DARK_BLUE),
'msg_code' : (Color.DARK_BLUE, Color.WHITE),
'msg_bold' : (Color.WHITE__BOLD, Color.DARK_BLUE),
'msg_time' : (Color.DARK_BLUE, Color.WHITE),
'footer' : (Color.WHITE, Color.DARK_GRAY),
'footer_contrast' : (Color.BLACK, Color.WHITE),
'starred' : (Color.LIGHT_RED__BOLD, Color.LIGHT_BLUE),
'unread_count' : (Color.YELLOW, Color.LIGHT_BLUE),
'starred_count' : (Color.BLACK, Color.LIGHT_BLUE),
'table_head' : (Color.BLACK__BOLD, Color.LIGHT_BLUE),
'filter_results' : (Color.WHITE, Color.DARK_GREEN),
'edit_topic' : (Color.WHITE, Color.DARK_BLUE),
'edit_tag' : (Color.WHITE, Color.DARK_BLUE),
'edit_author' : (Color.DARK_GRAY, Color.LIGHT_BLUE),
'edit_time' : (Color.DARK_BLUE, Color.LIGHT_BLUE),
'current_user' : (Color.LIGHT_GRAY, Color.LIGHT_BLUE),
'muted' : (Color.LIGHT_GRAY, Color.LIGHT_BLUE),
'popup_border' : (Color.WHITE, Color.LIGHT_BLUE),
'popup_category' : (Color.LIGHT_GRAY__BOLD, Color.LIGHT_BLUE),
'popup_contrast' : (Color.WHITE, Color.DARK_BLUE),
'popup_important' : (Color.LIGHT_RED__BOLD, Color.LIGHT_BLUE),
'widget_disabled' : (Color.DARK_GRAY, Color.LIGHT_BLUE),
'area:help' : (Color.WHITE, Color.DARK_GREEN),
'area:stream' : (Color.WHITE, Color.DARK_CYAN),
'area:msg' : (Color.WHITE, Color.BROWN),
'area:error' : (Color.WHITE, Color.DARK_RED),
'area:user' : (Color.WHITE, Color.DARK_BLUE),
'search_error' : (Color.LIGHT_RED, Color.LIGHT_BLUE),
'task:success' : (Color.WHITE, Color.DARK_GREEN),
'task:error' : (Color.WHITE, Color.DARK_RED),
'task:warning' : (Color.WHITE, Color.BROWN),
}
META = {
'pygments': {
'styles' : ZenburnStyle().styles,
'background': 'h25',
'overrides' : {
'err' : '#e37170, bold',
'kt' : '#dfdfbf, bold',
'nt' : '#e89393, bold',
'ne' : '#c3bf9f, bold',
'si' : '#dca3a3, bold',
'c' : '#7f9f7f, italics',
'cp' : '#dfaf8f, bold',
'cs' : '#dfdfdf, bold',
'g' : '#ecbcbc, bold',
'ge' : '#ffffff, bold',
'go' : '#5b605e, bold',
'gh' : '#efefef, bold',
'gd' : '#c3bf9f',
'gi' : '#709080, bold',
'gt' : '#80d4aa, bold',
'gu' : '#efefef, bold',
'w' : '#dcdccc', # inline/plain-codeblock
}
}
}
# fmt: on | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/themes/zt_blue.py | zt_blue.py |
from pygments.styles.perldoc import PerldocStyle
from zulipterminal.config.color import DefaultBoldColor as Color
# fmt: off
STYLES = {
# style_name : foreground background
None : (Color.BLACK, Color.WHITE),
'selected' : (Color.BLACK, Color.LIGHT_GREEN),
'msg_selected' : (Color.BLACK, Color.LIGHT_GREEN),
'header' : (Color.WHITE, Color.DARK_BLUE),
'general_narrow' : (Color.WHITE, Color.DARK_BLUE),
'general_bar' : (Color.DARK_BLUE, Color.WHITE),
'name' : (Color.DARK_GREEN, Color.WHITE),
'unread' : (Color.DARK_GRAY, Color.LIGHT_GRAY),
'user_active' : (Color.DARK_GREEN, Color.WHITE),
'user_idle' : (Color.DARK_BLUE, Color.WHITE),
'user_offline' : (Color.BLACK, Color.WHITE),
'user_inactive' : (Color.BLACK, Color.WHITE),
'title' : (Color.WHITE__BOLD, Color.DARK_GRAY),
'column_title' : (Color.BLACK__BOLD, Color.WHITE),
'time' : (Color.DARK_BLUE, Color.WHITE),
'bar' : (Color.WHITE, Color.DARK_GRAY),
'msg_emoji' : (Color.LIGHT_MAGENTA, Color.WHITE),
'reaction' : (Color.LIGHT_MAGENTA__BOLD, Color.WHITE),
'reaction_mine' : (Color.WHITE, Color.LIGHT_MAGENTA),
'msg_heading' : (Color.WHITE__BOLD, Color.DARK_RED),
'msg_math' : (Color.DARK_GRAY, Color.LIGHT_GRAY),
'msg_mention' : (Color.LIGHT_RED__BOLD, Color.WHITE),
'msg_link' : (Color.DARK_BLUE, Color.WHITE),
'msg_link_index' : (Color.DARK_BLUE__BOLD, Color.WHITE),
'msg_quote' : (Color.BLACK, Color.BROWN),
'msg_code' : (Color.BLACK, Color.LIGHT_GRAY),
'msg_bold' : (Color.WHITE__BOLD, Color.DARK_GRAY),
'msg_time' : (Color.WHITE, Color.DARK_GRAY),
'footer' : (Color.WHITE, Color.DARK_GRAY),
'footer_contrast' : (Color.BLACK, Color.WHITE),
'starred' : (Color.LIGHT_RED__BOLD, Color.WHITE),
'unread_count' : (Color.DARK_BLUE__BOLD, Color.WHITE),
'starred_count' : (Color.BLACK, Color.WHITE),
'table_head' : (Color.BLACK__BOLD, Color.WHITE),
'filter_results' : (Color.WHITE, Color.DARK_GREEN),
'edit_topic' : (Color.WHITE, Color.DARK_GRAY),
'edit_tag' : (Color.WHITE, Color.DARK_GRAY),
'edit_author' : (Color.DARK_GREEN, Color.WHITE),
'edit_time' : (Color.DARK_BLUE, Color.WHITE),
'current_user' : (Color.DARK_GRAY, Color.WHITE),
'muted' : (Color.DARK_GRAY, Color.WHITE),
'popup_border' : (Color.BLACK, Color.WHITE),
'popup_category' : (Color.DARK_GRAY__BOLD, Color.LIGHT_GRAY),
'popup_contrast' : (Color.WHITE, Color.DARK_GRAY),
'popup_important' : (Color.LIGHT_RED__BOLD, Color.WHITE),
'widget_disabled' : (Color.LIGHT_GRAY, Color.WHITE),
'area:help' : (Color.BLACK, Color.LIGHT_GREEN),
'area:stream' : (Color.BLACK, Color.LIGHT_BLUE),
'area:msg' : (Color.BLACK, Color.YELLOW),
'area:error' : (Color.BLACK, Color.LIGHT_RED),
'area:user' : (Color.WHITE, Color.DARK_BLUE),
'search_error' : (Color.LIGHT_RED, Color.WHITE),
'task:success' : (Color.BLACK, Color.DARK_GREEN),
'task:error' : (Color.WHITE, Color.DARK_RED),
'task:warning' : (Color.BLACK, Color.YELLOW),
}
META = {
'pygments': {
'styles' : PerldocStyle().styles,
'background': PerldocStyle().background_color,
'overrides' : {
'cs' : '#8B008B, bold',
'sh' : '#1c7e71, italics',
'k' : '#8B008B, bold',
'nc' : '#008b45, bold',
'ne' : '#008b45, bold',
'nn' : '#008b45, underline',
'nt' : '#8B008B, bold',
'gh' : '#000080, bold',
'gu' : '#800080, bold',
'ge' : 'default, italics',
'gs' : 'default, bold',
'err' : '#a61717',
'n' : '#666666',
'p' : '#666666',
'o' : '#8B008B',
'w' : '#666666', # inline/plain-codeblock
}
}
}
# fmt: on | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/themes/zt_light.py | zt_light.py |
from pygments.styles.material import MaterialStyle
from zulipterminal.config.color import DefaultBoldColor as Color
# fmt: off
STYLES = {
# style_name : foreground background
None : (Color.WHITE, Color.BLACK),
'selected' : (Color.WHITE, Color.DARK_BLUE),
'msg_selected' : (Color.WHITE, Color.DARK_BLUE),
'header' : (Color.DARK_CYAN, Color.DARK_BLUE),
'general_narrow' : (Color.WHITE, Color.DARK_BLUE),
'general_bar' : (Color.WHITE, Color.BLACK),
'name' : (Color.YELLOW__BOLD, Color.BLACK),
'unread' : (Color.DARK_BLUE, Color.BLACK),
'user_active' : (Color.LIGHT_GREEN, Color.BLACK),
'user_idle' : (Color.YELLOW, Color.BLACK),
'user_offline' : (Color.WHITE, Color.BLACK),
'user_inactive' : (Color.WHITE, Color.BLACK),
'title' : (Color.WHITE__BOLD, Color.BLACK),
'column_title' : (Color.WHITE__BOLD, Color.BLACK),
'time' : (Color.LIGHT_BLUE, Color.BLACK),
'bar' : (Color.WHITE, Color.DARK_GRAY),
'msg_emoji' : (Color.LIGHT_MAGENTA, Color.BLACK),
'reaction' : (Color.LIGHT_MAGENTA__BOLD, Color.BLACK),
'reaction_mine' : (Color.BLACK, Color.LIGHT_MAGENTA),
'msg_heading' : (Color.LIGHT_CYAN__BOLD, Color.DARK_MAGENTA),
'msg_math' : (Color.LIGHT_GRAY, Color.DARK_GRAY),
'msg_mention' : (Color.LIGHT_RED__BOLD, Color.BLACK),
'msg_link' : (Color.LIGHT_BLUE, Color.BLACK),
'msg_link_index' : (Color.LIGHT_BLUE__BOLD, Color.BLACK),
'msg_quote' : (Color.BROWN, Color.BLACK),
'msg_code' : (Color.BLACK, Color.WHITE),
'msg_bold' : (Color.WHITE__BOLD, Color.BLACK),
'msg_time' : (Color.BLACK, Color.WHITE),
'footer' : (Color.BLACK, Color.LIGHT_GRAY),
'footer_contrast' : (Color.WHITE, Color.BLACK),
'starred' : (Color.LIGHT_RED__BOLD, Color.BLACK),
'unread_count' : (Color.YELLOW, Color.BLACK),
'starred_count' : (Color.LIGHT_GRAY, Color.BLACK),
'table_head' : (Color.WHITE__BOLD, Color.BLACK),
'filter_results' : (Color.WHITE, Color.DARK_GREEN),
'edit_topic' : (Color.WHITE, Color.DARK_GRAY),
'edit_tag' : (Color.WHITE, Color.DARK_GRAY),
'edit_author' : (Color.YELLOW, Color.BLACK),
'edit_time' : (Color.LIGHT_BLUE, Color.BLACK),
'current_user' : (Color.WHITE, Color.BLACK),
'muted' : (Color.LIGHT_BLUE, Color.BLACK),
'popup_border' : (Color.WHITE, Color.BLACK),
'popup_category' : (Color.LIGHT_BLUE__BOLD, Color.BLACK),
'popup_contrast' : (Color.WHITE, Color.DARK_GRAY),
'popup_important' : (Color.LIGHT_RED__BOLD, Color.BLACK),
'widget_disabled' : (Color.DARK_GRAY, Color.BLACK),
'area:help' : (Color.WHITE, Color.DARK_GREEN),
'area:msg' : (Color.WHITE, Color.BROWN),
'area:stream' : (Color.WHITE, Color.DARK_CYAN),
'area:error' : (Color.WHITE, Color.DARK_RED),
'area:user' : (Color.WHITE, Color.DARK_BLUE),
'search_error' : (Color.LIGHT_RED, Color.BLACK),
'task:success' : (Color.WHITE, Color.DARK_GREEN),
'task:error' : (Color.WHITE, Color.DARK_RED),
'task:warning' : (Color.WHITE, Color.BROWN),
}
META = {
'pygments': {
'styles' : MaterialStyle().styles,
'background': 'h235',
'overrides' : {
'kn' : MaterialStyle().cyan + ', italics',
'sd' : MaterialStyle().faded + ', italics',
'ow' : MaterialStyle().cyan + ', italics',
'c' : MaterialStyle().faded + ', italics',
'n' : MaterialStyle().paleblue,
'no' : MaterialStyle().paleblue,
'nx' : MaterialStyle().paleblue,
'w' : MaterialStyle().paleblue, # inline/plain-codeblock
}
}
}
# fmt: on | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/themes/zt_dark.py | zt_dark.py |
from pygments.styles.solarized import SolarizedLightStyle
from zulipterminal.themes.colors_gruvbox import DefaultBoldColor as Color
# fmt: off
STYLES = {
# style_name : foreground background
None : (Color.DARK2, Color.LIGHT0_HARD),
'selected' : (Color.LIGHT0_HARD, Color.NEUTRAL_BLUE),
'msg_selected' : (Color.LIGHT0_HARD, Color.NEUTRAL_BLUE),
'header' : (Color.NEUTRAL_BLUE, Color.FADED_BLUE),
'general_narrow' : (Color.LIGHT0_HARD, Color.FADED_BLUE),
'general_bar' : (Color.DARK2, Color.LIGHT0_HARD),
'name' : (Color.NEUTRAL_YELLOW, Color.LIGHT0_HARD),
'unread' : (Color.NEUTRAL_PURPLE, Color.LIGHT0_HARD),
'user_active' : (Color.FADED_GREEN, Color.LIGHT0_HARD),
'user_idle' : (Color.NEUTRAL_YELLOW, Color.LIGHT0_HARD),
'user_offline' : (Color.DARK2, Color.LIGHT0_HARD),
'user_inactive' : (Color.DARK2, Color.LIGHT0_HARD),
'title' : (Color.DARK2__BOLD, Color.LIGHT0_HARD),
'column_title' : (Color.DARK2__BOLD, Color.LIGHT0_HARD),
'time' : (Color.FADED_BLUE, Color.LIGHT0_HARD),
'bar' : (Color.DARK2, Color.GRAY_245),
'msg_emoji' : (Color.NEUTRAL_PURPLE, Color.LIGHT0_HARD),
'reaction' : (Color.NEUTRAL_PURPLE__BOLD, Color.LIGHT0_HARD),
'reaction_mine' : (Color.LIGHT0_HARD, Color.NEUTRAL_PURPLE),
'msg_heading' : (Color.LIGHT0_HARD__BOLD, Color.FADED_GREEN),
'msg_math' : (Color.LIGHT0_HARD, Color.GRAY_245),
'msg_mention' : (Color.FADED_RED__BOLD, Color.LIGHT0_HARD),
'msg_link' : (Color.FADED_BLUE, Color.LIGHT0_HARD),
'msg_link_index' : (Color.FADED_BLUE__BOLD, Color.LIGHT0_HARD),
'msg_quote' : (Color.NEUTRAL_YELLOW, Color.LIGHT0_HARD),
'msg_code' : (Color.LIGHT0_HARD, Color.DARK2),
'msg_bold' : (Color.DARK2__BOLD, Color.LIGHT0_HARD),
'msg_time' : (Color.LIGHT0_HARD, Color.DARK2),
'footer' : (Color.LIGHT0_HARD, Color.DARK4),
'footer_contrast' : (Color.DARK2, Color.LIGHT0_HARD),
'starred' : (Color.FADED_RED__BOLD, Color.LIGHT0_HARD),
'unread_count' : (Color.NEUTRAL_YELLOW, Color.LIGHT0_HARD),
'starred_count' : (Color.DARK4, Color.LIGHT0_HARD),
'table_head' : (Color.DARK2__BOLD, Color.LIGHT0_HARD),
'filter_results' : (Color.LIGHT0_HARD, Color.FADED_GREEN),
'edit_topic' : (Color.LIGHT0_HARD, Color.GRAY_245),
'edit_tag' : (Color.LIGHT0_HARD, Color.GRAY_245),
'edit_author' : (Color.NEUTRAL_YELLOW, Color.LIGHT0_HARD),
'edit_time' : (Color.FADED_BLUE, Color.LIGHT0_HARD),
'current_user' : (Color.DARK2, Color.LIGHT0_HARD),
'muted' : (Color.FADED_BLUE, Color.LIGHT0_HARD),
'popup_border' : (Color.DARK2, Color.LIGHT0_HARD),
'popup_category' : (Color.FADED_BLUE__BOLD, Color.LIGHT0_HARD),
'popup_contrast' : (Color.LIGHT0_HARD, Color.GRAY_245),
'popup_important' : (Color.FADED_RED__BOLD, Color.LIGHT0_HARD),
'widget_disabled' : (Color.GRAY_245, Color.LIGHT0_HARD),
'area:help' : (Color.LIGHT0_HARD, Color.FADED_GREEN),
'area:msg' : (Color.LIGHT0_HARD, Color.NEUTRAL_PURPLE),
'area:stream' : (Color.LIGHT0_HARD, Color.FADED_BLUE),
'area:error' : (Color.LIGHT0_HARD, Color.FADED_RED),
'area:user' : (Color.LIGHT0_HARD, Color.FADED_YELLOW),
'search_error' : (Color.FADED_RED, Color.LIGHT0_HARD),
'task:success' : (Color.LIGHT0_HARD, Color.FADED_GREEN),
'task:error' : (Color.LIGHT0_HARD, Color.FADED_RED),
'task:warning' : (Color.LIGHT0_HARD, Color.NEUTRAL_PURPLE),
}
META = {
'pygments': {
'styles' : SolarizedLightStyle().styles,
'background': '#ffffcc',
'overrides' : {
'c' : '#586E75, italics', # base01
'cp' : '#859900', # magenta
'cpf' : '#586e75', # base01
'ge' : '#93A1A1, italics', # base0
'gh' : '#CB4B16, bold', # base0
'gu' : '#CB4B16, underline', # base0
'gp' : '#93A1A1, bold', # blue
'gs' : '#93A1A1, bold', # base0
'err' : '#93A1A1', # red
'n' : '#93A1A1', # gruvbox: light4
'p' : '#93A1A1', # gruvbox: light4
'w' : '#93A1A1', # gruvbox: light4
}
}
}
# fmt: on | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/themes/gruvbox_light.py | gruvbox_light.py |
from pygments.styles.solarized import SolarizedDarkStyle
from zulipterminal.themes.colors_gruvbox import DefaultBoldColor as Color
# fmt: off
STYLES = {
# style_name : foreground background
None : (Color.LIGHT2, Color.DARK0_HARD),
'selected' : (Color.DARK0_HARD, Color.NEUTRAL_BLUE),
'msg_selected' : (Color.DARK0_HARD, Color.NEUTRAL_BLUE),
'header' : (Color.NEUTRAL_BLUE, Color.BRIGHT_BLUE),
'general_narrow' : (Color.DARK0_HARD, Color.BRIGHT_BLUE),
'general_bar' : (Color.LIGHT2, Color.DARK0_HARD),
'name' : (Color.NEUTRAL_YELLOW__BOLD, Color.DARK0_HARD),
'unread' : (Color.NEUTRAL_PURPLE, Color.DARK0_HARD),
'user_active' : (Color.BRIGHT_GREEN, Color.DARK0_HARD),
'user_idle' : (Color.NEUTRAL_YELLOW, Color.DARK0_HARD),
'user_offline' : (Color.LIGHT2, Color.DARK0_HARD),
'user_inactive' : (Color.LIGHT2, Color.DARK0_HARD),
'title' : (Color.LIGHT2__BOLD, Color.DARK0_HARD),
'column_title' : (Color.LIGHT2__BOLD, Color.DARK0_HARD),
'time' : (Color.BRIGHT_BLUE, Color.DARK0_HARD),
'bar' : (Color.LIGHT2, Color.GRAY_244),
'msg_emoji' : (Color.NEUTRAL_PURPLE, Color.DARK0_HARD),
'reaction' : (Color.NEUTRAL_PURPLE__BOLD, Color.DARK0_HARD),
'reaction_mine' : (Color.DARK0_HARD, Color.NEUTRAL_PURPLE),
'msg_heading' : (Color.DARK0_HARD__BOLD, Color.BRIGHT_GREEN),
'msg_math' : (Color.DARK0_HARD, Color.GRAY_244),
'msg_mention' : (Color.BRIGHT_RED__BOLD, Color.DARK0_HARD),
'msg_link' : (Color.BRIGHT_BLUE, Color.DARK0_HARD),
'msg_link_index' : (Color.BRIGHT_BLUE__BOLD, Color.DARK0_HARD),
'msg_quote' : (Color.NEUTRAL_YELLOW, Color.DARK0_HARD),
'msg_code' : (Color.DARK0_HARD, Color.LIGHT2),
'msg_bold' : (Color.LIGHT2__BOLD, Color.DARK0_HARD),
'msg_time' : (Color.DARK0_HARD, Color.LIGHT2),
'footer' : (Color.DARK0_HARD, Color.LIGHT4),
'footer_contrast' : (Color.LIGHT2, Color.DARK0_HARD),
'starred' : (Color.BRIGHT_RED__BOLD, Color.DARK0_HARD),
'unread_count' : (Color.NEUTRAL_YELLOW, Color.DARK0_HARD),
'starred_count' : (Color.LIGHT4, Color.DARK0_HARD),
'table_head' : (Color.LIGHT2__BOLD, Color.DARK0_HARD),
'filter_results' : (Color.DARK0_HARD, Color.BRIGHT_GREEN),
'edit_topic' : (Color.DARK0_HARD, Color.GRAY_244),
'edit_tag' : (Color.DARK0_HARD, Color.GRAY_244),
'edit_author' : (Color.NEUTRAL_YELLOW, Color.DARK0_HARD),
'edit_time' : (Color.BRIGHT_BLUE, Color.DARK0_HARD),
'current_user' : (Color.LIGHT2, Color.DARK0_HARD),
'muted' : (Color.BRIGHT_BLUE, Color.DARK0_HARD),
'popup_border' : (Color.LIGHT2, Color.DARK0_HARD),
'popup_category' : (Color.BRIGHT_BLUE__BOLD, Color.DARK0_HARD),
'popup_contrast' : (Color.DARK0_HARD, Color.GRAY_244),
'popup_important' : (Color.BRIGHT_RED__BOLD, Color.DARK0_HARD),
'widget_disabled' : (Color.GRAY_244, Color.DARK0_HARD),
'area:help' : (Color.DARK0_HARD, Color.BRIGHT_GREEN),
'area:msg' : (Color.DARK0_HARD, Color.NEUTRAL_PURPLE),
'area:stream' : (Color.DARK0_HARD, Color.BRIGHT_BLUE),
'area:error' : (Color.DARK0_HARD, Color.BRIGHT_RED),
'area:user' : (Color.DARK0_HARD, Color.BRIGHT_YELLOW),
'search_error' : (Color.BRIGHT_RED, Color.DARK0_HARD),
'task:success' : (Color.DARK0_HARD, Color.BRIGHT_GREEN),
'task:error' : (Color.DARK0_HARD, Color.BRIGHT_RED),
'task:warning' : (Color.DARK0_HARD, Color.NEUTRAL_PURPLE),
}
META = {
'pygments': {
'styles' : SolarizedDarkStyle().styles,
'background': 'h236',
'overrides' : {
'c' : '#586e75, italics', # base01
'cp' : '#d33682', # magenta
'cpf' : '#586e75', # base01
'ge' : '#839496, italics', # base0
'gh' : '#839496, bold', # base0
'gu' : '#839496, underline', # base0
'gp' : '#268bd2, bold', # blue
'gs' : '#839496, bold', # base0
'err' : '#dc322f', # red
'n' : '#bdae93', # gruvbox: light4
'p' : '#bdae93', # gruvbox: light4
'w' : '#bdae93', # gruvbox: light4
}
}
}
# fmt: on | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/themes/gruvbox_dark.py | gruvbox_dark.py |
import re
from functools import partial
from typing import Any, Callable, Dict, List, Optional, Tuple, Union, cast
from urllib.parse import urljoin, urlparse
import urwid
from typing_extensions import TypedDict
from zulipterminal.api_types import RESOLVED_TOPIC_PREFIX, EditPropagateMode
from zulipterminal.config.keys import is_command_key, primary_key_for_command
from zulipterminal.config.regexes import REGEX_INTERNAL_LINK_STREAM_ID
from zulipterminal.config.symbols import CHECK_MARK, MUTE_MARKER
from zulipterminal.config.ui_mappings import EDIT_MODE_CAPTIONS, STREAM_ACCESS_TYPE
from zulipterminal.helper import Message, StreamData, hash_util_decode, process_media
from zulipterminal.urwid_types import urwid_Size
class TopButton(urwid.Button):
def __init__(
self,
*,
controller: Any,
caption: str,
show_function: Callable[[], Any],
prefix_character: Union[str, Tuple[Any, str]] = "\N{BULLET}",
text_color: Optional[str] = None,
count: int = 0,
count_style: Optional[str] = None,
) -> None:
self.controller = controller
self._caption = caption
self.show_function = show_function
self.prefix_character = prefix_character
self.original_color = text_color
self.count = count
self.count_style = count_style
super().__init__("")
self.button_prefix = urwid.Text("")
self._label.set_wrap_mode("ellipsis")
self._label.get_cursor_coords = lambda x: None
self.button_suffix = urwid.Text("")
cols = urwid.Columns(
[
("pack", self.button_prefix),
self._label,
("pack", self.button_suffix),
]
)
self._w = urwid.AttrMap(cols, None, "selected")
self.update_count(count, text_color)
urwid.connect_signal(self, "click", self.activate)
def update_count(self, count: int, text_color: Optional[str] = None) -> None:
new_color = self.original_color if text_color is None else text_color
self.count = count
if count == 0:
count_text = ""
else:
count_text = str(count)
self.update_widget((self.count_style, count_text), new_color)
def update_widget(
self, count_text: Tuple[Optional[str], str], text_color: Optional[str]
) -> Any:
if self.prefix_character:
prefix = [" ", self.prefix_character, " "]
else:
prefix = [" "]
if count_text[1]:
suffix = [" ", count_text, " "]
else:
suffix = [" "]
self.button_prefix.set_text(prefix)
self.set_label(self._caption)
self.button_suffix.set_text(suffix)
self._w.set_attr_map({None: text_color})
def activate(self, key: Any) -> None:
self.controller.view.show_left_panel(visible=False)
self.controller.view.show_right_panel(visible=False)
self.controller.view.body.focus_col = 1
self.show_function()
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("ENTER", key):
self.activate(key)
return None
else: # This is in the else clause, to avoid multiple activation
return super().keypress(size, key)
class HomeButton(TopButton):
def __init__(self, *, controller: Any, count: int) -> None:
button_text = f"All messages [{primary_key_for_command('ALL_MESSAGES')}]"
super().__init__(
controller=controller,
caption=button_text,
show_function=controller.narrow_to_all_messages,
prefix_character="",
count=count,
count_style="unread_count",
)
class PMButton(TopButton):
def __init__(self, *, controller: Any, count: int) -> None:
button_text = f"Private messages [{primary_key_for_command('ALL_PM')}]"
super().__init__(
controller=controller,
caption=button_text,
show_function=controller.narrow_to_all_pm,
prefix_character="",
count=count,
count_style="unread_count",
)
class MentionedButton(TopButton):
def __init__(self, *, controller: Any, count: int) -> None:
button_text = f"Mentions [{primary_key_for_command('ALL_MENTIONS')}]"
super().__init__(
controller=controller,
caption=button_text,
show_function=controller.narrow_to_all_mentions,
prefix_character="",
count=count,
count_style="unread_count",
)
class StarredButton(TopButton):
def __init__(self, *, controller: Any, count: int) -> None:
button_text = f"Starred messages [{primary_key_for_command('ALL_STARRED')}]"
super().__init__(
controller=controller,
caption=button_text,
show_function=controller.narrow_to_all_starred,
prefix_character="",
count=count, # Number of starred messages, not unread count
count_style="starred_count",
)
class StreamButton(TopButton):
def __init__(
self,
*,
properties: StreamData,
controller: Any,
view: Any,
count: int,
) -> None:
# FIXME Is having self.stream_id the best way to do this?
# (self.stream_id is used elsewhere)
self.stream_name = properties["name"]
self.stream_id = properties["id"]
self.color = properties["color"]
stream_access_type = properties["stream_access_type"]
self.description = properties["description"]
self.model = controller.model
self.count = count
self.view = view
for entry in view.palette:
if entry[0] is None:
background = entry[5] if len(entry) > 4 else entry[2]
inverse_text = background if background else "black"
break
view.palette.append(
(self.color, "", "", "bold", f"{self.color}, bold", background)
)
view.palette.append(
("s" + self.color, "", "", "standout", inverse_text, self.color)
)
stream_marker = STREAM_ACCESS_TYPE[stream_access_type]["icon"]
narrow_function = partial(
controller.narrow_to_stream,
stream_name=self.stream_name,
)
super().__init__(
controller=controller,
caption=self.stream_name,
show_function=narrow_function,
prefix_character=(self.color, stream_marker),
count=count,
count_style="unread_count",
)
# Mark muted streams 'M' during button creation.
if self.model.is_muted_stream(self.stream_id):
self.mark_muted()
def mark_muted(self) -> None:
self.update_widget(("muted", MUTE_MARKER), "muted")
self.view.home_button.update_count(self.model.unread_counts["all_msg"])
def mark_unmuted(self, unread_count: int) -> None:
self.update_count(unread_count)
self.view.home_button.update_count(self.model.unread_counts["all_msg"])
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("TOGGLE_TOPIC", key):
self.view.left_panel.show_topic_view(self)
elif is_command_key("TOGGLE_MUTE_STREAM", key):
self.controller.stream_muting_confirmation_popup(
self.stream_id, self.stream_name
)
elif is_command_key("STREAM_DESC", key):
self.model.controller.show_stream_info(self.stream_id)
return super().keypress(size, key)
class UserButton(TopButton):
def __init__(
self,
*,
user: Dict[str, Any],
controller: Any,
view: Any,
state_marker: str,
color: Optional[str] = None,
count: int,
is_current_user: bool = False,
) -> None:
# Properties accessed externally
self.email = user["email"]
self.user_id = user["user_id"]
self.controller = controller
self._view = view # Used in _narrow_with_compose
# FIXME Is this still needed?
self.recipients = frozenset({self.user_id, view.model.user_id})
super().__init__(
controller=controller,
caption=user["full_name"],
show_function=self._narrow_with_compose,
prefix_character=(color, state_marker),
text_color=color,
count=count,
)
if is_current_user:
self.update_widget(("current_user", "(you)"), color)
def _narrow_with_compose(self) -> None:
# Switches directly to composing with user
# FIXME should we just narrow?
self.controller.narrow_to_user(
recipient_emails=[self.email],
)
self._view.body.focus.original_widget.set_focus("footer")
self._view.write_box.private_box_view(recipient_user_ids=[self.user_id])
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("USER_INFO", key):
self.controller.show_user_info(self.user_id)
return super().keypress(size, key)
class TopicButton(TopButton):
def __init__(
self,
*,
stream_id: int,
topic: str,
controller: Any,
view: Any,
count: int,
) -> None:
self.stream_name = controller.model.stream_dict[stream_id]["name"]
self.topic_name = topic
self.stream_id = stream_id
self.model = controller.model
self.view = view
narrow_function = partial(
controller.narrow_to_topic,
stream_name=self.stream_name,
topic_name=self.topic_name,
)
# The space acts as a TopButton prefix and gives an effective 3 spaces for unresolved topics.
topic_prefix = " "
topic_name = self.topic_name
if self.topic_name.startswith(RESOLVED_TOPIC_PREFIX):
topic_prefix = self.topic_name[:1]
topic_name = self.topic_name[2:]
super().__init__(
controller=controller,
caption=topic_name,
show_function=narrow_function,
prefix_character=topic_prefix,
count=count,
count_style="unread_count",
)
if controller.model.is_muted_topic(self.stream_id, self.topic_name):
self.mark_muted()
def mark_muted(self) -> None:
self.update_widget(("muted", MUTE_MARKER), "muted")
# TODO: Handle event-based approach for topic-muting.
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("TOGGLE_TOPIC", key):
# Exit topic view
self.view.left_panel.show_stream_view()
return super().keypress(size, key)
class EmojiButton(TopButton):
def __init__(
self,
*,
controller: Any,
emoji_unit: Tuple[str, str, List[str]], # (emoji_name, emoji_code, aliases)
message: Message,
reaction_count: int = 0,
is_selected: Callable[[str], bool],
toggle_selection: Callable[[str, str], None],
) -> None:
self.controller = controller
self.message = message
self.is_selected = is_selected
self.reaction_count = reaction_count
self.toggle_selection = toggle_selection
self.emoji_name, self.emoji_code, self.aliases = emoji_unit
full_button_caption = ", ".join([self.emoji_name, *self.aliases])
super().__init__(
controller=controller,
caption=full_button_caption,
prefix_character="",
show_function=self.update_emoji_button,
)
has_check_mark = self._has_user_reacted_to_msg() or is_selected(self.emoji_name)
self.update_widget((None, self.get_update_widget_text(has_check_mark)), None)
def _has_user_reacted_to_msg(self) -> bool:
return self.controller.model.has_user_reacted_to_message(
self.message, emoji_code=self.emoji_code
)
def get_update_widget_text(self, user_reacted: bool) -> str:
count_text = str(self.reaction_count) if self.reaction_count > 0 else ""
reacted_check_mark = CHECK_MARK if user_reacted else ""
return f" {reacted_check_mark} {count_text} "
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: int
) -> bool:
if event == "mouse press":
if button == 1:
self.keypress(size, primary_key_for_command("ENTER"))
return True
return super().mouse_event(size, event, button, col, row, focus)
def update_emoji_button(self) -> None:
self.toggle_selection(self.emoji_code, self.emoji_name)
is_reaction_added = self._has_user_reacted_to_msg() != self.is_selected(
self.emoji_name
)
self.reaction_count = (
(self.reaction_count + 1)
if is_reaction_added
else (self.reaction_count - 1)
)
self.update_widget((None, self.get_update_widget_text(is_reaction_added)), None)
class DecodedStream(TypedDict):
stream_id: Optional[int]
stream_name: Optional[str]
class ParsedNarrowLink(TypedDict, total=False):
narrow: str
stream: DecodedStream
topic_name: str
message_id: Optional[int]
class MessageLinkButton(urwid.Button):
def __init__(
self, *, controller: Any, caption: str, link: str, display_attr: Optional[str]
) -> None:
self.controller = controller
self.model = self.controller.model
self.view = self.controller.view
self.link = link
super().__init__("")
self.update_widget(caption, display_attr)
urwid.connect_signal(self, "click", callback=self.handle_link)
def update_widget(self, caption: str, display_attr: Optional[str] = None) -> None:
"""
Overrides the existing button widget for custom styling.
"""
# Set cursor position next to len(caption) to avoid the cursor.
icon = urwid.SelectableIcon(caption, cursor_position=len(caption) + 1)
self._w = urwid.AttrMap(icon, display_attr, focus_map="selected")
def handle_link(self, *_: Any) -> None:
"""
Classifies and handles link.
"""
server_url = self.model.server_url
if self.link.startswith(urljoin(server_url, "/#narrow/")):
self.handle_narrow_link()
elif self.link.startswith(urljoin(server_url, "/user_uploads/")):
# Exit pop-up promptly, let the media download in the background.
if self.controller.is_any_popup_open():
self.controller.exit_popup()
process_media(self.controller, self.link)
@staticmethod
def _decode_stream_data(encoded_stream_data: str) -> DecodedStream:
"""
Returns a dict with optional stream ID and stream name.
"""
# Modern links come patched with the stream ID and '-' as delimiters.
if re.match(REGEX_INTERNAL_LINK_STREAM_ID, encoded_stream_data):
stream_id, *_ = encoded_stream_data.split("-")
# Given how encode_stream() in zerver/lib/url_encoding.py
# replaces ' ' with '-' in the stream name, skip extracting the
# stream name to avoid any ambiguity.
return DecodedStream(stream_id=int(stream_id), stream_name=None)
else:
# Deprecated links did not start with the stream ID.
stream_name = hash_util_decode(encoded_stream_data)
return DecodedStream(stream_id=None, stream_name=stream_name)
@staticmethod
def _decode_message_id(message_id: str) -> Optional[int]:
"""
Returns either the compatible near message ID or None.
"""
try:
return int(message_id)
except ValueError:
return None
@classmethod
def _parse_narrow_link(cls, link: str) -> ParsedNarrowLink:
"""
Returns either a dict with narrow parameters for supported links or an
empty dict.
"""
# NOTE: The optional stream_id link version is deprecated. The extended
# support is for old messages.
# We expect the fragment to be one of the following types:
# a. narrow/stream/[{stream_id}-]{stream-name}
# b. narrow/stream/[{stream_id}-]{stream-name}/near/{message_id}
# c. narrow/stream/[{stream_id}-]{stream-name}/topic/
# {encoded.20topic.20name}
# d. narrow/stream/[{stream_id}-]{stream-name}/topic/
# {encoded.20topic.20name}/near/{message_id}
fragments = urlparse(link.rstrip("/")).fragment.split("/")
len_fragments = len(fragments)
parsed_link = ParsedNarrowLink()
if len_fragments == 3 and fragments[1] == "stream":
stream_data = cls._decode_stream_data(fragments[2])
parsed_link = dict(narrow="stream", stream=stream_data)
elif (
len_fragments == 5 and fragments[1] == "stream" and fragments[3] == "topic"
):
stream_data = cls._decode_stream_data(fragments[2])
topic_name = hash_util_decode(fragments[4])
parsed_link = dict(
narrow="stream:topic", stream=stream_data, topic_name=topic_name
)
elif len_fragments == 5 and fragments[1] == "stream" and fragments[3] == "near":
stream_data = cls._decode_stream_data(fragments[2])
message_id = cls._decode_message_id(fragments[4])
parsed_link = dict(
narrow="stream:near", stream=stream_data, message_id=message_id
)
elif (
len_fragments == 7
and fragments[1] == "stream"
and fragments[3] == "topic"
and fragments[5] == "near"
):
stream_data = cls._decode_stream_data(fragments[2])
topic_name = hash_util_decode(fragments[4])
message_id = cls._decode_message_id(fragments[6])
parsed_link = dict(
narrow="stream:topic:near",
stream=stream_data,
topic_name=topic_name,
message_id=message_id,
)
return parsed_link
def _validate_and_patch_stream_data(self, parsed_link: ParsedNarrowLink) -> str:
"""
Validates stream data and patches the optional value in the nested
DecodedStream dict.
"""
stream_id = parsed_link["stream"]["stream_id"]
stream_name = parsed_link["stream"]["stream_name"]
assert (stream_id is None and stream_name is not None) or (
stream_id is not None and stream_name is None
)
model = self.model
# Validate stream ID and name.
if (stream_id and not model.is_user_subscribed_to_stream(stream_id)) or (
stream_name and not model.is_valid_stream(stream_name)
):
# TODO: Narrow to the concerned stream in a 'preview' mode or
# report whether the stream id is invalid instead.
return "The stream seems to be either unknown or unsubscribed"
# Patch the optional value.
if not stream_id:
stream_id = cast(int, model.stream_id_from_name(stream_name))
parsed_link["stream"]["stream_id"] = stream_id
else:
stream_name = cast(str, model.stream_dict[stream_id]["name"])
parsed_link["stream"]["stream_name"] = stream_name
return ""
def _validate_narrow_link(self, parsed_link: ParsedNarrowLink) -> str:
"""
Returns either an empty string for a successful validation or an
appropriate validation error.
"""
if not parsed_link:
return "The narrow link seems to be either broken or unsupported"
# Validate stream data.
if "stream" in parsed_link:
error = self._validate_and_patch_stream_data(parsed_link)
if error:
return error
# Validate topic name.
if "topic_name" in parsed_link:
topic_name = parsed_link["topic_name"]
stream_id = parsed_link["stream"]["stream_id"]
if topic_name not in self.model.topics_in_stream(stream_id):
return "Invalid topic name"
# Validate message ID for near.
if "near" in parsed_link["narrow"]:
message_id = parsed_link.get("message_id")
if message_id is None:
return "Invalid message ID"
return ""
def _switch_narrow_to(self, parsed_link: ParsedNarrowLink) -> None:
"""
Switches narrow via narrow_to_* methods.
"""
narrow = parsed_link["narrow"]
if "stream" == narrow:
self.controller.narrow_to_stream(
stream_name=parsed_link["stream"]["stream_name"],
)
elif "stream:near" == narrow:
self.controller.narrow_to_stream(
stream_name=parsed_link["stream"]["stream_name"],
contextual_message_id=parsed_link["message_id"],
)
elif "stream:topic" == narrow:
self.controller.narrow_to_topic(
stream_name=parsed_link["stream"]["stream_name"],
topic_name=parsed_link["topic_name"],
)
elif "stream:topic:near" == narrow:
self.controller.narrow_to_topic(
stream_name=parsed_link["stream"]["stream_name"],
topic_name=parsed_link["topic_name"],
contextual_message_id=parsed_link["message_id"],
)
def handle_narrow_link(self) -> None:
"""
Narrows to the respective narrow if the narrow link is valid or updates
the footer with an appropriate validation error message.
"""
parsed_link = self._parse_narrow_link(self.link)
error = self._validate_narrow_link(parsed_link)
if error:
self.controller.report_error([f" {error}"])
else:
self._switch_narrow_to(parsed_link)
# Exit pop-up if MessageLinkButton exists in one.
if self.controller.is_any_popup_open():
self.controller.exit_popup()
class EditModeButton(urwid.Button):
def __init__(self, *, controller: Any, width: int) -> None:
self.controller = controller
self.width = width
super().__init__(label="", on_press=controller.show_topic_edit_mode)
self.set_selected_mode("change_later") # set default mode
def set_selected_mode(self, mode: EditPropagateMode) -> None:
self.mode = mode
self._w = urwid.AttrMap(
urwid.SelectableIcon(EDIT_MODE_CAPTIONS[self.mode], self.width),
None,
"selected",
) | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/ui_tools/buttons.py | buttons.py |
import re
import typing
import unicodedata
from collections import Counter, OrderedDict, defaultdict
from datetime import date, datetime, timedelta
from time import sleep, time
from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Union
from urllib.parse import urljoin, urlparse
import dateutil.parser
import urwid
from bs4 import BeautifulSoup
from bs4.element import NavigableString, Tag
from typing_extensions import Literal
from tzlocal import get_localzone
from urwid_readline import ReadlineEdit
from zulipterminal.api_types import Composition, PrivateComposition, StreamComposition
from zulipterminal.config.keys import (
is_command_key,
keys_for_command,
primary_key_for_command,
)
from zulipterminal.config.regexes import (
REGEX_CLEANED_RECIPIENT,
REGEX_RECIPIENT_EMAIL,
REGEX_STREAM_AND_TOPIC_FENCED,
REGEX_STREAM_AND_TOPIC_FENCED_HALF,
REGEX_STREAM_AND_TOPIC_UNFENCED,
)
from zulipterminal.config.symbols import (
INVALID_MARKER,
MESSAGE_CONTENT_MARKER,
MESSAGE_HEADER_DIVIDER,
QUOTED_TEXT_MARKER,
STREAM_TOPIC_SEPARATOR,
TIME_MENTION_MARKER,
)
from zulipterminal.config.ui_mappings import STATE_ICON, STREAM_ACCESS_TYPE
from zulipterminal.helper import (
Message,
asynch,
format_string,
get_unused_fence,
match_emoji,
match_group,
match_stream,
match_topics,
match_user,
match_user_name_and_email,
)
from zulipterminal.server_url import near_message_url
from zulipterminal.ui_tools.buttons import EditModeButton
from zulipterminal.ui_tools.tables import render_table
from zulipterminal.urwid_types import urwid_Size
if typing.TYPE_CHECKING:
from zulipterminal.model import Model
class _MessageEditState(NamedTuple):
message_id: int
old_topic: str
DELIMS_MESSAGE_COMPOSE = "\t\n;"
class WriteBox(urwid.Pile):
def __init__(self, view: Any) -> None:
super().__init__(self.main_view(True))
self.model = view.model
self.view = view
# Used to indicate user's compose status, "closed" by default
self.compose_box_status: Literal[
"open_with_private", "open_with_stream", "closed"
]
# If editing a message, its state - otherwise None
self.msg_edit_state: Optional[_MessageEditState]
# Determines if the message body (content) can be edited
self.msg_body_edit_enabled: bool
self.is_in_typeahead_mode = False
# Set to int for stream box only
self.stream_id: Optional[int]
# Used in PM and stream boxes
# (empty list implies PM box empty, or not initialized)
# Prioritizes autocomplete in message body
self.recipient_user_ids: List[int]
# Updates server on PM typing events
# Is separate from recipient_user_ids because we
# don't include the user's own id in this list
self.typing_recipient_user_ids: List[int]
# Private message recipient text entry, None if stream-box
# or not initialized
self.to_write_box: Optional[ReadlineEdit]
# For tracking sending typing status updates
self.send_next_typing_update: datetime
self.last_key_update: datetime
self.idle_status_tracking: bool
self.sent_start_typing_status: bool
self._set_compose_attributes_to_defaults()
# Constant indices into self.contents
# (CONTAINER=vertical, HEADER/MESSAGE=horizontal)
self.FOCUS_CONTAINER_HEADER = 0
self.FOCUS_HEADER_BOX_RECIPIENT = 0
self.FOCUS_HEADER_BOX_STREAM = 1
self.FOCUS_HEADER_BOX_TOPIC = 3
self.FOCUS_HEADER_BOX_EDIT = 4
self.FOCUS_CONTAINER_MESSAGE = 1
self.FOCUS_MESSAGE_BOX_BODY = 0
# These are included to allow improved clarity
# FIXME: These elements don't acquire focus; replace prefix & in above?
self.FOCUS_HEADER_PREFIX_STREAM = 0
self.FOCUS_HEADER_PREFIX_TOPIC = 2
def _set_compose_attributes_to_defaults(self) -> None:
self.compose_box_status = "closed"
self.msg_edit_state = None
self.msg_body_edit_enabled = True
self.stream_id = None
self.to_write_box = None
# Maintain synchrony between *_user_ids by setting them
# to empty lists together using the helper method.
self._set_regular_and_typing_recipient_user_ids(None)
self.send_next_typing_update = datetime.now()
self.last_key_update = datetime.now()
self.idle_status_tracking = False
self.sent_start_typing_status = False
if hasattr(self, "msg_write_box"):
self.msg_write_box.edit_text = ""
def main_view(self, new: bool) -> Any:
if new:
return []
else:
self.contents.clear()
def set_editor_mode(self) -> None:
self.view.controller.enter_editor_mode_with(self)
def _set_regular_and_typing_recipient_user_ids(
self, user_id_list: Optional[List[int]]
) -> None:
if user_id_list:
self.recipient_user_ids = user_id_list
self.typing_recipient_user_ids = [
user_id
for user_id in self.recipient_user_ids
if user_id != self.model.user_id
]
else:
self.recipient_user_ids = list()
self.typing_recipient_user_ids = list()
def send_stop_typing_status(self) -> None:
# Send 'stop' updates only for PM narrows, when there are recipients
# to send to and a prior 'start' status has already been sent.
if (
self.compose_box_status == "open_with_private"
and self.typing_recipient_user_ids
and self.sent_start_typing_status
):
self.model.send_typing_status_by_user_ids(
self.typing_recipient_user_ids, status="stop"
)
self.send_next_typing_update = datetime.now()
self.idle_status_tracking = False
self.sent_start_typing_status = False
def private_box_view(
self,
*,
recipient_user_ids: Optional[List[int]] = None,
) -> None:
self.set_editor_mode()
self.compose_box_status = "open_with_private"
if recipient_user_ids:
self._set_regular_and_typing_recipient_user_ids(recipient_user_ids)
self.recipient_emails = [
self.model.user_id_email_dict[user_id]
for user_id in self.recipient_user_ids
]
recipient_info = ", ".join(
[
f"{self.model.user_dict[email]['full_name']} <{email}>"
for email in self.recipient_emails
]
)
else:
self._set_regular_and_typing_recipient_user_ids(None)
self.recipient_emails = []
recipient_info = ""
self.send_next_typing_update = datetime.now()
self.to_write_box = ReadlineEdit("To: ", edit_text=recipient_info)
self.to_write_box.enable_autocomplete(
func=self._to_box_autocomplete,
key=primary_key_for_command("AUTOCOMPLETE"),
key_reverse=primary_key_for_command("AUTOCOMPLETE_REVERSE"),
)
self.to_write_box.set_completer_delims("")
self.msg_write_box = ReadlineEdit(
multiline=True, max_char=self.model.max_message_length
)
self.msg_write_box.enable_autocomplete(
func=self.generic_autocomplete,
key=primary_key_for_command("AUTOCOMPLETE"),
key_reverse=primary_key_for_command("AUTOCOMPLETE_REVERSE"),
)
self.msg_write_box.set_completer_delims(DELIMS_MESSAGE_COMPOSE)
self.header_write_box = urwid.Columns([self.to_write_box])
header_line_box = urwid.LineBox(
self.header_write_box,
tlcorner="━",
tline="━",
trcorner="━",
lline="",
blcorner="─",
bline="─",
brcorner="─",
rline="",
)
self.contents = [
(header_line_box, self.options()),
(self.msg_write_box, self.options()),
]
self.focus_position = self.FOCUS_CONTAINER_MESSAGE
# Typing status is sent in regular intervals to limit the number of
# notifications sent. Idleness should also prompt a notification.
# Refer to https://zulip.com/api/set-typing-status for the protocol
# on typing notifications sent by clients.
TYPING_STARTED_WAIT_PERIOD = 10
TYPING_STOPPED_WAIT_PERIOD = 5
start_period_delta = timedelta(seconds=TYPING_STARTED_WAIT_PERIOD)
stop_period_delta = timedelta(seconds=TYPING_STOPPED_WAIT_PERIOD)
def on_type_send_status(edit: object, new_edit_text: str) -> None:
if new_edit_text and self.typing_recipient_user_ids:
self.last_key_update = datetime.now()
if self.last_key_update > self.send_next_typing_update:
self.model.send_typing_status_by_user_ids(
self.typing_recipient_user_ids, status="start"
)
self.send_next_typing_update += start_period_delta
self.sent_start_typing_status = True
# Initiate tracker function only if it isn't already
# initiated.
if not self.idle_status_tracking:
self.idle_status_tracking = True
track_idleness_and_update_status()
@asynch
def track_idleness_and_update_status() -> None:
while datetime.now() < self.last_key_update + stop_period_delta:
idle_check_time = (
self.last_key_update + stop_period_delta - datetime.now()
)
sleep(idle_check_time.total_seconds())
self.send_stop_typing_status()
urwid.connect_signal(self.msg_write_box, "change", on_type_send_status)
def update_recipients(self, write_box: ReadlineEdit) -> None:
self.recipient_emails = re.findall(REGEX_RECIPIENT_EMAIL, write_box.edit_text)
self._set_regular_and_typing_recipient_user_ids(
[self.model.user_dict[email]["user_id"] for email in self.recipient_emails]
)
def _tidy_valid_recipients_and_notify_invalid_ones(
self, write_box: ReadlineEdit
) -> bool:
tidied_recipients = list()
invalid_recipients = list()
recipients = [
recipient.strip()
for recipient in write_box.edit_text.split(",")
if recipient.strip() # This condition avoids whitespace recipients (", ,")
]
for recipient in recipients:
cleaned_recipient_list = re.findall(REGEX_CLEANED_RECIPIENT, recipient)
recipient_name, recipient_email, invalid_text = cleaned_recipient_list[0]
# Discard invalid_text as part of tidying up the recipient.
if recipient_email and self.model.is_valid_private_recipient(
recipient_email, recipient_name
):
tidied_recipients.append(f"{recipient_name} <{recipient_email}>")
else:
invalid_recipients.append(recipient)
tidied_recipients.append(recipient)
write_box.edit_text = ", ".join(tidied_recipients)
write_box.edit_pos = len(write_box.edit_text)
if invalid_recipients:
invalid_recipients_error = [
"Invalid recipient(s) - " + ", ".join(invalid_recipients),
" - Use ",
("footer_contrast", primary_key_for_command("AUTOCOMPLETE")),
" or ",
(
"footer_contrast",
primary_key_for_command("AUTOCOMPLETE_REVERSE"),
),
" to autocomplete.",
]
self.view.controller.report_error(invalid_recipients_error)
return False
return True
def _setup_common_stream_compose(
self, stream_id: int, caption: str, title: str
) -> None:
self.set_editor_mode()
self.compose_box_status = "open_with_stream"
self.stream_id = stream_id
self.recipient_user_ids = self.model.get_other_subscribers_in_stream(
stream_id=stream_id
)
self.msg_write_box = ReadlineEdit(
multiline=True, max_char=self.model.max_message_length
)
self.msg_write_box.enable_autocomplete(
func=self.generic_autocomplete,
key=primary_key_for_command("AUTOCOMPLETE"),
key_reverse=primary_key_for_command("AUTOCOMPLETE_REVERSE"),
)
self.msg_write_box.set_completer_delims(DELIMS_MESSAGE_COMPOSE)
self.title_write_box = ReadlineEdit(
edit_text=title, max_char=self.model.max_topic_length
)
self.title_write_box.enable_autocomplete(
func=self._topic_box_autocomplete,
key=primary_key_for_command("AUTOCOMPLETE"),
key_reverse=primary_key_for_command("AUTOCOMPLETE_REVERSE"),
)
self.title_write_box.set_completer_delims("")
# NOTE: stream marker should be set during initialization
self.header_write_box = urwid.Columns(
[
("pack", urwid.Text(("default", "?"))),
self.stream_write_box,
("pack", urwid.Text(STREAM_TOPIC_SEPARATOR)),
self.title_write_box,
],
dividechars=1,
)
header_line_box = urwid.LineBox(
self.header_write_box,
tlcorner="━",
tline="━",
trcorner="━",
lline="",
blcorner="─",
bline="─",
brcorner="─",
rline="",
)
write_box = [
(header_line_box, self.options()),
(self.msg_write_box, self.options()),
]
self.contents = write_box
def stream_box_view(
self, stream_id: int, caption: str = "", title: str = ""
) -> None:
self.stream_write_box = ReadlineEdit(
edit_text=caption, max_char=self.model.max_stream_name_length
)
self.stream_write_box.enable_autocomplete(
func=self._stream_box_autocomplete,
key=primary_key_for_command("AUTOCOMPLETE"),
key_reverse=primary_key_for_command("AUTOCOMPLETE_REVERSE"),
)
self.stream_write_box.set_completer_delims("")
self._setup_common_stream_compose(stream_id, caption, title)
# Use and set a callback to set the stream marker
self._set_stream_write_box_style(None, caption)
urwid.connect_signal(
self.stream_write_box, "change", self._set_stream_write_box_style
)
def stream_box_edit_view(
self, stream_id: int, caption: str = "", title: str = ""
) -> None:
self.stream_write_box = urwid.Text(caption)
self._setup_common_stream_compose(stream_id, caption, title)
self.edit_mode_button = EditModeButton(
controller=self.model.controller,
width=20,
)
self.header_write_box.widget_list.append(self.edit_mode_button)
# Use callback to set stream marker - it shouldn't change, so don't need signal
self._set_stream_write_box_style(None, caption)
def _set_stream_write_box_style(self, widget: ReadlineEdit, new_text: str) -> None:
# FIXME: Refactor when we have ~ Model.is_private_stream
stream_marker = INVALID_MARKER
color = "general_bar"
if self.model.is_valid_stream(new_text):
stream_id = self.model.stream_id_from_name(new_text)
stream_access_type = self.model.stream_access_type(stream_id)
stream_marker = STREAM_ACCESS_TYPE[stream_access_type]["icon"]
stream = self.model.stream_dict[stream_id]
color = stream["color"]
self.header_write_box[self.FOCUS_HEADER_PREFIX_STREAM].set_text(
(color, stream_marker)
)
def _to_box_autocomplete(self, text: str, state: Optional[int]) -> Optional[str]:
users_list = self.view.users
recipients = text.rsplit(",", 1)
# Use the most recent recipient for autocomplete.
previous_recipients = f"{recipients[0]}, " if len(recipients) > 1 else ""
latest_text = recipients[-1].strip()
matching_users = [
user for user in users_list if match_user_name_and_email(user, latest_text)
]
# Append the potential autocompleted recipients to the string
# containing the previous recipients.
updated_recipients = [
f"{previous_recipients}{user['full_name']} <{user['email']}>"
for user in matching_users
]
user_names = [user["full_name"] for user in matching_users]
return self._process_typeaheads(updated_recipients, state, user_names)
def _topic_box_autocomplete(self, text: str, state: Optional[int]) -> Optional[str]:
topic_names = self.model.topics_in_stream(self.stream_id)
topic_typeaheads = match_topics(topic_names, text)
# Typeaheads and suggestions are the same.
return self._process_typeaheads(topic_typeaheads, state, topic_typeaheads)
def _stream_box_autocomplete(
self, text: str, state: Optional[int]
) -> Optional[str]:
streams_list = self.view.pinned_streams + self.view.unpinned_streams
streams = [stream["name"] for stream in streams_list]
# match_streams takes stream names and typeaheads,
# but we don't have typeaheads here.
# FIXME: Refactor match_stream
stream_data = list(zip(streams, streams))
matched_streams = match_stream(stream_data, text, self.view.pinned_streams)
# matched_streams[0] and matched_streams[1] contains the same data.
return self._process_typeaheads(matched_streams[0], state, matched_streams[1])
def generic_autocomplete(self, text: str, state: Optional[int]) -> Optional[str]:
autocomplete_map = OrderedDict(
[
("@_", self.autocomplete_users),
("@_**", self.autocomplete_users),
("@", self.autocomplete_mentions),
("@*", self.autocomplete_groups),
("@**", self.autocomplete_users),
("#", self.autocomplete_streams),
("#**", self.autocomplete_streams),
(":", self.autocomplete_emojis),
]
)
# Look in a reverse order to find the last autocomplete prefix used in
# the text. For instance, if text='@#example', use '#' as the prefix.
# FIXME: Mentions can actually start with '#', and streams with
# anything; this implementation simply chooses the right-most
# match of the longest length
prefix_indices = {prefix: text.rfind(prefix) for prefix in autocomplete_map}
text = self.validate_and_patch_autocomplete_stream_and_topic(
text, autocomplete_map, prefix_indices
)
found_prefix_indices = {
prefix: index for prefix, index in prefix_indices.items() if index > -1
}
# Return text if it doesn't have any of the autocomplete prefixes.
if not found_prefix_indices:
return text
# Use latest longest matching prefix (so @_ wins vs @)
prefix_index = max(found_prefix_indices.values())
prefix = max(
(len(prefix), prefix)
for prefix, index in found_prefix_indices.items()
if index == prefix_index
)[1]
autocomplete_func = autocomplete_map[prefix]
# NOTE: The following block only executes if any of the autocomplete
# prefixes exist.
typeaheads, suggestions = autocomplete_func(text[prefix_index:], prefix)
typeahead = self._process_typeaheads(typeaheads, state, suggestions)
if typeahead:
typeahead = text[:prefix_index] + typeahead
return typeahead
def _process_typeaheads(
self, typeaheads: List[str], state: Optional[int], suggestions: List[str]
) -> Optional[str]:
num_suggestions = 10
fewer_typeaheads = typeaheads[:num_suggestions]
reduced_suggestions = suggestions[:num_suggestions]
is_truncated = len(fewer_typeaheads) != len(typeaheads)
if (
state is not None
and state < len(fewer_typeaheads)
and state >= -len(fewer_typeaheads)
):
typeahead: Optional[str] = fewer_typeaheads[state]
else:
typeahead = None
state = None
self.is_in_typeahead_mode = True
self.view.set_typeahead_footer(reduced_suggestions, state, is_truncated)
return typeahead
def autocomplete_mentions(
self, text: str, prefix_string: str
) -> Tuple[List[str], List[str]]:
# Handles user mentions (@ mentions and silent mentions)
# and group mentions.
user_typeahead, user_names = self.autocomplete_users(text, prefix_string)
group_typeahead, groups = self.autocomplete_groups(text, prefix_string)
combined_typeahead = user_typeahead + group_typeahead
combined_names = user_names + groups
return combined_typeahead, combined_names
def autocomplete_users(
self, text: str, prefix_string: str
) -> Tuple[List[str], List[str]]:
users_list = self.view.users
matching_users = [
user for user in users_list if match_user(user, text[len(prefix_string) :])
]
matching_ids = set([user["user_id"] for user in matching_users])
matching_recipient_ids = set(self.recipient_user_ids) & set(matching_ids)
# Display subscribed users/recipients first.
sorted_matching_users = sorted(
matching_users,
key=lambda user: user["user_id"] in matching_recipient_ids,
reverse=True,
)
user_names = [user["full_name"] for user in sorted_matching_users]
# Counter holds a count of each name in the list of users' names in a
# dict-like manner, which is a more efficient approach when compared to
# slicing the original list on each name.
# FIXME: Use a persistent counter rather than generate one on each autocomplete.
user_names_counter = Counter(user_names)
# Append user_id's to users with the same names.
user_names_with_distinct_duplicates = [
f"{user['full_name']}|{user['user_id']}"
if user_names_counter[user["full_name"]] > 1
else user["full_name"]
for user in sorted_matching_users
]
extra_prefix = "{}{}".format(
"*" if prefix_string[-1] != "*" else "",
"*" if prefix_string[-2:] != "**" else "",
)
user_typeahead = format_string(
user_names_with_distinct_duplicates, prefix_string + extra_prefix + "{}**"
)
return user_typeahead, user_names
def autocomplete_groups(
self, text: str, prefix_string: str
) -> Tuple[List[str], List[str]]:
prefix_length = len(prefix_string)
groups = [
group_name
for group_name in self.model.user_group_names
if match_group(group_name, text[prefix_length:])
]
extra_prefix = "*" if prefix_string[-1] != "*" else ""
group_typeahead = format_string(groups, prefix_string + extra_prefix + "{}*")
return group_typeahead, groups
def autocomplete_streams(
self, text: str, prefix_string: str
) -> Tuple[List[str], List[str]]:
streams_list = self.view.pinned_streams + self.view.unpinned_streams
streams = [stream["name"] for stream in streams_list]
stream_typeahead = format_string(streams, "#**{}**")
stream_data = list(zip(stream_typeahead, streams))
prefix_length = len(prefix_string)
matched_data = match_stream(
stream_data, text[prefix_length:], self.view.pinned_streams
)
return matched_data
def autocomplete_stream_and_topic(
self, text: str, prefix_string: str
) -> Tuple[List[str], List[str]]:
match = re.search(REGEX_STREAM_AND_TOPIC_FENCED_HALF, text)
stream = match.group(1) if match else ""
if self.model.is_valid_stream(stream):
stream_id = self.model.stream_id_from_name(stream)
topic_names = self.model.topics_in_stream(stream_id)
else:
topic_names = []
topic_suggestions = match_topics(topic_names, text[len(prefix_string) :])
topic_typeaheads = format_string(topic_suggestions, prefix_string + "{}**")
return topic_typeaheads, topic_suggestions
def validate_and_patch_autocomplete_stream_and_topic(
self,
text: str,
autocomplete_map: "OrderedDict[str, Callable[..., Any]]",
prefix_indices: Dict[str, int],
) -> str:
"""
Checks if a prefix string is possible candidate for stream+topic autocomplete.
If the prefix matches, we update the autocomplete_map and prefix_indices,
and return the (updated) text.
"""
match = re.search(REGEX_STREAM_AND_TOPIC_FENCED_HALF, text)
match_fenced = re.search(REGEX_STREAM_AND_TOPIC_FENCED, text)
match_unfenced = re.search(REGEX_STREAM_AND_TOPIC_UNFENCED, text)
if match:
prefix = f"#**{match.group(1)}>"
prefix_indices[prefix] = match.start()
elif match_fenced:
# Amending the prefix to remove stream fence `**`
prefix = f"#**{match_fenced.group(1)}>"
prefix_with_topic = prefix + match_fenced.group(2)
prefix_indices[prefix] = match_fenced.start()
# Amending the text to have new prefix (without `**` fence)
text = text[: match_fenced.start()] + prefix_with_topic
elif match_unfenced:
prefix = f"#**{match_unfenced.group(1)}>"
prefix_with_topic = prefix + match_unfenced.group(2)
prefix_indices[prefix] = match_unfenced.start()
# Amending the text to have new prefix (with `**` fence)
text = text[: match_unfenced.start()] + prefix_with_topic
if match or match_fenced or match_unfenced:
autocomplete_map.update({prefix: self.autocomplete_stream_and_topic})
return text
def autocomplete_emojis(
self, text: str, prefix_string: str
) -> Tuple[List[str], List[str]]:
emoji_list = self.model.all_emoji_names
emojis = [emoji for emoji in emoji_list if match_emoji(emoji, text[1:])]
emoji_typeahead = format_string(emojis, ":{}:")
return emoji_typeahead, emojis
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if self.is_in_typeahead_mode:
if not (
is_command_key("AUTOCOMPLETE", key)
or is_command_key("AUTOCOMPLETE_REVERSE", key)
):
# set default footer when done with autocomplete
self.is_in_typeahead_mode = False
self.view.set_footer_text()
if is_command_key("SEND_MESSAGE", key):
self.send_stop_typing_status()
if self.compose_box_status == "open_with_stream":
if re.fullmatch(r"\s*", self.title_write_box.edit_text):
topic = "(no topic)"
else:
topic = self.title_write_box.edit_text
if self.msg_edit_state is not None:
trimmed_topic = topic.strip()
# Trimmed topic must be compared since that is server check
if trimmed_topic == self.msg_edit_state.old_topic:
propagate_mode = "change_one" # No change in topic
else:
propagate_mode = self.edit_mode_button.mode
args = dict(
message_id=self.msg_edit_state.message_id,
topic=topic, # NOTE: Send untrimmed topic always for now
propagate_mode=propagate_mode,
)
if self.msg_body_edit_enabled:
args["content"] = self.msg_write_box.edit_text
success = self.model.update_stream_message(**args)
else:
success = self.model.send_stream_message(
stream=self.stream_write_box.edit_text,
topic=topic,
content=self.msg_write_box.edit_text,
)
else:
if self.msg_edit_state is not None:
success = self.model.update_private_message(
content=self.msg_write_box.edit_text,
msg_id=self.msg_edit_state.message_id,
)
else:
all_valid = self._tidy_valid_recipients_and_notify_invalid_ones(
self.to_write_box
)
if not all_valid:
return key
self.update_recipients(self.to_write_box)
if self.recipient_user_ids:
success = self.model.send_private_message(
recipients=self.recipient_user_ids,
content=self.msg_write_box.edit_text,
)
else:
self.view.controller.report_error(
["Cannot send message without specifying recipients."]
)
success = None
if success:
self.msg_write_box.edit_text = ""
if self.msg_edit_state is not None:
self.keypress(size, primary_key_for_command("GO_BACK"))
assert self.msg_edit_state is None
elif is_command_key("NARROW_MESSAGE_RECIPIENT", key):
if self.compose_box_status == "open_with_stream":
self.model.controller.narrow_to_topic(
stream_name=self.stream_write_box.edit_text,
topic_name=self.title_write_box.edit_text,
contextual_message_id=None,
)
elif self.compose_box_status == "open_with_private":
self.recipient_emails = [
self.model.user_id_email_dict[user_id]
for user_id in self.recipient_user_ids
]
if self.recipient_user_ids:
self.model.controller.narrow_to_user(
recipient_emails=self.recipient_emails,
contextual_message_id=None,
)
else:
self.view.controller.report_error(
"Cannot narrow to message without specifying recipients."
)
elif is_command_key("GO_BACK", key):
self.send_stop_typing_status()
self._set_compose_attributes_to_defaults()
self.view.controller.exit_editor_mode()
self.main_view(False)
self.view.middle_column.set_focus("body")
elif is_command_key("MARKDOWN_HELP", key):
self.view.controller.show_markdown_help()
return key
elif is_command_key("SAVE_AS_DRAFT", key):
if self.msg_edit_state is None:
if self.compose_box_status == "open_with_private":
all_valid = self._tidy_valid_recipients_and_notify_invalid_ones(
self.to_write_box
)
if not all_valid:
return key
self.update_recipients(self.to_write_box)
this_draft: Composition = PrivateComposition(
type="private",
to=self.recipient_user_ids,
content=self.msg_write_box.edit_text,
)
elif self.compose_box_status == "open_with_stream":
this_draft = StreamComposition(
type="stream",
to=self.stream_write_box.edit_text,
content=self.msg_write_box.edit_text,
subject=self.title_write_box.edit_text,
)
saved_draft = self.model.session_draft_message()
if not saved_draft:
self.model.save_draft(this_draft)
elif this_draft != saved_draft:
self.view.controller.save_draft_confirmation_popup(
this_draft,
)
elif is_command_key("CYCLE_COMPOSE_FOCUS", key):
if len(self.contents) == 0:
return key
header = self.header_write_box
# toggle focus position
if self.focus_position == self.FOCUS_CONTAINER_HEADER:
if self.compose_box_status == "open_with_stream":
if header.focus_col == self.FOCUS_HEADER_BOX_STREAM:
if self.msg_edit_state is None:
stream_name = header[self.FOCUS_HEADER_BOX_STREAM].edit_text
else:
stream_name = header[self.FOCUS_HEADER_BOX_STREAM].text
if not self.model.is_valid_stream(stream_name):
invalid_stream_error = (
"Invalid stream name."
" Use {} or {} to autocomplete.".format(
primary_key_for_command("AUTOCOMPLETE"),
primary_key_for_command("AUTOCOMPLETE_REVERSE"),
)
)
self.view.controller.report_error([invalid_stream_error])
return key
user_ids = self.model.get_other_subscribers_in_stream(
stream_name=stream_name
)
self.recipient_user_ids = user_ids
self.stream_id = self.model.stream_id_from_name(stream_name)
header.focus_col = self.FOCUS_HEADER_BOX_TOPIC
return key
elif (
header.focus_col == self.FOCUS_HEADER_BOX_TOPIC
and self.msg_edit_state is not None
):
header.focus_col = self.FOCUS_HEADER_BOX_EDIT
return key
elif header.focus_col == self.FOCUS_HEADER_BOX_EDIT:
if self.msg_body_edit_enabled:
header.focus_col = self.FOCUS_HEADER_BOX_STREAM
self.focus_position = self.FOCUS_CONTAINER_MESSAGE
else:
header.focus_col = self.FOCUS_HEADER_BOX_TOPIC
return key
else:
header.focus_col = self.FOCUS_HEADER_BOX_STREAM
else:
all_valid = self._tidy_valid_recipients_and_notify_invalid_ones(
self.to_write_box
)
if not all_valid:
return key
# We extract recipients' user_ids and emails only once we know
# that all the recipients are valid, to avoid including any
# invalid ones.
self.update_recipients(self.to_write_box)
if not self.msg_body_edit_enabled:
return key
if self.focus_position == self.FOCUS_CONTAINER_HEADER:
self.focus_position = self.FOCUS_CONTAINER_MESSAGE
else:
self.focus_position = self.FOCUS_CONTAINER_HEADER
if self.compose_box_status == "open_with_stream":
if self.msg_edit_state is not None:
header.focus_col = self.FOCUS_HEADER_BOX_TOPIC
else:
header.focus_col = self.FOCUS_HEADER_BOX_STREAM
else:
header.focus_col = self.FOCUS_HEADER_BOX_RECIPIENT
key = super().keypress(size, key)
return key
class MessageBox(urwid.Pile):
# type of last_message is Optional[Message], but needs refactoring
def __init__(self, message: Message, model: "Model", last_message: Any) -> None:
self.model = model
self.message = message
self.header: List[Any] = []
self.content: urwid.Text = urwid.Text("")
self.footer: List[Any] = []
self.stream_name = ""
self.stream_id: Optional[int] = None
self.topic_name = ""
self.email = "" # FIXME: Can we remove this?
self.user_id: Optional[int] = None
self.message_links: "OrderedDict[str, Tuple[str, int, bool]]" = OrderedDict()
self.topic_links: "OrderedDict[str, Tuple[str, int, bool]]" = OrderedDict()
self.time_mentions: List[Tuple[str, str]] = list()
self.last_message = last_message
# if this is the first message
if self.last_message is None:
self.last_message = defaultdict(dict)
if self.message["type"] == "stream":
# Set `topic_links` if present
for link in self.message.get("topic_links", []):
# Modernized response
self.topic_links[link["url"]] = (
link["text"],
len(self.topic_links) + 1,
True,
)
self.stream_name = self.message["display_recipient"]
self.stream_id = self.message["stream_id"]
self.topic_name = self.message["subject"]
elif self.message["type"] == "private":
self.email = self.message["sender_email"]
self.user_id = self.message["sender_id"]
else:
raise RuntimeError("Invalid message type")
if self.message["type"] == "private":
if self._is_private_message_to_self():
recipient = self.message["display_recipient"][0]
self.recipients_names = recipient["full_name"]
self.recipient_emails = [self.model.user_email]
self.recipient_ids = [self.model.user_id]
else:
self.recipients_names = ", ".join(
list(
recipient["full_name"]
for recipient in self.message["display_recipient"]
if recipient["email"] != self.model.user_email
)
)
self.recipient_emails = [
recipient["email"]
for recipient in self.message["display_recipient"]
if recipient["email"] != self.model.user_email
]
self.recipient_ids = [
recipient["id"]
for recipient in self.message["display_recipient"]
if recipient["id"] != self.model.user_id
]
super().__init__(self.main_view())
def need_recipient_header(self) -> bool:
# Prevent redundant information in recipient bar
if len(self.model.narrow) == 1 and self.model.narrow[0][0] == "pm_with":
return False
if len(self.model.narrow) == 2 and self.model.narrow[1][0] == "topic":
return False
last_msg = self.last_message
if self.message["type"] == "stream":
return not (
last_msg["type"] == "stream"
and self.topic_name == last_msg["subject"]
and self.stream_name == last_msg["display_recipient"]
)
elif self.message["type"] == "private":
recipient_ids = [
{
recipient["id"]
for recipient in message["display_recipient"]
if "id" in recipient
}
for message in (self.message, last_msg)
if "display_recipient" in message
]
return not (
len(recipient_ids) == 2
and recipient_ids[0] == recipient_ids[1]
and last_msg["type"] == "private"
)
else:
raise RuntimeError("Invalid message type")
def _is_private_message_to_self(self) -> bool:
recipient_list = self.message["display_recipient"]
return (
len(recipient_list) == 1
and recipient_list[0]["email"] == self.model.user_email
)
def stream_header(self) -> Any:
assert self.stream_id is not None
color = self.model.stream_dict[self.stream_id]["color"]
bar_color = f"s{color}"
stream_title_markup = (
"bar",
[
(bar_color, f"{self.stream_name} {STREAM_TOPIC_SEPARATOR} "),
("title", f" {self.topic_name}"),
],
)
stream_title = urwid.Text(stream_title_markup)
header = urwid.Columns(
[
("pack", stream_title),
(1, urwid.Text((color, " "))),
urwid.AttrWrap(urwid.Divider(MESSAGE_HEADER_DIVIDER), color),
]
)
header.markup = stream_title_markup
return header
def private_header(self) -> Any:
title_markup = (
"header",
[("general_narrow", "You and "), ("general_narrow", self.recipients_names)],
)
title = urwid.Text(title_markup)
header = urwid.Columns(
[
("pack", title),
(1, urwid.Text(("general_bar", " "))),
urwid.AttrWrap(urwid.Divider(MESSAGE_HEADER_DIVIDER), "general_bar"),
]
)
header.markup = title_markup
return header
def top_header_bar(self, message_view: Any) -> Any:
if self.message["type"] == "stream":
return message_view.stream_header()
else:
return message_view.private_header()
def top_search_bar(self) -> Any:
curr_narrow = self.model.narrow
is_search_narrow = self.model.is_search_narrow()
if is_search_narrow:
curr_narrow = [
sub_narrow for sub_narrow in curr_narrow if sub_narrow[0] != "search"
]
else:
self.model.controller.view.search_box.text_box.set_edit_text("")
if curr_narrow == []:
text_to_fill = "All messages"
elif len(curr_narrow) == 1 and curr_narrow[0][1] == "private":
text_to_fill = "All private messages"
elif len(curr_narrow) == 1 and curr_narrow[0][1] == "starred":
text_to_fill = "Starred messages"
elif len(curr_narrow) == 1 and curr_narrow[0][1] == "mentioned":
text_to_fill = "Mentions"
elif self.message["type"] == "stream":
assert self.stream_id is not None
bar_color = self.model.stream_dict[self.stream_id]["color"]
bar_color = f"s{bar_color}"
if len(curr_narrow) == 2 and curr_narrow[1][0] == "topic":
text_to_fill = (
"bar", # type: ignore
[
(bar_color, self.stream_name),
(bar_color, ": topic narrow"),
],
)
else:
text_to_fill = ("bar", [(bar_color, self.stream_name)]) # type: ignore
elif len(curr_narrow) == 1 and len(curr_narrow[0][1].split(",")) > 1:
text_to_fill = "Group private conversation"
else:
text_to_fill = "Private conversation"
if is_search_narrow:
title_markup = (
"header",
[
("general_narrow", text_to_fill),
(None, " "),
("filter_results", "Search Results"),
],
)
else:
title_markup = ("header", [("general_narrow", text_to_fill)])
title = urwid.Text(title_markup)
header = urwid.AttrWrap(title, "bar")
header.text_to_fill = text_to_fill
header.markup = title_markup
return header
def reactions_view(self, reactions: List[Dict[str, Any]]) -> Any:
if not reactions:
return ""
try:
MAXIMUM_USERNAMES_VISIBLE = 3
my_user_id = self.model.user_id
reaction_stats = defaultdict(list)
for reaction in reactions:
user_id = int(reaction["user"].get("id", -1))
if user_id == -1:
user_id = int(reaction["user"]["user_id"])
user_name = reaction["user"]["full_name"]
if user_id == my_user_id:
user_name = "You"
reaction_stats[reaction["emoji_name"]].append((user_id, user_name))
for reaction, ids in reaction_stats.items():
if (my_user_id, "You") in ids:
ids.remove((my_user_id, "You"))
ids.append((my_user_id, "You"))
reaction_texts = [
(
"reaction_mine"
if my_user_id in [id[0] for id in ids]
else "reaction",
f" :{reaction}: {len(ids)} "
if len(reactions) > MAXIMUM_USERNAMES_VISIBLE
else f" :{reaction}: {', '.join([id[1] for id in ids])} ",
)
for reaction, ids in reaction_stats.items()
]
spaced_reaction_texts = [
entry
for pair in zip(reaction_texts, " " * len(reaction_texts))
for entry in pair
]
return urwid.Padding(
urwid.Text(spaced_reaction_texts),
align="left",
width=("relative", 90),
left=25,
min_width=50,
)
except Exception:
return ""
# Use quotes as a workaround for OrderedDict typing issue.
# See https://github.com/python/mypy/issues/6904.
@staticmethod
def footlinks_view(
message_links: "OrderedDict[str, Tuple[str, int, bool]]",
*,
maximum_footlinks: int,
padded: bool,
wrap: str,
) -> Tuple[Any, int]:
"""
Returns a Tuple that consists footlinks view (widget) and its required
width.
"""
# Return if footlinks are disabled by the user.
if maximum_footlinks == 0:
return None, 0
footlinks = []
counter = 0
footlinks_width = 0
for link, (text, index, show_footlink) in message_links.items():
if counter == maximum_footlinks:
break
if not show_footlink:
continue
counter += 1
styled_footlink = [
("msg_link_index", f"{index}:"),
(None, " "),
("msg_link", link),
]
footlinks_width = max(
footlinks_width, sum([len(text) for style, text in styled_footlink])
)
footlinks.extend([*styled_footlink, "\n"])
if not footlinks:
return None, 0
footlinks[-1] = footlinks[-1][:-1] # Remove the last newline.
text_widget = urwid.Text(footlinks, wrap=wrap)
if padded:
return (
urwid.Padding(
text_widget,
align="left",
left=8,
width=("relative", 100),
min_width=10,
right=2,
),
footlinks_width,
)
else:
return text_widget, footlinks_width
@classmethod
def soup2markup(
cls, soup: Any, metadata: Dict[str, Any], **state: Any
) -> Tuple[
List[Any], "OrderedDict[str, Tuple[str, int, bool]]", List[Tuple[str, str]]
]:
# Ensure a string is provided, in case the soup finds none
# This could occur if eg. an image is removed or not shown
markup: List[Union[str, Tuple[Optional[str], Any]]] = [""]
if soup is None: # This is not iterable, so return promptly
return markup, metadata["message_links"], metadata["time_mentions"]
unrendered_tags = { # In pairs of 'tag_name': 'text'
# TODO: Some of these could be implemented
"br": "", # No indicator of absence
"hr": "RULER",
"img": "IMAGE",
}
unrendered_div_classes = { # In pairs of 'div_class': 'text'
# TODO: Support embedded content & twitter preview?
"message_embed": "EMBEDDED CONTENT",
"inline-preview-twitter": "TWITTER PREVIEW",
"message_inline_ref": "", # Duplicate of other content
"message_inline_image": "", # Duplicate of other content
}
unrendered_template = "[{} NOT RENDERED]"
for element in soup:
if isinstance(element, Tag):
# Caching element variables for use in the
# if/elif/else chain below for improving legibility.
tag = element.name
tag_attrs = element.attrs
tag_classes = tag_attrs.get("class", [])
tag_text = element.text
if isinstance(element, NavigableString):
# NORMAL STRINGS
if element == "\n" and metadata.get("bq_len", 0) > 0:
metadata["bq_len"] -= 1
continue
markup.append(element)
elif tag == "div" and (set(tag_classes) & set(unrendered_div_classes)):
# UNRENDERED DIV CLASSES
# NOTE: Though `matches` is generalized for multiple
# matches it is very unlikely that there would be any.
matches = set(unrendered_div_classes) & set(tag_classes)
text = unrendered_div_classes[matches.pop()]
if text:
markup.append(unrendered_template.format(text))
elif tag == "img" and tag_classes == ["emoji"]:
# CUSTOM EMOJIS AND ZULIP_EXTRA_EMOJI
emoji_name = tag_attrs.get("title", [])
markup.append(("msg_emoji", f":{emoji_name}:"))
elif tag in unrendered_tags:
# UNRENDERED SIMPLE TAGS
text = unrendered_tags[tag]
if text:
markup.append(unrendered_template.format(text))
elif tag in ("h1", "h2", "h3", "h4", "h5", "h6"):
# HEADING STYLE (h1 to h6)
markup.append(("msg_heading", tag_text))
elif tag in ("p", "del"):
# PARAGRAPH, STRIKE-THROUGH
markup.extend(cls.soup2markup(element, metadata)[0])
elif tag == "span" and "emoji" in tag_classes:
# EMOJI
markup.append(("msg_emoji", tag_text))
elif tag == "span" and ({"katex-display", "katex"} & set(tag_classes)):
# MATH TEXT
# FIXME: Add html -> urwid client-side logic for rendering KaTex text.
# Avoid displaying multiple markups, and show only the source
# as of now.
if element.find("annotation"):
tag_text = element.find("annotation").text
markup.append(("msg_math", tag_text))
elif tag == "span" and (
{"user-group-mention", "user-mention"} & set(tag_classes)
):
# USER MENTIONS & USER-GROUP MENTIONS
markup.append(("msg_mention", tag_text))
elif tag == "a":
# LINKS
# Use rstrip to avoid anomalies and edge cases like
# https://google.com vs https://google.com/.
link = tag_attrs["href"].rstrip("/")
text = element.img["src"] if element.img else tag_text
text = text.rstrip("/")
parsed_link = urlparse(link)
if not parsed_link.scheme: # => relative link
# Prepend org url to convert it to an absolute link
link = urljoin(metadata["server_url"], link)
text = text if text else link
show_footlink = True
# Only use the last segment if the text is redundant.
# NOTE: The 'without scheme' excerpt is to deal with the case
# where a user puts a link without any scheme and the server
# uses http as the default scheme but keeps the text as-is.
# For instance, see how example.com/some/path becomes
# <a href="http://example.com">example.com/some/path</a>.
link_without_scheme, text_without_scheme = [
data.split("://")[1] if "://" in data else data
for data in [link, text]
] # Split on '://' is for cases where text == link.
if link_without_scheme == text_without_scheme:
last_segment = text.split("/")[-1]
if "." in last_segment:
new_text = last_segment # Filename.
elif text.startswith(metadata["server_url"]):
# Relative URL.
new_text = text.split(metadata["server_url"])[-1]
else:
new_text = (
parsed_link.netloc
if parsed_link.netloc
else text.split("/")[0]
) # Domain name.
if new_text != text_without_scheme:
text = new_text
else:
# Do not show as a footlink as the text is sufficient
# to represent the link.
show_footlink = False
# Detect duplicate links to save screen real estate.
if link not in metadata["message_links"]:
metadata["message_links"][link] = (
text,
len(metadata["message_links"]) + 1,
show_footlink,
)
else:
# Append the text if its link already exist with a
# different text.
saved_text, saved_link_index, saved_footlink_status = metadata[
"message_links"
][link]
if saved_text != text:
metadata["message_links"][link] = (
f"{saved_text}, {text}",
saved_link_index,
show_footlink or saved_footlink_status,
)
markup.extend(
[
("msg_link", text),
" ",
("msg_link_index", f"[{metadata['message_links'][link][1]}]"),
]
)
elif tag == "blockquote":
# BLOCKQUOTE TEXT
markup.append(("msg_quote", cls.soup2markup(element, metadata)[0]))
elif tag == "code":
# CODE (INLINE?)
markup.append(("msg_code", tag_text))
elif tag == "div" and "codehilite" in tag_classes:
"""
CODE BLOCK
-------------
Structure: # Language is optional
<div class="codehilite" data-code-language="python">
<pre>
<span></span>
<code>
Code HTML
Made of <span>'s and NavigableStrings
</code>
</pre>
</div>
"""
code_soup = element.pre.code
# NOTE: Old messages don't have the additional `code` tag.
# Ref: https://github.com/Python-Markdown/markdown/pull/862
if code_soup is None:
code_soup = element.pre
for code_element in code_soup.contents:
code_text = (
code_element.text
if isinstance(code_element, Tag)
else code_element.string
)
if code_element.name == "span":
if len(code_text) == 0:
continue
css_style = code_element.attrs.get("class", ["w"])
markup.append((f"pygments:{css_style[0]}", code_text))
else:
markup.append(("pygments:w", code_text))
elif tag in ("strong", "em"):
# BOLD & ITALIC
markup.append(("msg_bold", tag_text))
elif tag in ("ul", "ol"):
# LISTS (UL & OL)
for part in element.contents:
if part == "\n":
part.replace_with("")
if "indent_level" not in state:
state["indent_level"] = 1
state["list_start"] = True
else:
state["indent_level"] += 1
state["list_start"] = False
if tag == "ol":
start_number = int(tag_attrs.get("start", 1))
state["list_index"] = start_number
markup.extend(cls.soup2markup(element, metadata, **state)[0])
del state["list_index"] # reset at end of this list
else:
if "list_index" in state:
del state["list_index"] # this is unordered
markup.extend(cls.soup2markup(element, metadata, **state)[0])
del state["indent_level"] # reset indents after any list
elif tag == "li":
# LIST ITEMS (LI)
for part in element.contents:
if part == "\n":
part.replace_with("")
if not state.get("list_start", False):
markup.append("\n")
indent = state.get("indent_level", 1)
if "list_index" in state:
markup.append(f"{' ' * indent}{state['list_index']}. ")
state["list_index"] += 1
else:
chars = [
"\N{BULLET}",
"\N{RING OPERATOR}", # small hollow
"\N{HYPHEN}",
]
markup.append(f"{' ' * indent}{chars[(indent - 1) % 3]} ")
state["list_start"] = False
markup.extend(cls.soup2markup(element, metadata, **state)[0])
elif tag == "table":
markup.extend(render_table(element))
elif tag == "time":
# New in feature level 16, server version 3.0.
# Render time in current user's local time zone.
timestamp = element.get("datetime")
# This should not happen. Regardless, we are interested in
# debugging and reporting it to zulip/zulip if it does.
assert timestamp is not None, "Could not find datetime attr"
utc_time = dateutil.parser.parse(timestamp)
local_time = utc_time.astimezone(get_localzone())
# TODO: Address 12-hour format support with application-wide
# support for different formats.
time_string = local_time.strftime("%a, %b %-d %Y, %-H:%M (%Z)")
markup.append(("msg_time", f" {TIME_MENTION_MARKER} {time_string} "))
source_text = f"Original text was {tag_text.strip()}"
metadata["time_mentions"].append((time_string, source_text))
else:
markup.extend(cls.soup2markup(element, metadata)[0])
return markup, metadata["message_links"], metadata["time_mentions"]
def main_view(self) -> List[Any]:
# Recipient Header
if self.need_recipient_header():
if self.message["type"] == "stream":
recipient_header = self.stream_header()
else:
recipient_header = self.private_header()
else:
recipient_header = None
# Content Header
message = {
key: {
"is_starred": "starred" in msg["flags"],
"author": (
msg["sender_full_name"] if "sender_full_name" in msg else None
),
"time": (
self.model.formatted_local_time(
msg["timestamp"], show_seconds=False
)
if "timestamp" in msg
else None
),
"datetime": (
datetime.fromtimestamp(msg["timestamp"])
if "timestamp" in msg
else None
),
}
for key, msg in dict(this=self.message, last=self.last_message).items()
}
different = { # How this message differs from the previous one
"recipients": recipient_header is not None,
"author": message["this"]["author"] != message["last"]["author"],
"24h": (
message["last"]["datetime"] is not None
and ((message["this"]["datetime"] - message["last"]["datetime"]).days)
),
"timestamp": (
message["last"]["time"] is not None
and message["this"]["time"] != message["last"]["time"]
),
"star_status": (
message["this"]["is_starred"] != message["last"]["is_starred"]
),
}
any_differences = any(different.values())
if any_differences: # Construct content_header, if needed
TextType = Dict[str, Tuple[Optional[str], str]]
text_keys = ("author", "star", "time", "status")
text: TextType = {key: (None, " ") for key in text_keys}
if any(different[key] for key in ("recipients", "author", "24h")):
text["author"] = ("name", message["this"]["author"])
# TODO: Refactor to use user ids for look up instead of emails.
email = self.message.get("sender_email", "")
user = self.model.user_dict.get(email, None)
# TODO: Currently status of bots are shown as `inactive`.
# Render bot users' status with bot marker as a follow-up
status = user.get("status", "inactive") if user else "inactive"
# The default text['status'] value is (None, ' ')
if status in STATE_ICON:
text["status"] = (f"user_{status}", STATE_ICON[status])
if message["this"]["is_starred"]:
text["star"] = ("starred", "*")
if any(different[key] for key in ("recipients", "author", "timestamp")):
this_year = date.today().year
msg_year = message["this"]["datetime"].year
if this_year != msg_year:
text["time"] = ("time", f"{msg_year} - {message['this']['time']}")
else:
text["time"] = ("time", message["this"]["time"])
content_header = urwid.Columns(
[
("pack", urwid.Text(text["status"])),
("weight", 10, urwid.Text(text["author"])),
(26, urwid.Text(text["time"], align="right")),
(1, urwid.Text(text["star"], align="right")),
],
dividechars=1,
)
else:
content_header = None
# If the message contains '/me' emote then replace it with
# sender's full name and show it in bold.
if self.message["is_me_message"]:
self.message["content"] = self.message["content"].replace(
"/me", f"<strong>{self.message['sender_full_name']}</strong>", 1
)
# Transform raw message content into markup (As needed by urwid.Text)
content, self.message_links, self.time_mentions = self.transform_content(
self.message["content"], self.model.server_url
)
self.content.set_text(content)
if self.message["id"] in self.model.index["edited_messages"]:
edited_label_size = 7
left_padding = 1
else:
edited_label_size = 0
left_padding = 8
wrapped_content = urwid.Padding(
urwid.Columns(
[
(edited_label_size, urwid.Text("EDITED")),
urwid.LineBox(
urwid.Columns(
[
(1, urwid.Text("")),
self.content,
]
),
tline="",
bline="",
rline="",
lline=MESSAGE_CONTENT_MARKER,
),
]
),
align="left",
left=left_padding,
width=("relative", 100),
min_width=10,
right=5,
)
# Reactions
reactions = self.reactions_view(self.message["reactions"])
# Footlinks.
footlinks, _ = self.footlinks_view(
self.message_links,
maximum_footlinks=self.model.controller.maximum_footlinks,
padded=True,
wrap="ellipsis",
)
# Build parts together and return
parts = [
(recipient_header, recipient_header is not None),
(content_header, any_differences),
(wrapped_content, True),
(footlinks, footlinks is not None),
(reactions, reactions != ""),
]
self.header = [part for part, condition in parts[:2] if condition]
self.footer = [part for part, condition in parts[3:] if condition]
return [part for part, condition in parts if condition]
def update_message_author_status(self) -> bool:
"""
Update the author status by resetting the entire message box
if author field is present.
"""
author_is_present = False
author_column = 1 # Index of author field in content header
if len(self.header) > 0:
# -1 represents that content header is the last row of header field
author_field = self.header[-1][author_column]
author_is_present = author_field.text != " "
if author_is_present:
# Re initialize the message if update is required.
# FIXME: Render specific element (here author field) instead?
super().__init__(self.main_view())
return author_is_present
@classmethod
def transform_content(
cls, content: Any, server_url: str
) -> Tuple[
Tuple[None, Any],
"OrderedDict[str, Tuple[str, int, bool]]",
List[Tuple[str, str]],
]:
soup = BeautifulSoup(content, "lxml")
body = soup.find(name="body")
metadata = dict(
server_url=server_url,
message_links=OrderedDict(),
time_mentions=list(),
) # type: Dict[str, Any]
if body and body.find(name="blockquote"):
metadata["bq_len"] = cls.indent_quoted_content(soup, QUOTED_TEXT_MARKER)
markup, message_links, time_mentions = cls.soup2markup(body, metadata)
return (None, markup), message_links, time_mentions
@staticmethod
def indent_quoted_content(soup: Any, padding_char: str) -> int:
"""
We indent quoted text by padding them.
The extent of indentation depends on their level of quoting.
For example:
[Before Padding] [After Padding]
<blockquote> <blockquote>
<blockquote> <blockquote>
<p>Foo</p> <p>▒ ▒ </p><p>Foo</p>
</blockquote> ---> </blockquote>
<p>Boo</p> <p>▒ </p><p>Boo</p>
</blockquote> </blockquote>
"""
pad_count = 1
blockquote_list = soup.find_all("blockquote")
bq_len = len(blockquote_list)
for tag in blockquote_list:
child_list = tag.findChildren(recursive=False)
child_block = tag.find_all("blockquote")
actual_padding = f"{padding_char} " * pad_count
if len(child_list) == 1:
pad_count -= 1
child_iterator = child_list
else:
if len(child_block) == 0:
child_iterator = child_list
else:
# If there is some text at the begining of a
# quote, we pad it seperately.
if child_list[0].name == "p":
new_tag = soup.new_tag("p")
new_tag.string = f"\n{actual_padding}"
child_list[0].insert_before(new_tag)
child_iterator = child_list[1:]
for child in child_iterator:
new_tag = soup.new_tag("p")
new_tag.string = actual_padding
# If the quoted message is multi-line message
# we deconstruct it and pad it at break-points (<br/>)
for br in child.findAll("br"):
next_s = br.nextSibling
text = str(next_s.string).strip()
if text:
insert_tag = soup.new_tag("p")
insert_tag.string = f"\n{padding_char} {text}"
next_s.replace_with(insert_tag)
child.insert_before(new_tag)
pad_count += 1
return bq_len
def selectable(self) -> bool:
# Returning True, indicates that this widget
# is designed to take focus.
return True
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: bool
) -> bool:
if event == "mouse press":
if button == 1:
if self.model.controller.is_in_editor_mode():
return True
self.keypress(size, primary_key_for_command("ENTER"))
return True
return super().mouse_event(size, event, button, col, row, focus)
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("REPLY_MESSAGE", key):
if self.message["type"] == "private":
self.model.controller.view.write_box.private_box_view(
recipient_user_ids=self.recipient_ids,
)
elif self.message["type"] == "stream":
self.model.controller.view.write_box.stream_box_view(
caption=self.message["display_recipient"],
title=self.message["subject"],
stream_id=self.stream_id,
)
elif is_command_key("STREAM_MESSAGE", key):
if len(self.model.narrow) != 0 and self.model.narrow[0][0] == "stream":
self.model.controller.view.write_box.stream_box_view(
caption=self.message["display_recipient"],
stream_id=self.stream_id,
)
else:
self.model.controller.view.write_box.stream_box_view(0)
elif is_command_key("STREAM_NARROW", key):
if self.message["type"] == "private":
self.model.controller.narrow_to_user(
recipient_emails=self.recipient_emails,
contextual_message_id=self.message["id"],
)
elif self.message["type"] == "stream":
self.model.controller.narrow_to_stream(
stream_name=self.stream_name,
contextual_message_id=self.message["id"],
)
elif is_command_key("TOGGLE_NARROW", key):
self.model.unset_search_narrow()
if self.message["type"] == "private":
if len(self.model.narrow) == 1 and self.model.narrow[0][0] == "pm_with":
self.model.controller.narrow_to_all_pm(
contextual_message_id=self.message["id"],
)
else:
self.model.controller.narrow_to_user(
recipient_emails=self.recipient_emails,
contextual_message_id=self.message["id"],
)
elif self.message["type"] == "stream":
if len(self.model.narrow) > 1: # in a topic
self.model.controller.narrow_to_stream(
stream_name=self.stream_name,
contextual_message_id=self.message["id"],
)
else:
self.model.controller.narrow_to_topic(
stream_name=self.stream_name,
topic_name=self.topic_name,
contextual_message_id=self.message["id"],
)
elif is_command_key("TOPIC_NARROW", key):
if self.message["type"] == "private":
self.model.controller.narrow_to_user(
recipient_emails=self.recipient_emails,
contextual_message_id=self.message["id"],
)
elif self.message["type"] == "stream":
self.model.controller.narrow_to_topic(
stream_name=self.stream_name,
topic_name=self.topic_name,
contextual_message_id=self.message["id"],
)
elif is_command_key("ALL_MESSAGES", key):
self.model.controller.narrow_to_all_messages(
contextual_message_id=self.message["id"]
)
elif is_command_key("REPLY_AUTHOR", key):
# All subscribers from recipient_ids are not needed here.
self.model.controller.view.write_box.private_box_view(
recipient_user_ids=[self.message["sender_id"]],
)
elif is_command_key("MENTION_REPLY", key):
self.keypress(size, primary_key_for_command("REPLY_MESSAGE"))
mention = f"@**{self.message['sender_full_name']}** "
self.model.controller.view.write_box.msg_write_box.set_edit_text(mention)
self.model.controller.view.write_box.msg_write_box.set_edit_pos(
len(mention)
)
self.model.controller.view.middle_column.set_focus("footer")
elif is_command_key("QUOTE_REPLY", key):
self.keypress(size, primary_key_for_command("REPLY_MESSAGE"))
# To correctly quote a message that contains quote/code-blocks,
# we need to fence quoted message containing ``` with ````,
# ```` with ````` and so on.
response = self.model.fetch_raw_message_content(self.message["id"])
message_raw_content = response if response is not None else ""
fence = get_unused_fence(message_raw_content)
absolute_url = near_message_url(self.model.server_url[:-1], self.message)
# Compose box should look something like this:
# @_**Zeeshan|514** [said](link to message):
# ```quote
# message_content
# ```
quote = "@_**{0}|{1}** [said]({2}):\n{3}quote\n{4}\n{3}\n".format(
self.message["sender_full_name"],
self.message["sender_id"],
absolute_url,
fence,
message_raw_content,
)
self.model.controller.view.write_box.msg_write_box.set_edit_text(quote)
self.model.controller.view.write_box.msg_write_box.set_edit_pos(len(quote))
self.model.controller.view.middle_column.set_focus("footer")
elif is_command_key("EDIT_MESSAGE", key):
# User can't edit messages of others that already have a subject
# For private messages, subject = "" (empty string)
# This also handles the realm_message_content_edit_limit_seconds == 0 case
if (
self.message["sender_id"] != self.model.user_id
and self.message["subject"] != "(no topic)"
):
if self.message["type"] == "stream":
self.model.controller.report_error(
[
" You can't edit messages sent by other users that"
" already have a topic."
]
)
else:
self.model.controller.report_error(
[" You can't edit private messages sent by other users."]
)
return key
# Check if editing is allowed in the realm
elif not self.model.initial_data["realm_allow_message_editing"]:
self.model.controller.report_error(
[" Editing sent message is disabled."]
)
return key
# Check if message is still editable, i.e. within
# the time limit. A limit of 0 signifies no limit
# on message body editing.
msg_body_edit_enabled = True
if self.model.initial_data["realm_message_content_edit_limit_seconds"] > 0:
if self.message["sender_id"] == self.model.user_id:
time_since_msg_sent = time() - self.message["timestamp"]
edit_time_limit = self.model.initial_data[
"realm_message_content_edit_limit_seconds"
]
# Don't allow editing message body if time-limit exceeded.
if time_since_msg_sent >= edit_time_limit:
if self.message["type"] == "private":
self.model.controller.report_error(
[
" Time Limit for editing the message has been exceeded."
]
)
return key
elif self.message["type"] == "stream":
self.model.controller.report_warning(
[
" Only topic editing allowed."
" Time Limit for editing the message body"
" has been exceeded."
]
)
msg_body_edit_enabled = False
elif self.message["type"] == "stream":
# Allow editing topic if the message has "(no topic)" subject
if self.message["subject"] == "(no topic)":
self.model.controller.report_warning(
[
" Only topic editing is allowed."
" This is someone else's message but with (no topic)."
]
)
msg_body_edit_enabled = False
else:
self.model.controller.report_error(
[
" You can't edit messages sent by other users that"
" already have a topic."
]
)
return key
else:
# The remaining case is of a private message not belonging to user.
# Which should be already handled by the topmost if block
raise RuntimeError(
"Reached unexpected block. This should be handled at the top."
)
if self.message["type"] == "private":
self.keypress(size, primary_key_for_command("REPLY_MESSAGE"))
elif self.message["type"] == "stream":
self.model.controller.view.write_box.stream_box_edit_view(
stream_id=self.stream_id,
caption=self.message["display_recipient"],
title=self.message["subject"],
)
msg_id = self.message["id"]
response = self.model.fetch_raw_message_content(msg_id)
msg = response if response is not None else ""
write_box = self.model.controller.view.write_box
write_box.msg_edit_state = _MessageEditState(
message_id=msg_id, old_topic=self.message["subject"]
)
write_box.msg_write_box.set_edit_text(msg)
write_box.msg_write_box.set_edit_pos(len(msg))
write_box.msg_body_edit_enabled = msg_body_edit_enabled
# Set focus to topic box if message body editing is disabled.
if not msg_body_edit_enabled:
write_box.focus_position = write_box.FOCUS_CONTAINER_HEADER
write_box.header_write_box.focus_col = write_box.FOCUS_HEADER_BOX_TOPIC
self.model.controller.view.middle_column.set_focus("footer")
elif is_command_key("MSG_INFO", key):
self.model.controller.show_msg_info(
self.message, self.topic_links, self.message_links, self.time_mentions
)
elif is_command_key("ADD_REACTION", key):
self.model.controller.show_emoji_picker(self.message)
return key
class SearchBox(urwid.Pile):
def __init__(self, controller: Any) -> None:
self.controller = controller
super().__init__(self.main_view())
def main_view(self) -> Any:
search_text = f"Search [{', '.join(keys_for_command('SEARCH_MESSAGES'))}]: "
self.text_box = ReadlineEdit(f"{search_text} ")
# Add some text so that when packing,
# urwid doesn't hide the widget.
self.conversation_focus = urwid.Text(" ")
self.search_bar = urwid.Columns(
[
("pack", self.conversation_focus),
("pack", urwid.Text(" ")),
self.text_box,
]
)
self.msg_narrow = urwid.Text("DONT HIDE")
self.recipient_bar = urwid.LineBox(
self.msg_narrow,
title="Current message recipients",
tline="─",
lline="",
trcorner="─",
tlcorner="─",
blcorner="─",
rline="",
bline="─",
brcorner="─",
)
return [self.search_bar, self.recipient_bar]
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if (
is_command_key("ENTER", key) and self.text_box.edit_text == ""
) or is_command_key("GO_BACK", key):
self.text_box.set_edit_text("")
self.controller.exit_editor_mode()
self.controller.view.middle_column.set_focus("body")
return key
elif is_command_key("ENTER", key):
self.controller.exit_editor_mode()
self.controller.search_messages(self.text_box.edit_text)
self.controller.view.middle_column.set_focus("body")
return key
key = super().keypress(size, key)
return key
class PanelSearchBox(urwid.Edit):
"""
Search Box to search panel views in real-time.
"""
def __init__(
self, panel_view: Any, search_command: str, update_function: Callable[..., None]
) -> None:
self.panel_view = panel_view
self.search_command = search_command
self.search_text = f" Search [{', '.join(keys_for_command(search_command))}]: "
self.search_error = urwid.AttrMap(
urwid.Text([" ", INVALID_MARKER, " No Results"]), "search_error"
)
urwid.connect_signal(self, "change", update_function)
super().__init__(caption=self.search_text, edit_text="")
def reset_search_text(self) -> None:
self.set_caption(self.search_text)
self.set_edit_text("")
def valid_char(self, ch: str) -> bool:
# This method 'strips' leading space *before* entering it in the box
if self.edit_text:
# Use regular validation if already have text
return super().valid_char(ch)
elif len(ch) != 1:
# urwid expands some unicode to strings to be useful
# (so we need to work around eg 'backspace')
return False
else:
# Skip unicode 'Control characters' and 'space Zeperators'
# This includes various invalid characters and complex spaces
return unicodedata.category(ch) not in ("Cc", "Zs")
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if (
is_command_key("ENTER", key) and self.get_edit_text() == ""
) or is_command_key("GO_BACK", key):
self.panel_view.view.controller.exit_editor_mode()
self.reset_search_text()
self.panel_view.set_focus("body")
# Don't call 'Esc' when inside a popup search-box.
if not self.panel_view.view.controller.is_any_popup_open():
self.panel_view.keypress(size, primary_key_for_command("GO_BACK"))
elif is_command_key("ENTER", key) and not self.panel_view.empty_search:
self.panel_view.view.controller.exit_editor_mode()
self.set_caption([("filter_results", " Search Results "), " "])
self.panel_view.set_focus("body")
if hasattr(self.panel_view, "log"):
self.panel_view.body.set_focus(0)
return super().keypress(size, key) | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/ui_tools/boxes.py | boxes.py |
from typing import Any, List, Optional, Tuple, Union, cast
def parse_html_table(table_element: Any) -> Tuple[List[str], List[List[str]]]:
"""
Parses an HTML table to extract cell items and column alignments.
The table cells are stored in `cells` in a row-wise manner.
cells = [[row0, row0, row0],
[row1, row1, row1],
[row2, row2, row2]]
"""
headers = table_element.thead.tr.find_all("th")
rows = table_element.tbody.find_all("tr")
column_alignments = []
# Add +1 to count the header row as well.
cells: List[List[str]] = [[] for _ in range(len(rows) + 1)]
# Fill up `cells` with the header/0th row and extract alignments.
for header in headers:
cells[0].append(header.text)
column_alignments.append(header.get(("align"), "left"))
# Fill up `cells` with body rows.
for index, row in enumerate(rows, start=1):
for tdata in row.find_all("td"):
cells[index].append(tdata.text)
return (column_alignments, cells)
StyledTableData = List[Union[str, Tuple[Optional[str], str]]]
def pad_row_strip(
row_strip: StyledTableData, fill_char: str = " ", fill_width: int = 1
) -> StyledTableData:
"""
Returns back a padded row strip.
This only pads the box-drawing unicode characters. In particular, all the
connector characters are padded both sides, the leftmost character is
padded right and the rightmost is padded left.
The structure of `row_strip` for a table with three columns:
row_strip = [
leftmost_char,
cell_content,
connector_char,
cell_content,
connector_char,
cell_content,
rightmost_char,
]
Note: `cast` is used for assisting mypy.
"""
fill = fill_char * fill_width
# Pad the leftmost box-drawing character.
row_strip[0] = cast(str, row_strip[0]) + fill
# Pad the connector box-drawing characters.
for index in range(2, len(row_strip) - 1, 2):
row_strip[index] = fill + cast(str, row_strip[index]) + fill
# Pad the rightmost box-drawing character.
row_strip[-1] = fill + cast(str, row_strip[-1])
return row_strip
def row_with_styled_content(
row: List[str],
column_alignments: List[str],
column_widths: List[int],
vertical_bar: str,
row_style: Optional[str] = None,
) -> StyledTableData:
"""
Constructs styled row strip, for markup table, using unicode characters
and row elements.
"""
aligner = {"center": str.center, "left": str.ljust, "right": str.rjust}
row_strip: StyledTableData = [vertical_bar]
for column_num, cell in enumerate(row):
aligned_text = aligner[column_alignments[column_num]](
cell, column_widths[column_num]
)
row_strip.extend([(row_style, aligned_text), vertical_bar])
row_strip.pop() # Remove the extra vertical_bar.
row_strip.append(vertical_bar + "\n")
return pad_row_strip(row_strip)
def row_with_only_border(
lcorner: str,
line: str,
connector: str,
rcorner: str,
column_widths: List[int],
newline: bool = True,
) -> StyledTableData:
"""
Given left corner, line, connecter and right corner unicode character,
constructs a border row strip for markup table.
"""
border: StyledTableData = [lcorner]
for width in column_widths:
border.extend([line * width, connector])
border.pop() # Remove the extra connector.
if newline:
rcorner += "\n"
border.append(rcorner)
return pad_row_strip(border, fill_char=line)
def render_table(table_element: Any) -> StyledTableData:
"""
A helper function for rendering a markup table in the MessageBox.
"""
column_alignments, cells = parse_html_table(table_element)
# Calculate the width required for each column.
column_widths = [
len(max(column, key=lambda string: len(string))) for column in zip(*cells)
]
top_border = row_with_only_border("┌", "─", "┬", "┐", column_widths)
middle_border = row_with_only_border("├", "─", "┼", "┤", column_widths)
bottom_border = row_with_only_border(
"└", "─", "┴", "┘", column_widths, newline=False
)
# Construct the table, row-by-row.
table: StyledTableData = []
# Add the header/0th row and the borders that surround it to the table.
table.extend(top_border)
table.extend(
row_with_styled_content(
cells.pop(0), column_alignments, column_widths, "│", row_style="table_head"
)
)
table.extend(middle_border)
# Add the body rows to the table followed by the bottom-most border in the
# end.
for row in cells:
table.extend(
row_with_styled_content(row, column_alignments, column_widths, "│")
)
table.extend(bottom_border)
return table | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/ui_tools/tables.py | tables.py |
import threading
from collections import OrderedDict
from datetime import datetime
from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple, Union
import pytz
import urwid
from typing_extensions import Literal
from zulipterminal.api_types import EditPropagateMode
from zulipterminal.config.keys import (
HELP_CATEGORIES,
KEY_BINDINGS,
is_command_key,
keys_for_command,
primary_key_for_command,
)
from zulipterminal.config.markdown_examples import MARKDOWN_ELEMENTS
from zulipterminal.config.symbols import (
CHECK_MARK,
COLUMN_TITLE_BAR_LINE,
PINNED_STREAMS_DIVIDER,
)
from zulipterminal.config.ui_mappings import (
BOT_TYPE_BY_ID,
EDIT_MODE_CAPTIONS,
ROLE_BY_ID,
STATE_ICON,
STREAM_ACCESS_TYPE,
STREAM_POST_POLICY,
)
from zulipterminal.config.ui_sizes import LEFT_WIDTH
from zulipterminal.helper import (
Message,
TidiedUserInfo,
asynch,
match_emoji,
match_stream,
match_user,
)
from zulipterminal.server_url import near_message_url
from zulipterminal.ui_tools.boxes import MessageBox, PanelSearchBox
from zulipterminal.ui_tools.buttons import (
EmojiButton,
HomeButton,
MentionedButton,
MessageLinkButton,
PMButton,
StarredButton,
StreamButton,
TopicButton,
UserButton,
)
from zulipterminal.ui_tools.utils import create_msg_box_list
from zulipterminal.urwid_types import urwid_Size
MIDDLE_COLUMN_MOUSE_SCROLL_LINES = 1
SIDE_PANELS_MOUSE_SCROLL_LINES = 5
class ModListWalker(urwid.SimpleFocusListWalker):
def set_focus(self, position: int) -> None:
# When setting focus via set_focus method.
self.focus = position
self._modified()
if hasattr(self, "read_message"):
self.read_message()
def _set_focus(self, index: int) -> None:
# This method is called when directly setting focus via
# self.focus = focus_position
if not self:
self._focus = 0
return
if index < 0 or index >= len(self):
raise IndexError(f"focus index is out of range: {index}")
if index != int(index):
raise IndexError(f"invalid focus index: {index}")
index = int(index)
if index != self._focus:
self._focus_changed(index)
self._focus = index
if hasattr(self, "read_message"):
self.read_message()
def extend(self, items: List[Any], focus_position: Optional[int] = None) -> int:
if focus_position is None:
focus = self._adjust_focus_on_contents_modified(
slice(len(self), len(self)), items
)
else:
focus = focus_position
rval = super(urwid.MonitoredFocusList, self).extend(items)
self._set_focus(focus)
return rval
class MessageView(urwid.ListBox):
def __init__(self, model: Any, view: Any) -> None:
self.model = model
self.view = view
# Initialize for reference
self.focus_msg = 0
self.log = ModListWalker(self.main_view())
self.log.read_message = self.read_message
super().__init__(self.log)
self.set_focus(self.focus_msg)
# if loading new/old messages - True
self.old_loading = False
self.new_loading = False
def main_view(self) -> List[Any]:
msg_btn_list = create_msg_box_list(self.model)
focus_msg = self.model.get_focus_in_current_narrow()
if focus_msg == set():
focus_msg = len(msg_btn_list) - 1
self.focus_msg = focus_msg
return msg_btn_list
@asynch
def load_old_messages(self, anchor: int) -> None:
self.old_loading = True
ids_to_keep = self.model.get_message_ids_in_current_narrow()
if self.log:
top_message_id = self.log[0].original_widget.message["id"]
ids_to_keep.remove(top_message_id) # update this id
no_update_baseline = {top_message_id}
else:
no_update_baseline = set()
self.model.get_messages(num_before=30, num_after=0, anchor=anchor)
ids_to_process = self.model.get_message_ids_in_current_narrow() - ids_to_keep
# Only update if more messages are provided
if ids_to_process != no_update_baseline:
if self.log:
self.log.remove(self.log[0]) # avoid duplication when updating
message_list = create_msg_box_list(self.model, ids_to_process)
message_list.reverse()
for msg_w in message_list:
self.log.insert(0, msg_w)
self.set_focus(self.focus_msg) # Return focus to original message
self.model.controller.update_screen()
self.old_loading = False
@asynch
def load_new_messages(self, anchor: int) -> None:
self.new_loading = True
current_ids = self.model.get_message_ids_in_current_narrow()
self.model.get_messages(num_before=0, num_after=30, anchor=anchor)
new_ids = self.model.get_message_ids_in_current_narrow() - current_ids
if self.log:
last_message = self.log[-1].original_widget.message
else:
last_message = None
message_list = create_msg_box_list(
self.model, new_ids, last_message=last_message
)
self.log.extend(message_list)
self.model.controller.update_screen()
self.new_loading = False
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: bool
) -> bool:
if event == "mouse press":
if button == 4:
for _ in range(MIDDLE_COLUMN_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_UP"))
return True
if button == 5:
for _ in range(MIDDLE_COLUMN_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_DOWN"))
return True
return super().mouse_event(size, event, button, col, row, focus)
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("GO_DOWN", key) and not self.new_loading:
try:
position = self.log.next_position(self.focus_position)
self.set_focus(position, "above")
self.set_focus_valign("middle")
return key
except Exception:
if self.focus:
id = self.focus.original_widget.message["id"]
self.load_new_messages(id)
return key
elif is_command_key("GO_UP", key) and not self.old_loading:
try:
position = self.log.prev_position(self.focus_position)
self.set_focus(position, "below")
self.set_focus_valign("middle")
return key
except Exception:
if self.focus:
id = self.focus.original_widget.message["id"]
self.load_old_messages(id)
return key
elif is_command_key("SCROLL_UP", key) and not self.old_loading:
if self.focus is not None and self.focus_position == 0:
return self.keypress(size, primary_key_for_command("GO_UP"))
else:
return super().keypress(size, primary_key_for_command("SCROLL_UP"))
elif is_command_key("SCROLL_DOWN", key) and not self.old_loading:
if self.focus is not None and self.focus_position == len(self.log) - 1:
return self.keypress(size, primary_key_for_command("GO_DOWN"))
else:
return super().keypress(size, primary_key_for_command("SCROLL_DOWN"))
elif is_command_key("THUMBS_UP", key):
if self.focus is not None:
self.model.toggle_message_reaction(
self.focus.original_widget.message, reaction_to_toggle="thumbs_up"
)
elif is_command_key("TOGGLE_STAR_STATUS", key):
if self.focus is not None:
message = self.focus.original_widget.message
self.model.toggle_message_star_status(message)
key = super().keypress(size, key)
return key
def update_search_box_narrow(self, message_view: Any) -> None:
if not hasattr(self.model.controller, "view"):
return
# if view is ready display current narrow
# at the bottom of the view.
recipient_bar = message_view.top_header_bar(message_view)
top_header = message_view.top_search_bar()
self.model.controller.view.search_box.conversation_focus.set_text(
top_header.markup
)
self.model.controller.view.search_box.msg_narrow.set_text(recipient_bar.markup)
self.model.controller.update_screen()
def read_message(self, index: int = -1) -> None:
# Message currently in focus
if hasattr(self.model.controller, "view"):
view = self.model.controller.view
else:
return
msg_w, curr_pos = self.body.get_focus()
if msg_w is None:
return
self.update_search_box_narrow(msg_w.original_widget)
# Do not read messages in explore mode.
if self.model.controller.in_explore_mode:
return
# Do not read messages in any search narrow.
if self.model.is_search_narrow():
return
# If this the last message in the view and focus is set on this message
# then read the message.
last_message_focused = curr_pos == len(self.log) - 1
# Only allow reading a message when middle column is
# in focus.
if not (view.body.focus_col == 1 or last_message_focused):
return
# save the current focus
self.model.set_focus_in_current_narrow(self.focus_position)
# msg ids that have been read
read_msg_ids = list()
# until we find a read message above the current message
while msg_w.attr_map == {None: "unread"}:
msg_id = msg_w.original_widget.message["id"]
read_msg_ids.append(msg_id)
self.model.index["messages"][msg_id]["flags"].append("read")
msg_w.set_attr_map({None: None})
msg_w, curr_pos = self.body.get_prev(curr_pos)
if msg_w is None:
break
self.model.mark_message_ids_as_read(read_msg_ids)
class StreamsViewDivider(urwid.Divider):
"""
A custom urwid.Divider to visually separate pinned and unpinned streams.
"""
def __init__(self) -> None:
# FIXME: Necessary since the divider is treated as a StreamButton.
# NOTE: This is specifically for stream search to work correctly.
self.stream_id = -1
self.stream_name = ""
super().__init__(div_char=PINNED_STREAMS_DIVIDER)
class StreamsView(urwid.Frame):
def __init__(self, streams_btn_list: List[Any], view: Any) -> None:
self.view = view
self.log = urwid.SimpleFocusListWalker(streams_btn_list)
self.streams_btn_list = streams_btn_list
self.focus_index_before_search = 0
list_box = urwid.ListBox(self.log)
self.stream_search_box = PanelSearchBox(
self, "SEARCH_STREAMS", self.update_streams
)
super().__init__(
list_box,
header=urwid.LineBox(
self.stream_search_box,
tlcorner="─",
tline="",
lline="",
trcorner="─",
blcorner="─",
rline="",
bline="─",
brcorner="─",
),
)
self.search_lock = threading.Lock()
self.empty_search = False
@asynch
def update_streams(self, search_box: Any, new_text: str) -> None:
if not self.view.controller.is_in_editor_mode():
return
# wait for any previously started search to finish to avoid
# displaying wrong stream list.
with self.search_lock:
stream_buttons = [
(stream, stream.stream_name) for stream in self.streams_btn_list.copy()
]
streams_display = match_stream(
stream_buttons, new_text, self.view.pinned_streams
)[0]
streams_display_num = len(streams_display)
self.empty_search = streams_display_num == 0
# Add a divider to separate pinned streams from the rest.
pinned_stream_names = [
stream["name"] for stream in self.view.pinned_streams
]
first_unpinned_index = streams_display_num
for index, stream in enumerate(streams_display):
if stream.stream_name not in pinned_stream_names:
first_unpinned_index = index
break
if first_unpinned_index not in [0, streams_display_num]:
# Do not add a divider when it is already present. This can
# happen when new_text=''.
if not isinstance(
streams_display[first_unpinned_index], StreamsViewDivider
):
streams_display.insert(first_unpinned_index, StreamsViewDivider())
self.log.clear()
if not self.empty_search:
self.log.extend(streams_display)
else:
self.log.extend([self.stream_search_box.search_error])
self.view.controller.update_screen()
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: bool
) -> bool:
if event == "mouse press":
if button == 4:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_UP"))
return True
elif button == 5:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_DOWN"))
return True
return super().mouse_event(size, event, button, col, row, focus)
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("SEARCH_STREAMS", key):
_, self.focus_index_before_search = self.log.get_focus()
self.set_focus("header")
self.stream_search_box.set_caption(" ")
self.view.controller.enter_editor_mode_with(self.stream_search_box)
return key
elif is_command_key("GO_BACK", key):
self.stream_search_box.reset_search_text()
self.log.clear()
self.log.extend(self.streams_btn_list)
self.set_focus("body")
self.log.set_focus(self.focus_index_before_search)
self.view.controller.update_screen()
return key
return super().keypress(size, key)
class TopicsView(urwid.Frame):
def __init__(
self, topics_btn_list: List[Any], view: Any, stream_button: Any
) -> None:
self.view = view
self.log = urwid.SimpleFocusListWalker(topics_btn_list)
self.topics_btn_list = topics_btn_list
self.stream_button = stream_button
self.focus_index_before_search = 0
self.list_box = urwid.ListBox(self.log)
self.topic_search_box = PanelSearchBox(
self, "SEARCH_TOPICS", self.update_topics
)
self.header_list = urwid.Pile(
[self.stream_button, urwid.Divider("─"), self.topic_search_box]
)
super().__init__(
self.list_box,
header=urwid.LineBox(
self.header_list,
tlcorner="─",
tline="",
lline="",
trcorner="─",
blcorner="─",
rline="",
bline="─",
brcorner="─",
),
)
self.search_lock = threading.Lock()
self.empty_search = False
@asynch
def update_topics(self, search_box: Any, new_text: str) -> None:
if not self.view.controller.is_in_editor_mode():
return
# wait for any previously started search to finish to avoid
# displaying wrong topics list.
with self.search_lock:
new_text = new_text.lower()
topics_to_display = [
topic
for topic in self.topics_btn_list.copy()
if new_text in topic.topic_name.lower()
]
self.empty_search = len(topics_to_display) == 0
self.log.clear()
if not self.empty_search:
self.log.extend(topics_to_display)
else:
self.log.extend([self.topic_search_box.search_error])
self.view.controller.update_screen()
def update_topics_list(
self, stream_id: int, topic_name: str, sender_id: int
) -> None:
# More recent topics are found towards the beginning
# of the list.
for topic_iterator, topic_button in enumerate(self.log):
if topic_button.topic_name == topic_name:
self.log.insert(0, self.log.pop(topic_iterator))
self.list_box.set_focus_valign("bottom")
if sender_id == self.view.model.user_id:
self.list_box.set_focus(0)
return
# No previous topics with same topic names are found
# hence we create a new topic button for it.
new_topic_button = TopicButton(
stream_id=stream_id,
topic=topic_name,
controller=self.view.controller,
view=self.view,
count=0,
)
self.log.insert(0, new_topic_button)
self.list_box.set_focus_valign("bottom")
if sender_id == self.view.model.user_id:
self.list_box.set_focus(0)
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: bool
) -> bool:
if event == "mouse press":
if button == 4:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_UP"))
return True
elif button == 5:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_DOWN"))
return True
return super().mouse_event(size, event, button, col, row, focus)
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("SEARCH_TOPICS", key):
_, self.focus_index_before_search = self.log.get_focus()
self.set_focus("header")
self.header_list.set_focus(2)
self.topic_search_box.set_caption(" ")
self.view.controller.enter_editor_mode_with(self.topic_search_box)
return key
elif is_command_key("GO_BACK", key):
self.topic_search_box.reset_search_text()
self.log.clear()
self.log.extend(self.topics_btn_list)
self.set_focus("body")
self.log.set_focus(self.focus_index_before_search)
self.view.controller.update_screen()
return key
return super().keypress(size, key)
class UsersView(urwid.ListBox):
def __init__(self, controller: Any, users_btn_list: List[Any]) -> None:
self.users_btn_list = users_btn_list
self.log = urwid.SimpleFocusListWalker(users_btn_list)
self.controller = controller
super().__init__(self.log)
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: bool
) -> bool:
if event == "mouse press":
if button == 1:
if self.controller.is_in_editor_mode():
return True
if button == 4:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_UP"))
return True
elif button == 5:
for _ in range(SIDE_PANELS_MOUSE_SCROLL_LINES):
self.keypress(size, primary_key_for_command("GO_DOWN"))
return super().mouse_event(size, event, button, col, row, focus)
class MiddleColumnView(urwid.Frame):
def __init__(self, view: Any, model: Any, write_box: Any, search_box: Any) -> None:
message_view = MessageView(model, view)
self.model = model
self.controller = model.controller
self.view = view
self.last_unread_topic = None
self.last_unread_pm = None
self.search_box = search_box
view.message_view = message_view
super().__init__(message_view, header=search_box, footer=write_box)
def get_next_unread_topic(self) -> Optional[Tuple[int, str]]:
topics = list(self.model.unread_counts["unread_topics"].keys())
next_topic = False
for topic in topics:
if next_topic is True:
self.last_unread_topic = topic
return topic
if topic == self.last_unread_topic:
next_topic = True
if len(topics) > 0:
topic = topics[0]
self.last_unread_topic = topic
return topic
return None
def get_next_unread_pm(self) -> Optional[int]:
pms = list(self.model.unread_counts["unread_pms"].keys())
next_pm = False
for pm in pms:
if next_pm is True:
self.last_unread_pm = pm
return pm
if pm == self.last_unread_pm:
next_pm = True
if len(pms) > 0:
pm = pms[0]
self.last_unread_pm = pm
return pm
return None
def update_message_list_status_markers(self) -> None:
for message_w in self.body.log:
message_box = message_w.original_widget
message_box.update_message_author_status()
self.controller.update_screen()
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if self.focus_position in ["footer", "header"]:
return super().keypress(size, key)
elif is_command_key("SEARCH_MESSAGES", key):
self.controller.enter_editor_mode_with(self.search_box)
self.set_focus("header")
return key
elif is_command_key("REPLY_MESSAGE", key):
self.body.keypress(size, key)
if self.footer.focus is not None:
self.set_focus("footer")
self.footer.focus_position = 1
return key
elif is_command_key("STREAM_MESSAGE", key):
self.body.keypress(size, key)
# For new streams with no previous conversation.
if self.footer.focus is None:
stream_id = self.model.stream_id
stream_dict = self.model.stream_dict
self.footer.stream_box_view(caption=stream_dict[stream_id]["name"])
self.set_focus("footer")
self.footer.focus_position = 0
return key
elif is_command_key("REPLY_AUTHOR", key):
self.body.keypress(size, key)
if self.footer.focus is not None:
self.set_focus("footer")
self.footer.focus_position = 1
return key
elif is_command_key("NEXT_UNREAD_TOPIC", key):
# narrow to next unread topic
stream_topic = self.get_next_unread_topic()
if stream_topic is None:
return key
stream_id, topic = stream_topic
self.controller.narrow_to_topic(
stream_name=self.model.stream_dict[stream_id]["name"],
topic_name=topic,
)
return key
elif is_command_key("NEXT_UNREAD_PM", key):
# narrow to next unread pm
pm = self.get_next_unread_pm()
if pm is None:
return key
email = self.model.user_id_email_dict[pm]
self.controller.narrow_to_user(
recipient_emails=[email],
contextual_message_id=pm,
)
elif is_command_key("PRIVATE_MESSAGE", key):
# Create new PM message
self.footer.private_box_view()
self.set_focus("footer")
self.footer.focus_position = 0
return key
elif is_command_key("GO_LEFT", key):
self.view.show_left_panel(visible=True)
elif is_command_key("GO_RIGHT", key):
self.view.show_right_panel(visible=True)
return super().keypress(size, key)
class RightColumnView(urwid.Frame):
"""
Displays the users list on the right side of the app.
"""
def __init__(self, view: Any) -> None:
self.view = view
self.user_search = PanelSearchBox(self, "SEARCH_PEOPLE", self.update_user_list)
self.view.user_search = self.user_search
search_box = urwid.LineBox(
self.user_search,
tlcorner="─",
tline="",
lline="",
trcorner="─",
blcorner="─",
rline="",
bline="─",
brcorner="─",
)
self.allow_update_user_list = True
self.search_lock = threading.Lock()
self.empty_search = False
super().__init__(self.users_view(), header=search_box)
@asynch
def update_user_list(
self,
search_box: Any = None,
new_text: Optional[str] = None,
user_list: Any = None,
) -> None:
"""
Updates user list via PanelSearchBox and _start_presence_updates.
"""
assert (user_list is None and search_box is not None) or ( # PanelSearchBox.
user_list is not None and search_box is None and new_text is None
) # _start_presence_updates.
# Return if the method is called by PanelSearchBox (urwid.Edit) while
# the search is inactive and user_list is None.
# NOTE: The additional not user_list check is to not false trap
# _start_presence_updates but allow it to update the user list.
if not self.view.controller.is_in_editor_mode() and not user_list:
return
# Return if the method is called from _start_presence_updates while the
# search, via PanelSearchBox, is active.
if not self.allow_update_user_list and new_text is None:
return
# wait for any previously started search to finish to avoid
# displaying wrong user list.
with self.search_lock:
if user_list:
self.view.users = user_list
users = self.view.users.copy()
if new_text:
users_display = [user for user in users if match_user(user, new_text)]
else:
users_display = users
self.empty_search = len(users_display) == 0
# FIXME Update log directly?
if not self.empty_search:
self.body = self.users_view(users_display)
else:
self.body = UsersView(
self.view.controller, [self.user_search.search_error]
)
self.set_body(self.body)
self.view.controller.update_screen()
def users_view(self, users: Any = None) -> Any:
reset_default_view_users = False
if users is None:
users = self.view.users.copy()
reset_default_view_users = True
users_btn_list = list()
for user in users:
status = user["status"]
# Only include `inactive` users in search result.
if status == "inactive" and not self.view.controller.is_in_editor_mode():
continue
unread_count = self.view.model.unread_counts["unread_pms"].get(
user["user_id"], 0
)
is_current_user = user["user_id"] == self.view.model.user_id
users_btn_list.append(
UserButton(
user=user,
controller=self.view.controller,
view=self.view,
state_marker=STATE_ICON[status],
color=f"user_{status}",
count=unread_count,
is_current_user=is_current_user,
)
)
user_w = UsersView(self.view.controller, users_btn_list)
# Donot reset them while searching.
if reset_default_view_users:
self.users_btn_list = users_btn_list
self.view.user_w = user_w
return user_w
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("SEARCH_PEOPLE", key):
self.allow_update_user_list = False
self.set_focus("header")
self.user_search.set_caption(" ")
self.view.controller.enter_editor_mode_with(self.user_search)
return key
elif is_command_key("GO_BACK", key):
self.user_search.reset_search_text()
self.allow_update_user_list = True
self.body = UsersView(self.view.controller, self.users_btn_list)
self.set_body(self.body)
self.set_focus("body")
self.view.controller.update_screen()
return key
elif is_command_key("GO_LEFT", key):
self.view.show_right_panel(visible=False)
return super().keypress(size, key)
class LeftColumnView(urwid.Pile):
"""
Displays the buttons at the left column of the app.
"""
def __init__(self, view: Any) -> None:
self.model = view.model
self.view = view
self.controller = view.controller
self.menu_v = self.menu_view()
self.stream_v = self.streams_view()
self.is_in_topic_view = False
contents = [(4, self.menu_v), self.stream_v]
super().__init__(contents)
def menu_view(self) -> Any:
count = self.model.unread_counts.get("all_msg", 0)
self.view.home_button = HomeButton(controller=self.controller, count=count)
count = self.model.unread_counts.get("all_pms", 0)
self.view.pm_button = PMButton(controller=self.controller, count=count)
self.view.mentioned_button = MentionedButton(
controller=self.controller,
count=self.model.unread_counts["all_mentions"],
)
# Starred messages are by definition read already
count = len(self.model.initial_data["starred_messages"])
self.view.starred_button = StarredButton(
controller=self.controller, count=count
)
menu_btn_list = [
self.view.home_button,
self.view.pm_button,
self.view.mentioned_button,
self.view.starred_button,
]
w = urwid.ListBox(urwid.SimpleFocusListWalker(menu_btn_list))
return w
def streams_view(self) -> Any:
streams_btn_list = [
StreamButton(
properties=stream,
controller=self.controller,
view=self.view,
count=self.model.unread_counts["streams"].get(stream["id"], 0),
)
for stream in self.view.pinned_streams
]
if len(streams_btn_list):
streams_btn_list += [StreamsViewDivider()]
streams_btn_list += [
StreamButton(
properties=stream,
controller=self.controller,
view=self.view,
count=self.model.unread_counts["streams"].get(stream["id"], 0),
)
for stream in self.view.unpinned_streams
]
self.view.stream_id_to_button = {
stream.stream_id: stream
for stream in streams_btn_list
if hasattr(stream, "stream_id")
}
self.view.stream_w = StreamsView(streams_btn_list, self.view)
w = urwid.LineBox(
self.view.stream_w,
title="Streams",
title_attr="column_title",
tlcorner=COLUMN_TITLE_BAR_LINE,
tline=COLUMN_TITLE_BAR_LINE,
trcorner=COLUMN_TITLE_BAR_LINE,
blcorner="",
rline="",
lline="",
bline="",
brcorner="─",
)
return w
def topics_view(self, stream_button: Any) -> Any:
stream_id = stream_button.stream_id
topics = self.model.topics_in_stream(stream_id)
topics_btn_list = [
TopicButton(
stream_id=stream_id,
topic=topic,
controller=self.controller,
view=self.view,
count=self.model.unread_counts["unread_topics"].get(
(stream_id, topic), 0
),
)
for topic in topics
]
self.view.topic_w = TopicsView(topics_btn_list, self.view, stream_button)
w = urwid.LineBox(
self.view.topic_w,
title="Topics",
title_attr="column_title",
tlcorner=COLUMN_TITLE_BAR_LINE,
tline=COLUMN_TITLE_BAR_LINE,
trcorner=COLUMN_TITLE_BAR_LINE,
blcorner="",
rline="",
lline="",
bline="",
brcorner="─",
)
return w
def is_in_topic_view_with_stream_id(self, stream_id: int) -> bool:
return (
self.is_in_topic_view
and stream_id == self.view.topic_w.stream_button.stream_id
)
def update_stream_view(self) -> None:
self.stream_v = self.streams_view()
if not self.is_in_topic_view:
self.show_stream_view()
def show_stream_view(self) -> None:
self.is_in_topic_view = False
self.contents[1] = (self.stream_v, self.options(height_type="weight"))
def show_topic_view(self, stream_button: Any) -> None:
self.is_in_topic_view = True
self.contents[1] = (
self.topics_view(stream_button),
self.options(height_type="weight"),
)
def keypress(self, size: urwid_Size, key: str) -> Optional[str]:
if is_command_key("SEARCH_STREAMS", key) or is_command_key(
"SEARCH_TOPICS", key
):
self.focus_position = 1
if self.is_in_topic_view:
self.view.topic_w.keypress(size, key)
else:
self.view.stream_w.keypress(size, key)
return key
elif is_command_key("GO_RIGHT", key):
self.view.show_left_panel(visible=False)
return super().keypress(size, key)
class TabView(urwid.WidgetWrap):
"""
Displays a tab that takes up the whole containers height
and has a flow width.
Currently used as closed tabs in the autohide layout.
"""
def __init__(self, text: str) -> None:
tab_widget_list = [urwid.Text(char) for char in text]
pile = urwid.Pile(tab_widget_list)
tab = urwid.Padding(urwid.Filler(pile), left=1, right=1, width=1)
super().__init__(tab)
# FIXME: This type could be improved, as Any isn't too explicit and clear.
# (this was previously str, but some types passed in can be more complex)
PopUpViewTableContent = Sequence[Tuple[str, Sequence[Union[str, Tuple[str, Any]]]]]
class PopUpView(urwid.Frame):
def __init__(
self,
controller: Any,
body: List[Any],
command: str,
requested_width: int,
title: str,
header: Optional[Any] = None,
footer: Optional[Any] = None,
) -> None:
self.controller = controller
self.command = command
self.title = title
self.log = urwid.SimpleFocusListWalker(body)
self.body = urwid.ListBox(self.log)
max_cols, max_rows = controller.maximum_popup_dimensions()
self.width = min(max_cols, requested_width)
height = self.calculate_popup_height(body, header, footer, self.width)
self.height = min(max_rows, height)
super().__init__(self.body, header=header, footer=footer)
@staticmethod
def calculate_popup_height(
body: List[Any],
header: Optional[Any],
footer: Optional[Any],
popup_width: int,
) -> int:
"""
Returns popup height. The popup height is calculated using urwid's
.rows method on every widget.
"""
height = sum(widget.rows((popup_width,)) for widget in body)
height += header.rows((popup_width,)) if header else 0
height += footer.rows((popup_width,)) if footer else 0
return height
@staticmethod
def calculate_table_widths(
contents: PopUpViewTableContent, title_len: int, dividechars: int = 2
) -> Tuple[int, List[int]]:
"""
Returns a tuple that contains the required width for the popup and a
list that has column widths.
"""
# Add 4 (for 2 Unicode characters on either side) to the popup title
# length to make sure that the title gets displayed even when the
# content or the category is shorter than the title length (+4 Unicode
# characters).
title_width = title_len + 4
category_width = 0
text_width = 0
strip_widths = []
for category, content in contents:
category_width = max(category_width, len(category))
for row in content:
if isinstance(row, str):
# Measure the longest line if the text is separated by
# newline(s).
text_width = max(text_width, len(max(row.split("\n"), key=len)))
elif isinstance(row, tuple):
# Measure the longest line if the text is separated by
# newline(s).
max_row_lengths = [
len(max(text.split("\n"), key=len)) for text in row
]
strip_widths.append(max_row_lengths)
column_widths = [max(width) for width in zip(*strip_widths)]
popup_width = max(
sum(column_widths) + dividechars, title_width, category_width, text_width
)
return (popup_width, column_widths)
@staticmethod
def make_table_with_categories(
contents: PopUpViewTableContent, column_widths: List[int], dividechars: int = 2
) -> List[Any]:
"""
Returns a list of widgets to render a table with different categories.
"""
widgets: List[Any] = []
for category, content in contents:
if category:
if len(widgets) > 0: # Separate categories with newline.
widgets.append(urwid.Text(""))
widgets.append(urwid.Text(("popup_category", category)))
for index, row in enumerate(content):
if isinstance(row, str) and row:
widgets.append(urwid.Text(row))
elif isinstance(row, tuple):
label, data = row
strip = urwid.Columns(
[(column_widths[0], urwid.Text(label)), urwid.Text(data)],
dividechars=dividechars,
)
widgets.append(
urwid.AttrWrap(strip, None if index % 2 else "popup_contrast")
)
return widgets
def keypress(self, size: urwid_Size, key: str) -> str:
if is_command_key("GO_BACK", key) or is_command_key(self.command, key):
self.controller.exit_popup()
return super().keypress(size, key)
class NoticeView(PopUpView):
def __init__(
self, controller: Any, notice_text: Any, width: int, title: str
) -> None:
widgets = [
urwid.Divider(),
urwid.Padding(urwid.Text(notice_text), left=1, right=1),
urwid.Divider(),
]
super().__init__(controller, widgets, "GO_BACK", width, title)
class AboutView(PopUpView):
def __init__(
self,
controller: Any,
title: str,
*,
zt_version: str,
server_version: str,
server_feature_level: Optional[int],
theme_name: str,
color_depth: int,
autohide_enabled: bool,
maximum_footlinks: int,
notify_enabled: bool,
) -> None:
self.feature_level_content = (
[("Feature level", str(server_feature_level))]
if server_feature_level
else []
)
contents = [
("Application", [("Zulip Terminal", zt_version)]),
("Server", [("Version", server_version)] + self.feature_level_content),
(
"Application Configuration",
[
("Theme", theme_name),
("Autohide", "enabled" if autohide_enabled else "disabled"),
("Maximum footlinks", str(maximum_footlinks)),
("Color depth", str(color_depth)),
("Notifications", "enabled" if notify_enabled else "disabled"),
],
),
]
popup_width, column_widths = self.calculate_table_widths(contents, len(title))
widgets = self.make_table_with_categories(contents, column_widths)
super().__init__(controller, widgets, "ABOUT", popup_width, title)
class UserInfoView(PopUpView):
def __init__(self, controller: Any, user_id: int, title: str) -> None:
display_data = self._fetch_user_data(controller, user_id)
user_details = [
(key, value) for key, value in display_data.items() if key != "Name"
]
user_view_content = [(display_data["Name"], user_details)]
popup_width, column_widths = self.calculate_table_widths(
user_view_content, len(title)
)
widgets = self.make_table_with_categories(user_view_content, column_widths)
super().__init__(controller, widgets, "USER_INFO", popup_width, title)
@staticmethod
def _fetch_user_data(controller: Any, user_id: int) -> Dict[str, Any]:
# Get user data from model
data: TidiedUserInfo = controller.model.get_user_info(user_id)
if not data:
display_data = {
"Name": "(Unavailable)",
"Error": "User data not found",
}
return display_data
# Style the data obtained to make it displayable
display_data = {"Name": data["full_name"]}
if data["email"]:
display_data["Email"] = data["email"]
if data["date_joined"]:
display_data["Date joined"] = data["date_joined"][:10]
if data["timezone"]:
display_data["Timezone"] = data["timezone"].replace("_", " ")
# Converting all timestamps to UTC
utc_time = datetime.now()
tz = pytz.timezone(data["timezone"])
time = utc_time.astimezone(tz).replace(tzinfo=None).timestamp()
# Take 24h vs AM/PM format into consideration
local_time = controller.model.formatted_local_time(
round(time), show_seconds=False
)
display_data["Local time"] = local_time[11:]
if data["is_bot"]:
assert data["bot_type"] is not None
display_data["Role"] = BOT_TYPE_BY_ID.get(
data["bot_type"], "Unknown Bot Type"
)
if data["bot_owner_name"]:
display_data["Owner"] = data["bot_owner_name"]
else:
display_data["Role"] = ROLE_BY_ID[data["role"]]["name"]
if data["last_active"]:
display_data["Last active"] = data["last_active"]
return display_data
class HelpView(PopUpView):
def __init__(self, controller: Any, title: str) -> None:
help_menu_content = []
for category in HELP_CATEGORIES:
keys_in_category = (
binding
for binding in KEY_BINDINGS.values()
if binding["key_category"] == category
)
key_bindings = []
for binding in keys_in_category:
key_bindings.append((binding["help_text"], ", ".join(binding["keys"])))
help_menu_content.append((HELP_CATEGORIES[category], key_bindings))
popup_width, column_widths = self.calculate_table_widths(
help_menu_content, len(title)
)
widgets = self.make_table_with_categories(help_menu_content, column_widths)
super().__init__(controller, widgets, "HELP", popup_width, title)
class MarkdownHelpView(PopUpView):
def __init__(self, controller: Any, title: str) -> None:
raw_menu_content = [] # to calculate table dimensions
rendered_menu_content = [] # to display rendered content in table
user_name = controller.model.user_full_name
for element in MARKDOWN_ELEMENTS:
raw_content = element["raw_text"]
html_element = element["html_element"].format(**dict(user=user_name))
rendered_content, *_ = MessageBox.transform_content(
html_element, controller.model.server_url
)
raw_menu_content.append((raw_content, raw_content))
rendered_menu_content.append((raw_content, rendered_content))
popup_width, column_widths = self.calculate_table_widths(
[("", raw_menu_content)], len(title)
)
header_widgets = [
urwid.Text([("popup_category", "You type")], align="center"),
urwid.Text([("popup_category", "You get")], align="center"),
]
header_columns = urwid.Columns(header_widgets)
header = urwid.Pile([header_columns, urwid.Divider(COLUMN_TITLE_BAR_LINE)])
body = self.make_table_with_categories(
[("", rendered_menu_content)], column_widths
)
super().__init__(controller, body, "MARKDOWN_HELP", popup_width, title, header)
PopUpConfirmationViewLocation = Literal["top-left", "center"]
class PopUpConfirmationView(urwid.Overlay):
def __init__(
self,
controller: Any,
question: Any,
success_callback: Callable[[], None],
location: PopUpConfirmationViewLocation = "top-left",
):
self.controller = controller
self.success_callback = success_callback
yes = urwid.Button("Yes", self.exit_popup_yes)
no = urwid.Button("No", self.exit_popup_no)
yes._w = urwid.AttrMap(urwid.SelectableIcon("Yes", 4), None, "selected")
no._w = urwid.AttrMap(urwid.SelectableIcon("No", 4), None, "selected")
display_widget = urwid.GridFlow([yes, no], 3, 5, 1, "center")
wrapped_widget = urwid.WidgetWrap(display_widget)
widgets = [question, urwid.Divider(), wrapped_widget]
prompt = urwid.LineBox(urwid.ListBox(urwid.SimpleFocusListWalker(widgets)))
if location == "top-left":
align = "left"
valign = "top"
width = LEFT_WIDTH + 1
height = 8
else:
align = "center"
valign = "middle"
max_cols, max_rows = controller.maximum_popup_dimensions()
# +2 to compensate for the LineBox characters.
width = min(max_cols, max(question.pack()[0], len("Yes"), len("No"))) + 2
height = min(max_rows, sum(widget.rows((width,)) for widget in widgets)) + 2
urwid.Overlay.__init__(
self,
prompt,
self.controller.view,
align=align,
valign=valign,
width=width,
height=height,
)
def exit_popup_yes(self, args: Any) -> None:
self.success_callback()
self.controller.exit_popup()
def exit_popup_no(self, args: Any) -> None:
self.controller.exit_popup()
def keypress(self, size: urwid_Size, key: str) -> str:
if is_command_key("GO_BACK", key):
self.controller.exit_popup()
return super().keypress(size, key)
class StreamInfoView(PopUpView):
def __init__(self, controller: Any, stream_id: int) -> None:
self.stream_id = stream_id
self.controller = controller
stream = controller.model.stream_dict[stream_id]
# New in feature level 30, server version 4.0
stream_creation_date = stream["date_created"]
date_created = (
[
(
"Created on",
controller.model.formatted_local_time(
stream_creation_date, show_seconds=False, show_year=True
),
)
]
if stream_creation_date is not None
else []
)
message_retention_days = [
(
"Message retention days",
self.controller.model.cached_retention_text[self.stream_id],
)
]
if "stream_post_policy" in stream:
stream_policy = STREAM_POST_POLICY[stream["stream_post_policy"]]
else:
if stream.get("is_announcement_only"):
stream_policy = STREAM_POST_POLICY[2]
else:
stream_policy = STREAM_POST_POLICY[1]
total_members = len(stream["subscribers"])
stream_access_type = controller.model.stream_access_type(stream_id)
type_of_stream = STREAM_ACCESS_TYPE[stream_access_type]["description"]
stream_marker = STREAM_ACCESS_TYPE[stream_access_type]["icon"]
availability_of_history = (
"Public to Users"
if stream["history_public_to_subscribers"]
else "Not Public to Users"
)
member_keys = ", ".join(map(repr, keys_for_command("STREAM_MEMBERS")))
self.stream_email = stream["email_address"]
email_keys = ", ".join(map(repr, keys_for_command("COPY_STREAM_EMAIL")))
weekly_traffic = stream["stream_weekly_traffic"]
weekly_msg_count = (
"Stream created recently" if weekly_traffic is None else str(weekly_traffic)
)
title = f"{stream_marker} {stream['name']}"
rendered_desc = stream["rendered_description"]
self.markup_desc, message_links, _ = MessageBox.transform_content(
rendered_desc,
self.controller.model.server_url,
)
desc = urwid.Text(self.markup_desc)
stream_info_content = [
(
"Stream Details",
[
("Stream ID", f"{self.stream_id}"),
("Type of Stream", f"{type_of_stream}"),
]
+ date_created
+ message_retention_days
+ [
("Weekly Message Count", str(weekly_msg_count)),
(
"Stream Members",
f"{total_members} (Press {member_keys} to view list)",
),
(
"Stream email",
f"Press {email_keys} to copy Stream email address",
),
("History of Stream", f"{availability_of_history}"),
("Posting Policy", f"{stream_policy}"),
],
),
("Stream settings", []),
] # type: PopUpViewTableContent
popup_width, column_widths = self.calculate_table_widths(
stream_info_content, len(title)
)
muted_setting = urwid.CheckBox(
label="Muted",
state=controller.model.is_muted_stream(stream_id),
checked_symbol=CHECK_MARK,
)
urwid.connect_signal(muted_setting, "change", self.toggle_mute_status)
pinned_state = controller.model.is_pinned_stream(stream_id)
pinned_setting = urwid.CheckBox(
label="Pinned to top", state=pinned_state, checked_symbol=CHECK_MARK
)
urwid.connect_signal(pinned_setting, "change", self.toggle_pinned_status)
visual_notification = urwid.CheckBox(
label="Visual notifications (Terminal/Web/Desktop)",
state=controller.model.is_visual_notifications_enabled(stream_id),
checked_symbol=CHECK_MARK,
)
urwid.connect_signal(
visual_notification, "change", self.toggle_visual_notification
)
footlinks, footlinks_width = MessageBox.footlinks_view(
message_links=message_links,
maximum_footlinks=10, # Show 'all', as no other way to add them
padded=False,
wrap="space",
)
# Manual because calculate_table_widths does not support checkboxes.
# Add 4 to checkbox label to accommodate the checkbox itself.
popup_width = max(
popup_width,
len(muted_setting.label) + 4,
len(pinned_setting.label) + 4,
desc.pack()[0],
footlinks_width,
len(visual_notification.label) + 4,
)
visual_notification_setting = [visual_notification]
# If notifications is not configured or enabled by the user, then
# disable the checkbox and mention it explicitly with a suffix text
if not self.controller.notify_enabled:
visual_notification_setting = [
urwid.WidgetDisable(
urwid.AttrMap(visual_notification, "widget_disabled")
),
urwid.Text(
("popup_important", " [notifications not configured or enabled]")
),
]
self.widgets = self.make_table_with_categories(
stream_info_content, column_widths
)
# Stream description.
self.widgets.insert(0, desc)
desc_newline = 1
if footlinks:
self.widgets.insert(1, footlinks)
desc_newline = 2
self.widgets.insert(desc_newline, urwid.Text("")) # Add a newline.
self.widgets.append(muted_setting)
self.widgets.append(pinned_setting)
self.widgets.extend(visual_notification_setting)
super().__init__(controller, self.widgets, "STREAM_DESC", popup_width, title)
def toggle_mute_status(self, button: Any, new_state: bool) -> None:
self.controller.model.toggle_stream_muted_status(self.stream_id)
def toggle_pinned_status(self, button: Any, new_state: bool) -> None:
self.controller.model.toggle_stream_pinned_status(self.stream_id)
def toggle_visual_notification(self, button: Any, new_state: bool) -> None:
self.controller.model.toggle_stream_visual_notifications(self.stream_id)
def keypress(self, size: urwid_Size, key: str) -> str:
if is_command_key("STREAM_MEMBERS", key):
self.controller.show_stream_members(stream_id=self.stream_id)
elif is_command_key("COPY_STREAM_EMAIL", key):
self.controller.copy_to_clipboard(self.stream_email, "Stream email")
return super().keypress(size, key)
class StreamMembersView(PopUpView):
def __init__(self, controller: Any, stream_id: int) -> None:
self.stream_id = stream_id
self.controller = controller
model = controller.model
user_ids = model.get_other_subscribers_in_stream(stream_id=stream_id)
user_names = [model.user_name_from_id(id) for id in user_ids]
sorted_user_names = sorted(user_names)
sorted_user_names.insert(0, model.user_full_name)
title = "Stream Members (up/down scrolls)"
stream_users_content = [("", [(name, "") for name in sorted_user_names])]
popup_width, column_width = self.calculate_table_widths(
stream_users_content, len(title)
)
widgets = self.make_table_with_categories(stream_users_content, column_width)
super().__init__(controller, widgets, "STREAM_DESC", popup_width, title)
def keypress(self, size: urwid_Size, key: str) -> str:
if is_command_key("GO_BACK", key) or is_command_key("STREAM_MEMBERS", key):
self.controller.show_stream_info(stream_id=self.stream_id)
return key
return super().keypress(size, key)
class MsgInfoView(PopUpView):
def __init__(
self,
controller: Any,
msg: Message,
title: str,
topic_links: "OrderedDict[str, Tuple[str, int, bool]]",
message_links: "OrderedDict[str, Tuple[str, int, bool]]",
time_mentions: List[Tuple[str, str]],
) -> None:
self.msg = msg
self.topic_links = topic_links
self.message_links = message_links
self.time_mentions = time_mentions
self.server_url = controller.model.server_url
date_and_time = controller.model.formatted_local_time(
msg["timestamp"], show_seconds=True, show_year=True
)
view_in_browser_keys = ", ".join(map(repr, keys_for_command("VIEW_IN_BROWSER")))
full_rendered_message_keys = ", ".join(
map(repr, keys_for_command("FULL_RENDERED_MESSAGE"))
)
full_raw_message_keys = ", ".join(
map(repr, keys_for_command("FULL_RAW_MESSAGE"))
)
msg_info = [
(
"",
[
("Date & Time", date_and_time),
("Sender", msg["sender_full_name"]),
("Sender's Email ID", msg["sender_email"]),
(
"View message in browser",
f"Press {view_in_browser_keys} to view message in browser",
),
(
"Full rendered message",
f"Press {full_rendered_message_keys} to view",
),
(
"Full raw message",
f"Press {full_raw_message_keys} to view",
),
],
),
]
# Only show the 'Edit History' label for edited messages.
self.show_edit_history_label = (
self.msg["id"] in controller.model.index["edited_messages"]
and controller.model.initial_data["realm_allow_edit_history"]
)
if self.show_edit_history_label:
msg_info[0][1][0] = ("Date & Time (Original)", date_and_time)
keys = ", ".join(map(repr, keys_for_command("EDIT_HISTORY")))
msg_info[0][1].append(("Edit History", f"Press {keys} to view"))
# Render the category using the existing table methods if links exist.
if topic_links:
msg_info.append(("Topic Links", []))
if message_links:
msg_info.append(("Message Links", []))
if time_mentions:
msg_info.append(("Time mentions", time_mentions))
if msg["reactions"]:
reactions = sorted(
(reaction["emoji_name"], reaction["user"]["full_name"])
for reaction in msg["reactions"]
)
grouped_reactions: Dict[str, str] = dict()
for reaction, user in reactions:
if reaction in grouped_reactions:
grouped_reactions[reaction] += f"\n{user}"
else:
grouped_reactions[reaction] = user
msg_info.append(("Reactions", list(grouped_reactions.items())))
popup_width, column_widths = self.calculate_table_widths(msg_info, len(title))
widgets = self.make_table_with_categories(msg_info, column_widths)
# To keep track of buttons (e.g., button links) and to facilitate
# computing their slice indexes
button_widgets = [] # type: List[Any]
if topic_links:
topic_link_widgets, topic_link_width = self.create_link_buttons(
controller, topic_links
)
# slice_index = Number of labels before topic links + 1 newline
# + 1 'Topic Links' category label.
slice_index = len(msg_info[0][1]) + 2
slice_index += sum([len(w) + 2 for w in button_widgets])
button_widgets.append(topic_links)
widgets = widgets[:slice_index] + topic_link_widgets + widgets[slice_index:]
popup_width = max(popup_width, topic_link_width)
if message_links:
message_link_widgets, message_link_width = self.create_link_buttons(
controller, message_links
)
# slice_index = Number of labels before message links + 1 newline
# + 1 'Message Links' category label.
slice_index = len(msg_info[0][1]) + 2
slice_index += sum([len(w) + 2 for w in button_widgets])
button_widgets.append(message_links)
widgets = (
widgets[:slice_index] + message_link_widgets + widgets[slice_index:]
)
popup_width = max(popup_width, message_link_width)
super().__init__(controller, widgets, "MSG_INFO", popup_width, title)
@staticmethod
def create_link_buttons(
controller: Any, links: "OrderedDict[str, Tuple[str, int, bool]]"
) -> Tuple[List[MessageLinkButton], int]:
link_widgets = []
link_width = 0
for index, link in enumerate(links):
text, link_index, _ = links[link]
if text:
caption = f"{link_index}: {text}\n{link}"
else:
caption = f"{link_index}: {link}"
link_width = max(link_width, len(max(caption.split("\n"), key=len)))
display_attr = None if index % 2 else "popup_contrast"
link_widgets.append(
MessageLinkButton(
controller=controller,
caption=caption,
link=link,
display_attr=display_attr,
)
)
return link_widgets, link_width
def keypress(self, size: urwid_Size, key: str) -> str:
if is_command_key("EDIT_HISTORY", key) and self.show_edit_history_label:
self.controller.show_edit_history(
message=self.msg,
topic_links=self.topic_links,
message_links=self.message_links,
time_mentions=self.time_mentions,
)
elif is_command_key("VIEW_IN_BROWSER", key):
url = near_message_url(self.server_url[:-1], self.msg)
self.controller.open_in_browser(url)
elif is_command_key("FULL_RENDERED_MESSAGE", key):
self.controller.show_full_rendered_message(
message=self.msg,
topic_links=self.topic_links,
message_links=self.message_links,
time_mentions=self.time_mentions,
)
return key
elif is_command_key("FULL_RAW_MESSAGE", key):
self.controller.show_full_raw_message(
message=self.msg,
topic_links=self.topic_links,
message_links=self.message_links,
time_mentions=self.time_mentions,
)
return key
return super().keypress(size, key)
class EditModeView(PopUpView):
def __init__(self, controller: Any, button: Any):
self.edit_mode_button = button
self.widgets: List[urwid.RadioButton] = []
for mode in EDIT_MODE_CAPTIONS.keys():
self.add_radio_button(mode)
super().__init__(
controller, self.widgets, "ENTER", 62, "Topic edit propagation mode"
)
# Set cursor to marked checkbox.
for i in range(len(self.widgets)):
if self.widgets[i].state:
self.body.set_focus(i)
def set_selected_mode(self, button: Any, new_state: bool, mode: str) -> None:
if new_state:
self.edit_mode_button.set_selected_mode(mode)
def add_radio_button(self, mode: EditPropagateMode) -> None:
state = mode == self.edit_mode_button.mode
radio_button = urwid.RadioButton(
self.widgets, EDIT_MODE_CAPTIONS[mode], state=state
)
urwid.connect_signal(radio_button, "change", self.set_selected_mode, mode)
def keypress(self, size: urwid_Size, key: str) -> str:
# Use space to select radio-button and exit popup too.
if key == " ":
key = "enter"
return super().keypress(size, key)
EditHistoryTag = Literal["(Current Version)", "(Original Version)", ""]
class EditHistoryView(PopUpView):
def __init__(
self,
controller: Any,
message: Message,
topic_links: "OrderedDict[str, Tuple[str, int, bool]]",
message_links: "OrderedDict[str, Tuple[str, int, bool]]",
time_mentions: List[Tuple[str, str]],
title: str,
) -> None:
self.controller = controller
self.message = message
self.topic_links = topic_links
self.message_links = message_links
self.time_mentions = time_mentions
width = 64
widgets: List[Any] = []
message_history = self.controller.model.fetch_message_history(
message_id=self.message["id"],
)
for index, snapshot in enumerate(message_history):
if len(widgets) > 0: # Separate edit blocks with newline.
widgets.append(urwid.Text(""))
tag: EditHistoryTag = ""
if index == 0:
tag = "(Original Version)"
elif index == len(message_history) - 1:
tag = "(Current Version)"
widgets.append(self._make_edit_block(snapshot, tag))
if not widgets:
feedback = [
"Could not find any message history. See ",
("msg_bold", "footer"),
" for the error message.",
]
widgets.append(urwid.Text(feedback, align="center"))
super().__init__(controller, widgets, "MSG_INFO", width, title)
def _make_edit_block(self, snapshot: Dict[str, Any], tag: EditHistoryTag) -> Any:
content = snapshot["content"]
topic = snapshot["topic"]
date_and_time = self.controller.model.formatted_local_time(
snapshot["timestamp"], show_seconds=True
)
user_id = snapshot.get("user_id")
if user_id:
author_name = self.controller.model.user_name_from_id(user_id)
else:
author_name = "Author N/A"
author_prefix = self._get_author_prefix(snapshot, tag)
author = f"{author_prefix} by {author_name}"
header = [
urwid.Text(("edit_topic", topic)),
# 18 = max(EditHistoryTag).
(18, urwid.Text(("edit_tag", tag), align="right")),
]
subheader = [
urwid.Text(("edit_author", author)),
# 22 = len(timestamp).
(22, urwid.Text(("edit_time", date_and_time), align="right")),
]
edit_block = [
urwid.AttrWrap(
urwid.Columns(header, dividechars=2),
"popup_contrast",
),
urwid.Columns(subheader, dividechars=2),
urwid.Text(content),
]
return urwid.Pile(edit_block)
@staticmethod
def _get_author_prefix(snapshot: Dict[str, Any], tag: EditHistoryTag) -> str:
if tag == "(Original Version)":
return "Posted"
# NOTE: The false alarm bit in the subsequent code block is a
# workaround for the inconsistency in the message history.
content = snapshot["content"]
topic = snapshot["topic"]
false_alarm_content = content == snapshot.get("prev_content")
false_alarm_topic = topic == snapshot.get("prev_topic")
if (
"prev_topic" in snapshot
and "prev_content" in snapshot
and not (false_alarm_content or false_alarm_topic)
):
author_prefix = "Content & Topic edited"
elif "prev_content" in snapshot and not false_alarm_content:
author_prefix = "Content edited"
elif "prev_topic" in snapshot and not false_alarm_topic:
author_prefix = "Topic edited"
else:
author_prefix = "Edited but no changes made"
return author_prefix
def keypress(self, size: urwid_Size, key: str) -> str:
if is_command_key("GO_BACK", key) or is_command_key("EDIT_HISTORY", key):
self.controller.show_msg_info(
msg=self.message,
topic_links=self.topic_links,
message_links=self.message_links,
time_mentions=self.time_mentions,
)
return key
return super().keypress(size, key)
class FullRenderedMsgView(PopUpView):
def __init__(
self,
controller: Any,
message: Message,
topic_links: "OrderedDict[str, Tuple[str, int, bool]]",
message_links: "OrderedDict[str, Tuple[str, int, bool]]",
time_mentions: List[Tuple[str, str]],
title: str,
) -> None:
self.controller = controller
self.message = message
self.topic_links = topic_links
self.message_links = message_links
self.time_mentions = time_mentions
max_cols, max_rows = controller.maximum_popup_dimensions()
# Get rendered message
msg_box = MessageBox(message, controller.model, None)
super().__init__(
controller,
[msg_box.content],
"MSG_INFO",
max_cols,
title,
urwid.Pile(msg_box.header),
urwid.Pile(msg_box.footer),
)
def keypress(self, size: urwid_Size, key: str) -> str:
if is_command_key("GO_BACK", key) or is_command_key(
"FULL_RENDERED_MESSAGE", key
):
self.controller.show_msg_info(
msg=self.message,
topic_links=self.topic_links,
message_links=self.message_links,
time_mentions=self.time_mentions,
)
return key
return super().keypress(size, key)
class FullRawMsgView(PopUpView):
def __init__(
self,
controller: Any,
message: Message,
topic_links: "OrderedDict[str, Tuple[str, int, bool]]",
message_links: "OrderedDict[str, Tuple[str, int, bool]]",
time_mentions: List[Tuple[str, str]],
title: str,
) -> None:
self.controller = controller
self.message = message
self.topic_links = topic_links
self.message_links = message_links
self.time_mentions = time_mentions
max_cols, max_rows = controller.maximum_popup_dimensions()
# Get rendered message header and footer
msg_box = MessageBox(message, controller.model, None)
# Get raw message content widget list
response = controller.model.fetch_raw_message_content(message["id"])
if response is None:
return
body_list = [urwid.Text(response)]
super().__init__(
controller,
body_list,
"MSG_INFO",
max_cols,
title,
urwid.Pile(msg_box.header),
urwid.Pile(msg_box.footer),
)
def keypress(self, size: urwid_Size, key: str) -> str:
if is_command_key("GO_BACK", key) or is_command_key("FULL_RAW_MESSAGE", key):
self.controller.show_msg_info(
msg=self.message,
topic_links=self.topic_links,
message_links=self.message_links,
time_mentions=self.time_mentions,
)
return key
return super().keypress(size, key)
class EmojiPickerView(PopUpView):
"""
Displays Emoji Picker view for messages.
"""
def __init__(
self,
controller: Any,
title: str,
emoji_units: List[Tuple[str, str, List[str]]],
message: Message,
view: Any,
) -> None:
self.view = view
self.message = message
self.controller = controller
self.selected_emojis: Dict[str, str] = {}
self.emoji_buttons = self.generate_emoji_buttons(emoji_units)
width = max(len(button.label) for button in self.emoji_buttons)
max_cols, max_rows = controller.maximum_popup_dimensions()
popup_width = min(max_cols, width)
self.emoji_search = PanelSearchBox(
self, "SEARCH_EMOJIS", self.update_emoji_list
)
search_box = urwid.LineBox(
self.emoji_search,
tlcorner="─",
tline="",
lline="",
trcorner="─",
blcorner="─",
rline="",
bline="─",
brcorner="─",
)
self.empty_search = False
self.search_lock = threading.Lock()
super().__init__(
controller,
self.emoji_buttons,
"ADD_REACTION",
popup_width,
title,
header=search_box,
)
self.set_focus("header")
self.controller.enter_editor_mode_with(self.emoji_search)
@asynch
def update_emoji_list(
self,
search_box: Any = None,
new_text: Optional[str] = None,
emoji_list: Any = None,
) -> None:
"""
Updates emoji list via PanelSearchBox.
"""
assert (emoji_list is None and search_box is not None) or (
emoji_list is not None and search_box is None and new_text is None
)
# Return if the method is called by PanelSearchBox without
# self.emoji_search being defined.
if not hasattr(self, "emoji_search"):
return
with self.search_lock:
self.emojis_display = list()
if new_text and new_text != self.emoji_search.search_text:
for button in self.emoji_buttons:
if match_emoji(button.emoji_name, new_text):
self.emojis_display.append(button)
else:
for alias in button.aliases:
if match_emoji(alias, new_text):
self.emojis_display.append(button)
break
else:
self.emojis_display = self.emoji_buttons
self.empty_search = len(self.emojis_display) == 0
body_content = self.emojis_display
if self.empty_search:
body_content = [self.emoji_search.search_error]
self.contents["body"] = (
urwid.ListBox(urwid.SimpleFocusListWalker(body_content)),
None,
)
self.controller.update_screen()
def is_selected_emoji(self, emoji_name: str) -> bool:
return emoji_name in self.selected_emojis.values()
def add_or_remove_selected_emoji(self, emoji_code: str, emoji_name: str) -> None:
if emoji_name in self.selected_emojis.values():
self.selected_emojis.pop(emoji_code, None)
else:
self.selected_emojis.update({emoji_code: emoji_name})
def count_reactions(self, emoji_code: str) -> int:
num_reacts = 0
for reaction in self.message["reactions"]:
if reaction["emoji_code"] == emoji_code:
num_reacts += 1
return num_reacts
def generate_emoji_buttons(
self, emoji_units: List[Tuple[str, str, List[str]]]
) -> List[EmojiButton]:
emoji_buttons = [
EmojiButton(
controller=self.controller,
emoji_unit=emoji_unit,
message=self.message,
reaction_count=self.count_reactions(emoji_unit[1]),
is_selected=self.is_selected_emoji,
toggle_selection=self.add_or_remove_selected_emoji,
)
for emoji_unit in emoji_units
]
sorted_emoji_buttons = sorted(
emoji_buttons, key=lambda button: button.reaction_count, reverse=True
)
return sorted_emoji_buttons
def mouse_event(
self, size: urwid_Size, event: str, button: int, col: int, row: int, focus: int
) -> bool:
if event == "mouse press":
if button == 1 and self.controller.is_in_editor_mode():
super().keypress(size, "enter")
return True
if button == 4:
self.keypress(size, "up")
return True
elif button == 5:
self.keypress(size, "down")
return True
return super().mouse_event(size, event, button, col, row, focus)
def keypress(self, size: urwid_Size, key: str) -> str:
if (
is_command_key("SEARCH_EMOJIS", key)
and not self.controller.is_in_editor_mode()
):
self.set_focus("header")
self.emoji_search.set_caption(" ")
self.controller.enter_editor_mode_with(self.emoji_search)
return key
elif is_command_key("GO_BACK", key) or is_command_key("ADD_REACTION", key):
for emoji_code, emoji_name in self.selected_emojis.items():
self.controller.model.toggle_message_reaction(self.message, emoji_name)
self.emoji_search.reset_search_text()
self.controller.exit_editor_mode()
self.controller.exit_popup()
return key
return super().keypress(size, key) | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/ui_tools/views.py | views.py |
from typing import Any, Iterable, List, Optional
import urwid
from zulipterminal.api_types import Message
from zulipterminal.ui_tools.boxes import MessageBox
def create_msg_box_list(
model: Any,
messages: Optional[Iterable[Any]] = None,
*,
focus_msg_id: Optional[int] = None,
last_message: Optional[Message] = None,
) -> List[Any]:
"""
MessageBox for every message displayed is created here.
"""
if not model.narrow and messages is None:
messages = list(model.index["all_msg_ids"])
if messages is not None:
message_list = [model.index["messages"][id] for id in messages]
message_list.sort(key=lambda msg: msg["timestamp"])
w_list = []
focus_msg = None
last_msg = last_message
muted_msgs = 0 # No of messages that are muted.
for msg in message_list:
if is_unsubscribed_message(msg, model):
continue
# Remove messages of muted topics / streams.
if is_muted(msg, model):
muted_msgs += 1
if model.narrow == []: # Don't show in 'All messages'.
continue
msg_flag: Optional[str] = "unread"
flags = msg.get("flags")
# update_messages sends messages with no flags
# but flags are set to [] when fetching old messages.
if flags and ("read" in flags):
msg_flag = None
elif focus_msg is None:
focus_msg = message_list.index(msg) - muted_msgs
if msg["id"] == focus_msg_id:
focus_msg = message_list.index(msg) - muted_msgs
w_list.append(
urwid.AttrMap(MessageBox(msg, model, last_msg), msg_flag, "msg_selected")
)
last_msg = msg
if focus_msg is not None:
model.set_focus_in_current_narrow(focus_msg)
return w_list
def is_muted(msg: Message, model: Any) -> bool:
# PMs cannot be muted
if msg["type"] == "private":
return False
# In a topic narrow
elif len(model.narrow) == 2:
return False
elif model.is_muted_stream(msg["stream_id"]):
return True
elif model.is_muted_topic(msg["stream_id"], msg["subject"]):
return True
return False
def is_unsubscribed_message(msg: Message, model: Any) -> bool:
if msg["type"] == "private":
return False
if not model.is_user_subscribed_to_stream(msg["stream_id"]):
return True
return False | zulip-term | /zulip_term-0.7.0-py3-none-any.whl/zulipterminal/ui_tools/utils.py | utils.py |
#### Dependencies
The [Zulip API](https://zulip.com/api) Python bindings require the
following dependencies:
* **Python (version >= 3.6)**
* requests (version >= 0.12.1)
**Note**: If you'd like to use the Zulip bindings with Python 2, we
recommend installing version 0.6.4.
#### Installing
This package uses setuptools, so you can just run:
python setup.py install
#### Using the API
For now, the only fully supported API operation is sending a message.
The other API queries work, but are under active development, so
please make sure we know you're using them so that we can notify you
as we make any changes to them.
The easiest way to use these API bindings is to base your tools off
of the example tools under zulip/examples/ in this distribution.
If you place your API key in the config file `~/.zuliprc` the Python
API bindings will automatically read it in. The format of the config
file is as follows:
[api]
key=<api key from the web interface>
email=<your email address>
site=<your Zulip server's URI>
insecure=<true or false, true means do not verify the server certificate>
cert_bundle=<path to a file containing CA or server certificates to trust>
If omitted, these settings have the following defaults:
insecure=false
cert_bundle=<the default CA bundle trusted by Python>
Alternatively, you may explicitly use "--user", "--api-key", and
`--site` in our examples, which is especially useful when testing. If
you are running several bots which share a home directory, we
recommend using `--config` to specify the path to the `zuliprc` file
for a specific bot. Finally, you can control the defaults for all of
these variables using the environment variables `ZULIP_CONFIG`,
`ZULIP_API_KEY`, `ZULIP_EMAIL`, `ZULIP_SITE`, `ZULIP_CERT`,
`ZULIP_CERT_KEY`, and `ZULIP_CERT_BUNDLE`. Command-line options take
precedence over environment variables take precedence over the config
files.
The command line equivalents for other configuration options are:
--insecure
--cert-bundle=<file>
You can obtain your Zulip API key, create bots, and manage bots all
from your Zulip settings page; with current Zulip there's also a
button to download a `zuliprc` file for your account/server pair.
A typical simple bot sending API messages will look as follows:
At the top of the file:
# Make sure the Zulip API distribution's root directory is in sys.path, then:
import zulip
zulip_client = zulip.Client(email="[email protected]", client="MyTestClient/0.1")
When you want to send a message:
message = {
"type": "stream",
"to": ["support"],
"subject": "your subject",
"content": "your content",
}
zulip_client.send_message(message)
If you are parsing arguments, you may find it useful to use Zulip's
option group; see any of our API examples for details on how to do this.
Additional examples:
client.send_message({'type': 'stream', 'content': 'Zulip rules!',
'subject': 'feedback', 'to': ['support']})
client.send_message({'type': 'private', 'content': 'Zulip rules!',
'to': ['[email protected]', '[email protected]']})
send_message() returns a dict guaranteed to contain the following
keys: msg, result. For successful calls, result will be "success" and
msg will be the empty string. On error, result will be "error" and
msg will describe what went wrong.
#### Examples
The API bindings package comes with several nice example scripts that
show how to use the APIs; they are installed as part of the API
bindings bundle.
#### Logging
The Zulip API comes with a ZulipStream class which can be used with the
logging module:
```
import zulip
import logging
stream = zulip.ZulipStream(type="stream", to=["support"], subject="your subject")
logger = logging.getLogger("your_logger")
logger.addHandler(logging.StreamHandler(stream))
logger.setLevel(logging.DEBUG)
logger.info("This is an INFO test.")
logger.debug("This is a DEBUG test.")
logger.warn("This is a WARN test.")
logger.error("This is a ERROR test.")
```
#### Sending messages
You can use the included `zulip-send` script to send messages via the
API directly from existing scripts.
zulip-send [email protected] [email protected] -m \
"Conscience doth make cowards of us all."
Alternatively, if you don't want to use your ~/.zuliprc file:
zulip-send --user [email protected] \
--api-key a0b1c2d3e4f5a6b7c8d9e0f1a2b3c4d5 \
--site https://zulip.example.com \
[email protected] [email protected] -m \
"Conscience doth make cowards of us all."
#### Working with an untrusted server certificate
If your server has either a self-signed certificate, or a certificate signed
by a CA that you don't wish to globally trust then by default the API will
fail with an SSL verification error.
You can add `insecure=true` to your .zuliprc file.
[api]
site=https://zulip.example.com
insecure=true
This disables verification of the server certificate, so connections are
encrypted but unauthenticated. This is not secure, but may be good enough
for a development environment.
You can explicitly trust the server certificate using `cert_bundle=<filename>`
in your .zuliprc file.
[api]
site=https://zulip.example.com
cert_bundle=/home/bots/certs/zulip.example.com.crt
You can also explicitly trust a different set of Certificate Authorities from
the default bundle that is trusted by Python. For example to trust a company
internal CA.
[api]
site=https://zulip.example.com
cert_bundle=/home/bots/certs/example.com.ca-bundle
Save the server certificate (or the CA certificate) in its own file,
converting to PEM format first if necessary.
Verify that the certificate you have saved is the same as the one on the
server.
The `cert_bundle` option trusts the server / CA certificate only for
interaction with the zulip site, and is relatively secure.
Note that a certificate bundle is merely one or more certificates combined
into a single file.
| zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/README.md | README.md |
# Inter-realm bot
Let `realm_1` be the first realm, `realm_2` be the second realm. Let `bot_1` be
the relay bot in `realm_1`, `bot_2` be the relay bot in `realm_2`.
This bot relays each message received at a specified topic in a specified
stream from `realm_1` to a specified topic in a specified stream in `realm_2`.
Steps to create an inter-realm bridge:
1. Register a generic bot (`bot_1`) in `realm_1`
2. Enter the api info of `bot_1` into the config file (interrealm_bridge_config.py)
3. Create a stream in `realm_1` (`stream_1`) and a topic for the bridge
4. Make sure `bot_1` is subscribed to `stream_1`
5. Enter the stream and the topic into the config file.
6. Do step 1-5 but for `bot_2` and with all occurrences of `_1` replaced with `_2`
7. Run the script `run-interrealm-bridge`
If the `--stream` flag is added (i.e. `run-interrealm-bridge --stream`), then
the mirroring granularity becomes stream-wide. Instead of one topic, all
topics within the stream are mirrored as-is without translation.
| zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/bridge_between_zulips/README.md | README.md |
import argparse
import configparser
import logging
import os
import re
import signal
import sys
import traceback
from collections import OrderedDict
from types import FrameType
from typing import Any, Callable, Dict, Optional
from matrix_client.client import MatrixClient
from matrix_client.errors import MatrixRequestError
from requests.exceptions import MissingSchema
import zulip
GENERAL_NETWORK_USERNAME_REGEX = "@_?[a-zA-Z0-9]+_([a-zA-Z0-9-_]+):[a-zA-Z0-9.]+"
MATRIX_USERNAME_REGEX = "@([a-zA-Z0-9-_]+):matrix.org"
# change these templates to change the format of displayed message
ZULIP_MESSAGE_TEMPLATE = "**{username}**: {message}"
MATRIX_MESSAGE_TEMPLATE = "<{username}> {message}"
class Bridge_ConfigException(Exception):
pass
class Bridge_FatalMatrixException(Exception):
pass
class Bridge_ZulipFatalException(Exception):
pass
def matrix_login(matrix_client: Any, matrix_config: Dict[str, Any]) -> None:
try:
matrix_client.login_with_password(matrix_config["mxid"], matrix_config["password"])
except MatrixRequestError as exception:
if exception.code == 403:
raise Bridge_FatalMatrixException("Bad mxid or password.")
else:
raise Bridge_FatalMatrixException("Check if your server details are correct.")
except MissingSchema:
raise Bridge_FatalMatrixException("Bad URL format.")
def matrix_join_room(matrix_client: Any, matrix_config: Dict[str, Any]) -> Any:
try:
room = matrix_client.join_room(matrix_config["room_id"])
return room
except MatrixRequestError as exception:
if exception.code == 403:
raise Bridge_FatalMatrixException("Room ID/Alias in the wrong format")
else:
raise Bridge_FatalMatrixException("Couldn't find room.")
def die(signal: int, frame: FrameType) -> None:
# We actually want to exit, so run os._exit (so as not to be caught and restarted)
os._exit(1)
def matrix_to_zulip(
zulip_client: zulip.Client,
zulip_config: Dict[str, Any],
matrix_config: Dict[str, Any],
no_noise: bool,
) -> Callable[[Any, Dict[str, Any]], None]:
def _matrix_to_zulip(room: Any, event: Dict[str, Any]) -> None:
"""
Matrix -> Zulip
"""
content = get_message_content_from_event(event, no_noise)
zulip_bot_user = matrix_config["mxid"]
# We do this to identify the messages generated from Zulip -> Matrix
# and we make sure we don't forward it again to the Zulip stream.
not_from_zulip_bot = event["sender"] != zulip_bot_user
if not_from_zulip_bot and content:
try:
result = zulip_client.send_message(
{
"type": "stream",
"to": zulip_config["stream"],
"subject": zulip_config["topic"],
"content": content,
}
)
except Exception as exception: # XXX This should be more specific
# Generally raised when user is forbidden
raise Bridge_ZulipFatalException(exception)
if result["result"] != "success":
# Generally raised when API key is invalid
raise Bridge_ZulipFatalException(result["msg"])
return _matrix_to_zulip
def get_message_content_from_event(event: Dict[str, Any], no_noise: bool) -> Optional[str]:
irc_nick = shorten_irc_nick(event["sender"])
if event["type"] == "m.room.member":
if no_noise:
return None
# Join and leave events can be noisy. They are ignored by default.
# To enable these events pass `no_noise` as `False` as the script argument
if event["membership"] == "join":
content = ZULIP_MESSAGE_TEMPLATE.format(username=irc_nick, message="joined")
elif event["membership"] == "leave":
content = ZULIP_MESSAGE_TEMPLATE.format(username=irc_nick, message="quit")
elif event["type"] == "m.room.message":
if event["content"]["msgtype"] == "m.text" or event["content"]["msgtype"] == "m.emote":
content = ZULIP_MESSAGE_TEMPLATE.format(
username=irc_nick, message=event["content"]["body"]
)
else:
content = event["type"]
return content
def shorten_irc_nick(nick: str) -> str:
"""
Add nick shortner functions for specific IRC networks
Eg: For freenode change '@freenode_user:matrix.org' to 'user'
Check the list of IRC networks here:
https://github.com/matrix-org/matrix-appservice-irc/wiki/Bridged-IRC-networks
"""
match = re.match(GENERAL_NETWORK_USERNAME_REGEX, nick)
if match:
return match.group(1)
# For matrix users
match = re.match(MATRIX_USERNAME_REGEX, nick)
if match:
return match.group(1)
return nick
def zulip_to_matrix(config: Dict[str, Any], room: Any) -> Callable[[Dict[str, Any]], None]:
def _zulip_to_matrix(msg: Dict[str, Any]) -> None:
"""
Zulip -> Matrix
"""
message_valid = check_zulip_message_validity(msg, config)
if message_valid:
matrix_username = msg["sender_full_name"].replace(" ", "")
matrix_text = MATRIX_MESSAGE_TEMPLATE.format(
username=matrix_username, message=msg["content"]
)
# Forward Zulip message to Matrix
room.send_text(matrix_text)
return _zulip_to_matrix
def check_zulip_message_validity(msg: Dict[str, Any], config: Dict[str, Any]) -> bool:
is_a_stream = msg["type"] == "stream"
in_the_specified_stream = msg["display_recipient"] == config["stream"]
at_the_specified_subject = msg["subject"] == config["topic"]
# We do this to identify the messages generated from Matrix -> Zulip
# and we make sure we don't forward it again to the Matrix.
not_from_zulip_bot = msg["sender_email"] != config["email"]
if is_a_stream and not_from_zulip_bot and in_the_specified_stream and at_the_specified_subject:
return True
return False
def generate_parser() -> argparse.ArgumentParser:
description = """
Script to bridge between a topic in a Zulip stream, and a Matrix channel.
Tested connections:
* Zulip <-> Matrix channel
* Zulip <-> IRC channel (bridged via Matrix)
Example matrix 'room_id' options might be, if via matrix.org:
* #zulip:matrix.org (zulip channel on Matrix)
* #freenode_#zulip:matrix.org (zulip channel on irc.freenode.net)"""
parser = argparse.ArgumentParser(
description=description, formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
"-c", "--config", required=False, help="Path to the config file for the bridge."
)
parser.add_argument(
"--write-sample-config",
metavar="PATH",
dest="sample_config",
help="Generate a configuration template at the specified location.",
)
parser.add_argument(
"--from-zuliprc",
metavar="ZULIPRC",
dest="zuliprc",
help="Optional path to zuliprc file for bot, when using --write-sample-config",
)
parser.add_argument(
"--show-join-leave",
dest="no_noise",
default=True,
action="store_false",
help="Enable IRC join/leave events.",
)
return parser
def read_configuration(config_file: str) -> Dict[str, Dict[str, str]]:
config = configparser.ConfigParser()
try:
config.read(config_file)
except configparser.Error as exception:
raise Bridge_ConfigException(str(exception))
if set(config.sections()) != {"matrix", "zulip"}:
raise Bridge_ConfigException("Please ensure the configuration has zulip & matrix sections.")
# TODO Could add more checks for configuration content here
return {section: dict(config[section]) for section in config.sections()}
def write_sample_config(target_path: str, zuliprc: Optional[str]) -> None:
if os.path.exists(target_path):
raise Bridge_ConfigException(f"Path '{target_path}' exists; not overwriting existing file.")
sample_dict = OrderedDict(
(
(
"matrix",
OrderedDict(
(
("host", "https://matrix.org"),
("mxid", "@username:matrix.org"),
("password", "password"),
("room_id", "#zulip:matrix.org"),
)
),
),
(
"zulip",
OrderedDict(
(
("email", "[email protected]"),
("api_key", "aPiKeY"),
("site", "https://chat.zulip.org"),
("stream", "test here"),
("topic", "matrix"),
)
),
),
)
)
if zuliprc is not None:
if not os.path.exists(zuliprc):
raise Bridge_ConfigException(f"Zuliprc file '{zuliprc}' does not exist.")
zuliprc_config = configparser.ConfigParser()
try:
zuliprc_config.read(zuliprc)
except configparser.Error as exception:
raise Bridge_ConfigException(str(exception))
# Can add more checks for validity of zuliprc file here
sample_dict["zulip"]["email"] = zuliprc_config["api"]["email"]
sample_dict["zulip"]["site"] = zuliprc_config["api"]["site"]
sample_dict["zulip"]["api_key"] = zuliprc_config["api"]["key"]
sample = configparser.ConfigParser()
sample.read_dict(sample_dict)
with open(target_path, "w") as target:
sample.write(target)
def main() -> None:
signal.signal(signal.SIGINT, die)
logging.basicConfig(level=logging.WARNING)
parser = generate_parser()
options = parser.parse_args()
if options.sample_config:
try:
write_sample_config(options.sample_config, options.zuliprc)
except Bridge_ConfigException as exception:
print(f"Could not write sample config: {exception}")
sys.exit(1)
if options.zuliprc is None:
print(f"Wrote sample configuration to '{options.sample_config}'")
else:
print(
"Wrote sample configuration to '{}' using zuliprc file '{}'".format(
options.sample_config, options.zuliprc
)
)
sys.exit(0)
elif not options.config:
print("Options required: -c or --config to run, OR --write-sample-config.")
parser.print_usage()
sys.exit(1)
try:
config = read_configuration(options.config)
except Bridge_ConfigException as exception:
print(f"Could not parse config file: {exception}")
sys.exit(1)
# Get config for each client
zulip_config = config["zulip"]
matrix_config = config["matrix"]
# Initiate clients
backoff = zulip.RandomExponentialBackoff(timeout_success_equivalent=300)
while backoff.keep_going():
print("Starting matrix mirroring bot (this may take a minute)")
try:
zulip_client = zulip.Client(
email=zulip_config["email"],
api_key=zulip_config["api_key"],
site=zulip_config["site"],
)
matrix_client = MatrixClient(matrix_config["host"])
# Login to Matrix
matrix_login(matrix_client, matrix_config)
# Join a room in Matrix
room = matrix_join_room(matrix_client, matrix_config)
room.add_listener(
matrix_to_zulip(zulip_client, zulip_config, matrix_config, options.no_noise)
)
print("Starting listener thread on Matrix client")
matrix_client.start_listener_thread()
print("Starting message handler on Zulip client")
zulip_client.call_on_each_message(zulip_to_matrix(zulip_config, room))
except Bridge_FatalMatrixException as exception:
sys.exit(f"Matrix bridge error: {exception}")
except Bridge_ZulipFatalException as exception:
sys.exit(f"Zulip bridge error: {exception}")
except zulip.ZulipError as exception:
sys.exit(f"Zulip error: {exception}")
except Exception:
traceback.print_exc()
backoff.fail()
if __name__ == "__main__":
main() | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/bridge_with_matrix/matrix_bridge.py | matrix_bridge.py |
# Matrix <--> Zulip bridge
This acts as a bridge between Matrix and Zulip. It also enables a
Zulip topic to be federated between two Zulip servers.
## Usage
### For IRC bridges
Matrix has been bridged to the listed
[IRC networks](https://github.com/matrix-org/matrix-appservice-irc/wiki/Bridged-IRC-networks),
where the 'Room alias format' refers to the `room_id` for the corresponding IRC channel.
For example, for the freenode channel `#zulip-test`, the `room_id` would be
`#freenode_#zulip-test:matrix.org`.
Hence, this can also be used as a IRC <--> Zulip bridge.
## Steps to configure the Matrix bridge
To obtain a configuration file template, run the script with the
`--write-sample-config` option to obtain a configuration file to fill in the
details mentioned below. For example:
* If you installed the `zulip` package: `zulip-matrix-bridge --write-sample-config matrix_bridge.conf`
* If you are running from the Zulip GitHub repo: `python matrix_bridge.py --write-sample-config matrix_bridge.conf`
### 1. Zulip endpoint
1. Create a generic Zulip bot, with a full name like `IRC Bot` or `Matrix Bot`.
2. Subscribe the bot user to the stream you'd like to bridge your IRC or Matrix
channel into.
3. In the `zulip` section of the configuration file, enter the bot's `zuliprc`
details (`email`, `api_key`, and `site`).
4. In the same section, also enter the Zulip `stream` and `topic`.
### 2. Matrix endpoint
1. Create a user on [matrix.org](https://matrix.org/), preferably with
a formal name like to `zulip-bot`.
2. In the `matrix` section of the configuration file, enter the user's username
and password.
3. Also enter the `host` and `room_id` into the same section.
## Running the bridge
After the steps above have been completed, assuming you have the configuration
in a file called `matrix_bridge.conf`:
* If you installed the `zulip` package: run `zulip-matrix-bridge -c matrix_bridge.conf`
* If you are running from the Zulip GitHub repo: run `python matrix_bridge.py -c matrix_bridge.conf`
## Caveats for IRC mirroring
There are certain
[IRC channels](https://github.com/matrix-org/matrix-appservice-irc/wiki/Channels-from-which-the-IRC-bridge-is-banned)
where the Matrix.org IRC bridge has been banned for technical reasons.
You can't mirror those IRC channels using this integration.
| zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/bridge_with_matrix/README.md | README.md |
import argparse
import sys
try:
import requests
except ImportError:
print("Error: Please install the python requests library before running this script:")
print("http://docs.python-requests.org/en/master/user/install/")
sys.exit(1)
def get_model_id(options):
"""get_model_id
Get Model Id from Trello API
:options: argparse.Namespace arguments
:returns: str id_model Trello board idModel
"""
trello_api_url = f"https://api.trello.com/1/board/{options.trello_board_id}"
params = {
"key": options.trello_api_key,
"token": options.trello_token,
}
trello_response = requests.get(trello_api_url, params=params)
if trello_response.status_code != 200:
print("Error: Can't get the idModel. Please check the configuration")
sys.exit(1)
board_info_json = trello_response.json()
return board_info_json["id"]
def get_webhook_id(options, id_model):
"""get_webhook_id
Get webhook id from Trello API
:options: argparse.Namespace arguments
:id_model: str Trello board idModel
:returns: str id_webhook Trello webhook id
"""
trello_api_url = "https://api.trello.com/1/webhooks/"
data = {
"key": options.trello_api_key,
"token": options.trello_token,
"description": "Webhook for Zulip integration (From Trello {} to Zulip)".format(
options.trello_board_name,
),
"callbackURL": options.zulip_webhook_url,
"idModel": id_model,
}
trello_response = requests.post(trello_api_url, data=data)
if trello_response.status_code != 200:
print("Error: Can't create the Webhook:", trello_response.text)
sys.exit(1)
webhook_info_json = trello_response.json()
return webhook_info_json["id"]
def create_webhook(options):
"""create_webhook
Create Trello webhook
:options: argparse.Namespace arguments
"""
# first, we need to get the idModel
print(f"Getting Trello idModel for the {options.trello_board_name} board...")
id_model = get_model_id(options)
if id_model:
print("Success! The idModel is", id_model)
id_webhook = get_webhook_id(options, id_model)
if id_webhook:
print("Success! The webhook ID is", id_webhook)
print(
"Success! The webhook for the {} Trello board was successfully created.".format(
options.trello_board_name
)
)
def main():
description = """
zulip_trello.py is a handy little script that allows Zulip users to
quickly set up a Trello webhook.
Note: The Trello webhook instructions available on your Zulip server
may be outdated. Please make sure you follow the updated instructions
at <https://zulip.com/integrations/doc/trello>.
"""
parser = argparse.ArgumentParser(description=description)
parser.add_argument("--trello-board-name", required=True, help="The Trello board name.")
parser.add_argument(
"--trello-board-id",
required=True,
help=("The Trello board short ID. Can usually be found " "in the URL of the Trello board."),
)
parser.add_argument(
"--trello-api-key",
required=True,
help=(
"Visit https://trello.com/1/appkey/generate to generate "
"an APPLICATION_KEY (need to be logged into Trello)."
),
)
parser.add_argument(
"--trello-token",
required=True,
help=(
"Visit https://trello.com/1/appkey/generate and under "
"`Developer API Keys`, click on `Token` and generate "
"a Trello access token."
),
)
parser.add_argument(
"--zulip-webhook-url", required=True, help="The webhook URL that Trello will query."
)
options = parser.parse_args()
create_webhook(options)
if __name__ == "__main__":
main() | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/trello/zulip_trello.py | zulip_trello.py |
# A script that automates setting up a webhook with Trello
Usage :
1. Make sure you have all of the relevant Trello credentials before
executing the script:
- The Trello API KEY
- The Trello TOKEN
- The Zulip webhook URL
- Trello board name
- Trello board ID
2. Execute the script :
$ python zulip_trello.py --trello-board-name <trello_board_name> \
--trello-board-id <trello_board_id> \
--trello-api-key <trello_api_key> \
--trello-token <trello_token> \
--zulip-webhook-url <zulip_webhook_url>
For more information, please see Zulip's documentation on how to set up
a Trello integration [here](https://zulip.com/integrations/doc/trello).
| zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/trello/README.md | README.md |
import hashlib
import json
import logging
import optparse
import os
import re
import select
import signal
import subprocess
import sys
import tempfile
import textwrap
import time
from types import FrameType
from typing import IO, Any, Dict, List, NoReturn, Optional, Set, Tuple, Union
from typing_extensions import Literal, TypedDict
from zulip import RandomExponentialBackoff
DEFAULT_SITE = "https://api.zulip.com"
class States:
Startup, ZulipToZephyr, ZephyrToZulip, ChildSending = list(range(4))
CURRENT_STATE = States.Startup
logger: logging.Logger
def to_zulip_username(zephyr_username: str) -> str:
if "@" in zephyr_username:
(user, realm) = zephyr_username.split("@")
else:
(user, realm) = (zephyr_username, "ATHENA.MIT.EDU")
if realm.upper() == "ATHENA.MIT.EDU":
# Hack to make ctl's fake username setup work :)
if user.lower() == "golem":
user = "ctl"
return user.lower() + "@mit.edu"
return user.lower() + "|" + realm.upper() + "@mit.edu"
def to_zephyr_username(zulip_username: str) -> str:
(user, realm) = zulip_username.split("@")
if "|" not in user:
# Hack to make ctl's fake username setup work :)
if user.lower() == "ctl":
user = "golem"
return user.lower() + "@ATHENA.MIT.EDU"
match_user = re.match(r"([a-zA-Z0-9_]+)\|(.+)", user)
if not match_user:
raise Exception(f"Could not parse Zephyr realm for cross-realm user {zulip_username}")
return match_user.group(1).lower() + "@" + match_user.group(2).upper()
# Checks whether the pair of adjacent lines would have been
# linewrapped together, had they been intended to be parts of the same
# paragraph. Our check is whether if you move the first word on the
# 2nd line onto the first line, the resulting line is either (1)
# significantly shorter than the following line (which, if they were
# in the same paragraph, should have been wrapped in a way consistent
# with how the previous line was wrapped) or (2) shorter than 60
# characters (our assumed minimum linewrapping threshold for Zephyr)
# or (3) the first word of the next line is longer than this entire
# line.
def different_paragraph(line: str, next_line: str) -> bool:
words = next_line.split()
return (
len(line + " " + words[0]) < len(next_line) * 0.8
or len(line + " " + words[0]) < 50
or len(line) < len(words[0])
)
# Linewrapping algorithm based on:
# http://gcbenison.wordpress.com/2011/07/03/a-program-to-intelligently-remove-carriage-returns-so-you-can-paste-text-without-having-it-look-awful/ #ignorelongline
def unwrap_lines(body: str) -> str:
lines = body.split("\n")
result = ""
previous_line = lines[0]
for line in lines[1:]:
line = line.rstrip()
if re.match(r"^\W", line, flags=re.UNICODE) and re.match(
r"^\W", previous_line, flags=re.UNICODE
):
result += previous_line + "\n"
elif (
line == ""
or previous_line == ""
or re.match(r"^\W", line, flags=re.UNICODE)
or different_paragraph(previous_line, line)
):
# Use 2 newlines to separate sections so that we
# trigger proper Markdown processing on things like
# bulleted lists
result += previous_line + "\n\n"
else:
result += previous_line + " "
previous_line = line
result += previous_line
return result
class ZephyrDict(TypedDict, total=False):
type: Literal["private", "stream"]
time: str
sender: str
stream: str
subject: str
recipient: Union[str, List[str]]
content: str
zsig: str
def send_zulip(zeph: ZephyrDict) -> Dict[str, Any]:
message: Dict[str, Any]
message = {}
if options.forward_class_messages:
message["forged"] = "yes"
message["type"] = zeph["type"]
message["time"] = zeph["time"]
message["sender"] = to_zulip_username(zeph["sender"])
if "subject" in zeph:
# Truncate the subject to the current limit in Zulip. No
# need to do this for stream names, since we're only
# subscribed to valid stream names.
message["subject"] = zeph["subject"][:60]
if zeph["type"] == "stream":
# Forward messages sent to -c foo -i bar to stream bar subject "instance"
if zeph["stream"] == "message":
message["to"] = zeph["subject"].lower()
message["subject"] = "instance {}".format(zeph["subject"])
elif zeph["stream"] == "tabbott-test5":
message["to"] = zeph["subject"].lower()
message["subject"] = "test instance {}".format(zeph["subject"])
else:
message["to"] = zeph["stream"]
else:
message["to"] = zeph["recipient"]
message["content"] = unwrap_lines(zeph["content"])
if options.test_mode and options.site == DEFAULT_SITE:
logger.debug(f"Message is: {str(message)}")
return {"result": "success"}
return zulip_client.send_message(message)
def send_error_zulip(error_msg: str) -> None:
message = {
"type": "private",
"sender": zulip_account_email,
"to": zulip_account_email,
"content": error_msg,
}
zulip_client.send_message(message)
current_zephyr_subs = set()
def zephyr_bulk_subscribe(subs: List[Tuple[str, str, str]]) -> None:
try:
zephyr._z.subAll(subs)
except OSError:
# Since we haven't added the subscription to
# current_zephyr_subs yet, we can just return (so that we'll
# continue processing normal messages) and we'll end up
# retrying the next time the bot checks its subscriptions are
# up to date.
logger.exception("Error subscribing to streams (will retry automatically):")
logger.warning(f"Streams were: {[cls for cls, instance, recipient in subs]}")
return
try:
actual_zephyr_subs = [cls for (cls, _, _) in zephyr._z.getSubscriptions()]
except OSError:
logger.exception("Error getting current Zephyr subscriptions")
# Don't add anything to current_zephyr_subs so that we'll
# retry the next time we check for streams to subscribe to
# (within 15 seconds).
return
for (cls, instance, recipient) in subs:
if cls not in actual_zephyr_subs:
logger.error(f"Zephyr failed to subscribe us to {cls}; will retry")
try:
# We'll retry automatically when we next check for
# streams to subscribe to (within 15 seconds), but
# it's worth doing 1 retry immediately to avoid
# missing 15 seconds of messages on the affected
# classes
zephyr._z.sub(cls, instance, recipient)
except OSError:
pass
else:
current_zephyr_subs.add(cls)
def update_subscriptions() -> None:
try:
f = open(options.stream_file_path)
public_streams: List[str] = json.loads(f.read())
f.close()
except Exception:
logger.exception("Error reading public streams:")
return
classes_to_subscribe = set()
for stream in public_streams:
zephyr_class = stream
if options.shard is not None and not hashlib.sha1(
zephyr_class.encode("utf-8")
).hexdigest().startswith(options.shard):
# This stream is being handled by a different zephyr_mirror job.
continue
if zephyr_class in current_zephyr_subs:
continue
classes_to_subscribe.add((zephyr_class, "*", "*"))
if len(classes_to_subscribe) > 0:
zephyr_bulk_subscribe(list(classes_to_subscribe))
def maybe_kill_child() -> None:
try:
if child_pid is not None:
os.kill(child_pid, signal.SIGTERM)
except OSError:
# We don't care if the child process no longer exists, so just log the error
logger.exception("")
def maybe_restart_mirroring_script() -> None:
if os.stat(
os.path.join(options.stamp_path, "stamps", "restart_stamp")
).st_mtime > start_time or (
(options.user == "tabbott" or options.user == "tabbott/extra")
and os.stat(os.path.join(options.stamp_path, "stamps", "tabbott_stamp")).st_mtime
> start_time
):
logger.warning("")
logger.warning("zephyr mirroring script has been updated; restarting...")
maybe_kill_child()
try:
zephyr._z.cancelSubs()
except OSError:
# We don't care whether we failed to cancel subs properly, but we should log it
logger.exception("")
backoff = RandomExponentialBackoff(
maximum_retries=3,
)
while backoff.keep_going():
try:
os.execvp(os.path.abspath(__file__), sys.argv)
# No need for backoff.succeed, since this can't be reached
except Exception:
logger.exception("Error restarting mirroring script; trying again... Traceback:")
backoff.fail()
raise Exception("Failed to reload too many times, aborting!")
def process_loop(log: Optional[IO[str]]) -> NoReturn:
restart_check_count = 0
last_check_time = time.time()
recieve_backoff = RandomExponentialBackoff()
while True:
select.select([zephyr._z.getFD()], [], [], 15)
try:
process_backoff = RandomExponentialBackoff()
# Fetch notices from the queue until its empty
while True:
notice = zephyr.receive(block=False)
recieve_backoff.succeed()
if notice is None:
break
try:
process_notice(notice, log)
process_backoff.succeed()
except Exception:
logger.exception("Error relaying zephyr:")
process_backoff.fail()
except Exception:
logger.exception("Error checking for new zephyrs:")
recieve_backoff.fail()
continue
if time.time() - last_check_time > 15:
last_check_time = time.time()
try:
maybe_restart_mirroring_script()
if restart_check_count > 0:
logger.info("Stopped getting errors checking whether restart is required.")
restart_check_count = 0
except Exception:
if restart_check_count < 5:
logger.exception("Error checking whether restart is required:")
restart_check_count += 1
if options.forward_class_messages:
try:
update_subscriptions()
except Exception:
logger.exception("Error updating subscriptions from Zulip:")
def parse_zephyr_body(zephyr_data: str, notice_format: str) -> Tuple[str, str]:
try:
(zsig, body) = zephyr_data.split("\x00", 1)
if (
notice_format == "New transaction [$1] entered in $2\nFrom: $3 ($5)\nSubject: $4"
or notice_format == "New transaction [$1] entered in $2\nFrom: $3\nSubject: $4"
):
# Logic based off of owl_zephyr_get_message in barnowl
fields = body.split("\x00")
if len(fields) == 5:
body = "New transaction [{}] entered in {}\nFrom: {} ({})\nSubject: {}".format(
fields[0],
fields[1],
fields[2],
fields[4],
fields[3],
)
except ValueError:
(zsig, body) = ("", zephyr_data)
# Clean body of any null characters, since they're invalid in our protocol.
body = body.replace("\x00", "")
return (zsig, body)
def parse_crypt_table(zephyr_class: str, instance: str) -> Optional[str]:
try:
crypt_table = open(os.path.join(os.environ["HOME"], ".crypt-table"))
except OSError:
return None
for line in crypt_table.readlines():
if line.strip() == "":
# Ignore blank lines
continue
match = re.match(
r"^crypt-(?P<class>\S+):\s+((?P<algorithm>(AES|DES)):\s+)?(?P<keypath>\S+)$", line
)
if match is None:
# Malformed crypt_table line
logger.debug("Invalid crypt_table line!")
continue
groups = match.groupdict()
if (
groups["class"].lower() == zephyr_class
and "keypath" in groups
and groups.get("algorithm") == "AES"
):
return groups["keypath"]
return None
def decrypt_zephyr(zephyr_class: str, instance: str, body: str) -> str:
keypath = parse_crypt_table(zephyr_class, instance)
if keypath is None:
# We can't decrypt it, so we just return the original body
return body
# Enable handling SIGCHLD briefly while we call into
# subprocess to avoid http://bugs.python.org/issue9127
signal.signal(signal.SIGCHLD, signal.SIG_DFL)
# decrypt the message!
p = subprocess.Popen(
[
"gpg",
"--decrypt",
"--no-options",
"--no-default-keyring",
"--keyring=/dev/null",
"--secret-keyring=/dev/null",
"--batch",
"--quiet",
"--no-use-agent",
"--passphrase-file",
keypath,
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
errors="replace",
)
decrypted, _ = p.communicate(input=body)
# Restore our ignoring signals
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
return decrypted
def process_notice(notice: "zephyr.ZNotice", log: Optional[IO[str]]) -> None:
assert notice.sender is not None
(zsig, body) = parse_zephyr_body(notice.message, notice.format)
is_personal = False
is_huddle = False
if notice.opcode == "PING":
# skip PING messages
return
zephyr_class = notice.cls.lower()
if zephyr_class == options.nagios_class:
# Mark that we got the message and proceed
with open(options.nagios_path, "w") as f:
f.write("0\n")
return
if notice.recipient != "":
is_personal = True
# Drop messages not to the listed subscriptions
if is_personal and not options.forward_personals:
return
if (zephyr_class not in current_zephyr_subs) and not is_personal:
logger.debug(f"Skipping ... {zephyr_class}/{notice.instance}/{is_personal}")
return
if notice.format.startswith("Zephyr error: See") or notice.format.endswith("@(@color(blue))"):
logger.debug("Skipping message we got from Zulip!")
return
if (
zephyr_class == "mail"
and notice.instance.lower() == "inbox"
and is_personal
and not options.forward_mail_zephyrs
):
# Only forward mail zephyrs if forwarding them is enabled.
return
if is_personal:
if body.startswith("CC:"):
is_huddle = True
# Map "CC: user1 user2" => "[email protected], [email protected]"
huddle_recipients = [
to_zulip_username(x.strip()) for x in body.split("\n")[0][4:].split()
]
if notice.sender not in huddle_recipients:
huddle_recipients.append(to_zulip_username(notice.sender))
body = body.split("\n", 1)[1]
if (
options.forward_class_messages
and notice.opcode is not None
and notice.opcode.lower() == "crypt"
):
body = decrypt_zephyr(zephyr_class, notice.instance.lower(), body)
zeph: ZephyrDict
zeph = {
"time": str(notice.time),
"sender": notice.sender,
"zsig": zsig, # logged here but not used by app
"content": body,
}
if is_huddle:
zeph["type"] = "private"
zeph["recipient"] = huddle_recipients
elif is_personal:
assert notice.recipient is not None
zeph["type"] = "private"
zeph["recipient"] = to_zulip_username(notice.recipient)
else:
zeph["type"] = "stream"
zeph["stream"] = zephyr_class
if notice.instance.strip() != "":
zeph["subject"] = notice.instance
else:
zeph["subject"] = f'(instance "{notice.instance}")'
# Add instances in for instanced personals
if is_personal:
if notice.cls.lower() != "message" and notice.instance.lower() != "personal":
heading = f"[-c {notice.cls} -i {notice.instance}]\n"
elif notice.cls.lower() != "message":
heading = f"[-c {notice.cls}]\n"
elif notice.instance.lower() != "personal":
heading = f"[-i {notice.instance}]\n"
else:
heading = ""
zeph["content"] = heading + zeph["content"]
logger.info(f"Received a message on {zephyr_class}/{notice.instance} from {notice.sender}...")
if log is not None:
log.write(json.dumps(zeph) + "\n")
log.flush()
if os.fork() == 0:
global CURRENT_STATE
CURRENT_STATE = States.ChildSending
# Actually send the message in a child process, to avoid blocking.
try:
res = send_zulip(zeph)
if res.get("result") != "success":
logger.error(f"Error relaying zephyr:\n{zeph}\n{res}")
except Exception:
logger.exception("Error relaying zephyr:")
finally:
os._exit(0)
def quit_failed_initialization(message: str) -> str:
logger.error(message)
maybe_kill_child()
sys.exit(1)
def zephyr_init_autoretry() -> None:
backoff = zulip.RandomExponentialBackoff()
while backoff.keep_going():
try:
# zephyr.init() tries to clear old subscriptions, and thus
# sometimes gets a SERVNAK from the server
zephyr.init()
backoff.succeed()
return
except OSError:
logger.exception("Error initializing Zephyr library (retrying). Traceback:")
backoff.fail()
quit_failed_initialization("Could not initialize Zephyr library, quitting!")
def zephyr_load_session_autoretry(session_path: str) -> None:
backoff = zulip.RandomExponentialBackoff()
while backoff.keep_going():
try:
with open(session_path, "rb") as f:
session = f.read()
zephyr._z.initialize()
zephyr._z.load_session(session)
zephyr.__inited = True
return
except OSError:
logger.exception("Error loading saved Zephyr session (retrying). Traceback:")
backoff.fail()
quit_failed_initialization("Could not load saved Zephyr session, quitting!")
def zephyr_subscribe_autoretry(sub: Tuple[str, str, str]) -> None:
backoff = zulip.RandomExponentialBackoff()
while backoff.keep_going():
try:
zephyr.Subscriptions().add(sub)
backoff.succeed()
return
except OSError:
# Probably a SERVNAK from the zephyr server, but log the
# traceback just in case it's something else
logger.exception("Error subscribing to personals (retrying). Traceback:")
backoff.fail()
quit_failed_initialization("Could not subscribe to personals, quitting!")
def zephyr_to_zulip(options: optparse.Values) -> None:
if options.use_sessions and os.path.exists(options.session_path):
logger.info("Loading old session")
zephyr_load_session_autoretry(options.session_path)
else:
zephyr_init_autoretry()
if options.forward_class_messages:
update_subscriptions()
if options.forward_personals:
# Subscribe to personals; we really can't operate without
# those subscriptions, so just retry until it works.
zephyr_subscribe_autoretry(("message", "*", "%me%"))
zephyr_subscribe_autoretry(("mail", "inbox", "%me%"))
if options.nagios_class:
zephyr_subscribe_autoretry((options.nagios_class, "*", "*"))
if options.use_sessions:
with open(options.session_path, "wb") as f:
f.write(zephyr._z.dump_session())
if options.logs_to_resend is not None:
with open(options.logs_to_resend) as log:
for ln in log:
try:
zeph = json.loads(ln)
# Handle importing older zephyrs in the logs
# where it isn't called a "stream" yet
if "class" in zeph:
zeph["stream"] = zeph["class"]
if "instance" in zeph:
zeph["subject"] = zeph["instance"]
logger.info(
"sending saved message to %s from %s..."
% (zeph.get("stream", zeph.get("recipient")), zeph["sender"])
)
send_zulip(zeph)
except Exception:
logger.exception("Could not send saved zephyr:")
time.sleep(2)
logger.info("Successfully initialized; Starting receive loop.")
if options.resend_log_path is not None:
with open(options.resend_log_path, "a") as log:
process_loop(log)
else:
process_loop(None)
def send_zephyr(zwrite_args: List[str], content: str) -> Tuple[int, str]:
p = subprocess.Popen(
zwrite_args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
stdout, stderr = p.communicate(input=content)
if p.returncode:
logger.error(
"zwrite command '%s' failed with return code %d:"
% (
" ".join(zwrite_args),
p.returncode,
)
)
if stdout:
logger.info("stdout: " + stdout)
elif stderr:
logger.warning(
"zwrite command '{}' printed the following warning:".format(" ".join(zwrite_args))
)
if stderr:
logger.warning("stderr: " + stderr)
return (p.returncode, stderr)
def send_authed_zephyr(zwrite_args: List[str], content: str) -> Tuple[int, str]:
return send_zephyr(zwrite_args, content)
def send_unauthed_zephyr(zwrite_args: List[str], content: str) -> Tuple[int, str]:
return send_zephyr(zwrite_args + ["-d"], content)
def zcrypt_encrypt_content(zephyr_class: str, instance: str, content: str) -> Optional[str]:
keypath = parse_crypt_table(zephyr_class, instance)
if keypath is None:
return None
# encrypt the message!
p = subprocess.Popen(
[
"gpg",
"--symmetric",
"--no-options",
"--no-default-keyring",
"--keyring=/dev/null",
"--secret-keyring=/dev/null",
"--batch",
"--quiet",
"--no-use-agent",
"--armor",
"--cipher-algo",
"AES",
"--passphrase-file",
keypath,
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
universal_newlines=True,
)
encrypted, _ = p.communicate(input=content)
return encrypted
def forward_to_zephyr(message: Dict[str, Any]) -> None:
# 'Any' can be of any type of text
support_heading = "Hi there! This is an automated message from Zulip."
support_closing = """If you have any questions, please be in touch through the \
Feedback button or at [email protected]."""
wrapper = textwrap.TextWrapper(break_long_words=False, break_on_hyphens=False)
wrapped_content = "\n".join(
"\n".join(wrapper.wrap(line)) for line in message["content"].replace("@", "@@").split("\n")
)
zwrite_args = [
"zwrite",
"-n",
"-s",
message["sender_full_name"],
"-F",
"Zephyr error: See http://zephyr.1ts.org/wiki/df",
"-x",
"UTF-8",
]
# Hack to make ctl's fake username setup work :)
if message["type"] == "stream" and zulip_account_email == "[email protected]":
zwrite_args.extend(["-S", "ctl"])
if message["type"] == "stream":
zephyr_class = message["display_recipient"]
instance = message["subject"]
match_whitespace_instance = re.match(r'^\(instance "(\s*)"\)$', instance)
if match_whitespace_instance:
# Forward messages sent to '(instance "WHITESPACE")' back to the
# appropriate WHITESPACE instance for bidirectional mirroring
instance = match_whitespace_instance.group(1)
elif instance == f"instance {zephyr_class}" or instance == "test instance {}".format(
zephyr_class,
):
# Forward messages to e.g. -c -i white-magic back from the
# place we forward them to
if instance.startswith("test"):
instance = zephyr_class
zephyr_class = "tabbott-test5"
else:
instance = zephyr_class
zephyr_class = "message"
zwrite_args.extend(["-c", zephyr_class, "-i", instance])
logger.info(f"Forwarding message to class {zephyr_class}, instance {instance}")
elif message["type"] == "private":
if len(message["display_recipient"]) == 1:
recipient = to_zephyr_username(message["display_recipient"][0]["email"])
recipients = [recipient]
elif len(message["display_recipient"]) == 2:
recipient = ""
for r in message["display_recipient"]:
if r["email"].lower() != zulip_account_email.lower():
recipient = to_zephyr_username(r["email"])
break
recipients = [recipient]
else:
zwrite_args.extend(["-C"])
# We drop the @ATHENA.MIT.EDU here because otherwise the
# "CC: user1 user2 ..." output will be unnecessarily verbose.
recipients = [
to_zephyr_username(user["email"]).replace("@ATHENA.MIT.EDU", "")
for user in message["display_recipient"]
]
logger.info(f"Forwarding message to {recipients}")
zwrite_args.extend(recipients)
if message.get("invite_only_stream"):
result = zcrypt_encrypt_content(zephyr_class, instance, wrapped_content)
if result is None:
send_error_zulip(
"""%s
Your Zulip-Zephyr mirror bot was unable to forward that last message \
from Zulip to Zephyr because you were sending to a zcrypted Zephyr \
class and your mirroring bot does not have access to the relevant \
key (perhaps because your AFS tokens expired). That means that while \
Zulip users (like you) received it, Zephyr users did not.
%s"""
% (support_heading, support_closing)
)
return
# Proceed with sending a zcrypted message
wrapped_content = result
zwrite_args.extend(["-O", "crypt"])
if options.test_mode:
logger.debug(f"Would have forwarded: {zwrite_args}\n{wrapped_content}")
return
(code, stderr) = send_authed_zephyr(zwrite_args, wrapped_content)
if code == 0 and stderr == "":
return
elif code == 0:
send_error_zulip(
"""%s
Your last message was successfully mirrored to zephyr, but zwrite \
returned the following warning:
%s
%s"""
% (support_heading, stderr, support_closing)
)
return
elif code != 0 and (
stderr.startswith("zwrite: Ticket expired while sending notice to ")
or stderr.startswith("zwrite: No credentials cache found while sending notice to ")
):
# Retry sending the message unauthenticated; if that works,
# just notify the user that they need to renew their tickets
(code, stderr) = send_unauthed_zephyr(zwrite_args, wrapped_content)
if code == 0:
if options.ignore_expired_tickets:
return
send_error_zulip(
"""%s
Your last message was forwarded from Zulip to Zephyr unauthenticated, \
because your Kerberos tickets have expired. It was sent successfully, \
but please renew your Kerberos tickets in the screen session where you \
are running the Zulip-Zephyr mirroring bot, so we can send \
authenticated Zephyr messages for you again.
%s"""
% (support_heading, support_closing)
)
return
# zwrite failed and it wasn't because of expired tickets: This is
# probably because the recipient isn't subscribed to personals,
# but regardless, we should just notify the user.
send_error_zulip(
"""%s
Your Zulip-Zephyr mirror bot was unable to forward that last message \
from Zulip to Zephyr. That means that while Zulip users (like you) \
received it, Zephyr users did not. The error message from zwrite was:
%s
%s"""
% (support_heading, stderr, support_closing)
)
return
def maybe_forward_to_zephyr(message: Dict[str, Any]) -> None:
# The key string can be used to direct any type of text.
if message["sender_email"] == zulip_account_email:
if not (
(message["type"] == "stream")
or (
message["type"] == "private"
and False
not in [
u["email"].lower().endswith("mit.edu") for u in message["display_recipient"]
]
)
):
# Don't try forward private messages with non-MIT users
# to MIT Zephyr.
return
timestamp_now = int(time.time())
if float(message["timestamp"]) < timestamp_now - 15:
logger.warning(
"Skipping out of order message: {} < {}".format(message["timestamp"], timestamp_now)
)
return
try:
forward_to_zephyr(message)
except Exception:
# Don't let an exception forwarding one message crash the
# whole process
logger.exception("Error forwarding message:")
def zulip_to_zephyr(options: optparse.Values) -> NoReturn:
# Sync messages from zulip to zephyr
logger.info("Starting syncing messages.")
backoff = RandomExponentialBackoff(timeout_success_equivalent=120)
while True:
try:
zulip_client.call_on_each_message(maybe_forward_to_zephyr)
except Exception:
logger.exception("Error syncing messages:")
backoff.fail()
def subscribed_to_mail_messages() -> bool:
# In case we have lost our AFS tokens and those won't be able to
# parse the Zephyr subs file, first try reading in result of this
# query from the environment so we can avoid the filesystem read.
stored_result = os.environ.get("HUMBUG_FORWARD_MAIL_ZEPHYRS")
if stored_result is not None:
return stored_result == "True"
for (cls, instance, recipient) in parse_zephyr_subs(verbose=False):
if cls.lower() == "mail" and instance.lower() == "inbox":
os.environ["HUMBUG_FORWARD_MAIL_ZEPHYRS"] = "True"
return True
os.environ["HUMBUG_FORWARD_MAIL_ZEPHYRS"] = "False"
return False
def add_zulip_subscriptions(verbose: bool) -> None:
zephyr_subscriptions = set()
skipped = set()
for (cls, instance, recipient) in parse_zephyr_subs(verbose=verbose):
if cls.lower() == "message":
if recipient != "*":
# We already have a (message, *, you) subscription, so
# these are redundant
continue
# We don't support subscribing to (message, *)
if instance == "*":
if recipient == "*":
skipped.add(
(
cls,
instance,
recipient,
"subscribing to all of class message is not supported.",
)
)
continue
# If you're on -i white-magic on zephyr, get on stream white-magic on zulip
# instead of subscribing to stream "message" on zulip
zephyr_subscriptions.add(instance)
continue
elif cls.lower() == "mail" and instance.lower() == "inbox":
# We forward mail zephyrs, so no need to log a warning.
continue
elif len(cls) > 60:
skipped.add((cls, instance, recipient, "Class longer than 60 characters"))
continue
elif instance != "*":
skipped.add((cls, instance, recipient, "Unsupported non-* instance"))
continue
elif recipient != "*":
skipped.add((cls, instance, recipient, "Unsupported non-* recipient."))
continue
zephyr_subscriptions.add(cls)
if len(zephyr_subscriptions) != 0:
res = zulip_client.add_subscriptions(
list({"name": stream} for stream in zephyr_subscriptions),
authorization_errors_fatal=False,
)
if res.get("result") != "success":
logger.error("Error subscribing to streams:\n{}".format(res["msg"]))
return
already = res.get("already_subscribed")
new = res.get("subscribed")
unauthorized = res.get("unauthorized")
if verbose:
if already is not None and len(already) > 0:
logger.info(
"\nAlready subscribed to: {}".format(", ".join(list(already.values())[0]))
)
if new is not None and len(new) > 0:
logger.info(
"\nSuccessfully subscribed to: {}".format(", ".join(list(new.values())[0]))
)
if unauthorized is not None and len(unauthorized) > 0:
logger.info(
"\n"
+ "\n".join(
textwrap.wrap(
"""\
The following streams you have NOT been subscribed to,
because they have been configured in Zulip as invitation-only streams.
This was done at the request of users of these Zephyr classes, usually
because traffic to those streams is sent within the Zephyr world encrypted
via zcrypt (in Zulip, we achieve the same privacy goals through invitation-only streams).
If you wish to read these streams in Zulip, you need to contact the people who are
on these streams and already use Zulip. They can subscribe you to them via the
"streams" page in the Zulip web interface:
"""
)
)
+ "\n\n {}".format(", ".join(unauthorized))
)
if len(skipped) > 0:
if verbose:
logger.info(
"\n"
+ "\n".join(
textwrap.wrap(
"""\
You have some lines in ~/.zephyr.subs that could not be
synced to your Zulip subscriptions because they do not
use "*" as both the instance and recipient and not one of
the special cases (e.g. personals and mail zephyrs) that
Zulip has a mechanism for forwarding. Zulip does not
allow subscribing to only some subjects on a Zulip
stream, so this tool has not created a corresponding
Zulip subscription to these lines in ~/.zephyr.subs:
"""
)
)
+ "\n"
)
for (cls, instance, recipient, reason) in skipped:
if verbose:
if reason != "":
logger.info(f" [{cls},{instance},{recipient}] ({reason})")
else:
logger.info(f" [{cls},{instance},{recipient}]")
if len(skipped) > 0:
if verbose:
logger.info(
"\n"
+ "\n".join(
textwrap.wrap(
"""\
If you wish to be subscribed to any Zulip streams related
to these .zephyrs.subs lines, please do so via the Zulip
web interface.
"""
)
)
+ "\n"
)
def valid_stream_name(name: str) -> bool:
return name != ""
def parse_zephyr_subs(verbose: bool = False) -> Set[Tuple[str, str, str]]:
zephyr_subscriptions = set() # type: Set[Tuple[str, str, str]]
subs_file = os.path.join(os.environ["HOME"], ".zephyr.subs")
if not os.path.exists(subs_file):
if verbose:
logger.error("Couldn't find ~/.zephyr.subs!")
return zephyr_subscriptions
for line in open(subs_file).readlines():
line = line.strip()
if len(line) == 0:
continue
try:
(cls, instance, recipient) = line.split(",")
cls = cls.replace("%me%", options.user)
instance = instance.replace("%me%", options.user)
recipient = recipient.replace("%me%", options.user)
if not valid_stream_name(cls):
if verbose:
logger.error(f"Skipping subscription to unsupported class name: [{line}]")
continue
except Exception:
if verbose:
logger.error(f"Couldn't parse ~/.zephyr.subs line: [{line}]")
continue
zephyr_subscriptions.add((cls.strip(), instance.strip(), recipient.strip()))
return zephyr_subscriptions
def open_logger() -> logging.Logger:
if options.log_path is not None:
log_file = options.log_path
elif options.forward_class_messages:
if options.test_mode:
log_file = "/var/log/zulip/test-mirror-log"
else:
log_file = "/var/log/zulip/mirror-log"
else:
f = tempfile.NamedTemporaryFile(prefix=f"zulip-log.{options.user}.", delete=False)
log_file = f.name
# Close the file descriptor, since the logging system will
# reopen it anyway.
f.close()
logger = logging.getLogger(__name__)
log_format = "%(asctime)s <initial>: %(message)s"
formatter = logging.Formatter(log_format)
logging.basicConfig(format=log_format)
logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
return logger
def configure_logger(logger: logging.Logger, direction_name: Optional[str]) -> None:
if direction_name is None:
log_format = "%(message)s"
else:
log_format = "%(asctime)s [" + direction_name + "] %(message)s"
formatter = logging.Formatter(log_format)
# Replace the formatters for the file and stdout loggers
for handler in logger.handlers:
handler.setFormatter(formatter)
root_logger = logging.getLogger()
for handler in root_logger.handlers:
handler.setFormatter(formatter)
def parse_args() -> Tuple[optparse.Values, List[str]]:
parser = optparse.OptionParser()
parser.add_option(
"--forward-class-messages", default=False, help=optparse.SUPPRESS_HELP, action="store_true"
)
parser.add_option("--shard", help=optparse.SUPPRESS_HELP)
parser.add_option("--noshard", default=False, help=optparse.SUPPRESS_HELP, action="store_true")
parser.add_option("--resend-log", dest="logs_to_resend", help=optparse.SUPPRESS_HELP)
parser.add_option("--enable-resend-log", dest="resend_log_path", help=optparse.SUPPRESS_HELP)
parser.add_option("--log-path", dest="log_path", help=optparse.SUPPRESS_HELP)
parser.add_option(
"--stream-file-path",
dest="stream_file_path",
default="/home/zulip/public_streams",
help=optparse.SUPPRESS_HELP,
)
parser.add_option(
"--no-forward-personals",
dest="forward_personals",
help=optparse.SUPPRESS_HELP,
default=True,
action="store_false",
)
parser.add_option(
"--forward-mail-zephyrs",
dest="forward_mail_zephyrs",
help=optparse.SUPPRESS_HELP,
default=False,
action="store_true",
)
parser.add_option(
"--no-forward-from-zulip",
default=True,
dest="forward_from_zulip",
help=optparse.SUPPRESS_HELP,
action="store_false",
)
parser.add_option("--verbose", default=False, help=optparse.SUPPRESS_HELP, action="store_true")
parser.add_option("--sync-subscriptions", default=False, action="store_true")
parser.add_option("--ignore-expired-tickets", default=False, action="store_true")
parser.add_option("--site", default=DEFAULT_SITE, help=optparse.SUPPRESS_HELP)
parser.add_option("--on-startup-command", default=None, help=optparse.SUPPRESS_HELP)
parser.add_option("--user", default=os.environ["USER"], help=optparse.SUPPRESS_HELP)
parser.add_option(
"--stamp-path",
default="/afs/athena.mit.edu/user/t/a/tabbott/for_friends",
help=optparse.SUPPRESS_HELP,
)
parser.add_option("--session-path", default=None, help=optparse.SUPPRESS_HELP)
parser.add_option("--nagios-class", default=None, help=optparse.SUPPRESS_HELP)
parser.add_option("--nagios-path", default=None, help=optparse.SUPPRESS_HELP)
parser.add_option(
"--use-sessions", default=False, action="store_true", help=optparse.SUPPRESS_HELP
)
parser.add_option(
"--test-mode", default=False, help=optparse.SUPPRESS_HELP, action="store_true"
)
parser.add_option(
"--api-key-file", default=os.path.join(os.environ["HOME"], "Private", ".humbug-api-key")
)
return parser.parse_args()
def die_gracefully(signal: int, frame: FrameType) -> None:
if CURRENT_STATE == States.ZulipToZephyr or CURRENT_STATE == States.ChildSending:
# this is a child process, so we want os._exit (no clean-up necessary)
os._exit(1)
if CURRENT_STATE == States.ZephyrToZulip and not options.use_sessions:
try:
# zephyr=>zulip processes may have added subs, so run cancelSubs
zephyr._z.cancelSubs()
except OSError:
# We don't care whether we failed to cancel subs properly, but we should log it
logger.exception("")
sys.exit(1)
if __name__ == "__main__":
# Set the SIGCHLD handler back to SIG_DFL to prevent these errors
# when importing the "requests" module after being restarted using
# the restart_stamp functionality:
#
# close failed in file object destructor:
# IOError: [Errno 10] No child processes
signal.signal(signal.SIGCHLD, signal.SIG_DFL)
signal.signal(signal.SIGINT, die_gracefully)
(options, args) = parse_args()
logger = open_logger()
configure_logger(logger, "parent")
# In case this is an automated restart of the mirroring script,
# and we have lost AFS tokens, first try reading the API key from
# the environment so that we can skip doing a filesystem read.
if os.environ.get("HUMBUG_API_KEY") is not None:
api_key = os.environ.get("HUMBUG_API_KEY")
else:
if not os.path.exists(options.api_key_file):
logger.error(
"\n"
+ "\n".join(
textwrap.wrap(
"""\
Could not find API key file.
You need to either place your api key file at %s,
or specify the --api-key-file option."""
% (options.api_key_file,)
)
)
)
sys.exit(1)
api_key = open(options.api_key_file).read().strip()
# Store the API key in the environment so that our children
# don't need to read it in
os.environ["HUMBUG_API_KEY"] = api_key
if options.nagios_path is None and options.nagios_class is not None:
logger.error("\n" + "nagios_path is required with nagios_class\n")
sys.exit(1)
zulip_account_email = options.user + "@mit.edu"
import zulip
zulip_client = zulip.Client(
email=zulip_account_email,
api_key=api_key,
verbose=True,
client="zephyr_mirror",
site=options.site,
)
start_time = time.time()
if options.sync_subscriptions:
configure_logger(logger, None) # make the output cleaner
logger.info("Syncing your ~/.zephyr.subs to your Zulip Subscriptions!")
add_zulip_subscriptions(True)
sys.exit(0)
# Kill all zephyr_mirror processes other than this one and its parent.
if not options.test_mode:
pgrep_query = "python.*zephyr_mirror"
if options.shard is not None:
# sharded class mirror
pgrep_query = f"{pgrep_query}.*--shard={options.shard}"
elif options.user is not None:
# Personals mirror on behalf of another user.
pgrep_query = f"{pgrep_query}.*--user={options.user}"
proc = subprocess.Popen(
["pgrep", "-U", os.environ["USER"], "-f", pgrep_query],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
out, _err_unused = proc.communicate()
for pid in map(int, out.split()):
if pid == os.getpid() or pid == os.getppid():
continue
# Another copy of zephyr_mirror.py! Kill it.
logger.info(f"Killing duplicate zephyr_mirror process {pid}")
try:
os.kill(pid, signal.SIGINT)
except OSError:
# We don't care if the target process no longer exists, so just log the error
logger.exception("")
if options.shard is not None and set(options.shard) != set("a"):
# The shard that is all "a"s is the one that handles personals
# forwarding and zulip => zephyr forwarding
options.forward_personals = False
options.forward_from_zulip = False
if options.forward_mail_zephyrs is None:
options.forward_mail_zephyrs = subscribed_to_mail_messages()
if options.session_path is None:
options.session_path = f"/var/tmp/{options.user}"
if options.forward_from_zulip:
child_pid = os.fork() # type: Optional[int]
if child_pid == 0:
CURRENT_STATE = States.ZulipToZephyr
# Run the zulip => zephyr mirror in the child
configure_logger(logger, "zulip=>zephyr")
zulip_to_zephyr(options)
else:
child_pid = None
CURRENT_STATE = States.ZephyrToZulip
import zephyr
logger_name = "zephyr=>zulip"
if options.shard is not None:
logger_name += f"({options.shard})"
configure_logger(logger, logger_name)
# Have the kernel reap children for when we fork off processes to send Zulips
signal.signal(signal.SIGCHLD, signal.SIG_IGN)
zephyr_to_zulip(options) | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/zephyr/zephyr_mirror_backend.py | zephyr_mirror_backend.py |
# Zulip hook for Mercurial changeset pushes.
#
# This hook is called when changesets are pushed to the default repository (ie
# `hg push`). See https://zulip.com/integrations for installation instructions.
import sys
from mercurial import repository as repo
from mercurial import ui
import zulip
VERSION = "0.9"
def format_summary_line(
web_url: str, user: str, base: int, tip: int, branch: str, node: str
) -> str:
"""
Format the first line of the message, which contains summary
information about the changeset and links to the changelog if a
web URL has been configured:
Jane Doe <[email protected]> pushed 1 commit to default (170:e494a5be3393):
"""
revcount = tip - base
plural = "s" if revcount > 1 else ""
if web_url:
shortlog_base_url = web_url.rstrip("/") + "/shortlog/"
summary_url = "{shortlog}{tip}?revcount={revcount}".format(
shortlog=shortlog_base_url, tip=tip - 1, revcount=revcount
)
formatted_commit_count = "[{revcount} commit{s}]({url})".format(
revcount=revcount, s=plural, url=summary_url
)
else:
formatted_commit_count = f"{revcount} commit{plural}"
return "**{user}** pushed {commits} to **{branch}** (`{tip}:{node}`):\n\n".format(
user=user, commits=formatted_commit_count, branch=branch, tip=tip, node=node[:12]
)
def format_commit_lines(web_url: str, repo: repo, base: int, tip: int) -> str:
"""
Format the per-commit information for the message, including the one-line
commit summary and a link to the diff if a web URL has been configured:
"""
if web_url:
rev_base_url = web_url.rstrip("/") + "/rev/"
commit_summaries = []
for rev in range(base, tip):
rev_node = repo.changelog.node(rev)
rev_ctx = repo[rev_node]
one_liner = rev_ctx.description().split("\n")[0]
if web_url:
summary_url = rev_base_url + str(rev_ctx)
summary = f"* [{one_liner}]({summary_url})"
else:
summary = f"* {one_liner}"
commit_summaries.append(summary)
return "\n".join(summary for summary in commit_summaries)
def send_zulip(
email: str, api_key: str, site: str, stream: str, subject: str, content: str
) -> None:
"""
Send a message to Zulip using the provided credentials, which should be for
a bot in most cases.
"""
client = zulip.Client(
email=email, api_key=api_key, site=site, client="ZulipMercurial/" + VERSION
)
message_data = {
"type": "stream",
"to": stream,
"subject": subject,
"content": content,
}
client.send_message(message_data)
def get_config(ui: ui, item: str) -> str:
try:
# config returns configuration value.
return ui.config("zulip", item)
except IndexError:
ui.warn(f"Zulip: Could not find required item {item} in hg config.")
sys.exit(1)
def hook(ui: ui, repo: repo, **kwargs: str) -> None:
"""
Invoked by configuring a [hook] entry in .hg/hgrc.
"""
hooktype = kwargs["hooktype"]
node = kwargs["node"]
ui.debug(f"Zulip: received {hooktype} event\n")
if hooktype != "changegroup":
ui.warn(f"Zulip: {hooktype} not supported\n")
sys.exit(1)
ctx = repo[node]
branch = ctx.branch()
# If `branches` isn't specified, notify on all branches.
branch_whitelist = get_config(ui, "branches")
branch_blacklist = get_config(ui, "ignore_branches")
if branch_whitelist:
# Only send notifications on branches we are watching.
watched_branches = [b.lower().strip() for b in branch_whitelist.split(",")]
if branch.lower() not in watched_branches:
ui.debug(f"Zulip: ignoring event for {branch}\n")
sys.exit(0)
if branch_blacklist:
# Don't send notifications for branches we've ignored.
ignored_branches = [b.lower().strip() for b in branch_blacklist.split(",")]
if branch.lower() in ignored_branches:
ui.debug(f"Zulip: ignoring event for {branch}\n")
sys.exit(0)
# The first and final commits in the changeset.
base = repo[node].rev()
tip = len(repo)
email = get_config(ui, "email")
api_key = get_config(ui, "api_key")
site = get_config(ui, "site")
if not (email and api_key):
ui.warn("Zulip: missing email or api_key configurations\n")
ui.warn("in the [zulip] section of your .hg/hgrc.\n")
sys.exit(1)
stream = get_config(ui, "stream")
# Give a default stream if one isn't provided.
if not stream:
stream = "commits"
web_url = get_config(ui, "web_url")
user = ctx.user()
content = format_summary_line(web_url, user, base, tip, branch, node)
content += format_commit_lines(web_url, repo, base, tip)
subject = branch
ui.debug("Sending to Zulip:\n")
ui.debug(content + "\n")
send_zulip(email, api_key, site, stream, subject, content) | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/hg/zulip_changegroup.py | zulip_changegroup.py |
import os.path
import sys
from trac.core import Component, implements
from trac.ticket import ITicketChangeListener
sys.path.insert(0, os.path.dirname(__file__))
import zulip_trac_config as config
VERSION = "0.9"
from typing import Any, Dict
if config.ZULIP_API_PATH is not None:
sys.path.append(config.ZULIP_API_PATH)
import zulip
client = zulip.Client(
email=config.ZULIP_USER,
site=config.ZULIP_SITE,
api_key=config.ZULIP_API_KEY,
client="ZulipTrac/" + VERSION,
)
def markdown_ticket_url(ticket: Any, heading: str = "ticket") -> str:
return f"[{heading} #{ticket.id}]({config.TRAC_BASE_TICKET_URL}/{ticket.id})"
def markdown_block(desc: str) -> str:
return "\n\n>" + "\n> ".join(desc.split("\n")) + "\n"
def truncate(string: str, length: int) -> str:
if len(string) <= length:
return string
return string[: length - 3] + "..."
def trac_subject(ticket: Any) -> str:
return truncate("#{}: {}".format(ticket.id, ticket.values.get("summary")), 60)
def send_update(ticket: Any, content: str) -> None:
client.send_message(
{
"type": "stream",
"to": config.STREAM_FOR_NOTIFICATIONS,
"content": content,
"subject": trac_subject(ticket),
}
)
class ZulipPlugin(Component):
implements(ITicketChangeListener)
def ticket_created(self, ticket: Any) -> None:
"""Called when a ticket is created."""
content = "{} created {} in component **{}**, priority **{}**:\n".format(
ticket.values.get("reporter"),
markdown_ticket_url(ticket),
ticket.values.get("component"),
ticket.values.get("priority"),
)
# Include the full subject if it will be truncated
if len(ticket.values.get("summary")) > 60:
content += "**{}**\n".format(ticket.values.get("summary"))
if ticket.values.get("description") != "":
content += "{}".format(markdown_block(ticket.values.get("description")))
send_update(ticket, content)
def ticket_changed(
self, ticket: Any, comment: str, author: str, old_values: Dict[str, Any]
) -> None:
"""Called when a ticket is modified.
`old_values` is a dictionary containing the previous values of the
fields that have changed.
"""
if not (
set(old_values.keys()).intersection(set(config.TRAC_NOTIFY_FIELDS))
or (comment and "comment" in set(config.TRAC_NOTIFY_FIELDS))
):
return
content = f"{author} updated {markdown_ticket_url(ticket)}"
if comment:
content += f" with comment: {markdown_block(comment)}\n\n"
else:
content += ":\n\n"
field_changes = []
for key, value in old_values.items():
if key == "description":
content += "- Changed {} from {}\n\nto {}".format(
key,
markdown_block(value),
markdown_block(ticket.values.get(key)),
)
elif old_values.get(key) == "":
field_changes.append(f"{key}: => **{ticket.values.get(key)}**")
elif ticket.values.get(key) == "":
field_changes.append(f'{key}: **{old_values.get(key)}** => ""')
else:
field_changes.append(
f"{key}: **{old_values.get(key)}** => **{ticket.values.get(key)}**"
)
content += ", ".join(field_changes)
send_update(ticket, content)
def ticket_deleted(self, ticket: Any) -> None:
"""Called when a ticket is deleted."""
content = "{} was deleted.".format(markdown_ticket_url(ticket, heading="Ticket"))
send_update(ticket, content) | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/trac/zulip_trac.py | zulip_trac.py |
from typing import Dict, Optional
# Change these values to configure authentication for the plugin
ZULIP_USER = "[email protected]"
ZULIP_API_KEY = "0123456789abcdef0123456789abcdef"
# deployment_notice_destination() lets you customize where deployment notices
# are sent to with the full power of a Python function.
#
# It takes the following arguments:
# * branch = the name of the branch where the deployed commit was
# pushed to
#
# Returns a dictionary encoding the stream and subject to send the
# notification to (or None to send no notification).
#
# The default code below will send every commit pushed to "main" to
# * stream "deployments"
# * topic "main"
# And similarly for branch "test-post-receive" (for use when testing).
def deployment_notice_destination(branch: str) -> Optional[Dict[str, str]]:
if branch in ["main", "master", "test-post-receive"]:
return dict(stream="deployments", subject=f"{branch}")
# Return None for cases where you don't want a notice sent
return None
# Modify this function to change how deployments are displayed
#
# It takes the following arguments:
# * app_name = the name of the app being deployed
# * url = the FQDN (Fully Qualified Domain Name) where the app
# can be found
# * branch = the name of the branch where the deployed commit was
# pushed to
# * commit_id = hash of the commit that triggered the deployment
# * dep_id = deployment id
# * dep_time = deployment timestamp
def format_deployment_message(
app_name: str = "",
url: str = "",
branch: str = "",
commit_id: str = "",
dep_id: str = "",
dep_time: str = "",
) -> str:
return f"Deployed commit `{commit_id}` ({branch}) in [{app_name}]({url})"
## If properly installed, the Zulip API should be in your import
## path, but if not, set a custom path below
ZULIP_API_PATH = None # type: Optional[str]
# Set this to your Zulip server's API URI
ZULIP_SITE = "https://zulip.example.com" | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/openshift/zulip_openshift_config.py | zulip_openshift_config.py |
import sys
if sys.hexversion < 0x02040000:
# The limiter is the subprocess module
sys.stderr.write("git-p4: requires Python 2.4 or later.\n")
sys.exit(1)
import os
import optparse
import marshal
import subprocess
import tempfile
import time
import platform
import re
import shutil
import stat
try:
from subprocess import CalledProcessError
except ImportError:
# from python:subprocess.py
# Exception classes used by this module.
class CalledProcessError(Exception):
"""This exception is raised when a process run by check_call() returns
a non-zero exit status. The exit status will be stored in the
returncode attribute."""
def __init__(self, returncode, cmd):
self.returncode = returncode
self.cmd = cmd
def __str__(self):
return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode)
verbose = False
# Only labels/tags matching this will be imported/exported
defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$'
def p4_build_cmd(cmd):
"""Build a suitable p4 command line.
This consolidates building and returning a p4 command line into one
location. It means that hooking into the environment, or other configuration
can be done more easily.
"""
real_cmd = ["p4"]
if isinstance(cmd, str):
real_cmd = ' '.join(real_cmd) + ' ' + cmd
else:
real_cmd += cmd
return real_cmd
def chdir(path, is_client_path=False):
"""Do chdir to the given path, and set the PWD environment
variable for use by P4. It does not look at getcwd() output.
Since we're not using the shell, it is necessary to set the
PWD environment variable explicitly.
Normally, expand the path to force it to be absolute. This
addresses the use of relative path names inside P4 settings,
e.g. P4CONFIG=.p4config. P4 does not simply open the filename
as given; it looks for .p4config using PWD.
If is_client_path, the path was handed to us directly by p4,
and may be a symbolic link. Do not call os.getcwd() in this
case, because it will cause p4 to think that PWD is not inside
the client path.
"""
os.chdir(path)
if not is_client_path:
path = os.getcwd()
os.environ['PWD'] = path
def die(msg):
if verbose:
raise Exception(msg)
else:
sys.stderr.write(msg + "\n")
sys.exit(1)
def write_pipe(c, stdin):
if verbose:
sys.stderr.write('Writing pipe: %s\n' % str(c))
expand = isinstance(c, str)
p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)
pipe = p.stdin
val = pipe.write(stdin)
pipe.close()
if p.wait():
die('Command failed: %s' % str(c))
return val
def p4_write_pipe(c, stdin):
real_cmd = p4_build_cmd(c)
return write_pipe(real_cmd, stdin)
def read_pipe(c, ignore_error=False):
if verbose:
sys.stderr.write('Reading pipe: %s\n' % str(c))
expand = isinstance(c, str)
p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
pipe = p.stdout
val = pipe.read()
if p.wait() and not ignore_error:
die('Command failed: %s' % str(c))
return val
def p4_read_pipe(c, ignore_error=False):
real_cmd = p4_build_cmd(c)
return read_pipe(real_cmd, ignore_error)
def read_pipe_lines(c):
if verbose:
sys.stderr.write('Reading pipe: %s\n' % str(c))
expand = isinstance(c, str)
p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
pipe = p.stdout
val = pipe.readlines()
if pipe.close() or p.wait():
die('Command failed: %s' % str(c))
return val
def p4_read_pipe_lines(c):
"""Specifically invoke p4 on the command supplied. """
real_cmd = p4_build_cmd(c)
return read_pipe_lines(real_cmd)
def p4_has_command(cmd):
"""Ask p4 for help on this command. If it returns an error, the
command does not exist in this version of p4."""
real_cmd = p4_build_cmd(["help", cmd])
p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
p.communicate()
return p.returncode == 0
def p4_has_move_command():
"""See if the move command exists, that it supports -k, and that
it has not been administratively disabled. The arguments
must be correct, but the filenames do not have to exist. Use
ones with wildcards so even if they exist, it will fail."""
if not p4_has_command("move"):
return False
cmd = p4_build_cmd(["move", "-k", "@from", "@to"])
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = p.communicate()
# return code will be 1 in either case
if err.find("Invalid option") >= 0:
return False
if err.find("disabled") >= 0:
return False
# assume it failed because @... was invalid changelist
return True
def system(cmd):
expand = isinstance(cmd, str)
if verbose:
sys.stderr.write("executing %s\n" % str(cmd))
retcode = subprocess.call(cmd, shell=expand)
if retcode:
raise CalledProcessError(retcode, cmd)
def p4_system(cmd):
"""Specifically invoke p4 as the system command. """
real_cmd = p4_build_cmd(cmd)
expand = isinstance(real_cmd, str)
retcode = subprocess.call(real_cmd, shell=expand)
if retcode:
raise CalledProcessError(retcode, real_cmd)
_p4_version_string = None
def p4_version_string():
"""Read the version string, showing just the last line, which
hopefully is the interesting version bit.
$ p4 -V
Perforce - The Fast Software Configuration Management System.
Copyright 1995-2011 Perforce Software. All rights reserved.
Rev. P4/NTX86/2011.1/393975 (2011/12/16).
"""
global _p4_version_string
if not _p4_version_string:
a = p4_read_pipe_lines(["-V"])
_p4_version_string = a[-1].rstrip()
return _p4_version_string
def p4_integrate(src, dest):
p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)])
def p4_sync(f, *options):
p4_system(["sync"] + list(options) + [wildcard_encode(f)])
def p4_add(f):
# forcibly add file names with wildcards
if wildcard_present(f):
p4_system(["add", "-f", f])
else:
p4_system(["add", f])
def p4_delete(f):
p4_system(["delete", wildcard_encode(f)])
def p4_edit(f):
p4_system(["edit", wildcard_encode(f)])
def p4_revert(f):
p4_system(["revert", wildcard_encode(f)])
def p4_reopen(type, f):
p4_system(["reopen", "-t", type, wildcard_encode(f)])
def p4_move(src, dest):
p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)])
def p4_describe(change):
"""Make sure it returns a valid result by checking for
the presence of field "time". Return a dict of the
results."""
ds = p4CmdList(["describe", "-s", str(change)])
if len(ds) != 1:
die("p4 describe -s %d did not return 1 result: %s" % (change, str(ds)))
d = ds[0]
if "p4ExitCode" in d:
die("p4 describe -s %d exited with %d: %s" % (change, d["p4ExitCode"],
str(d)))
if "code" in d:
if d["code"] == "error":
die("p4 describe -s %d returned error code: %s" % (change, str(d)))
if "time" not in d:
die("p4 describe -s %d returned no \"time\": %s" % (change, str(d)))
return d
#
# Canonicalize the p4 type and return a tuple of the
# base type, plus any modifiers. See "p4 help filetypes"
# for a list and explanation.
#
def split_p4_type(p4type):
p4_filetypes_historical = {
"ctempobj": "binary+Sw",
"ctext": "text+C",
"cxtext": "text+Cx",
"ktext": "text+k",
"kxtext": "text+kx",
"ltext": "text+F",
"tempobj": "binary+FSw",
"ubinary": "binary+F",
"uresource": "resource+F",
"uxbinary": "binary+Fx",
"xbinary": "binary+x",
"xltext": "text+Fx",
"xtempobj": "binary+Swx",
"xtext": "text+x",
"xunicode": "unicode+x",
"xutf16": "utf16+x",
}
if p4type in p4_filetypes_historical:
p4type = p4_filetypes_historical[p4type]
mods = ""
s = p4type.split("+")
base = s[0]
mods = ""
if len(s) > 1:
mods = s[1]
return (base, mods)
#
# return the raw p4 type of a file (text, text+ko, etc)
#
def p4_type(file):
results = p4CmdList(["fstat", "-T", "headType", file])
return results[0]['headType']
#
# Given a type base and modifier, return a regexp matching
# the keywords that can be expanded in the file
#
def p4_keywords_regexp_for_type(base, type_mods):
if base in ("text", "unicode", "binary"):
kwords = None
if "ko" in type_mods:
kwords = 'Id|Header'
elif "k" in type_mods:
kwords = 'Id|Header|Author|Date|DateTime|Change|File|Revision'
else:
return None
pattern = r"""
\$ # Starts with a dollar, followed by...
(%s) # one of the keywords, followed by...
(:[^$\n]+)? # possibly an old expansion, followed by...
\$ # another dollar
""" % kwords
return pattern
else:
return None
#
# Given a file, return a regexp matching the possible
# RCS keywords that will be expanded, or None for files
# with kw expansion turned off.
#
def p4_keywords_regexp_for_file(file):
if not os.path.exists(file):
return None
else:
(type_base, type_mods) = split_p4_type(p4_type(file))
return p4_keywords_regexp_for_type(type_base, type_mods)
def setP4ExecBit(file, mode):
# Reopens an already open file and changes the execute bit to match
# the execute bit setting in the passed in mode.
p4Type = "+x"
if not isModeExec(mode):
p4Type = getP4OpenedType(file)
p4Type = re.sub(r'^([cku]?)x(.*)', '\\1\\2', p4Type)
p4Type = re.sub(r'(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
if p4Type[-1] == "+":
p4Type = p4Type[0:-1]
p4_reopen(p4Type, file)
def getP4OpenedType(file):
# Returns the perforce file type for the given file.
result = p4_read_pipe(["opened", wildcard_encode(file)])
match = re.match(".*\\((.+)\\)\r?$", result)
if match:
return match.group(1)
else:
die("Could not determine file type for %s (result: '%s')" % (file, result))
# Return the set of all p4 labels
def getP4Labels(depotPaths):
labels = set()
if isinstance(depotPaths, str):
depotPaths = [depotPaths]
for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]):
label = l['label']
labels.add(label)
return labels
# Return the set of all git tags
def getGitTags():
gitTags = set()
for line in read_pipe_lines(["git", "tag"]):
tag = line.strip()
gitTags.add(tag)
return gitTags
def diffTreePattern():
# This is a simple generator for the diff tree regex pattern. This could be
# a class variable if this and parseDiffTreeEntry were a part of a class.
pattern = re.compile(':(\\d+) (\\d+) (\\w+) (\\w+) ([A-Z])(\\d+)?\t(.*?)((\t(.*))|$)')
while True:
yield pattern
def parseDiffTreeEntry(entry):
"""Parses a single diff tree entry into its component elements.
See git-diff-tree(1) manpage for details about the format of the diff
output. This method returns a dictionary with the following elements:
src_mode - The mode of the source file
dst_mode - The mode of the destination file
src_sha1 - The sha1 for the source file
dst_sha1 - The sha1 fr the destination file
status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
status_score - The score for the status (applicable for 'C' and 'R'
statuses). This is None if there is no score.
src - The path for the source file.
dst - The path for the destination file. This is only present for
copy or renames. If it is not present, this is None.
If the pattern is not matched, None is returned."""
match = diffTreePattern().next().match(entry)
if match:
return {
'src_mode': match.group(1),
'dst_mode': match.group(2),
'src_sha1': match.group(3),
'dst_sha1': match.group(4),
'status': match.group(5),
'status_score': match.group(6),
'src': match.group(7),
'dst': match.group(10)
}
return None
def isModeExec(mode):
# Returns True if the given git mode represents an executable file,
# otherwise False.
return mode[-3:] == "755"
def isModeExecChanged(src_mode, dst_mode):
return isModeExec(src_mode) != isModeExec(dst_mode)
def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None):
if isinstance(cmd, str):
cmd = "-G " + cmd
expand = True
else:
cmd = ["-G"] + cmd
expand = False
cmd = p4_build_cmd(cmd)
if verbose:
sys.stderr.write("Opening pipe: %s\n" % str(cmd))
# Use a temporary file to avoid deadlocks without
# subprocess.communicate(), which would put another copy
# of stdout into memory.
stdin_file = None
if stdin is not None:
stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
if isinstance(stdin, str):
stdin_file.write(stdin)
else:
for i in stdin:
stdin_file.write(i + '\n')
stdin_file.flush()
stdin_file.seek(0)
p4 = subprocess.Popen(cmd,
shell=expand,
stdin=stdin_file,
stdout=subprocess.PIPE)
result = []
try:
while True:
entry = marshal.load(p4.stdout)
if cb is not None:
cb(entry)
else:
result.append(entry)
except EOFError:
pass
exitCode = p4.wait()
if exitCode != 0:
entry = {}
entry["p4ExitCode"] = exitCode
result.append(entry)
return result
def p4Cmd(cmd):
list = p4CmdList(cmd)
result = {}
for entry in list:
result.update(entry)
return result;
def p4Where(depotPath):
if not depotPath.endswith("/"):
depotPath += "/"
depotPath = depotPath + "..."
outputList = p4CmdList(["where", depotPath])
output = None
for entry in outputList:
if "depotFile" in entry:
if entry["depotFile"] == depotPath:
output = entry
break
elif "data" in entry:
data = entry.get("data")
space = data.find(" ")
if data[:space] == depotPath:
output = entry
break
if output == None:
return ""
if output["code"] == "error":
return ""
clientPath = ""
if "path" in output:
clientPath = output.get("path")
elif "data" in output:
data = output.get("data")
lastSpace = data.rfind(" ")
clientPath = data[lastSpace + 1:]
if clientPath.endswith("..."):
clientPath = clientPath[:-3]
return clientPath
def currentGitBranch():
return read_pipe("git name-rev HEAD").split(" ")[1].strip()
def isValidGitDir(path):
if (os.path.exists(path + "/HEAD")
and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
return True;
return False
def parseRevision(ref):
return read_pipe("git rev-parse %s" % ref).strip()
def branchExists(ref):
rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref],
ignore_error=True)
return len(rev) > 0
def extractLogMessageFromGitCommit(commit):
logMessage = ""
## fixme: title is first line of commit, not 1st paragraph.
foundTitle = False
for log in read_pipe_lines("git cat-file commit %s" % commit):
if not foundTitle:
if len(log) == 1:
foundTitle = True
continue
logMessage += log
return logMessage
def extractSettingsGitLog(log):
values = {}
for line in log.split("\n"):
line = line.strip()
m = re.search (r"^ *\[git-p4: (.*)\]$", line)
if not m:
continue
assignments = m.group(1).split (':')
for a in assignments:
vals = a.split ('=')
key = vals[0].strip()
val = ('='.join (vals[1:])).strip()
if val.endswith ('\"') and val.startswith('"'):
val = val[1:-1]
values[key] = val
paths = values.get("depot-paths")
if not paths:
paths = values.get("depot-path")
if paths:
values['depot-paths'] = paths.split(',')
return values
def gitBranchExists(branch):
proc = subprocess.Popen(["git", "rev-parse", branch],
stderr=subprocess.PIPE, stdout=subprocess.PIPE);
return proc.wait() == 0;
_gitConfig = {}
def gitConfig(key):
if key not in _gitConfig:
cmd = [ "git", "config", key ]
s = read_pipe(cmd, ignore_error=True)
_gitConfig[key] = s.strip()
return _gitConfig[key]
def gitConfigBool(key):
"""Return a bool, using git config --bool. It is True only if the
variable is set to true, and False if set to false or not present
in the config."""
if key not in _gitConfig:
cmd = [ "git", "config", "--bool", key ]
s = read_pipe(cmd, ignore_error=True)
v = s.strip()
_gitConfig[key] = v == "true"
return _gitConfig[key]
def gitConfigList(key):
if key not in _gitConfig:
s = read_pipe(["git", "config", "--get-all", key], ignore_error=True)
_gitConfig[key] = s.strip().split(os.linesep)
return _gitConfig[key]
def p4BranchesInGit(branchesAreInRemotes=True):
"""Find all the branches whose names start with "p4/", looking
in remotes or heads as specified by the argument. Return
a dictionary of { branch: revision } for each one found.
The branch names are the short names, without any
"p4/" prefix."""
branches = {}
cmdline = "git rev-parse --symbolic "
if branchesAreInRemotes:
cmdline += "--remotes"
else:
cmdline += "--branches"
for line in read_pipe_lines(cmdline):
line = line.strip()
# only import to p4/
if not line.startswith('p4/'):
continue
# special symbolic ref to p4/master
if line == "p4/HEAD":
continue
# strip off p4/ prefix
branch = line[len("p4/"):]
branches[branch] = parseRevision(line)
return branches
def branch_exists(branch):
"""Make sure that the given ref name really exists."""
cmd = [ "git", "rev-parse", "--symbolic", "--verify", branch ]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, _ = p.communicate()
if p.returncode:
return False
# expect exactly one line of output: the branch name
return out.rstrip() == branch
def findUpstreamBranchPoint(head = "HEAD"):
branches = p4BranchesInGit()
# map from depot-path to branch name
branchByDepotPath = {}
for branch in branches.keys():
tip = branches[branch]
log = extractLogMessageFromGitCommit(tip)
settings = extractSettingsGitLog(log)
if "depot-paths" in settings:
paths = ",".join(settings["depot-paths"])
branchByDepotPath[paths] = "remotes/p4/" + branch
settings = None
parent = 0
while parent < 65535:
commit = head + "~%s" % parent
log = extractLogMessageFromGitCommit(commit)
settings = extractSettingsGitLog(log)
if "depot-paths" in settings:
paths = ",".join(settings["depot-paths"])
if paths in branchByDepotPath:
return [branchByDepotPath[paths], settings]
parent = parent + 1
return ["", settings]
def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
if not silent:
print ("Creating/updating branch(es) in %s based on origin branch(es)"
% localRefPrefix)
originPrefix = "origin/p4/"
for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
line = line.strip()
if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
continue
headName = line[len(originPrefix):]
remoteHead = localRefPrefix + headName
originHead = line
original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
if ('depot-paths' not in original
or 'change' not in original):
continue
update = False
if not gitBranchExists(remoteHead):
if verbose:
print("creating %s" % remoteHead)
update = True
else:
settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
if ('change' in settings) > 0:
if settings['depot-paths'] == original['depot-paths']:
originP4Change = int(original['change'])
p4Change = int(settings['change'])
if originP4Change > p4Change:
print ("%s (%s) is newer than %s (%s). "
"Updating p4 branch from origin."
% (originHead, originP4Change,
remoteHead, p4Change))
update = True
else:
print ("Ignoring: %s was imported from %s while "
"%s was imported from %s"
% (originHead, ','.join(original['depot-paths']),
remoteHead, ','.join(settings['depot-paths'])))
if update:
system("git update-ref %s %s" % (remoteHead, originHead))
def originP4BranchesExist():
return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
def p4ChangesForPaths(depotPaths, changeRange):
assert depotPaths
cmd = ['changes']
for p in depotPaths:
cmd += ["%s...%s" % (p, changeRange)]
output = p4_read_pipe_lines(cmd)
changes = {}
for line in output:
changeNum = int(line.split(" ")[1])
changes[changeNum] = True
changelist = sorted(changes.keys())
return changelist
def p4PathStartsWith(path, prefix):
# This method tries to remedy a potential mixed-case issue:
#
# If UserA adds //depot/DirA/file1
# and UserB adds //depot/dira/file2
#
# we may or may not have a problem. If you have core.ignorecase=true,
# we treat DirA and dira as the same directory
if gitConfigBool("core.ignorecase"):
return path.lower().startswith(prefix.lower())
return path.startswith(prefix)
def getClientSpec():
"""Look at the p4 client spec, create a View() object that contains
all the mappings, and return it."""
specList = p4CmdList("client -o")
if len(specList) != 1:
die('Output from "client -o" is %d lines, expecting 1' %
len(specList))
# dictionary of all client parameters
entry = specList[0]
# the //client/ name
client_name = entry["Client"]
# just the keys that start with "View"
view_keys = [ k for k in entry.keys() if k.startswith("View") ]
# hold this new View
view = View(client_name)
# append the lines, in order, to the view
for view_num in range(len(view_keys)):
k = "View%d" % view_num
if k not in view_keys:
die("Expected view key %s missing" % k)
view.append(entry[k])
return view
def getClientRoot():
"""Grab the client directory."""
output = p4CmdList("client -o")
if len(output) != 1:
die('Output from "client -o" is %d lines, expecting 1' % len(output))
entry = output[0]
if "Root" not in entry:
die('Client has no "Root"')
return entry["Root"]
#
# P4 wildcards are not allowed in filenames. P4 complains
# if you simply add them, but you can force it with "-f", in
# which case it translates them into %xx encoding internally.
#
def wildcard_decode(path):
# Search for and fix just these four characters. Do % last so
# that fixing it does not inadvertently create new %-escapes.
# Cannot have * in a filename in windows; untested as to
# what p4 would do in such a case.
if not platform.system() == "Windows":
path = path.replace("%2A", "*")
path = path.replace("%23", "#") \
.replace("%40", "@") \
.replace("%25", "%")
return path
def wildcard_encode(path):
# do % first to avoid double-encoding the %s introduced here
path = path.replace("%", "%25") \
.replace("*", "%2A") \
.replace("#", "%23") \
.replace("@", "%40")
return path
def wildcard_present(path):
m = re.search(r"[*#@%]", path)
return m is not None
class Command:
def __init__(self):
self.usage = "usage: %prog [options]"
self.needsGit = True
self.verbose = False
class P4UserMap:
def __init__(self):
self.userMapFromPerforceServer = False
self.myP4UserId = None
def p4UserId(self):
if self.myP4UserId:
return self.myP4UserId
results = p4CmdList("user -o")
for r in results:
if 'User' in r:
self.myP4UserId = r['User']
return r['User']
die("Could not find your p4 user id")
def p4UserIsMe(self, p4User):
# return True if the given p4 user is actually me
me = self.p4UserId()
if not p4User or p4User != me:
return False
else:
return True
def getUserCacheFilename(self):
home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
return home + "/.gitp4-usercache.txt"
def getUserMapFromPerforceServer(self):
if self.userMapFromPerforceServer:
return
self.users = {}
self.emails = {}
for output in p4CmdList("users"):
if "User" not in output:
continue
self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
self.emails[output["Email"]] = output["User"]
s = ''
for (key, val) in self.users.items():
s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
open(self.getUserCacheFilename(), "wb").write(s)
self.userMapFromPerforceServer = True
def loadUserMapFromCache(self):
self.users = {}
self.userMapFromPerforceServer = False
try:
cache = open(self.getUserCacheFilename(), "rb")
lines = cache.readlines()
cache.close()
for line in lines:
entry = line.strip().split("\t")
self.users[entry[0]] = entry[1]
except OSError:
self.getUserMapFromPerforceServer()
class P4Debug(Command):
def __init__(self):
Command.__init__(self)
self.options = []
self.description = "A tool to debug the output of p4 -G."
self.needsGit = False
def run(self, args):
j = 0
for output in p4CmdList(args):
print('Element: %d' % j)
j += 1
print(output)
return True
class P4RollBack(Command):
def __init__(self):
Command.__init__(self)
self.options = [
optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
]
self.description = "A tool to debug the multi-branch import. Don't use :)"
self.rollbackLocalBranches = False
def run(self, args):
if len(args) != 1:
return False
maxChange = int(args[0])
if "p4ExitCode" in p4Cmd("changes -m 1"):
die("Problems executing p4");
if self.rollbackLocalBranches:
refPrefix = "refs/heads/"
lines = read_pipe_lines("git rev-parse --symbolic --branches")
else:
refPrefix = "refs/remotes/"
lines = read_pipe_lines("git rev-parse --symbolic --remotes")
for line in lines:
if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
line = line.strip()
ref = refPrefix + line
log = extractLogMessageFromGitCommit(ref)
settings = extractSettingsGitLog(log)
depotPaths = settings['depot-paths']
change = settings['change']
changed = False
if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
for p in depotPaths]))) == 0:
print("Branch %s did not exist at change %s, deleting." % (ref, maxChange))
system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
continue
while change and int(change) > maxChange:
changed = True
if self.verbose:
print("%s is at %s ; rewinding towards %s" % (ref, change, maxChange))
system("git update-ref %s \"%s^\"" % (ref, ref))
log = extractLogMessageFromGitCommit(ref)
settings = extractSettingsGitLog(log)
depotPaths = settings['depot-paths']
change = settings['change']
if changed:
print("%s rewound to %s" % (ref, change))
return True
class P4Submit(Command, P4UserMap):
conflict_behavior_choices = ("ask", "skip", "quit")
def __init__(self):
Command.__init__(self)
P4UserMap.__init__(self)
self.options = [
optparse.make_option("--origin", dest="origin"),
optparse.make_option("-M", dest="detectRenames", action="store_true"),
# preserve the user, requires relevant p4 permissions
optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
optparse.make_option("--conflict", dest="conflict_behavior",
choices=self.conflict_behavior_choices),
optparse.make_option("--branch", dest="branch"),
]
self.description = "Submit changes from git to the perforce depot."
self.usage += " [name of git branch to submit into perforce depot]"
self.origin = ""
self.detectRenames = False
self.preserveUser = gitConfigBool("git-p4.preserveUser")
self.dry_run = False
self.prepare_p4_only = False
self.conflict_behavior = None
self.isWindows = (platform.system() == "Windows")
self.exportLabels = False
self.p4HasMoveCommand = p4_has_move_command()
self.branch = None
def check(self):
if len(p4CmdList("opened ...")) > 0:
die("You have files opened with perforce! Close them before starting the sync.")
def separate_jobs_from_description(self, message):
"""Extract and return a possible Jobs field in the commit
message. It goes into a separate section in the p4 change
specification.
A jobs line starts with "Jobs:" and looks like a new field
in a form. Values are white-space separated on the same
line or on following lines that start with a tab.
This does not parse and extract the full git commit message
like a p4 form. It just sees the Jobs: line as a marker
to pass everything from then on directly into the p4 form,
but outside the description section.
Return a tuple (stripped log message, jobs string)."""
m = re.search(r'^Jobs:', message, re.MULTILINE)
if m is None:
return (message, None)
jobtext = message[m.start():]
stripped_message = message[:m.start()].rstrip()
return (stripped_message, jobtext)
def prepareLogMessage(self, template, message, jobs):
"""Edits the template returned from "p4 change -o" to insert
the message in the Description field, and the jobs text in
the Jobs field."""
result = ""
inDescriptionSection = False
for line in template.split("\n"):
if line.startswith("#"):
result += line + "\n"
continue
if inDescriptionSection:
if line.startswith("Files:") or line.startswith("Jobs:"):
inDescriptionSection = False
# insert Jobs section
if jobs:
result += jobs + "\n"
else:
continue
else:
if line.startswith("Description:"):
inDescriptionSection = True
line += "\n"
for messageLine in message.split("\n"):
line += "\t" + messageLine + "\n"
result += line + "\n"
return result
def patchRCSKeywords(self, file, pattern):
# Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern
(handle, outFileName) = tempfile.mkstemp(dir='.')
try:
outFile = os.fdopen(handle, "w+")
inFile = open(file)
regexp = re.compile(pattern, re.VERBOSE)
for line in inFile.readlines():
line = regexp.sub(r'$\1$', line)
outFile.write(line)
inFile.close()
outFile.close()
# Forcibly overwrite the original file
os.unlink(file)
shutil.move(outFileName, file)
except:
# cleanup our temporary file
os.unlink(outFileName)
print("Failed to strip RCS keywords in %s" % file)
raise
print("Patched up RCS keywords in %s" % file)
def p4UserForCommit(self, id):
# Return the tuple (perforce user,git email) for a given git commit id
self.getUserMapFromPerforceServer()
gitEmail = read_pipe(["git", "log", "--max-count=1",
"--format=%ae", id])
gitEmail = gitEmail.strip()
if gitEmail not in self.emails:
return (None, gitEmail)
else:
return (self.emails[gitEmail], gitEmail)
def checkValidP4Users(self, commits):
# check if any git authors cannot be mapped to p4 users
for id in commits:
(user, email) = self.p4UserForCommit(id)
if not user:
msg = "Cannot find p4 user for email %s in commit %s." % (email, id)
if gitConfigBool("git-p4.allowMissingP4Users"):
print("%s" % msg)
else:
die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
def lastP4Changelist(self):
# Get back the last changelist number submitted in this client spec. This
# then gets used to patch up the username in the change. If the same
# client spec is being used by multiple processes then this might go
# wrong.
results = p4CmdList("client -o") # find the current client
client = None
for r in results:
if 'Client' in r:
client = r['Client']
break
if not client:
die("could not get client spec")
results = p4CmdList(["changes", "-c", client, "-m", "1"])
for r in results:
if 'change' in r:
return r['change']
die("Could not get changelist number for last submit - cannot patch up user details")
def modifyChangelistUser(self, changelist, newUser):
# fixup the user field of a changelist after it has been submitted.
changes = p4CmdList("change -o %s" % changelist)
if len(changes) != 1:
die("Bad output from p4 change modifying %s to user %s" %
(changelist, newUser))
c = changes[0]
if c['User'] == newUser: return # nothing to do
c['User'] = newUser
input = marshal.dumps(c)
result = p4CmdList("change -f -i", stdin=input)
for r in result:
if 'code' in r:
if r['code'] == 'error':
die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
if 'data' in r:
print("Updated user field for changelist %s to %s" % (changelist, newUser))
return
die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
def canChangeChangelists(self):
# check to see if we have p4 admin or super-user permissions, either of
# which are required to modify changelists.
results = p4CmdList(["protects", self.depotPath])
for r in results:
if 'perm' in r:
if r['perm'] == 'admin':
return 1
if r['perm'] == 'super':
return 1
return 0
def prepareSubmitTemplate(self):
"""Run "p4 change -o" to grab a change specification template.
This does not use "p4 -G", as it is nice to keep the submission
template in original order, since a human might edit it.
Remove lines in the Files section that show changes to files
outside the depot path we're committing into."""
template = ""
inFilesSection = False
for line in p4_read_pipe_lines(['change', '-o']):
if line.endswith("\r\n"):
line = line[:-2] + "\n"
if inFilesSection:
if line.startswith("\t"):
# path starts and ends with a tab
path = line[1:]
lastTab = path.rfind("\t")
if lastTab != -1:
path = path[:lastTab]
if not p4PathStartsWith(path, self.depotPath):
continue
else:
inFilesSection = False
else:
if line.startswith("Files:"):
inFilesSection = True
template += line
return template
def edit_template(self, template_file):
"""Invoke the editor to let the user change the submission
message. Return true if okay to continue with the submit."""
# if configured to skip the editing part, just submit
if gitConfigBool("git-p4.skipSubmitEdit"):
return True
# look at the modification time, to check later if the user saved
# the file
mtime = os.stat(template_file).st_mtime
# invoke the editor
if "P4EDITOR" in os.environ and (os.environ.get("P4EDITOR") != ""):
editor = os.environ.get("P4EDITOR")
else:
editor = read_pipe("git var GIT_EDITOR").strip()
system(editor + " " + template_file)
# If the file was not saved, prompt to see if this patch should
# be skipped. But skip this verification step if configured so.
if gitConfigBool("git-p4.skipSubmitEditCheck"):
return True
# modification time updated means user saved the file
if os.stat(template_file).st_mtime > mtime:
return True
while True:
response = input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
if response == 'y':
return True
if response == 'n':
return False
def applyCommit(self, id):
"""Apply one commit, return True if it succeeded."""
print("Applying", read_pipe(["git", "show", "-s",
"--format=format:%h %s", id]))
(p4User, gitEmail) = self.p4UserForCommit(id)
diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (self.diffOpts, id, id))
filesToAdd = set()
filesToDelete = set()
editedFiles = set()
pureRenameCopy = set()
filesToChangeExecBit = {}
for line in diff:
diff = parseDiffTreeEntry(line)
modifier = diff['status']
path = diff['src']
if modifier == "M":
p4_edit(path)
if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
filesToChangeExecBit[path] = diff['dst_mode']
editedFiles.add(path)
elif modifier == "A":
filesToAdd.add(path)
filesToChangeExecBit[path] = diff['dst_mode']
if path in filesToDelete:
filesToDelete.remove(path)
elif modifier == "D":
filesToDelete.add(path)
if path in filesToAdd:
filesToAdd.remove(path)
elif modifier == "C":
src, dest = diff['src'], diff['dst']
p4_integrate(src, dest)
pureRenameCopy.add(dest)
if diff['src_sha1'] != diff['dst_sha1']:
p4_edit(dest)
pureRenameCopy.discard(dest)
if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
p4_edit(dest)
pureRenameCopy.discard(dest)
filesToChangeExecBit[dest] = diff['dst_mode']
if self.isWindows:
# turn off read-only attribute
os.chmod(dest, stat.S_IWRITE)
os.unlink(dest)
editedFiles.add(dest)
elif modifier == "R":
src, dest = diff['src'], diff['dst']
if self.p4HasMoveCommand:
p4_edit(src) # src must be open before move
p4_move(src, dest) # opens for (move/delete, move/add)
else:
p4_integrate(src, dest)
if diff['src_sha1'] != diff['dst_sha1']:
p4_edit(dest)
else:
pureRenameCopy.add(dest)
if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
if not self.p4HasMoveCommand:
p4_edit(dest) # with move: already open, writable
filesToChangeExecBit[dest] = diff['dst_mode']
if not self.p4HasMoveCommand:
if self.isWindows:
os.chmod(dest, stat.S_IWRITE)
os.unlink(dest)
filesToDelete.add(src)
editedFiles.add(dest)
else:
die("unknown modifier %s for %s" % (modifier, path))
diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
patchcmd = diffcmd + " | git apply "
tryPatchCmd = patchcmd + "--check -"
applyPatchCmd = patchcmd + "--check --apply -"
patch_succeeded = True
if os.system(tryPatchCmd) != 0:
fixed_rcs_keywords = False
patch_succeeded = False
print("Unfortunately applying the change failed!")
# Patch failed, maybe it's just RCS keyword woes. Look through
# the patch to see if that's possible.
if gitConfigBool("git-p4.attemptRCSCleanup"):
file = None
pattern = None
kwfiles = {}
for file in editedFiles | filesToDelete:
# did this file's delta contain RCS keywords?
pattern = p4_keywords_regexp_for_file(file)
if pattern:
# this file is a possibility...look for RCS keywords.
regexp = re.compile(pattern, re.VERBOSE)
for line in read_pipe_lines(["git", "diff", "%s^..%s" % (id, id), file]):
if regexp.search(line):
if verbose:
print("got keyword match on %s in %s in %s" % (pattern, line, file))
kwfiles[file] = pattern
break
for file in kwfiles:
if verbose:
print("zapping %s with %s" % (line, pattern))
# File is being deleted, so not open in p4. Must
# disable the read-only bit on windows.
if self.isWindows and file not in editedFiles:
os.chmod(file, stat.S_IWRITE)
self.patchRCSKeywords(file, kwfiles[file])
fixed_rcs_keywords = True
if fixed_rcs_keywords:
print("Retrying the patch with RCS keywords cleaned up")
if os.system(tryPatchCmd) == 0:
patch_succeeded = True
if not patch_succeeded:
for f in editedFiles:
p4_revert(f)
return False
#
# Apply the patch for real, and do add/delete/+x handling.
#
system(applyPatchCmd)
for f in filesToAdd:
p4_add(f)
for f in filesToDelete:
p4_revert(f)
p4_delete(f)
# Set/clear executable bits
for f in filesToChangeExecBit.keys():
mode = filesToChangeExecBit[f]
setP4ExecBit(f, mode)
#
# Build p4 change description, starting with the contents
# of the git commit message.
#
logMessage = extractLogMessageFromGitCommit(id)
logMessage = logMessage.strip()
(logMessage, jobs) = self.separate_jobs_from_description(logMessage)
template = self.prepareSubmitTemplate()
submitTemplate = self.prepareLogMessage(template, logMessage, jobs)
if self.preserveUser:
submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User
if self.checkAuthorship and not self.p4UserIsMe(p4User):
submitTemplate += "######## git author %s does not match your p4 account.\n" % gitEmail
submitTemplate += "######## Use option --preserve-user to modify authorship.\n"
submitTemplate += "######## Variable git-p4.skipUserNameCheck hides this message.\n"
separatorLine = "######## everything below this line is just the diff #######\n"
# diff
if "P4DIFF" in os.environ:
del(os.environ["P4DIFF"])
diff = ""
for editedFile in editedFiles:
diff += p4_read_pipe(['diff', '-du',
wildcard_encode(editedFile)])
# new file diff
newdiff = ""
for newFile in filesToAdd:
newdiff += "==== new file ====\n"
newdiff += "--- /dev/null\n"
newdiff += "+++ %s\n" % newFile
f = open(newFile)
for line in f.readlines():
newdiff += "+" + line
f.close()
# change description file: submitTemplate, separatorLine, diff, newdiff
(handle, fileName) = tempfile.mkstemp()
tmpFile = os.fdopen(handle, "w+")
if self.isWindows:
submitTemplate = submitTemplate.replace("\n", "\r\n")
separatorLine = separatorLine.replace("\n", "\r\n")
newdiff = newdiff.replace("\n", "\r\n")
tmpFile.write(submitTemplate + separatorLine + diff + newdiff)
tmpFile.close()
if self.prepare_p4_only:
#
# Leave the p4 tree prepared, and the submit template around
# and let the user decide what to do next
#
print()
print("P4 workspace prepared for submission.")
print("To submit or revert, go to client workspace")
print(" " + self.clientPath)
print()
print("To submit, use \"p4 submit\" to write a new description,")
print("or \"p4 submit -i %s\" to use the one prepared by" \
" \"git p4\"." % fileName)
print("You can delete the file \"%s\" when finished." % fileName)
if self.preserveUser and p4User and not self.p4UserIsMe(p4User):
print("To preserve change ownership by user %s, you must\n" \
"do \"p4 change -f <change>\" after submitting and\n" \
"edit the User field.")
if pureRenameCopy:
print("After submitting, renamed files must be re-synced.")
print("Invoke \"p4 sync -f\" on each of these files:")
for f in pureRenameCopy:
print(" " + f)
print()
print("To revert the changes, use \"p4 revert ...\", and delete")
print("the submit template file \"%s\"" % fileName)
if filesToAdd:
print("Since the commit adds new files, they must be deleted:")
for f in filesToAdd:
print(" " + f)
print()
return True
#
# Let the user edit the change description, then submit it.
#
if self.edit_template(fileName):
# read the edited message and submit
ret = True
tmpFile = open(fileName, "rb")
message = tmpFile.read()
tmpFile.close()
submitTemplate = message[:message.index(separatorLine)]
if self.isWindows:
submitTemplate = submitTemplate.replace("\r\n", "\n")
p4_write_pipe(['submit', '-i'], submitTemplate)
if self.preserveUser:
if p4User:
# Get last changelist number. Cannot easily get it from
# the submit command output as the output is
# unmarshalled.
changelist = self.lastP4Changelist()
self.modifyChangelistUser(changelist, p4User)
# The rename/copy happened by applying a patch that created a
# new file. This leaves it writable, which confuses p4.
for f in pureRenameCopy:
p4_sync(f, "-f")
else:
# skip this patch
ret = False
print("Submission cancelled, undoing p4 changes.")
for f in editedFiles:
p4_revert(f)
for f in filesToAdd:
p4_revert(f)
os.remove(f)
for f in filesToDelete:
p4_revert(f)
os.remove(fileName)
return ret
# Export git tags as p4 labels. Create a p4 label and then tag
# with that.
def exportGitTags(self, gitTags):
validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
if len(validLabelRegexp) == 0:
validLabelRegexp = defaultLabelRegexp
m = re.compile(validLabelRegexp)
for name in gitTags:
if not m.match(name):
if verbose:
print("tag %s does not match regexp %s" % (name, validLabelRegexp))
continue
# Get the p4 commit this corresponds to
logMessage = extractLogMessageFromGitCommit(name)
values = extractSettingsGitLog(logMessage)
if 'change' not in values:
# a tag pointing to something not sent to p4; ignore
if verbose:
print("git tag %s does not give a p4 commit" % name)
continue
else:
changelist = values['change']
# Get the tag details.
inHeader = True
isAnnotated = False
body = []
for l in read_pipe_lines(["git", "cat-file", "-p", name]):
l = l.strip()
if inHeader:
if re.match(r'tag\s+', l):
isAnnotated = True
elif re.match(r'\s*$', l):
inHeader = False
continue
else:
body.append(l)
if not isAnnotated:
body = ["lightweight tag imported by git p4\n"]
# Create the label - use the same view as the client spec we are using
clientSpec = getClientSpec()
labelTemplate = "Label: %s\n" % name
labelTemplate += "Description:\n"
for b in body:
labelTemplate += "\t" + b + "\n"
labelTemplate += "View:\n"
for depot_side in clientSpec.mappings:
labelTemplate += "\t%s\n" % depot_side
if self.dry_run:
print("Would create p4 label %s for tag" % name)
elif self.prepare_p4_only:
print("Not creating p4 label %s for tag due to option" \
" --prepare-p4-only" % name)
else:
p4_write_pipe(["label", "-i"], labelTemplate)
# Use the label
p4_system(["tag", "-l", name] +
["%s@%s" % (depot_side, changelist) for depot_side in clientSpec.mappings])
if verbose:
print("created p4 label for tag %s" % name)
def run(self, args):
if len(args) == 0:
self.master = currentGitBranch()
if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
die("Detecting current git branch failed!")
elif len(args) == 1:
self.master = args[0]
if not branchExists(self.master):
die("Branch %s does not exist" % self.master)
else:
return False
allowSubmit = gitConfig("git-p4.allowSubmit")
if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","):
die("%s is not in git-p4.allowSubmit" % self.master)
[upstream, settings] = findUpstreamBranchPoint()
self.depotPath = settings['depot-paths'][0]
if len(self.origin) == 0:
self.origin = upstream
if self.preserveUser:
if not self.canChangeChangelists():
die("Cannot preserve user names without p4 super-user or admin permissions")
# if not set from the command line, try the config file
if self.conflict_behavior is None:
val = gitConfig("git-p4.conflict")
if val:
if val not in self.conflict_behavior_choices:
die("Invalid value '%s' for config git-p4.conflict" % val)
else:
val = "ask"
self.conflict_behavior = val
if self.verbose:
print("Origin branch is " + self.origin)
if len(self.depotPath) == 0:
print("Internal error: cannot locate perforce depot path from existing branches")
sys.exit(128)
self.useClientSpec = False
if gitConfigBool("git-p4.useclientspec"):
self.useClientSpec = True
if self.useClientSpec:
self.clientSpecDirs = getClientSpec()
if self.useClientSpec:
# all files are relative to the client spec
self.clientPath = getClientRoot()
else:
self.clientPath = p4Where(self.depotPath)
if self.clientPath == "":
die("Error: Cannot locate perforce checkout of %s in client view" % self.depotPath)
print("Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath))
self.oldWorkingDirectory = os.getcwd()
# ensure the clientPath exists
new_client_dir = False
if not os.path.exists(self.clientPath):
new_client_dir = True
os.makedirs(self.clientPath)
chdir(self.clientPath, is_client_path=True)
if self.dry_run:
print("Would synchronize p4 checkout in %s" % self.clientPath)
else:
print("Synchronizing p4 checkout...")
if new_client_dir:
# old one was destroyed, and maybe nobody told p4
p4_sync("...", "-f")
else:
p4_sync("...")
self.check()
commits = []
for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (self.origin, self.master)]):
commits.append(line.strip())
commits.reverse()
if self.preserveUser or gitConfigBool("git-p4.skipUserNameCheck"):
self.checkAuthorship = False
else:
self.checkAuthorship = True
if self.preserveUser:
self.checkValidP4Users(commits)
#
# Build up a set of options to be passed to diff when
# submitting each commit to p4.
#
if self.detectRenames:
# command-line -M arg
self.diffOpts = "-M"
else:
# If not explicitly set check the config variable
detectRenames = gitConfig("git-p4.detectRenames")
if detectRenames.lower() == "false" or detectRenames == "":
self.diffOpts = ""
elif detectRenames.lower() == "true":
self.diffOpts = "-M"
else:
self.diffOpts = "-M%s" % detectRenames
# no command-line arg for -C or --find-copies-harder, just
# config variables
detectCopies = gitConfig("git-p4.detectCopies")
if detectCopies.lower() == "false" or detectCopies == "":
pass
elif detectCopies.lower() == "true":
self.diffOpts += " -C"
else:
self.diffOpts += " -C%s" % detectCopies
if gitConfigBool("git-p4.detectCopiesHarder"):
self.diffOpts += " --find-copies-harder"
#
# Apply the commits, one at a time. On failure, ask if should
# continue to try the rest of the patches, or quit.
#
if self.dry_run:
print("Would apply")
applied = []
last = len(commits) - 1
for i, commit in enumerate(commits):
if self.dry_run:
print(" ", read_pipe(["git", "show", "-s",
"--format=format:%h %s", commit]))
ok = True
else:
ok = self.applyCommit(commit)
if ok:
applied.append(commit)
else:
if self.prepare_p4_only and i < last:
print("Processing only the first commit due to option" \
" --prepare-p4-only")
break
if i < last:
quit = False
while True:
# prompt for what to do, or use the option/variable
if self.conflict_behavior == "ask":
print("What do you want to do?")
response = input("[s]kip this commit but apply"
" the rest, or [q]uit? ")
if not response:
continue
elif self.conflict_behavior == "skip":
response = "s"
elif self.conflict_behavior == "quit":
response = "q"
else:
die("Unknown conflict_behavior '%s'" %
self.conflict_behavior)
if response[0] == "s":
print("Skipping this commit, but applying the rest")
break
if response[0] == "q":
print("Quitting")
quit = True
break
if quit:
break
chdir(self.oldWorkingDirectory)
if self.dry_run:
pass
elif self.prepare_p4_only:
pass
elif len(commits) == len(applied):
print("All commits applied!")
sync = P4Sync()
if self.branch:
sync.branch = self.branch
sync.run([])
rebase = P4Rebase()
rebase.rebase()
else:
if len(applied) == 0:
print("No commits applied.")
else:
print("Applied only the commits marked with '*':")
for c in commits:
if c in applied:
star = "*"
else:
star = " "
print(star, read_pipe(["git", "show", "-s",
"--format=format:%h %s", c]))
print("You will have to do 'git p4 sync' and rebase.")
if gitConfigBool("git-p4.exportLabels"):
self.exportLabels = True
if self.exportLabels:
p4Labels = getP4Labels(self.depotPath)
gitTags = getGitTags()
missingGitTags = gitTags - p4Labels
self.exportGitTags(missingGitTags)
# exit with error unless everything applied perfectly
if len(commits) != len(applied):
sys.exit(1)
return True
class View:
"""Represent a p4 view ("p4 help views"), and map files in a
repo according to the view."""
def __init__(self, client_name):
self.mappings = []
self.client_prefix = "//%s/" % client_name
# cache results of "p4 where" to lookup client file locations
self.client_spec_path_cache = {}
def append(self, view_line):
"""Parse a view line, splitting it into depot and client
sides. Append to self.mappings, preserving order. This
is only needed for tag creation."""
# Split the view line into exactly two words. P4 enforces
# structure on these lines that simplifies this quite a bit.
#
# Either or both words may be double-quoted.
# Single quotes do not matter.
# Double-quote marks cannot occur inside the words.
# A + or - prefix is also inside the quotes.
# There are no quotes unless they contain a space.
# The line is already white-space stripped.
# The two words are separated by a single space.
#
if view_line[0] == '"':
# First word is double quoted. Find its end.
close_quote_index = view_line.find('"', 1)
if close_quote_index <= 0:
die("No first-word closing quote found: %s" % view_line)
depot_side = view_line[1:close_quote_index]
# skip closing quote and space
rhs_index = close_quote_index + 1 + 1
else:
space_index = view_line.find(" ")
if space_index <= 0:
die("No word-splitting space found: %s" % view_line)
depot_side = view_line[0:space_index]
rhs_index = space_index + 1
# prefix + means overlay on previous mapping
if depot_side.startswith("+"):
depot_side = depot_side[1:]
# prefix - means exclude this path, leave out of mappings
exclude = False
if depot_side.startswith("-"):
exclude = True
depot_side = depot_side[1:]
if not exclude:
self.mappings.append(depot_side)
def convert_client_path(self, clientFile):
# chop off //client/ part to make it relative
if not clientFile.startswith(self.client_prefix):
die("No prefix '%s' on clientFile '%s'" %
(self.client_prefix, clientFile))
return clientFile[len(self.client_prefix):]
def update_client_spec_path_cache(self, files):
""" Caching file paths by "p4 where" batch query """
# List depot file paths exclude that already cached
fileArgs = [f['path'] for f in files if f['path'] not in self.client_spec_path_cache]
if len(fileArgs) == 0:
return # All files in cache
where_result = p4CmdList(["-x", "-", "where"], stdin=fileArgs)
for res in where_result:
if "code" in res and res["code"] == "error":
# assume error is "... file(s) not in client view"
continue
if "clientFile" not in res:
die("No clientFile from 'p4 where %s'" % depot_path)
if "unmap" in res:
# it will list all of them, but only one not unmap-ped
continue
self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])
# not found files or unmap files set to ""
for depotFile in fileArgs:
if depotFile not in self.client_spec_path_cache:
self.client_spec_path_cache[depotFile] = ""
def map_in_client(self, depot_path):
"""Return the relative location in the client where this
depot file should live. Returns "" if the file should
not be mapped in the client."""
if depot_path in self.client_spec_path_cache:
return self.client_spec_path_cache[depot_path]
die( "Error: %s is not found in client spec path" % depot_path )
return ""
class P4Sync(Command, P4UserMap):
delete_actions = ( "delete", "move/delete", "purge" )
def __init__(self):
Command.__init__(self)
P4UserMap.__init__(self)
self.options = [
optparse.make_option("--branch", dest="branch"),
optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
optparse.make_option("--changesfile", dest="changesFile"),
optparse.make_option("--silent", dest="silent", action="store_true"),
optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
help="Import into refs/heads/ , not refs/remotes"),
optparse.make_option("--max-changes", dest="maxChanges"),
optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
help="Only sync files that are included in the Perforce Client Spec")
]
self.description = """Imports from Perforce into a git repository.\n
example:
//depot/my/project/ -- to import the current head
//depot/my/project/@all -- to import everything
//depot/my/project/@1,6 -- to import only from revision 1 to 6
(a ... is not needed in the path p4 specification, it's added implicitly)"""
self.usage += " //depot/path[@revRange]"
self.silent = False
self.createdBranches = set()
self.committedChanges = set()
self.branch = ""
self.detectBranches = False
self.detectLabels = False
self.importLabels = False
self.changesFile = ""
self.syncWithOrigin = True
self.importIntoRemotes = True
self.maxChanges = ""
self.keepRepoPath = False
self.depotPaths = None
self.p4BranchesInGit = []
self.cloneExclude = []
self.useClientSpec = False
self.useClientSpec_from_options = False
self.clientSpecDirs = None
self.tempBranches = []
self.tempBranchLocation = "git-p4-tmp"
if gitConfig("git-p4.syncFromOrigin") == "false":
self.syncWithOrigin = False
# Force a checkpoint in fast-import and wait for it to finish
def checkpoint(self):
self.gitStream.write("checkpoint\n\n")
self.gitStream.write("progress checkpoint\n\n")
out = self.gitOutput.readline()
if self.verbose:
print("checkpoint finished: " + out)
def extractFilesFromCommit(self, commit):
self.cloneExclude = [re.sub(r"\.\.\.$", "", path)
for path in self.cloneExclude]
files = []
fnum = 0
while "depotFile%s" % fnum in commit:
path = commit["depotFile%s" % fnum]
if [p for p in self.cloneExclude
if p4PathStartsWith(path, p)]:
found = False
else:
found = [p for p in self.depotPaths
if p4PathStartsWith(path, p)]
if not found:
fnum = fnum + 1
continue
file = {}
file["path"] = path
file["rev"] = commit["rev%s" % fnum]
file["action"] = commit["action%s" % fnum]
file["type"] = commit["type%s" % fnum]
files.append(file)
fnum = fnum + 1
return files
def stripRepoPath(self, path, prefixes):
"""When streaming files, this is called to map a p4 depot path
to where it should go in git. The prefixes are either
self.depotPaths, or self.branchPrefixes in the case of
branch detection."""
if self.useClientSpec:
# branch detection moves files up a level (the branch name)
# from what client spec interpretation gives
path = self.clientSpecDirs.map_in_client(path)
if self.detectBranches:
for b in self.knownBranches:
if path.startswith(b + "/"):
path = path[len(b)+1:]
elif self.keepRepoPath:
# Preserve everything in relative path name except leading
# //depot/; just look at first prefix as they all should
# be in the same depot.
depot = re.sub(r"^(//[^/]+/).*", r'\1', prefixes[0])
if p4PathStartsWith(path, depot):
path = path[len(depot):]
else:
for p in prefixes:
if p4PathStartsWith(path, p):
path = path[len(p):]
break
path = wildcard_decode(path)
return path
def splitFilesIntoBranches(self, commit):
"""Look at each depotFile in the commit to figure out to what
branch it belongs."""
if self.clientSpecDirs:
files = self.extractFilesFromCommit(commit)
self.clientSpecDirs.update_client_spec_path_cache(files)
branches = {}
fnum = 0
while "depotFile%s" % fnum in commit:
path = commit["depotFile%s" % fnum]
found = [p for p in self.depotPaths
if p4PathStartsWith(path, p)]
if not found:
fnum = fnum + 1
continue
file = {}
file["path"] = path
file["rev"] = commit["rev%s" % fnum]
file["action"] = commit["action%s" % fnum]
file["type"] = commit["type%s" % fnum]
fnum = fnum + 1
# start with the full relative path where this file would
# go in a p4 client
if self.useClientSpec:
relPath = self.clientSpecDirs.map_in_client(path)
else:
relPath = self.stripRepoPath(path, self.depotPaths)
for branch in self.knownBranches.keys():
# add a trailing slash so that a commit into qt/4.2foo
# doesn't end up in qt/4.2, e.g.
if relPath.startswith(branch + "/"):
if branch not in branches:
branches[branch] = []
branches[branch].append(file)
break
return branches
# output one file from the P4 stream
# - helper for streamP4Files
def streamOneP4File(self, file, contents):
relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)
if verbose:
sys.stderr.write("%s\n" % relPath)
(type_base, type_mods) = split_p4_type(file["type"])
git_mode = "100644"
if "x" in type_mods:
git_mode = "100755"
if type_base == "symlink":
git_mode = "120000"
# p4 print on a symlink sometimes contains "target\n";
# if it does, remove the newline
data = ''.join(contents)
if data[-1] == '\n':
contents = [data[:-1]]
else:
contents = [data]
if type_base == "utf16":
# p4 delivers different text in the python output to -G
# than it does when using "print -o", or normal p4 client
# operations. utf16 is converted to ascii or utf8, perhaps.
# But ascii text saved as -t utf16 is completely mangled.
# Invoke print -o to get the real contents.
#
# On windows, the newlines will always be mangled by print, so put
# them back too. This is not needed to the cygwin windows version,
# just the native "NT" type.
#
text = p4_read_pipe(['print', '-q', '-o', '-', file['depotFile']])
if p4_version_string().find("/NT") >= 0:
text = text.replace("\r\n", "\n")
contents = [ text ]
if type_base == "apple":
# Apple filetype files will be streamed as a concatenation of
# its appledouble header and the contents. This is useless
# on both macs and non-macs. If using "print -q -o xx", it
# will create "xx" with the data, and "%xx" with the header.
# This is also not very useful.
#
# Ideally, someday, this script can learn how to generate
# appledouble files directly and import those to git, but
# non-mac machines can never find a use for apple filetype.
print("\nIgnoring apple filetype file %s" % file['depotFile'])
return
# Note that we do not try to de-mangle keywords on utf16 files,
# even though in theory somebody may want that.
pattern = p4_keywords_regexp_for_type(type_base, type_mods)
if pattern:
regexp = re.compile(pattern, re.VERBOSE)
text = ''.join(contents)
text = regexp.sub(r'$\1$', text)
contents = [ text ]
self.gitStream.write("M %s inline %s\n" % (git_mode, relPath))
# total length...
length = 0
for d in contents:
length = length + len(d)
self.gitStream.write("data %d\n" % length)
for d in contents:
self.gitStream.write(d)
self.gitStream.write("\n")
def streamOneP4Deletion(self, file):
relPath = self.stripRepoPath(file['path'], self.branchPrefixes)
if verbose:
sys.stderr.write("delete %s\n" % relPath)
self.gitStream.write("D %s\n" % relPath)
# handle another chunk of streaming data
def streamP4FilesCb(self, marshalled):
# catch p4 errors and complain
err = None
if "code" in marshalled:
if marshalled["code"] == "error":
if "data" in marshalled:
err = marshalled["data"].rstrip()
if err:
f = None
if self.stream_have_file_info:
if "depotFile" in self.stream_file:
f = self.stream_file["depotFile"]
# force a failure in fast-import, else an empty
# commit will be made
self.gitStream.write("\n")
self.gitStream.write("die-now\n")
self.gitStream.close()
# ignore errors, but make sure it exits first
self.importProcess.wait()
if f:
die("Error from p4 print for %s: %s" % (f, err))
else:
die("Error from p4 print: %s" % err)
if 'depotFile' in marshalled and self.stream_have_file_info:
# start of a new file - output the old one first
self.streamOneP4File(self.stream_file, self.stream_contents)
self.stream_file = {}
self.stream_contents = []
self.stream_have_file_info = False
# pick up the new file information... for the
# 'data' field we need to append to our array
for k in marshalled.keys():
if k == 'data':
self.stream_contents.append(marshalled['data'])
else:
self.stream_file[k] = marshalled[k]
self.stream_have_file_info = True
# Stream directly from "p4 files" into "git fast-import"
def streamP4Files(self, files):
filesForCommit = []
filesToRead = []
filesToDelete = []
for f in files:
# if using a client spec, only add the files that have
# a path in the client
if self.clientSpecDirs:
if self.clientSpecDirs.map_in_client(f['path']) == "":
continue
filesForCommit.append(f)
if f['action'] in self.delete_actions:
filesToDelete.append(f)
else:
filesToRead.append(f)
# deleted files...
for f in filesToDelete:
self.streamOneP4Deletion(f)
if len(filesToRead) > 0:
self.stream_file = {}
self.stream_contents = []
self.stream_have_file_info = False
# curry self argument
def streamP4FilesCbSelf(entry):
self.streamP4FilesCb(entry)
fileArgs = ['%s#%s' % (f['path'], f['rev']) for f in filesToRead]
p4CmdList(["-x", "-", "print"],
stdin=fileArgs,
cb=streamP4FilesCbSelf)
# do the last chunk
if 'depotFile' in self.stream_file:
self.streamOneP4File(self.stream_file, self.stream_contents)
def make_email(self, userid):
if userid in self.users:
return self.users[userid]
else:
return "%s <a@b>" % userid
# Stream a p4 tag
def streamTag(self, gitStream, labelName, labelDetails, commit, epoch):
if verbose:
print("writing tag %s for commit %s" % (labelName, commit))
gitStream.write("tag %s\n" % labelName)
gitStream.write("from %s\n" % commit)
if 'Owner' in labelDetails:
owner = labelDetails["Owner"]
else:
owner = None
# Try to use the owner of the p4 label, or failing that,
# the current p4 user id.
if owner:
email = self.make_email(owner)
else:
email = self.make_email(self.p4UserId())
tagger = "%s %s %s" % (email, epoch, self.tz)
gitStream.write("tagger %s\n" % tagger)
print("labelDetails=", labelDetails)
if 'Description' in labelDetails:
description = labelDetails['Description']
else:
description = 'Label from git p4'
gitStream.write("data %d\n" % len(description))
gitStream.write(description)
gitStream.write("\n")
def commit(self, details, files, branch, parent = ""):
epoch = details["time"]
author = details["user"]
if self.verbose:
print("commit into %s" % branch)
# start with reading files; if that fails, we should not
# create a commit.
new_files = []
for f in files:
if [p for p in self.branchPrefixes if p4PathStartsWith(f['path'], p)]:
new_files.append (f)
else:
sys.stderr.write("Ignoring file outside of prefix: %s\n" % f['path'])
if self.clientSpecDirs:
self.clientSpecDirs.update_client_spec_path_cache(files)
self.gitStream.write("commit %s\n" % branch)
# gitStream.write("mark :%s\n" % details["change"])
self.committedChanges.add(int(details["change"]))
committer = ""
if author not in self.users:
self.getUserMapFromPerforceServer()
committer = "%s %s %s" % (self.make_email(author), epoch, self.tz)
self.gitStream.write("committer %s\n" % committer)
self.gitStream.write("data <<EOT\n")
self.gitStream.write(details["desc"])
self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s" %
(','.join(self.branchPrefixes), details["change"]))
if len(details['options']) > 0:
self.gitStream.write(": options = %s" % details['options'])
self.gitStream.write("]\nEOT\n\n")
if len(parent) > 0:
if self.verbose:
print("parent %s" % parent)
self.gitStream.write("from %s\n" % parent)
self.streamP4Files(new_files)
self.gitStream.write("\n")
change = int(details["change"])
if change in self.labels:
label = self.labels[change]
labelDetails = label[0]
labelRevisions = label[1]
if self.verbose:
print("Change %s is labelled %s" % (change, labelDetails))
files = p4CmdList(["files"] + ["%s...@%s" % (p, change)
for p in self.branchPrefixes])
if len(files) == len(labelRevisions):
cleanedFiles = {}
for info in files:
if info["action"] in self.delete_actions:
continue
cleanedFiles[info["depotFile"]] = info["rev"]
if cleanedFiles == labelRevisions:
self.streamTag(self.gitStream, 'tag_%s' % labelDetails['label'], labelDetails, branch, epoch)
else:
if not self.silent:
print ("Tag %s does not match with change %s: files do not match."
% (labelDetails["label"], change))
else:
if not self.silent:
print ("Tag %s does not match with change %s: file count is different."
% (labelDetails["label"], change))
# Build a dictionary of changelists and labels, for "detect-labels" option.
def getLabels(self):
self.labels = {}
l = p4CmdList(["labels"] + ["%s..." % p for p in self.depotPaths])
if len(l) > 0 and not self.silent:
print("Finding files belonging to labels in %s" % repr(self.depotPaths))
for output in l:
label = output["label"]
revisions = {}
newestChange = 0
if self.verbose:
print("Querying files for label %s" % label)
for file in p4CmdList(["files"] +
["%s...@%s" % (p, label)
for p in self.depotPaths]):
revisions[file["depotFile"]] = file["rev"]
change = int(file["change"])
if change > newestChange:
newestChange = change
self.labels[newestChange] = [output, revisions]
if self.verbose:
print("Label changes: %s" % (list(self.labels.keys()),))
# Import p4 labels as git tags. A direct mapping does not
# exist, so assume that if all the files are at the same revision
# then we can use that, or it's something more complicated we should
# just ignore.
def importP4Labels(self, stream, p4Labels):
if verbose:
print("import p4 labels: " + ' '.join(p4Labels))
ignoredP4Labels = gitConfigList("git-p4.ignoredP4Labels")
validLabelRegexp = gitConfig("git-p4.labelImportRegexp")
if len(validLabelRegexp) == 0:
validLabelRegexp = defaultLabelRegexp
m = re.compile(validLabelRegexp)
for name in p4Labels:
commitFound = False
if not m.match(name):
if verbose:
print("label %s does not match regexp %s" % (name, validLabelRegexp))
continue
if name in ignoredP4Labels:
continue
labelDetails = p4CmdList(['label', "-o", name])[0]
# get the most recent changelist for each file in this label
change = p4Cmd(["changes", "-m", "1"] + ["%s...@%s" % (p, name)
for p in self.depotPaths])
if 'change' in change:
# find the corresponding git commit; take the oldest commit
changelist = int(change['change'])
gitCommit = read_pipe(["git", "rev-list", "--max-count=1",
"--reverse", r":/\[git-p4:.*change = %d\]" % changelist])
if len(gitCommit) == 0:
print("could not find git commit for changelist %d" % changelist)
else:
gitCommit = gitCommit.strip()
commitFound = True
# Convert from p4 time format
try:
tmwhen = time.strptime(labelDetails['Update'], "%Y/%m/%d %H:%M:%S")
except ValueError:
print("Could not convert label time %s" % labelDetails['Update'])
tmwhen = 1
when = int(time.mktime(tmwhen))
self.streamTag(stream, name, labelDetails, gitCommit, when)
if verbose:
print("p4 label %s mapped to git commit %s" % (name, gitCommit))
else:
if verbose:
print("Label %s has no changelists - possibly deleted?" % name)
if not commitFound:
# We can't import this label; don't try again as it will get very
# expensive repeatedly fetching all the files for labels that will
# never be imported. If the label is moved in the future, the
# ignore will need to be removed manually.
system(["git", "config", "--add", "git-p4.ignoredP4Labels", name])
def guessProjectName(self):
for p in self.depotPaths:
if p.endswith("/"):
p = p[:-1]
p = p[p.strip().rfind("/") + 1:]
if not p.endswith("/"):
p += "/"
return p
def getBranchMapping(self):
lostAndFoundBranches = set()
user = gitConfig("git-p4.branchUser")
if len(user) > 0:
command = "branches -u %s" % user
else:
command = "branches"
for info in p4CmdList(command):
details = p4Cmd(["branch", "-o", info["branch"]])
viewIdx = 0
while "View%s" % viewIdx in details:
paths = details["View%s" % viewIdx].split(" ")
viewIdx = viewIdx + 1
# require standard //depot/foo/... //depot/bar/... mapping
if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
continue
source = paths[0]
destination = paths[1]
## HACK
if p4PathStartsWith(source, self.depotPaths[0]) and p4PathStartsWith(destination, self.depotPaths[0]):
source = source[len(self.depotPaths[0]):-4]
destination = destination[len(self.depotPaths[0]):-4]
if destination in self.knownBranches:
if not self.silent:
print("p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination))
print("but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination))
continue
self.knownBranches[destination] = source
lostAndFoundBranches.discard(destination)
if source not in self.knownBranches:
lostAndFoundBranches.add(source)
# Perforce does not strictly require branches to be defined, so we also
# check git config for a branch list.
#
# Example of branch definition in git config file:
# [git-p4]
# branchList=main:branchA
# branchList=main:branchB
# branchList=branchA:branchC
configBranches = gitConfigList("git-p4.branchList")
for branch in configBranches:
if branch:
(source, destination) = branch.split(":")
self.knownBranches[destination] = source
lostAndFoundBranches.discard(destination)
if source not in self.knownBranches:
lostAndFoundBranches.add(source)
for branch in lostAndFoundBranches:
self.knownBranches[branch] = branch
def getBranchMappingFromGitBranches(self):
branches = p4BranchesInGit(self.importIntoRemotes)
for branch in branches.keys():
if branch == "master":
branch = "main"
else:
branch = branch[len(self.projectName):]
self.knownBranches[branch] = branch
def updateOptionDict(self, d):
option_keys = {}
if self.keepRepoPath:
option_keys['keepRepoPath'] = 1
d["options"] = ' '.join(sorted(option_keys.keys()))
def readOptions(self, d):
self.keepRepoPath = ('options' in d
and ('keepRepoPath' in d['options']))
def gitRefForBranch(self, branch):
if branch == "main":
return self.refPrefix + "master"
if len(branch) <= 0:
return branch
return self.refPrefix + self.projectName + branch
def gitCommitByP4Change(self, ref, change):
if self.verbose:
print("looking in ref " + ref + " for change %s using bisect..." % change)
earliestCommit = ""
latestCommit = parseRevision(ref)
while True:
if self.verbose:
print("trying: earliest %s latest %s" % (earliestCommit, latestCommit))
next = read_pipe("git rev-list --bisect %s %s" % (latestCommit, earliestCommit)).strip()
if len(next) == 0:
if self.verbose:
print("argh")
return ""
log = extractLogMessageFromGitCommit(next)
settings = extractSettingsGitLog(log)
currentChange = int(settings['change'])
if self.verbose:
print("current change %s" % currentChange)
if currentChange == change:
if self.verbose:
print("found %s" % next)
return next
if currentChange < change:
earliestCommit = "^%s" % next
else:
latestCommit = "%s" % next
return ""
def importNewBranch(self, branch, maxChange):
# make fast-import flush all changes to disk and update the refs using the checkpoint
# command so that we can try to find the branch parent in the git history
self.gitStream.write("checkpoint\n\n");
self.gitStream.flush();
branchPrefix = self.depotPaths[0] + branch + "/"
range = "@1,%s" % maxChange
#print "prefix" + branchPrefix
changes = p4ChangesForPaths([branchPrefix], range)
if len(changes) <= 0:
return False
firstChange = changes[0]
#print "first change in branch: %s" % firstChange
sourceBranch = self.knownBranches[branch]
sourceDepotPath = self.depotPaths[0] + sourceBranch
sourceRef = self.gitRefForBranch(sourceBranch)
#print "source " + sourceBranch
branchParentChange = int(p4Cmd(["changes", "-m", "1", "%s...@1,%s" % (sourceDepotPath, firstChange)])["change"])
#print "branch parent: %s" % branchParentChange
gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)
if len(gitParent) > 0:
self.initialParents[self.gitRefForBranch(branch)] = gitParent
#print "parent git commit: %s" % gitParent
self.importChanges(changes)
return True
def searchParent(self, parent, branch, target):
parentFound = False
for blob in read_pipe_lines(["git", "rev-list", "--reverse",
"--no-merges", parent]):
blob = blob.strip()
if len(read_pipe(["git", "diff-tree", blob, target])) == 0:
parentFound = True
if self.verbose:
print("Found parent of %s in commit %s" % (branch, blob))
break
if parentFound:
return blob
else:
return None
def importChanges(self, changes):
cnt = 1
for change in changes:
description = p4_describe(change)
self.updateOptionDict(description)
if not self.silent:
sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
sys.stdout.flush()
cnt = cnt + 1
try:
if self.detectBranches:
branches = self.splitFilesIntoBranches(description)
for branch in branches.keys():
## HACK --hwn
branchPrefix = self.depotPaths[0] + branch + "/"
self.branchPrefixes = [ branchPrefix ]
parent = ""
filesForCommit = branches[branch]
if self.verbose:
print("branch is %s" % branch)
self.updatedBranches.add(branch)
if branch not in self.createdBranches:
self.createdBranches.add(branch)
parent = self.knownBranches[branch]
if parent == branch:
parent = ""
else:
fullBranch = self.projectName + branch
if fullBranch not in self.p4BranchesInGit:
if not self.silent:
print("\n Importing new branch %s" % fullBranch);
if self.importNewBranch(branch, change - 1):
parent = ""
self.p4BranchesInGit.append(fullBranch)
if not self.silent:
print("\n Resuming with change %s" % change);
if self.verbose:
print("parent determined through known branches: %s" % parent)
branch = self.gitRefForBranch(branch)
parent = self.gitRefForBranch(parent)
if self.verbose:
print("looking for initial parent for %s; current parent is %s" % (branch, parent))
if len(parent) == 0 and branch in self.initialParents:
parent = self.initialParents[branch]
del self.initialParents[branch]
blob = None
if len(parent) > 0:
tempBranch = "%s/%d" % (self.tempBranchLocation, change)
if self.verbose:
print("Creating temporary branch: " + tempBranch)
self.commit(description, filesForCommit, tempBranch)
self.tempBranches.append(tempBranch)
self.checkpoint()
blob = self.searchParent(parent, branch, tempBranch)
if blob:
self.commit(description, filesForCommit, branch, blob)
else:
if self.verbose:
print("Parent of %s not found. Committing into head of %s" % (branch, parent))
self.commit(description, filesForCommit, branch, parent)
else:
files = self.extractFilesFromCommit(description)
self.commit(description, files, self.branch,
self.initialParent)
# only needed once, to connect to the previous commit
self.initialParent = ""
except OSError:
print(self.gitError.read())
sys.exit(1)
def importHeadRevision(self, revision):
print("Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch))
details = {}
details["user"] = "git perforce import user"
details["desc"] = ("Initial import of %s from the state at revision %s\n"
% (' '.join(self.depotPaths), revision))
details["change"] = revision
newestRevision = 0
fileCnt = 0
fileArgs = ["%s...%s" % (p, revision) for p in self.depotPaths]
for info in p4CmdList(["files"] + fileArgs):
if 'code' in info and info['code'] == 'error':
sys.stderr.write("p4 returned an error: %s\n"
% info['data'])
if info['data'].find("must refer to client") >= 0:
sys.stderr.write("This particular p4 error is misleading.\n")
sys.stderr.write("Perhaps the depot path was misspelled.\n");
sys.stderr.write("Depot path: %s\n" % " ".join(self.depotPaths))
sys.exit(1)
if 'p4ExitCode' in info:
sys.stderr.write("p4 exitcode: %s\n" % info['p4ExitCode'])
sys.exit(1)
change = int(info["change"])
if change > newestRevision:
newestRevision = change
if info["action"] in self.delete_actions:
# don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
#fileCnt = fileCnt + 1
continue
for prop in ["depotFile", "rev", "action", "type" ]:
details["%s%s" % (prop, fileCnt)] = info[prop]
fileCnt = fileCnt + 1
details["change"] = newestRevision
# Use time from top-most change so that all git p4 clones of
# the same p4 repo have the same commit SHA1s.
res = p4_describe(newestRevision)
details["time"] = res["time"]
self.updateOptionDict(details)
try:
self.commit(details, self.extractFilesFromCommit(details), self.branch)
except OSError:
print("IO error with git fast-import. Is your git version recent enough?")
print(self.gitError.read())
def run(self, args):
self.depotPaths = []
self.changeRange = ""
self.previousDepotPaths = []
self.hasOrigin = False
# map from branch depot path to parent branch
self.knownBranches = {}
self.initialParents = {}
if self.importIntoRemotes:
self.refPrefix = "refs/remotes/p4/"
else:
self.refPrefix = "refs/heads/p4/"
if self.syncWithOrigin:
self.hasOrigin = originP4BranchesExist()
if self.hasOrigin:
if not self.silent:
print('Syncing with origin first, using "git fetch origin"')
system("git fetch origin")
branch_arg_given = bool(self.branch)
if len(self.branch) == 0:
self.branch = self.refPrefix + "master"
if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
system("git update-ref %s refs/heads/p4" % self.branch)
system("git branch -D p4")
# accept either the command-line option, or the configuration variable
if self.useClientSpec:
# will use this after clone to set the variable
self.useClientSpec_from_options = True
else:
if gitConfigBool("git-p4.useclientspec"):
self.useClientSpec = True
if self.useClientSpec:
self.clientSpecDirs = getClientSpec()
# TODO: should always look at previous commits,
# merge with previous imports, if possible.
if args == []:
if self.hasOrigin:
createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
# branches holds mapping from branch name to sha1
branches = p4BranchesInGit(self.importIntoRemotes)
# restrict to just this one, disabling detect-branches
if branch_arg_given:
short = self.branch.split("/")[-1]
if short in branches:
self.p4BranchesInGit = [ short ]
else:
self.p4BranchesInGit = list(branches.keys())
if len(self.p4BranchesInGit) > 1:
if not self.silent:
print("Importing from/into multiple branches")
self.detectBranches = True
for branch in branches.keys():
self.initialParents[self.refPrefix + branch] = \
branches[branch]
if self.verbose:
print("branches: %s" % self.p4BranchesInGit)
p4Change = 0
for branch in self.p4BranchesInGit:
logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
settings = extractSettingsGitLog(logMsg)
self.readOptions(settings)
if ('depot-paths' in settings
and 'change' in settings):
change = int(settings['change']) + 1
p4Change = max(p4Change, change)
depotPaths = sorted(settings['depot-paths'])
if self.previousDepotPaths == []:
self.previousDepotPaths = depotPaths
else:
paths = []
for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
prev_list = prev.split("/")
cur_list = cur.split("/")
for i in range(0, min(len(cur_list), len(prev_list))):
if cur_list[i] != prev_list[i]:
i = i - 1
break
paths.append ("/".join(cur_list[:i + 1]))
self.previousDepotPaths = paths
if p4Change > 0:
self.depotPaths = sorted(self.previousDepotPaths)
self.changeRange = "@%s,#head" % p4Change
if not self.silent and not self.detectBranches:
print("Performing incremental import into %s git branch" % self.branch)
# accept multiple ref name abbreviations:
# refs/foo/bar/branch -> use it exactly
# p4/branch -> prepend refs/remotes/ or refs/heads/
# branch -> prepend refs/remotes/p4/ or refs/heads/p4/
if not self.branch.startswith("refs/"):
if self.importIntoRemotes:
prepend = "refs/remotes/"
else:
prepend = "refs/heads/"
if not self.branch.startswith("p4/"):
prepend += "p4/"
self.branch = prepend + self.branch
if len(args) == 0 and self.depotPaths:
if not self.silent:
print("Depot paths: %s" % ' '.join(self.depotPaths))
else:
if self.depotPaths and self.depotPaths != args:
print ("previous import used depot path %s and now %s was specified. "
"This doesn't work!" % (' '.join (self.depotPaths),
' '.join (args)))
sys.exit(1)
self.depotPaths = sorted(args)
revision = ""
self.users = {}
# Make sure no revision specifiers are used when --changesfile
# is specified.
bad_changesfile = False
if len(self.changesFile) > 0:
for p in self.depotPaths:
if p.find("@") >= 0 or p.find("#") >= 0:
bad_changesfile = True
break
if bad_changesfile:
die("Option --changesfile is incompatible with revision specifiers")
newPaths = []
for p in self.depotPaths:
if p.find("@") != -1:
atIdx = p.index("@")
self.changeRange = p[atIdx:]
if self.changeRange == "@all":
self.changeRange = ""
elif ',' not in self.changeRange:
revision = self.changeRange
self.changeRange = ""
p = p[:atIdx]
elif p.find("#") != -1:
hashIdx = p.index("#")
revision = p[hashIdx:]
p = p[:hashIdx]
elif self.previousDepotPaths == []:
# pay attention to changesfile, if given, else import
# the entire p4 tree at the head revision
if len(self.changesFile) == 0:
revision = "#head"
p = re.sub (r"\.\.\.$", "", p)
if not p.endswith("/"):
p += "/"
newPaths.append(p)
self.depotPaths = newPaths
# --detect-branches may change this for each branch
self.branchPrefixes = self.depotPaths
self.loadUserMapFromCache()
self.labels = {}
if self.detectLabels:
self.getLabels();
if self.detectBranches:
## FIXME - what's a P4 projectName ?
self.projectName = self.guessProjectName()
if self.hasOrigin:
self.getBranchMappingFromGitBranches()
else:
self.getBranchMapping()
if self.verbose:
print("p4-git branches: %s" % self.p4BranchesInGit)
print("initial parents: %s" % self.initialParents)
for b in self.p4BranchesInGit:
if b != "master":
## FIXME
b = b[len(self.projectName):]
self.createdBranches.add(b)
self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) // 60))
self.importProcess = subprocess.Popen(["git", "fast-import"],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE);
self.gitOutput = self.importProcess.stdout
self.gitStream = self.importProcess.stdin
self.gitError = self.importProcess.stderr
if revision:
self.importHeadRevision(revision)
else:
changes = []
if len(self.changesFile) > 0:
output = open(self.changesFile).readlines()
changeSet = set()
for line in output:
changeSet.add(int(line))
for change in changeSet:
changes.append(change)
changes.sort()
else:
# catch "git p4 sync" with no new branches, in a repo that
# does not have any existing p4 branches
if len(args) == 0:
if not self.p4BranchesInGit:
die("No remote p4 branches. Perhaps you never did \"git p4 clone\" in here.")
# The default branch is master, unless --branch is used to
# specify something else. Make sure it exists, or complain
# nicely about how to use --branch.
if not self.detectBranches:
if not branch_exists(self.branch):
if branch_arg_given:
die("Error: branch %s does not exist." % self.branch)
else:
die("Error: no branch %s; perhaps specify one with --branch." %
self.branch)
if self.verbose:
print("Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
self.changeRange))
changes = p4ChangesForPaths(self.depotPaths, self.changeRange)
if len(self.maxChanges) > 0:
changes = changes[:min(int(self.maxChanges), len(changes))]
if len(changes) == 0:
if not self.silent:
print("No changes to import!")
else:
if not self.silent and not self.detectBranches:
print("Import destination: %s" % self.branch)
self.updatedBranches = set()
if not self.detectBranches:
if args:
# start a new branch
self.initialParent = ""
else:
# build on a previous revision
self.initialParent = parseRevision(self.branch)
self.importChanges(changes)
if not self.silent:
print("")
if len(self.updatedBranches) > 0:
sys.stdout.write("Updated branches: ")
for b in self.updatedBranches:
sys.stdout.write("%s " % b)
sys.stdout.write("\n")
if gitConfigBool("git-p4.importLabels"):
self.importLabels = True
if self.importLabels:
p4Labels = getP4Labels(self.depotPaths)
gitTags = getGitTags()
missingP4Labels = p4Labels - gitTags
self.importP4Labels(self.gitStream, missingP4Labels)
self.gitStream.close()
if self.importProcess.wait() != 0:
die("fast-import failed: %s" % self.gitError.read())
self.gitOutput.close()
self.gitError.close()
# Cleanup temporary branches created during import
if self.tempBranches != []:
for branch in self.tempBranches:
read_pipe("git update-ref -d %s" % branch)
os.rmdir(os.path.join(os.environ.get("GIT_DIR", ".git"), self.tempBranchLocation))
# Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow
# a convenient shortcut refname "p4".
if self.importIntoRemotes:
head_ref = self.refPrefix + "HEAD"
if not gitBranchExists(head_ref) and gitBranchExists(self.branch):
system(["git", "symbolic-ref", head_ref, self.branch])
return True
class P4Rebase(Command):
def __init__(self):
Command.__init__(self)
self.options = [
optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
]
self.importLabels = False
self.description = ("Fetches the latest revision from perforce and "
+ "rebases the current work (branch) against it")
def run(self, args):
sync = P4Sync()
sync.importLabels = self.importLabels
sync.run([])
return self.rebase()
def rebase(self):
if os.system("git update-index --refresh") != 0:
die("Some files in your working directory are modified and different than what is in your index. You can use git update-index <filename> to bring the index up-to-date or stash away all your changes with git stash.");
if len(read_pipe("git diff-index HEAD --")) > 0:
die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");
[upstream, settings] = findUpstreamBranchPoint()
if len(upstream) == 0:
die("Cannot find upstream branchpoint for rebase")
# the branchpoint may be p4/foo~3, so strip off the parent
upstream = re.sub(r"~[0-9]+$", "", upstream)
print("Rebasing the current branch onto %s" % upstream)
oldHead = read_pipe("git rev-parse HEAD").strip()
system("git rebase %s" % upstream)
system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
return True
class P4Clone(P4Sync):
def __init__(self):
P4Sync.__init__(self)
self.description = "Creates a new git repository and imports from Perforce into it"
self.usage = "usage: %prog [options] //depot/path[@revRange]"
self.options += [
optparse.make_option("--destination", dest="cloneDestination",
action='store', default=None,
help="where to leave result of the clone"),
optparse.make_option("-/", dest="cloneExclude",
action="append", type="string",
help="exclude depot path"),
optparse.make_option("--bare", dest="cloneBare",
action="store_true", default=False),
]
self.cloneDestination = None
self.needsGit = False
self.cloneBare = False
# This is required for the "append" cloneExclude action
def ensure_value(self, attr, value):
if not hasattr(self, attr) or getattr(self, attr) is None:
setattr(self, attr, value)
return getattr(self, attr)
def defaultDestination(self, args):
## TODO: use common prefix of args?
depotPath = args[0]
depotDir = re.sub(r"(@[^@]*)$", "", depotPath)
depotDir = re.sub(r"(#[^#]*)$", "", depotDir)
depotDir = re.sub(r"\.\.\.$", "", depotDir)
depotDir = re.sub(r"/$", "", depotDir)
return os.path.split(depotDir)[1]
def run(self, args):
if len(args) < 1:
return False
if self.keepRepoPath and not self.cloneDestination:
sys.stderr.write("Must specify destination for --keep-path\n")
sys.exit(1)
depotPaths = args
if not self.cloneDestination and len(depotPaths) > 1:
self.cloneDestination = depotPaths[-1]
depotPaths = depotPaths[:-1]
self.cloneExclude = ["/"+p for p in self.cloneExclude]
for p in depotPaths:
if not p.startswith("//"):
sys.stderr.write('Depot paths must start with "//": %s\n' % p)
return False
if not self.cloneDestination:
self.cloneDestination = self.defaultDestination(args)
print("Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination))
if not os.path.exists(self.cloneDestination):
os.makedirs(self.cloneDestination)
chdir(self.cloneDestination)
init_cmd = [ "git", "init" ]
if self.cloneBare:
init_cmd.append("--bare")
retcode = subprocess.call(init_cmd)
if retcode:
raise CalledProcessError(retcode, init_cmd)
if not P4Sync.run(self, depotPaths):
return False
# create a master branch and check out a work tree
if gitBranchExists(self.branch):
system([ "git", "branch", "master", self.branch ])
if not self.cloneBare:
system([ "git", "checkout", "-f" ])
else:
print('Not checking out any branch, use ' \
'"git checkout -q -b master <branch>"')
# auto-set this variable if invoked with --use-client-spec
if self.useClientSpec_from_options:
system("git config --bool git-p4.useclientspec true")
return True
class P4Branches(Command):
def __init__(self):
Command.__init__(self)
self.options = [ ]
self.description = ("Shows the git branches that hold imports and their "
+ "corresponding perforce depot paths")
self.verbose = False
def run(self, args):
if originP4BranchesExist():
createOrUpdateBranchesFromOrigin()
cmdline = "git rev-parse --symbolic "
cmdline += " --remotes"
for line in read_pipe_lines(cmdline):
line = line.strip()
if not line.startswith('p4/') or line == "p4/HEAD":
continue
branch = line
log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
settings = extractSettingsGitLog(log)
print("%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"]))
return True
class HelpFormatter(optparse.IndentedHelpFormatter):
def __init__(self):
optparse.IndentedHelpFormatter.__init__(self)
def format_description(self, description):
if description:
return description + "\n"
else:
return ""
def printUsage(commands):
print("usage: %s <command> [options]" % sys.argv[0])
print("")
print("valid commands: %s" % ", ".join(commands))
print("")
print("Try %s <command> --help for command specific help." % sys.argv[0])
print("")
commands = {
"debug" : P4Debug,
"submit" : P4Submit,
"commit" : P4Submit,
"sync" : P4Sync,
"rebase" : P4Rebase,
"clone" : P4Clone,
"rollback" : P4RollBack,
"branches" : P4Branches
}
def main():
if len(sys.argv[1:]) == 0:
printUsage(list(commands.keys()))
sys.exit(2)
cmdName = sys.argv[1]
try:
klass = commands[cmdName]
cmd = klass()
except KeyError:
print("unknown command %s" % cmdName)
print("")
printUsage(list(commands.keys()))
sys.exit(2)
options = cmd.options
cmd.gitdir = os.environ.get("GIT_DIR", None)
args = sys.argv[2:]
options.append(optparse.make_option("--verbose", "-v", dest="verbose", action="store_true"))
if cmd.needsGit:
options.append(optparse.make_option("--git-dir", dest="gitdir"))
parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
options,
description = cmd.description,
formatter = HelpFormatter())
(cmd, args) = parser.parse_args(sys.argv[2:], cmd);
global verbose
verbose = cmd.verbose
if cmd.needsGit:
if cmd.gitdir == None:
cmd.gitdir = os.path.abspath(".git")
if not isValidGitDir(cmd.gitdir):
cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
if os.path.exists(cmd.gitdir):
cdup = read_pipe("git rev-parse --show-cdup").strip()
if len(cdup) > 0:
chdir(cdup);
if not isValidGitDir(cmd.gitdir):
if isValidGitDir(cmd.gitdir + "/.git"):
cmd.gitdir += "/.git"
else:
die("fatal: cannot locate git repository at %s" % cmd.gitdir)
os.environ["GIT_DIR"] = cmd.gitdir
if not cmd.run(args):
parser.print_help()
sys.exit(2)
if __name__ == '__main__':
main() | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/perforce/git_p4.py | git_p4.py |
import os
import os.path
import sys
import git_p4
__version__ = "0.1"
sys.path.insert(0, os.path.dirname(__file__))
from typing import Any, Dict, Optional
import zulip_perforce_config as config
if config.ZULIP_API_PATH is not None:
sys.path.append(config.ZULIP_API_PATH)
import zulip
client = zulip.Client(
email=config.ZULIP_USER,
site=config.ZULIP_SITE,
api_key=config.ZULIP_API_KEY,
client="ZulipPerforce/" + __version__,
) # type: zulip.Client
try:
changelist = int(sys.argv[1]) # type: int
changeroot = sys.argv[2] # type: str
except IndexError:
print("Wrong number of arguments.\n\n", end=" ", file=sys.stderr)
print(__doc__, file=sys.stderr)
sys.exit(-1)
except ValueError:
print("First argument must be an integer.\n\n", end=" ", file=sys.stderr)
print(__doc__, file=sys.stderr)
sys.exit(-1)
metadata = git_p4.p4_describe(changelist) # type: Dict[str, str]
destination = config.commit_notice_destination(
changeroot, changelist
) # type: Optional[Dict[str, str]]
if destination is None:
# Don't forward the notice anywhere
sys.exit(0)
ignore_missing_stream = None
if hasattr(config, "ZULIP_IGNORE_MISSING_STREAM"):
ignore_missing_stream = config.ZULIP_IGNORE_MISSING_STREAM
if ignore_missing_stream:
# Check if the destination stream exists yet
stream_state = client.get_stream_id(destination["stream"])
if stream_state["result"] == "error":
# Silently discard the message
sys.exit(0)
change = metadata["change"]
p4web = None
if hasattr(config, "P4_WEB"):
p4web = config.P4_WEB
if p4web is not None:
# linkify the change number
change = "[{change}]({p4web}/{change}?ac=10)".format(p4web=p4web, change=change)
message = """**{user}** committed revision @{change} to `{path}`.
```quote
{desc}
```
""".format(
user=metadata["user"], change=change, path=changeroot, desc=metadata["desc"]
) # type: str
message_data = {
"type": "stream",
"to": destination["stream"],
"subject": destination["subject"],
"content": message,
} # type: Dict[str, Any]
client.send_message(message_data) | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/perforce/zulip_change-commit.py | zulip_change-commit.py |
import logging
import optparse
import sys
from configparser import SafeConfigParser
# The following is a table showing which kinds of messages are handled by the
# mirror in each mode:
#
# Message origin/type --> | Jabber | Zulip
# Mode/sender-, +-----+----+--------+----
# V | MUC | PM | stream | PM
# --------------+-------------+-----+----+--------+----
# | other sender| | x | |
# personal mode +-------------+-----+----+--------+----
# | self sender | | x | x | x
# ------------- +-------------+-----+----+--------+----
# | other sender| x | | |
# public mode +-------------+-----+----+--------+----
# | self sender | | | |
from typing import Any, Callable, Dict, List, Optional, Set
from sleekxmpp import JID, ClientXMPP, InvalidJID
from sleekxmpp.stanza import Message as JabberMessage
import zulip
from zulip import Client
__version__ = "1.1"
def room_to_stream(room: str) -> str:
return room + "/xmpp"
def stream_to_room(stream: str) -> str:
return stream.lower().rpartition("/xmpp")[0]
def jid_to_zulip(jid: JID) -> str:
suffix = ""
if not jid.username.endswith("-bot"):
suffix = options.zulip_email_suffix
return f"{jid.username}{suffix}@{options.zulip_domain}"
def zulip_to_jid(email: str, jabber_domain: str) -> JID:
jid = JID(email, domain=jabber_domain)
if (
options.zulip_email_suffix
and options.zulip_email_suffix in jid.username
and not jid.username.endswith("-bot")
):
jid.username = jid.username.rpartition(options.zulip_email_suffix)[0]
return jid
class JabberToZulipBot(ClientXMPP):
def __init__(self, jid: JID, password: str, rooms: List[str]) -> None:
if jid.resource:
self.nick = jid.resource
else:
self.nick = jid.username
jid.resource = "zulip"
ClientXMPP.__init__(self, jid, password)
self.rooms = set() # type: Set[str]
self.rooms_to_join = rooms
self.add_event_handler("session_start", self.session_start)
self.add_event_handler("message", self.message)
self.zulip = None
self.use_ipv6 = False
self.register_plugin("xep_0045") # Jabber chatrooms
self.register_plugin("xep_0199") # XMPP Ping
def set_zulip_client(self, zulipToJabberClient: "ZulipToJabberBot") -> None:
self.zulipToJabber = zulipToJabberClient
def session_start(self, event: Dict[str, Any]) -> None:
self.get_roster()
self.send_presence()
for room in self.rooms_to_join:
self.join_muc(room)
def join_muc(self, room: str) -> None:
if room in self.rooms:
return
logging.debug("Joining " + room)
self.rooms.add(room)
muc_jid = JID(local=room, domain=options.conference_domain)
xep0045 = self.plugin["xep_0045"]
try:
xep0045.joinMUC(muc_jid, self.nick, wait=True)
except InvalidJID:
logging.error("Could not join room: " + str(muc_jid))
return
# Configure the room. Really, we should only do this if the room is
# newly created.
form = None
try:
form = xep0045.getRoomConfig(muc_jid)
except ValueError:
pass
if form:
xep0045.configureRoom(muc_jid, form)
else:
logging.error("Could not configure room: " + str(muc_jid))
def leave_muc(self, room: str) -> None:
if room not in self.rooms:
return
logging.debug("Leaving " + room)
self.rooms.remove(room)
muc_jid = JID(local=room, domain=options.conference_domain)
self.plugin["xep_0045"].leaveMUC(muc_jid, self.nick)
def message(self, msg: JabberMessage) -> Any:
try:
if msg["type"] == "groupchat":
return self.group(msg)
elif msg["type"] == "chat":
return self.private(msg)
else:
logging.warning("Got unexpected message type")
logging.warning(msg)
except Exception:
logging.exception("Error forwarding Jabber => Zulip")
def private(self, msg: JabberMessage) -> None:
if options.mode == "public" or msg["thread"] == "\u1FFFE":
return
sender = jid_to_zulip(msg["from"])
recipient = jid_to_zulip(msg["to"])
zulip_message = dict(
sender=sender,
type="private",
to=recipient,
content=msg["body"],
)
ret = self.zulipToJabber.client.send_message(zulip_message)
if ret.get("result") != "success":
logging.error(str(ret))
def group(self, msg: JabberMessage) -> None:
if options.mode == "personal" or msg["thread"] == "\u1FFFE":
return
subject = msg["subject"]
if len(subject) == 0:
subject = "(no topic)"
stream = room_to_stream(msg["from"].local)
sender_nick = msg.get_mucnick()
if not sender_nick:
# Messages from the room itself have no nickname. We should not try
# to mirror these
return
jid = self.nickname_to_jid(msg.get_mucroom(), sender_nick)
sender = jid_to_zulip(jid)
zulip_message = dict(
forged="yes",
sender=sender,
type="stream",
subject=subject,
to=stream,
content=msg["body"],
)
ret = self.zulipToJabber.client.send_message(zulip_message)
if ret.get("result") != "success":
logging.error(str(ret))
def nickname_to_jid(self, room: str, nick: str) -> JID:
jid = self.plugin["xep_0045"].getJidProperty(room, nick, "jid")
if jid is None or jid == "":
return JID(local=nick.replace(" ", ""), domain=self.boundjid.domain)
else:
return jid
class ZulipToJabberBot:
def __init__(self, zulip_client: Client) -> None:
self.client = zulip_client
self.jabber = None # type: Optional[JabberToZulipBot]
def set_jabber_client(self, client: JabberToZulipBot) -> None:
self.jabber = client
def process_event(self, event: Dict[str, Any]) -> None:
if event["type"] == "message":
message = event["message"]
if message["sender_email"] != self.client.email:
return
try:
if message["type"] == "stream":
self.stream_message(message)
elif message["type"] == "private":
self.private_message(message)
except Exception:
logging.exception("Exception forwarding Zulip => Jabber")
elif event["type"] == "subscription":
self.process_subscription(event)
def stream_message(self, msg: Dict[str, str]) -> None:
assert self.jabber is not None
stream = msg["display_recipient"]
if not stream.endswith("/xmpp"):
return
room = stream_to_room(stream)
jabber_recipient = JID(local=room, domain=options.conference_domain)
outgoing = self.jabber.make_message(
mto=jabber_recipient, mbody=msg["content"], mtype="groupchat"
)
outgoing["thread"] = "\u1FFFE"
outgoing.send()
def private_message(self, msg: Dict[str, Any]) -> None:
assert self.jabber is not None
for recipient in msg["display_recipient"]:
if recipient["email"] == self.client.email:
continue
if not recipient["is_mirror_dummy"]:
continue
recip_email = recipient["email"]
jabber_recipient = zulip_to_jid(recip_email, self.jabber.boundjid.domain)
outgoing = self.jabber.make_message(
mto=jabber_recipient, mbody=msg["content"], mtype="chat"
)
outgoing["thread"] = "\u1FFFE"
outgoing.send()
def process_subscription(self, event: Dict[str, Any]) -> None:
assert self.jabber is not None
if event["op"] == "add":
streams = [s["name"].lower() for s in event["subscriptions"]]
streams = [s for s in streams if s.endswith("/xmpp")]
for stream in streams:
self.jabber.join_muc(stream_to_room(stream))
if event["op"] == "remove":
streams = [s["name"].lower() for s in event["subscriptions"]]
streams = [s for s in streams if s.endswith("/xmpp")]
for stream in streams:
self.jabber.leave_muc(stream_to_room(stream))
def get_rooms(zulipToJabber: ZulipToJabberBot) -> List[str]:
def get_stream_infos(key: str, method: Callable[[], Dict[str, Any]]) -> Any:
ret = method()
if ret.get("result") != "success":
logging.error(str(ret))
sys.exit(f"Could not get initial list of Zulip {key}")
return ret[key]
if options.mode == "public":
stream_infos = get_stream_infos("streams", zulipToJabber.client.get_streams)
else:
stream_infos = get_stream_infos("subscriptions", zulipToJabber.client.get_subscriptions)
rooms = [] # type: List[str]
for stream_info in stream_infos:
stream = stream_info["name"]
if stream.endswith("/xmpp"):
rooms.append(stream_to_room(stream))
return rooms
def config_error(msg: str) -> None:
sys.stderr.write(f"{msg}\n")
sys.exit(2)
if __name__ == "__main__":
parser = optparse.OptionParser(
epilog="""Most general and Jabber configuration options may also be specified in the
zulip configuration file under the jabber_mirror section (exceptions are noted
in their help sections). Keys have the same name as options with hyphens
replaced with underscores. Zulip configuration options go in the api section,
as normal.""".replace(
"\n", " "
)
)
parser.add_option(
"--mode",
default=None,
action="store",
help='''Which mode to run in. Valid options are "personal" and "public". In
"personal" mode, the mirror uses an individual users' credentials and mirrors
all messages they send on Zulip to Jabber and all private Jabber messages to
Zulip. In "public" mode, the mirror uses the credentials for a dedicated mirror
user and mirrors messages sent to Jabber rooms to Zulip. Defaults to
"personal"'''.replace(
"\n", " "
),
)
parser.add_option(
"--zulip-email-suffix",
default=None,
action="store",
help="""Add the specified suffix to the local part of email addresses constructed
from JIDs and nicks before sending requests to the Zulip server, and remove the
suffix before sending requests to the Jabber server. For example, specifying
"+foo" will cause messages that are sent to the "bar" room by nickname "qux" to
be mirrored to the "bar/xmpp" stream in Zulip by user "[email protected]". This
option does not affect login credentials.""".replace(
"\n", " "
),
)
parser.add_option(
"-d",
"--debug",
help="set logging to DEBUG. Can not be set via config file.",
action="store_const",
dest="log_level",
const=logging.DEBUG,
default=logging.INFO,
)
jabber_group = optparse.OptionGroup(parser, "Jabber configuration")
jabber_group.add_option(
"--jid",
default=None,
action="store",
help="Your Jabber JID. If a resource is specified, "
"it will be used as the nickname when joining MUCs. "
"Specifying the nickname is mostly useful if you want "
"to run the public mirror from a regular user instead of "
"from a dedicated account.",
)
jabber_group.add_option(
"--jabber-password", default=None, action="store", help="Your Jabber password"
)
jabber_group.add_option(
"--conference-domain",
default=None,
action="store",
help="Your Jabber conference domain (E.g. conference.jabber.example.com). "
'If not specifed, "conference." will be prepended to your JID\'s domain.',
)
jabber_group.add_option("--no-use-tls", default=None, action="store_true")
jabber_group.add_option(
"--jabber-server-address",
default=None,
action="store",
help="The hostname of your Jabber server. This is only needed if "
"your server is missing SRV records",
)
jabber_group.add_option(
"--jabber-server-port",
default="5222",
action="store",
help="The port of your Jabber server. This is only needed if "
"your server is missing SRV records",
)
parser.add_option_group(jabber_group)
parser.add_option_group(zulip.generate_option_group(parser, "zulip-"))
(options, args) = parser.parse_args()
logging.basicConfig(level=options.log_level, format="%(levelname)-8s %(message)s")
if options.zulip_config_file is None:
default_config_file = zulip.get_default_config_filename()
if default_config_file is not None:
config_file = default_config_file
else:
config_error("Config file not found via --zulip-config_file or environment variable.")
else:
config_file = options.zulip_config_file
config = SafeConfigParser()
try:
with open(config_file) as f:
config.readfp(f, config_file)
except OSError:
pass
for option in (
"jid",
"jabber_password",
"conference_domain",
"mode",
"zulip_email_suffix",
"jabber_server_address",
"jabber_server_port",
):
if getattr(options, option) is None and config.has_option("jabber_mirror", option):
setattr(options, option, config.get("jabber_mirror", option))
for option in ("no_use_tls",):
if getattr(options, option) is None:
if config.has_option("jabber_mirror", option):
setattr(options, option, config.getboolean("jabber_mirror", option))
else:
setattr(options, option, False)
if options.mode is None:
options.mode = "personal"
if options.zulip_email_suffix is None:
options.zulip_email_suffix = ""
if options.mode not in ("public", "personal"):
config_error("Bad value for --mode: must be one of 'public' or 'personal'")
if None in (options.jid, options.jabber_password):
config_error(
"You must specify your Jabber JID and Jabber password either "
"in the Zulip configuration file or on the commandline"
)
zulipToJabber = ZulipToJabberBot(
zulip.init_from_options(options, "JabberMirror/" + __version__)
)
# This won't work for open realms that don't have a consistent domain
options.zulip_domain = zulipToJabber.client.email.partition("@")[-1]
try:
jid = JID(options.jid)
except InvalidJID as e:
config_error(f"Bad JID: {options.jid}: {e.message}")
if options.conference_domain is None:
options.conference_domain = f"conference.{jid.domain}"
xmpp = JabberToZulipBot(jid, options.jabber_password, get_rooms(zulipToJabber))
address = None
if options.jabber_server_address:
address = (options.jabber_server_address, options.jabber_server_port)
if not xmpp.connect(use_tls=not options.no_use_tls, address=address):
sys.exit("Unable to connect to Jabber server")
xmpp.set_zulip_client(zulipToJabber)
zulipToJabber.set_jabber_client(xmpp)
xmpp.process(block=False)
if options.mode == "public":
event_types = ["stream"]
else:
event_types = ["message", "subscription"]
try:
logging.info("Connecting to Zulip.")
zulipToJabber.client.call_on_each_event(
zulipToJabber.process_event, event_types=event_types
)
except BaseException:
logging.exception("Exception in main loop")
xmpp.abort()
sys.exit(1) | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/jabber/jabber_mirror_backend.py | jabber_mirror_backend.py |
# IRC <--> Zulip bridge
## Usage
```
./irc-mirror.py --irc-server=IRC_SERVER --channel=<CHANNEL> --nick-prefix=<NICK> --stream=<STREAM> [optional args]
```
`--stream` is a Zulip stream.
`--topic` is a Zulip topic, is optionally specified, defaults to "IRC".
`--nickserv-pw` is the IRC nick password.
IMPORTANT: Make sure the bot is subscribed to the relevant Zulip stream!!
Specify your Zulip API credentials and server in a ~/.zuliprc file or using the options.
IMPORTANT: Note that "_zulip" will be automatically appended to the IRC nick provided, so make sure that your actual registered nick ends with "_zulip".
## Example
```
./irc-mirror.py --irc-server=irc.freenode.net --channel='#python-mypy' --nick-prefix=irc_mirror \
--stream='test here' --topic='#mypy' \
--site="https://chat.zulip.org" --user=<bot-email> \
--api-key=<bot-api-key>
```
| zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/bridge_with_irc/README.md | README.md |
import multiprocessing as mp
from typing import Any, Dict
import irc.bot
import irc.strings
from irc.client import Event, ServerConnection, ip_numstr_to_quad
from irc.client_aio import AioReactor
class IRCBot(irc.bot.SingleServerIRCBot):
reactor_class = AioReactor
def __init__(
self,
zulip_client: Any,
stream: str,
topic: str,
channel: irc.bot.Channel,
nickname: str,
server: str,
nickserv_password: str = "",
port: int = 6667,
) -> None:
self.channel = channel # type: irc.bot.Channel
self.zulip_client = zulip_client
self.stream = stream
self.topic = topic
self.IRC_DOMAIN = server
self.nickserv_password = nickserv_password
# Make sure the bot is subscribed to the stream
self.check_subscription_or_die()
# Initialize IRC bot after proper connection to Zulip server has been confirmed.
irc.bot.SingleServerIRCBot.__init__(self, [(server, port)], nickname, nickname)
def zulip_sender(self, sender_string: str) -> str:
nick = sender_string.split("!")[0]
return nick + "@" + self.IRC_DOMAIN
def connect(self, *args: Any, **kwargs: Any) -> None:
# Taken from
# https://github.com/jaraco/irc/blob/main/irc/client_aio.py,
# in particular the method of AioSimpleIRCClient
self.c = self.reactor.loop.run_until_complete(self.connection.connect(*args, **kwargs))
print("Listening now. Please send an IRC message to verify operation")
def check_subscription_or_die(self) -> None:
resp = self.zulip_client.get_subscriptions()
if resp["result"] != "success":
print("ERROR: {}".format(resp["msg"]))
exit(1)
subs = [s["name"] for s in resp["subscriptions"]]
if self.stream not in subs:
print(
"The bot is not yet subscribed to stream '%s'. Please subscribe the bot to the stream first."
% (self.stream,)
)
exit(1)
def on_nicknameinuse(self, c: ServerConnection, e: Event) -> None:
c.nick(c.get_nickname().replace("_zulip", "__zulip"))
def on_welcome(self, c: ServerConnection, e: Event) -> None:
if len(self.nickserv_password) > 0:
msg = f"identify {self.nickserv_password}"
c.privmsg("NickServ", msg)
c.join(self.channel)
def forward_to_irc(msg: Dict[str, Any]) -> None:
not_from_zulip_bot = msg["sender_email"] != self.zulip_client.email
if not not_from_zulip_bot:
# Do not forward echo
return
is_a_stream = msg["type"] == "stream"
if is_a_stream:
in_the_specified_stream = msg["display_recipient"] == self.stream
at_the_specified_subject = msg["subject"].casefold() == self.topic.casefold()
if in_the_specified_stream and at_the_specified_subject:
msg["content"] = ("@**{}**: ".format(msg["sender_full_name"])) + msg["content"]
send = lambda x: self.c.privmsg(self.channel, x)
else:
return
else:
recipients = [
u["short_name"]
for u in msg["display_recipient"]
if u["email"] != msg["sender_email"]
]
if len(recipients) == 1:
send = lambda x: self.c.privmsg(recipients[0], x)
else:
send = lambda x: self.c.privmsg_many(recipients, x)
for line in msg["content"].split("\n"):
send(line)
z2i = mp.Process(target=self.zulip_client.call_on_each_message, args=(forward_to_irc,))
z2i.start()
def on_privmsg(self, c: ServerConnection, e: Event) -> None:
content = e.arguments[0]
sender = self.zulip_sender(e.source)
if sender.endswith("_zulip@" + self.IRC_DOMAIN):
return
# Forward the PM to Zulip
print(
self.zulip_client.send_message(
{
"sender": sender,
"type": "private",
"to": "[email protected]",
"content": content,
}
)
)
def on_pubmsg(self, c: ServerConnection, e: Event) -> None:
content = e.arguments[0]
sender = self.zulip_sender(e.source)
if sender.endswith("_zulip@" + self.IRC_DOMAIN):
return
# Forward the stream message to Zulip
print(
self.zulip_client.send_message(
{
"type": "stream",
"to": self.stream,
"subject": self.topic,
"content": f"**{sender}**: {content}",
}
)
)
def on_dccmsg(self, c: ServerConnection, e: Event) -> None:
c.privmsg("You said: " + e.arguments[0])
def on_dccchat(self, c: ServerConnection, e: Event) -> None:
if len(e.arguments) != 2:
return
args = e.arguments[1].split()
if len(args) == 4:
try:
address = ip_numstr_to_quad(args[2])
port = int(args[3])
except ValueError:
return
self.dcc_connect(address, port) | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/bridge_with_irc/irc_mirror_backend.py | irc_mirror_backend.py |
import argparse
import sys
import traceback
import zulip
usage = """./irc-mirror.py --irc-server=IRC_SERVER --channel=<CHANNEL> --nick-prefix=<NICK> --stream=<STREAM> [optional args]
Example:
./irc-mirror.py --irc-server=127.0.0.1 --channel='#test' --nick-prefix=username --stream='test' --topic='#mypy'
--stream is a Zulip stream.
--topic is a Zulip topic, is optionally specified, defaults to "IRC".
--nickserv-pw is a password for the nickserv, is optionally specified.
Specify your Zulip API credentials and server in a ~/.zuliprc file or using the options.
Note that "_zulip" will be automatically appended to the IRC nick provided
"""
if __name__ == "__main__":
parser = zulip.add_default_arguments(
argparse.ArgumentParser(usage=usage), allow_provisioning=True
)
parser.add_argument("--irc-server", default=None)
parser.add_argument("--port", default=6667)
parser.add_argument("--nick-prefix", default=None)
parser.add_argument("--channel", default=None)
parser.add_argument("--stream", default="general")
parser.add_argument("--topic", default="IRC")
parser.add_argument("--nickserv-pw", default="")
options = parser.parse_args()
# Setting the client to irc_mirror is critical for this to work
options.client = "irc_mirror"
zulip_client = zulip.init_from_options(options)
try:
from irc_mirror_backend import IRCBot
except ImportError:
traceback.print_exc()
print(
"You have unsatisfied dependencies. Install all missing dependencies with "
"{} --provision".format(sys.argv[0])
)
sys.exit(1)
if options.irc_server is None or options.nick_prefix is None or options.channel is None:
parser.error("Missing required argument")
nickname = options.nick_prefix + "_zulip"
bot = IRCBot(
zulip_client,
options.stream,
options.topic,
options.channel,
nickname,
options.irc_server,
options.nickserv_pw,
options.port,
)
bot.start() | zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/bridge_with_irc/irc-mirror.py | irc-mirror.py |
# Slack <--> Zulip bridge
This is a bridge between Slack and Zulip.
## Usage
### 1. Zulip endpoint
1. Create a generic Zulip bot, with a full name like `Slack Bot`.
2. (Important) Subscribe the bot user to the Zulip stream you'd like to bridge your Slack
channel into.
3. In the `zulip` section of the configuration file, enter the bot's `zuliprc`
details (`email`, `api_key`, and `site`).
4. In the same section, also enter the Zulip `stream` and `topic`.
### 2. Slack endpoint
1. Make sure Websocket isn't blocked in the computer where you run this bridge.
Test it at https://www.websocket.org/echo.html.
2. Go to https://api.slack.com/apps?new_classic_app=1 and create a new classic
app (note: must be a classic app). Choose a bot name that will be put into
bridge_with_slack_config.py, e.g. "zulip_mirror". In the process of doing
this, you need to add oauth token scope. Simply choose `bot`. Slack will say
that this is a legacy scope, but we still need to use it anyway. The reason
why we need the legacy scope is because otherwise the RTM API wouldn't work.
We might remove the RTM API usage in newer version of this bot. Make sure to
install the app to the workspace. When successful, you should see a token
that starts with "xoxb-...". There is also a token that starts with
"xoxp-...", we need the "xoxb-..." one.
3. Go to "App Home", click the button "Add Legacy Bot User".
4. (Important) Make sure the bot is subscribed to the channel. You can do this by typing e.g. `/invite @zulip_mirror` in the relevant channel.
5. In the `slack` section of the Zulip-Slack bridge configuration file, enter the bot name (e.g. "zulip_mirror") and token, and the channel ID (note: must be ID, not name).
### Running the bridge
Run `python3 run-slack-bridge`
| zulip | /zulip-0.8.2.tar.gz/zulip-0.8.2/integrations/bridge_with_slack/README.md | README.md |
Subsets and Splits