Commit 0a4aca94 authored by Elizabeth Myers's avatar Elizabeth Myers 💬
Browse files

Initial commit

parents
db/*
media/*
__pycache__
*.py[co]
config.toml
.*.sw[op]
*.pem
# Creative Commons CC0 1.0 Universal
CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED HEREUNDER.
### Statement of Purpose
The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work").
Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others.
For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights.
1. __Copyright and Related Rights.__ A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following:
i. the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work;
ii. moral rights retained by the original author(s) and/or performer(s);
iii. publicity and privacy rights pertaining to a person's image or likeness depicted in a Work;
iv. rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below;
v. rights protecting the extraction, dissemination, use and reuse of data in a Work;
vi. database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and
vii. other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof.
2. __Waiver.__ To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose.
3. __Public License Fallback.__ Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose.
4. __Limitations and Disclaimers.__
a. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document.
b. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law.
c. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work.
d. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work.
Kitty demo client
-----------------
This is a demo client for Kitty.
import sys
import shlex
from PySide2.QtWidgets import (QApplication, QMainWindow, QListWidget,
QTreeWidget, QTreeWidgetItem, QTextBrowser,
QLineEdit, QSplitter, QWidget, QVBoxLayout)
from PySide2.QtCore import Qt, QCoreApplication, QSettings, QTimer
from PySide2.QtWebSockets import QWebSocket
from proto.frame import Frame
def parse_input(string):
s = shlex.split(string)
if len(s) == 1:
return Frame.create('@', '$', s[0])
elif len(s) == 2:
return Frame.create('@', s[1], s[0])
elif len(s) == 3:
return Frame.create(s[1], s[2], s[0])
command = s[0]
src = s[1]
dest = s[2]
keyvals = dict()
for element in s[3:]:
key, sep, val = element.partition(':')
keyvals[key] = val
return Frame.create(src, dest, command, data=keyvals)
class NetworkConnection:
def __init__(self, window, name, url):
self.window = window
self.name = name
self.url = url
self.src = '@'
self.text_bufs = dict()
self.text_bufs[''] = list()
self.member_bufs = dict()
self.member_bufs[''] = set()
self.tree_children = dict()
self.tree_children[''] = QTreeWidgetItem([name])
self.window.tree_widget.addTopLevelItem(self.tree_children[''])
self.socket = QWebSocket()
self.socket.binaryMessageReceived.connect(self.message_received)
self.socket.sslErrors.connect(self.ignore_ssl_errors)
self.socket.connected.connect(self.connected)
self.socket.disconnected.connect(self.disconnected)
self.socket.error.connect(self.error)
self.do_connect()
def end(self):
i = (self.window.tree_widget.
indexOfTopLevelItem(self.tree_children[''])
)
self.window.tree_widget.takeTopLevelItem(i)
def add_buf(self, name):
if name in self.text_bufs:
return
self.text_bufs[name] = list()
self.member_bufs[name] = set()
self.tree_children[name] = QTreeWidgetItem([name])
self.tree_children[''].addChild(self.tree_children[name])
def del_buf(self, name):
if name not in self.text_bufs:
return
del self.text_bufs[name]
del self.member_bufs[name]
i = self.tree_children[''].indexOfChild(self.tree_children[name])
self.tree_children[''].takeChild(i)
def add_text_to_buf(self, name, text):
if name not in self.text_bufs:
return
self.text_bufs[name].append(text)
if self.window.current_buf == (self, name):
self.window.text_box.append(text)
def switch_buf(self, name):
if name not in self.text_bufs:
return
self.window.text_box.clear()
for text in self.text_bufs[name]:
self.window.text_box.append(text)
self.window.list_widget.clear()
for member in self.member_bufs[name]:
self.window.list_widget.addItem(member)
self.window.current_buf = (self, name)
def do_connect(self):
self.socket.open(self.url)
def connected(self):
self.add_text_to_buf('', f'* Connected to {self.name}')
def disconnected(self):
self.add_text_to_buf('', f'* Disconnected from {self.name}')
self.src = '@'
def error(self, e):
err = self.socket.errorString()
self.add_text_to_buf('', f'* Socket error ({err}), trying to reconnect')
QTimer.singleShot(5000, self.do_connect)
def ignore_ssl_errors(self):
self.socket.ignoreSslErrors()
def message_received(self, message):
frame = Frame.from_ubjson(message)
self.add_text_to_buf('', f'← {frame.type} {frame.src} {frame.dst} {frame.data!r}')
t = frame.type
if t == 'listgroups':
if frame.dst[0] == '@':
for group in frame.data.get('groups', []):
self.add_buf(group)
elif t == 'login':
self.src = frame.dst
self.send(Frame.create(self.src, self.src, 'listgroups'))
elif t == 'join':
if frame.dst not in self.member_bufs:
print(frame.dst)
return
if 'members' in frame.data:
self.member_bufs[frame.dst].update(frame.data['members'])
else:
self.member_bufs[frame.dst].add(frame.src)
if self.window.current_buf == (self, frame.dst):
self.window.list_widget.addItem(frame.src)
elif t == 'part':
if frame.dst not in self.member_bufs:
return
self.member_bufs[frame.dst].discard(frame.src)
members = self.window.list_widget.findItems(frame.src, Qt.MatchExactly)
if not members:
return
for item in members:
i = self.window.list_widget.row(item)
self.window.list_widget.takeItem(i)
elif t == 'message':
message = frame.data.get('message', None)
embed = frame.data.get('embed', None)
action = frame.data.get('action', None)
react = frame.data.get('react', None)
if frame.src not in self.text_bufs:
self.add_buf(frame.src)
if message:
self.add_text_to_buf(frame.src, f'<{frame.src[1:]}> {message}')
if embed:
self.add_text_to_buf(frame.src, f'-!- ({frame.src[1:]}) embed: {embed}')
if action:
self.add_text_to_buf(frame.src, f'* ({frame.src[1:]}) {action}')
if react:
self.add_text_to_buf(frame.src, f'-!- ({frame.src[1:]}) react: {react}')
def send(self, frame):
self.add_text_to_buf('', f'→ {frame.type} {frame.src} {frame.dst} {frame.data!r}')
t = frame.type
if t == 'message':
if self.src == '@':
self.add_text_to_buf('', '* You are not logged in')
return
message = frame.data.get('message', None)
embed = frame.data.get('embed', None)
action = frame.data.get('action', None)
react = frame.data.get('react', None)
if message:
self.add_text_to_buf(frame.dst, f'<{self.src[1:]}> {message}')
if embed:
self.add_text_to_buf(frame.dst, f'-!- ({self.src[1:]}) embed: {embed}')
if action:
self.add_text_to_buf(frame.dst, f'* ({self.src[1:]}) {action}')
if react:
self.add_text_to_buf(frame.dst, f'-!- ({self.src[1:]}) react: {react}')
self.socket.sendBinaryMessage(frame.to_ubjson())
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
QCoreApplication.setOrganizationName("Kitty")
QCoreApplication.setOrganizationDomain("kittyproto.chat")
QCoreApplication.setApplicationName("Kitty demo client")
self.default_buf = QTextBrowser()
self.tree_widget = QTreeWidget()
self.vbox_layout = QVBoxLayout()
self.text_box = self.default_buf
self.edit_box = QLineEdit()
self.vbox_layout.addWidget(self.text_box)
self.vbox_layout.addWidget(self.edit_box)
self.middle_widget = QWidget()
self.middle_widget.setLayout(self.vbox_layout)
self.list_widget = QListWidget()
self.splitter = QSplitter(Qt.Horizontal)
self.splitter.addWidget(self.tree_widget)
self.splitter.addWidget(self.middle_widget)
self.splitter.addWidget(self.list_widget)
self.splitter.setSizes([150, 600, 100])
self.setCentralWidget(self.splitter)
self.edit_box.returnPressed.connect(self.send)
self.tree_widget.itemDoubleClicked.connect(self.on_tree_double_click)
self.connection = NetworkConnection(self, 'localhost', 'wss://localhost:8080/ws')
self.connection.switch_buf('')
def send(self):
text = self.edit_box.text()
frame = parse_input(text)
self.connection.send(frame)
self.edit_box.clear()
def on_tree_double_click(self, item, column):
if item.parent() == None:
print("Switching buf to parent")
self.connection.switch_buf('')
else:
print("Switching to", item.text(0))
self.connection.switch_buf(item.text(0))
app = QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
import ubjson
import time
import uuid
class FrameError(Exception):
pass
class FrameParserError(FrameError):
pass
class Frame:
def __init__(self, id_, ts, src, dst, type_, related=None, data=None):
try:
uuid.UUID(id_)
except (ValueError, AttributeError) as e:
raise FrameParserError("id must be a valid UUID") from e
if not isinstance(ts, int) or not ts:
raise FrameParserError("ts must be an integer")
if not isinstance(src, str) or not src:
raise FrameParserError("src must be a string")
if not isinstance(dst, str) or not dst:
raise FrameParserError("dst must be a string")
if not isinstance(type_, str) or not type_:
raise FrameParserError("type must be a string")
try:
if related is not None:
uuid.UUID(related)
except (ValueError, AttributeError) as e:
raise FrameParserError(
"related must be null or a valid UUID") from e
if data is not None and not isinstance(data, dict):
raise FrameParserError("data must be null or a valid object")
self.id = id_
self.ts = ts
self.src = src
self.dst = dst
self.type = type_
self.related = related
self.data = {} if data is None else data
@classmethod
def create(cls, src, dst, type_, related=None, data=None):
id_ = str(uuid.uuid1())
ts = round(time.time())
return cls(id_, ts, src, dst, type_, related, data)
@classmethod
def from_ubjson(cls, data):
data = ubjson.loadb(data)
id_ = data['id']
ts = data['ts']
src = data['src']
dst = data['dst']
type_ = data['type']
related = data.get('related', None)
data = data.get('data', {})
return cls(id_, ts, src, dst, type_, related, data)
@classmethod
def from_dcp(cls, data):
length = int.from_bytes(data[:4], 'big')
data = ubjson.loadb(data[4:length + 4])
id_ = data['id']
ts = data['ts']
src = data['src']
dst = data['dst']
type_ = data['type']
related = data.get('related', None)
data = data.get('data', {})
return cls(id_, ts, src, dst, type_, related, data)
def to_dcp(self):
frame_data = {'id': self.id, 'ts': self.ts, 'src': self.src,
'dst': self.dst, 'type': self.type, 'data': self.data}
if self.related is not None:
frame_data['related'] = self.related
data = ubjson.dumpb(frame_data)
return int.to_bytes(len(data), 4, 'big') + data
def to_ubjson(self):
frame_data = {'id': self.id, 'ts': self.ts, 'src': self.src,
'dst': self.dst, 'type': self.type, 'data': self.data}
if self.related is not None:
frame_data['related'] = self.related
data = ubjson.dumpb(frame_data)
return data
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment