├── .gitignore ├── LICENSE ├── README.md ├── irccloud └── client │ ├── __init__.py │ ├── client.py │ ├── http_client.py │ ├── log_render.py │ ├── messages.py │ └── model.py └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | 47 | # Translations 48 | *.mo 49 | *.pot 50 | 51 | # Django stuff: 52 | *.log 53 | 54 | # Sphinx documentation 55 | docs/_build/ 56 | 57 | # PyBuilder 58 | target/ 59 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Official IRCCloud Python Client 2 | =============================== 3 | 4 | This is the beginnings of an IRCCloud python client, which we aim to 5 | officially support. It's at a pretty early stage currently. 6 | 7 | Requirements 8 | ------- 9 | 10 | * Python >= 3.4 (3.3 with asyncio may work; asyncio is required by the 11 | websockets library) 12 | 13 | License 14 | ------ 15 | Copyright (C) 2015 IRCCloud, Ltd. 16 | Licensed under the Apache License, Version 2.0 (the "License"); 17 | you may not use this file except in compliance with the License. 18 | You may obtain a copy of the License at 19 | 20 | http://www.apache.org/licenses/LICENSE-2.0 21 | 22 | Unless required by applicable law or agreed to in writing, software 23 | distributed under the License is distributed on an "AS IS" BASIS, 24 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 25 | See the License for the specific language governing permissions and 26 | limitations under the License. 27 | -------------------------------------------------------------------------------- /irccloud/client/__init__.py: -------------------------------------------------------------------------------- 1 | from .client import IRCCloudClient 2 | -------------------------------------------------------------------------------- /irccloud/client/client.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import division, absolute_import, print_function, unicode_literals 3 | import asyncio 4 | import logging 5 | import ujson as json 6 | from .messages import BUFFER_MESSAGES 7 | from .http_client import IRCCloudHTTPClient 8 | from .model import Connection, Buffer, User 9 | 10 | 11 | IGNORE_MESSAGES = {'idle', 'backlog_starts', 'end_of_backlog', 'backlog_complete', 'num_invites', 12 | 'heartbeat_echo', 'isupport_params', 'whois_response', 'user_account'} 13 | CREATION_MESSAGES = {'makeserver', 'makebuffer', 'channel_init'} 14 | SERVER_MESSAGES = {'server_details_changed', 'status_changed'} 15 | 16 | 17 | class IRCCloudClient(object): 18 | """ A Python client for IRCCloud, which connects using websockets. """ 19 | def __init__(self, host="www.irccloud.com", verify_certificate=True, 20 | track_channel_state=True): 21 | self.log = logging.getLogger(__name__) 22 | self.irccloud = IRCCloudHTTPClient(host, verify_certificate=verify_certificate) 23 | self.track_channel_state = track_channel_state 24 | self.stream_id = None 25 | self.user_info = None 26 | self.connections = {} 27 | self.buffers = {} 28 | self.message_callback = None 29 | self.state_callback = None 30 | self.running = True 31 | self.reqid = 0 32 | self.response_queues = {} 33 | 34 | def login(self, email, password): 35 | self.irccloud.login(email, password) 36 | 37 | @asyncio.coroutine 38 | def add_server(self, name, hostname, port, nickname, realname, ssl=False, 39 | server_pass=None, nspass=None, joincommands=None, channels=None): 40 | if ssl is True: 41 | ssl = "1" 42 | else: 43 | ssl = "0" 44 | 45 | message = {'_method': 'add-server', 46 | 'hostname': hostname, 'port': port, 'nickname': nickname, 47 | 'realname': realname, 'server_pass': server_pass, 'ssl': ssl, 48 | 'nspass': nspass, 'joincommands': joincommands, 'channels': channels} 49 | response = yield from self.send_message(message) 50 | if response['success'] is False: 51 | raise Exception("Error creating network: %s" % response['message']) 52 | return response 53 | 54 | @asyncio.coroutine 55 | def join_channel(self, conn, channel, key=None): 56 | message = {'_method': 'join', 57 | 'cid': conn.id, 'channel': channel} 58 | if key is not None: 59 | message['key'] = key 60 | response = yield from self.send_message(message) 61 | if response['success'] is False: 62 | raise Exception("Error creating network: %s" % response['message']) 63 | return response 64 | 65 | @asyncio.coroutine 66 | def say(self, to_buffer, message): 67 | # TODO: allow sending messages to buffers which aren't open yet (per docs) 68 | message = {'_method': 'say', 69 | 'cid': to_buffer.connection.id, 70 | 'to': to_buffer.name, 'msg': message} 71 | response = yield from self.send_message(message) 72 | if response['success'] is False: 73 | raise Exception("Error sending message: %s" % response['message']) 74 | return response 75 | 76 | @asyncio.coroutine 77 | def send_message(self, message): 78 | self.reqid += 1 79 | reqid = self.reqid 80 | message['_reqid'] = reqid 81 | 82 | res_queue = asyncio.Queue(1) 83 | self.response_queues[reqid] = res_queue 84 | yield from self.socket.send(json.dumps(message)) 85 | response = yield from res_queue.get() 86 | del self.response_queues[reqid] 87 | return response 88 | 89 | @asyncio.coroutine 90 | def oob_fetch(self, url): 91 | self.log.info("Starting OOB fetch...") 92 | if self.state_callback: 93 | self.state_callback('backlog_fetch') 94 | 95 | oob_data = self.irccloud.fetch(url) 96 | self.log.info("Parsing OOB data") 97 | for message in json.loads(oob_data): 98 | yield from self.handle_message(message, oob=True) 99 | self.log.info("OOB processing completed. %s connections, %s buffers.", 100 | len(self.connections), len(self.buffers)) 101 | if self.state_callback: 102 | self.state_callback('online') 103 | 104 | @asyncio.coroutine 105 | def handle_message(self, message, oob=False): 106 | if '_reqid' in message and message['_reqid'] in self.response_queues: 107 | yield from self.response_queues[message['_reqid']].put(message) 108 | if message['success'] is False: 109 | return 110 | 111 | try: 112 | mtype = message['type'] 113 | except KeyError: 114 | self.log.error("No message type in message: %s", message) 115 | return 116 | 117 | if mtype == 'header': 118 | self.stream_id = message['streamid'] 119 | elif mtype == 'stat_user': 120 | self.user_info = message 121 | elif mtype == 'oob_include': 122 | yield from self.oob_fetch(message['url']) 123 | elif mtype in IGNORE_MESSAGES: 124 | pass 125 | elif mtype in CREATION_MESSAGES: 126 | self.handle_creation_message(mtype, message) 127 | elif mtype in SERVER_MESSAGES: 128 | self.handle_server_message(mtype, message) 129 | elif mtype in BUFFER_MESSAGES: 130 | self.handle_buffer_message(message['bid'], message, oob) 131 | else: 132 | self.log.warn("Unhandled message. Type: %s, message: %s", mtype, message) 133 | 134 | def handle_creation_message(self, mtype, message): 135 | if mtype == 'makeserver': 136 | conn = Connection(message['cid']) 137 | conn.hostname = message['ircserver'] 138 | conn.port = message['port'] 139 | conn.status = message.get('status') 140 | self.connections[message['cid']] = conn 141 | elif mtype == 'makebuffer': 142 | conn = self.connections[message['cid']] 143 | buff = Buffer(message['bid'], message['name'], message['type'], conn) 144 | buff.archived = message.get('archived', False) 145 | conn.buffers.append(buff) 146 | self.buffers[message['bid']] = buff 147 | elif mtype == 'channel_init': 148 | buff = self.buffers[message['bid']] 149 | if self.track_channel_state: 150 | for member in message['members']: 151 | buff.members.append(User(member['nick'], member['realname'], member['usermask'])) 152 | 153 | def handle_server_message(self, mtype, message): 154 | conn = self.connections[message['cid']] 155 | if mtype == 'status_changed': 156 | conn.status = message['new_status'] 157 | elif mtype == 'server_details_changed': 158 | conn.status = message['status'] 159 | 160 | def handle_buffer_message(self, bid, message, oob): 161 | buff = self.buffers[bid] 162 | if self.track_channel_state: 163 | if message['type'] in ('quit', 'part'): 164 | buff.remove_member(message['nick']) 165 | if message['type'] == 'join': 166 | buff.members.append(User(message['nick'], message['realname'], message['usermask'])) 167 | 168 | if not oob and self.message_callback is not None: 169 | self.message_callback(buff, message) 170 | 171 | def register_message_callback(self, callback): 172 | self.message_callback = callback 173 | 174 | def register_state_callback(self, callback): 175 | self.state_callback = callback 176 | 177 | def disconnect(self): 178 | self.running = False 179 | 180 | @asyncio.coroutine 181 | def run(self): 182 | if self.state_callback: 183 | self.state_callback('connecting') 184 | 185 | self.socket = yield from self.irccloud.websocket() 186 | if self.state_callback: 187 | self.state_callback('connected') 188 | 189 | while self.running: 190 | res = yield from self.socket.recv() 191 | if res is None: 192 | break 193 | yield from self.handle_message(json.loads(res)) 194 | yield from self.socket.close() 195 | if self.state_callback: 196 | self.state_callback('disconnected') 197 | -------------------------------------------------------------------------------- /irccloud/client/http_client.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import division, absolute_import, print_function, unicode_literals 3 | from urllib.parse import urljoin 4 | import ssl 5 | import logging 6 | import requests 7 | import websockets 8 | 9 | 10 | class IRCCloudHTTPError(Exception): 11 | pass 12 | 13 | 14 | class RateLimitedError(Exception): 15 | pass 16 | 17 | 18 | class IRCCloudHTTPClient(object): 19 | def __init__(self, host, verify_certificate=True): 20 | # TODO: Test this SSL verification logic. 21 | self.log = logging.getLogger(__name__) 22 | self.host = host 23 | 24 | self.http = requests.Session() 25 | self.http.verify = verify_certificate 26 | self.ssl_context = ssl.create_default_context() 27 | if not verify_certificate: 28 | self.ssl_context.check_hostname = False 29 | self.ssl_context.verify_mode = ssl.CERT_NONE 30 | 31 | self.http.headers['User-Agent'] = 'IRCCloud-python' 32 | self.logged_in = False 33 | 34 | def get_url(self, path): 35 | return urljoin("https://%s" % self.host, path) 36 | 37 | def get_auth_formtoken(self): 38 | response = self.http.post(self.get_url("/chat/auth-formtoken")) 39 | response.raise_for_status() 40 | data = response.json() 41 | if not data['success']: 42 | raise IRCCloudHTTPError("Failure to get formtoken: %s" % data) 43 | return data['token'] 44 | 45 | def login(self, email, password): 46 | token = self.get_auth_formtoken() 47 | request_data = { 48 | 'token': token, 49 | 'email': email, 50 | 'password': password 51 | } 52 | headers = {'x-auth-formtoken': token} 53 | response = self.http.post(self.get_url("/chat/login"), data=request_data, headers=headers) 54 | if response.status_code == 400: 55 | data = response.json() 56 | if data['message'] == 'rate_limited': 57 | raise RateLimitedError(data) 58 | response.raise_for_status() 59 | data = response.json() 60 | if not data['success']: 61 | raise IRCCloudHTTPError("Failure to log in: %s" % data) 62 | self.log.info("Login successful, sid: %s", data['session']) 63 | self.logged_in = True 64 | 65 | def websocket(self): 66 | if not self.logged_in: 67 | raise IRCCloudHTTPError("Login required!") 68 | headers = { 69 | 'Origin': self.get_url(''), 70 | 'Cookie': 'session=%s' % (self.http.cookies['session']) 71 | } 72 | self.log.info("Connecting websocket...") 73 | return websockets.connect('wss://%s/' % self.host, 74 | extra_headers=headers, 75 | ssl=self.ssl_context) 76 | 77 | def fetch(self, path): 78 | url = self.get_url(path) 79 | response = self.http.get(url) 80 | response.raise_for_status() 81 | return response.text 82 | -------------------------------------------------------------------------------- /irccloud/client/log_render.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import division, absolute_import, print_function, unicode_literals 3 | import logging 4 | from datetime import datetime 5 | from string import Template 6 | from collections import defaultdict 7 | from .messages import VERBATIM, MESSAGES, STATS 8 | 9 | 10 | def eid_to_datetime(eid, tz=None): 11 | unixtime = eid // 1000000 12 | return datetime.fromtimestamp(unixtime, tz) 13 | 14 | 15 | class TextLogRenderer(object): 16 | """Render IRCCloud log events to human-readable text.""" 17 | def __init__(self, tz=None): 18 | self.log = logging.getLogger(__name__) 19 | self.tz = tz 20 | 21 | def render_buffer(self, lines): 22 | """ Take an iterable list of log events and yield human-readable text strings """ 23 | for line in lines: 24 | try: 25 | yield self.render_line(line.body) 26 | except KeyError: 27 | self.log.exception("Rendering exception") 28 | 29 | def render_line(self, line): 30 | """ Render a single log event to a string. """ 31 | time = eid_to_datetime(line['eid'], self.tz) 32 | msg = "[%s] " % (time.strftime('%Y-%m-%d %H:%M:%S')) 33 | if line['type'] == 'buffer_msg': 34 | msg += "<%s> %s" % (line.get('from', line.get('server')), line['msg']) 35 | return msg 36 | if line['type'] == 'buffer_me_msg': 37 | msg += "— %s %s" % (line['from'], line['msg']) 38 | return msg 39 | 40 | if line['type'] in ['joined_channel', 'you_joined_channel']: 41 | msg += '→ ' 42 | elif line['type'] in ['parted_channel', 'you_parted_channel']: 43 | msg += '← ' 44 | elif line['type'] == 'quit': 45 | msg += '⇐ ' 46 | else: 47 | msg += '* ' 48 | 49 | if line['type'] in VERBATIM: 50 | try: 51 | msg += line['msg'] 52 | except KeyError: 53 | self.log.warn("Log type %s has no attribute 'msg'", line['type']) 54 | elif line['type'] in MESSAGES: 55 | temp = Template(MESSAGES[line['type']]) 56 | msg += temp.safe_substitute(defaultdict(lambda: '', line)) 57 | elif line['type'] in STATS: 58 | if 'parts' in line: 59 | msg += line['parts'] + ": " 60 | msg += line['msg'] 61 | elif line['type'] == 'user_channel_mode': 62 | msg += '%s set %s %s' % (line.get('from', line.get('server')), line['diff'], line['nick']) 63 | elif line['type'] == 'channel_query': 64 | if line['query_type'] == 'timestamp': 65 | msg += 'channel timestamp is %s' % line['timestamp'] 66 | elif line['query_type'] == 'mode': 67 | msg += 'channel mode is %s' % line['newmode'] 68 | else: 69 | self.log.warn('Unknown channel_query type: %s', line['query_type']) 70 | elif line['type'] == 'channel_mode': 71 | msg += 'Channel mode set to %s by ' % line['diff'] 72 | if 'from' in line: 73 | msg += line['from'] 74 | else: 75 | msg += 'the server %s' % line['server'] 76 | elif line['type'] == 'motd_response': 77 | msg += "\n".join(line['lines']) 78 | elif line['type'] in ['cap_ls', 'cap_req', 'cap_ack']: 79 | if line['type'] == 'cap_ls': 80 | msg += 'Available' 81 | if line['type'] == 'cap_req': 82 | msg += 'Requested' 83 | if line['type'] == 'cap_ack': 84 | msg += 'Acknowledged' 85 | msg += ' capabilities: %s' % ' | '.join(line['caps']) 86 | elif line['type'] == 'unknown_umode': 87 | if 'flag' in line: 88 | msg += line['flag'] + " " 89 | msg += line['msg'] 90 | elif line['type'] == 'time': 91 | msg += 'Server time: %s' % line['time_string'] 92 | if 'time_stamp' in line: 93 | msg += ' (%s)' % line['time_stamp'] 94 | msg += ' - %s' % line['time_server'] 95 | else: 96 | if 'msg' in line: 97 | msg += line['msg'] 98 | self.log.warn('Unknown message type (%s)', line['type']) 99 | return msg 100 | -------------------------------------------------------------------------------- /irccloud/client/messages.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import division, absolute_import, print_function, unicode_literals 3 | VERBATIM = {'notice', 'quit_server', 'server_welcome', 4 | 'server_yourhost', 'server_created', 'server_luserme', 5 | 'server_n_local', 'server_n_global', 'server_luserconns', 6 | 'starircd_welcome', 'zurna_motd', 'codepage', 'logged_out', 7 | 'nick_locked', 'text', 'admin_info', 'server_luserclient', 8 | 'invalid_nick_change', 'nickname_in_use', 'self_away', 9 | 'error', 'sasl_success', 'sasl_aborted', 'sasl_fail', 10 | 'sasl_too_long', 'sasl_already', 'logged_in_as', 11 | 'server_motdstart', 'msg_services', 'not_for_halfops', 12 | 'ambiguous_error_message', 'list_syntax', 'who_syntax', 13 | 'server_motd', 'server_endofmotd', 'btn_metadata_set', 14 | 'unhandled_line', 'unparsed_line', 'wait', 15 | 'server_snomask', 'you_are_operator', 16 | 'generic_server_info', 'help_topics_start', 'help_topics', 17 | 'help_topics_end', 'helphdr', 'link_channel', 'helpfwd', 18 | 'helpop', 'helphlp', 'helpign', 'admin_info', 19 | 'invalid_nick', 'helptlr', 'info_response', 20 | 'no_bots', 'too_fast', 'wallops', 'server_nomotd', 21 | 'watch_status', 'bad_ping', 'list_usage'} 22 | 23 | STATS = {'stats', 'statslinkinfo', 'statscommands', 'statscline', 24 | 'statsyline', 'statsbline', 'statsgline', 'statstline', 25 | 'statseline', 'statsvline', 'statslline', 'statsuptime', 26 | 'statsoline', 'statshline', 'statssline', 'statsuline', 27 | 'statsdebug', 'endofstats', 'spamfilter'} 28 | 29 | MESSAGES = {'joined_channel': '$nick joined ($hostmask)', 30 | 'quit': '$nick quit ($hostmask): $msg', 31 | 'parted_channel': '$nick left ($hostmask)', 32 | 'you_parted_channel': 'You left the channel: $msg', 33 | 'channel_timestamp': 'Channel timestamp is $timestamp', 34 | 'socket_closed': 'Socket closed', 35 | 'channel_mode_is': 'Channel mode is +$newmode', 36 | 'you_joined_channel': 'Joined channel $chan', 37 | 'user_mode': 'Your user mode: +$newmode', 38 | 'self_details': 'Your hostmask: $usermask', 39 | 'server_luserchannels': '$value $msg', 40 | 'server_luserunknown': '$value $msg', 41 | 'server_luserop': '$value $msg', 42 | 'hidden_host_set': '$hidden_host $msg', 43 | 'you_nickchange': '$oldnick → $newnick', 44 | 'self_back': 'You are now marked as back', 45 | 'nickchange': '$oldnick is now known as $newnick', 46 | 'myinfo': 'Host: $server, IRCd: $version, user modes: $user_modes,' 47 | 'channel modes: $channel_modes, parametric channel modes: $rest', 48 | 'banned': 'You are banned: $msg', 49 | 'connecting': 'Connecting to $hostname...', 50 | 'connected': 'Connected', 51 | 'connecting_failed': 'Connecting failed: $reason', 52 | 'connecting_cancelled': 'Connecting cancelled', 53 | 'connecting_finished': 'Connected', 54 | 'channel_invite': '$from invited you to $channel', 55 | 'inviting_to_channel': 'You invited $recipient to $channel', 56 | 'channel_url': 'Channel URL is $url', 57 | 'channel_mode_list_change': '$from set channel modes $diff', 58 | 'kill': 'You were killed by $from: $reason', 59 | 'kicked_channel': '$nick was kicked by $kicker ($msg)', 60 | 'you_kicked_channel': 'You kicked $nick ($msg)', 61 | 'channel_topic': '$author set the topic to $topic', 62 | 'away': '$nick is away: $msg', 63 | 'your_unique_id': '$msg $unique_id', 64 | 'version': 'Version: $server_version ($comments)', 65 | 'target_callerid': '$nick $msg', 66 | 'callerid': '$nick ($usermask) $msg', 67 | 'target_notified': '$target_nick $msg', 68 | 'services_down': '$services_name $msg', 69 | 'kill_deny': '$channel $msg', 70 | 'chan_own_priv_needed': '$channel $msg', 71 | 'chan_forbidden': '$channel $msg', 72 | 'watch_status': '$watch_nick $msg ($username@$userhost)', 73 | 'sqline_nick': '$charset $msg', 74 | 'bad_channel_mask': '$channel $msg', 75 | 'rehashed_config': 'Rehashed config: $file ($msg)', 76 | 'ban_on_chan': 'Attempt to change nick to $proposed_nick while banned on $channel', 77 | 'no_such_server': '$server: $msg' 78 | } 79 | 80 | OTHER_BUFFER_MESSAGES = {'buffer_msg', 'buffer_me_msg', 'joined_channel', 'you_joined_channel', 81 | 'parted_channel', 'you_parted_channel', 'quit', 'user_channel_mode', 82 | 'channel_query', 'channel_mode', 'motd_response', 'cap_ls', 'cap_req', 83 | 'cap_ack', 'unknown_umode', 'time'} 84 | 85 | BUFFER_MESSAGES = OTHER_BUFFER_MESSAGES | VERBATIM | STATS | set(MESSAGES.keys()) 86 | -------------------------------------------------------------------------------- /irccloud/client/model.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import division, absolute_import, print_function, unicode_literals 3 | from collections import deque, namedtuple 4 | 5 | 6 | class Connection(object): 7 | def __init__(self, id): 8 | self.id = id 9 | self.port = None 10 | self.hostname = None 11 | self.buffers = [] 12 | self.status = None 13 | 14 | def get_buffer(self, name): 15 | for buf in self.buffers: 16 | if buf.name == name: 17 | return buf 18 | return None 19 | 20 | def __repr__(self): 21 | return "" % (self.id, self.hostname) 22 | 23 | 24 | class Buffer(object): 25 | def __init__(self, id, name, buffer_type, connection, max_backlog=500): 26 | self.id = id 27 | self.name = name 28 | self.buffer_type = buffer_type 29 | self.connection = connection 30 | self.lines = deque(maxlen=max_backlog) 31 | self.archived = False 32 | self.members = [] 33 | 34 | def remove_member(self, nick): 35 | for member in self.members: 36 | if member.nick == nick: 37 | self.members.remove(member) 38 | return 39 | 40 | def __repr__(self): 41 | return "" % (self.id, self.name) 42 | 43 | User = namedtuple('User', 'nick realname usermask') 44 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | # coding=utf-8 2 | from __future__ import division, absolute_import, print_function, unicode_literals 3 | from setuptools import setup 4 | 5 | setup(name='irccloud-client', 6 | version='0.1', 7 | description='IRCCloud python client', 8 | author='Russ Garrett', 9 | author_email='russ@irccloud.com', 10 | url='https://www.github.com/irccloud/python', 11 | packages=['irccloud.client'], 12 | install_requires=[ 13 | 'websockets == 2.6', 14 | 'ujson', 15 | 'requests' 16 | ]) 17 | --------------------------------------------------------------------------------