|
| 1 | +# Copyright (c) 2015-2017 The Botogram Authors (see AUTHORS) |
| 2 | +# |
| 3 | +# Permission is hereby granted, free of charge, to any person obtaining a copy |
| 4 | +# of this software and associated documentation files (the "Software"), to deal |
| 5 | +# in the Software without restriction, including without limitation the rights |
| 6 | +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell |
| 7 | +# copies of the Software, and to permit persons to whom the Software is |
| 8 | +# furnished to do so, subject to the following conditions: |
| 9 | +# |
| 10 | +# The above copyright notice and this permission notice shall be included in |
| 11 | +# all copies or substantial portions of the Software. |
| 12 | +# |
| 13 | +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR |
| 14 | +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, |
| 15 | +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE |
| 16 | +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER |
| 17 | +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING |
| 18 | +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER |
| 19 | + |
| 20 | +import base64 |
| 21 | +import binascii |
| 22 | +import hashlib |
| 23 | + |
| 24 | +from . import crypto |
| 25 | +from .context import ctx |
| 26 | + |
| 27 | + |
| 28 | +DIGEST = hashlib.md5 |
| 29 | +DIGEST_LEN = 16 |
| 30 | + |
| 31 | + |
| 32 | +class ButtonsRow: |
| 33 | + """A row of an inline keyboard""" |
| 34 | + |
| 35 | + def __init__(self): |
| 36 | + self._content = [] |
| 37 | + |
| 38 | + def url(self, label, url): |
| 39 | + """Open an URL when the button is pressed""" |
| 40 | + self._content.append({"text": label, "url": url}) |
| 41 | + |
| 42 | + def callback(self, label, callback, data=None): |
| 43 | + """Trigger a callback when the button is pressed""" |
| 44 | + def generate_callback_data(): |
| 45 | + c = ctx() |
| 46 | + |
| 47 | + name = "%s:%s" % (c.component_name(), callback) |
| 48 | + return get_callback_data(c.bot, c.chat(), name, data) |
| 49 | + |
| 50 | + self._content.append({ |
| 51 | + "text": label, |
| 52 | + "callback_data": generate_callback_data, |
| 53 | + }) |
| 54 | + |
| 55 | + def switch_inline_query(self, label, query="", current_chat=False): |
| 56 | + """Switch the user to this bot's inline query""" |
| 57 | + if current_chat: |
| 58 | + self._content.append({ |
| 59 | + "text": label, |
| 60 | + "switch_inline_query_current_chat": query, |
| 61 | + }) |
| 62 | + else: |
| 63 | + self._content.append({ |
| 64 | + "text": label, |
| 65 | + "switch_inline_query": query, |
| 66 | + }) |
| 67 | + |
| 68 | + def _get_content(self): |
| 69 | + """Get the content of this row""" |
| 70 | + for item in self._content: |
| 71 | + new = item.copy() |
| 72 | + |
| 73 | + # Replace any callable with its value |
| 74 | + # This allows to dynamically generate field values |
| 75 | + for key, value in new.items(): |
| 76 | + if callable(value): |
| 77 | + new[key] = value() |
| 78 | + |
| 79 | + yield new |
| 80 | + |
| 81 | + |
| 82 | +class Buttons: |
| 83 | + """Factory for inline keyboards""" |
| 84 | + |
| 85 | + def __init__(self): |
| 86 | + self._rows = {} |
| 87 | + |
| 88 | + def __getitem__(self, index): |
| 89 | + if index not in self._rows: |
| 90 | + self._rows[index] = ButtonsRow() |
| 91 | + return self._rows[index] |
| 92 | + |
| 93 | + def _serialize_attachment(self): |
| 94 | + rows = [ |
| 95 | + list(row._get_content()) for i, row in sorted( |
| 96 | + tuple(self._rows.items()), key=lambda i: i[0] |
| 97 | + ) |
| 98 | + ] |
| 99 | + |
| 100 | + return {"inline_keyboard": rows} |
| 101 | + |
| 102 | + |
| 103 | +def parse_callback_data(bot, chat, raw): |
| 104 | + """Parse the callback data generated by botogram and return it""" |
| 105 | + raw = raw.encode("utf-8") |
| 106 | + |
| 107 | + if len(raw) < 32: |
| 108 | + raise crypto.TamperedMessageError |
| 109 | + |
| 110 | + try: |
| 111 | + prelude = base64.b64decode(raw[:32]) |
| 112 | + except binascii.Error: |
| 113 | + raise crypto.TamperedMessageError |
| 114 | + |
| 115 | + signature = prelude[:16] |
| 116 | + name = prelude[16:] |
| 117 | + data = raw[32:] |
| 118 | + |
| 119 | + # Don't check the signature if the user explicitly disabled the check |
| 120 | + if bot.validate_callback_signatures: |
| 121 | + correct = get_signature(bot, chat, name, data) |
| 122 | + if not crypto.compare(correct, signature): |
| 123 | + raise crypto.TamperedMessageError |
| 124 | + |
| 125 | + if data: |
| 126 | + return name, data.decode("utf-8") |
| 127 | + else: |
| 128 | + return name, None |
| 129 | + |
| 130 | + |
| 131 | +def get_callback_data(bot, chat, name, data=None): |
| 132 | + """Get the callback data for the provided name and data""" |
| 133 | + name = hashed_callback_name(name) |
| 134 | + |
| 135 | + if data is None: |
| 136 | + data = "" |
| 137 | + data = data.encode("utf-8") |
| 138 | + |
| 139 | + if len(data) > 32: |
| 140 | + raise ValueError( |
| 141 | + "The provided data is too big (%s bytes), try to reduce it to " |
| 142 | + "32 bytes" % len(data) |
| 143 | + ) |
| 144 | + |
| 145 | + # Get the signature of the hook name and data |
| 146 | + signature = get_signature(bot, chat, name, data) |
| 147 | + |
| 148 | + # Base64 the signature and the hook name together to save space |
| 149 | + return (base64.b64encode(signature + name) + data).decode("utf-8") |
| 150 | + |
| 151 | + |
| 152 | +def get_signature(bot, chat, name, data): |
| 153 | + """Generate a signature for the provided information""" |
| 154 | + chat_id = str(chat.id).encode("utf-8") |
| 155 | + return crypto.get_hmac(bot, name + b'\0' + chat_id + b'\0' + data) |
| 156 | + |
| 157 | + |
| 158 | +def hashed_callback_name(name): |
| 159 | + """Get the hashed name of a callback""" |
| 160 | + # Get only the first 8 bytes of the hash to fit it into the payload |
| 161 | + return DIGEST(name.encode("utf-8")).digest()[:8] |
| 162 | + |
| 163 | + |
| 164 | +def process(bot, chains, update): |
| 165 | + """Process a callback sent to the bot""" |
| 166 | + chat = update.callback_query.message.chat |
| 167 | + raw = update.callback_query._data |
| 168 | + |
| 169 | + try: |
| 170 | + name, data = parse_callback_data(bot, chat, raw) |
| 171 | + except crypto.TamperedMessageError: |
| 172 | + bot.logger.warn( |
| 173 | + "The user tampered with the #%s update's data. Skipped it." |
| 174 | + % update.update_id |
| 175 | + ) |
| 176 | + return |
| 177 | + |
| 178 | + for hook in chains["callbacks"]: |
| 179 | + bot.logger.debug("Processing update #%s with the hook %s" % |
| 180 | + (update.update_id, hook.name)) |
| 181 | + |
| 182 | + result = hook.call(bot, update, name, data) |
| 183 | + if result is True: |
| 184 | + bot.logger.debug("Update #%s was just processed by the %s hook" % |
| 185 | + (update.update_id, hook.name)) |
| 186 | + return |
| 187 | + |
| 188 | + bot.logger.debug("No hook actually processed the #%s update." % |
| 189 | + update.update_id) |
0 commit comments