Skip to content

Commit 69db9d2

Browse files
authored
Merge pull request #50 from CactusDev/rel-v0.3.6
Rel v0.3.6
2 parents fcd1ef1 + 85b686a commit 69db9d2

File tree

3 files changed

+81
-107
lines changed

3 files changed

+81
-107
lines changed

beam.py

+74-103
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
from tornado.websocket import websocket_connect
44
from tornado.gen import coroutine
5-
from tornado.ioloop import PeriodicCallback
65

76
from requests import Session
87
from requests.compat import urljoin
@@ -18,7 +17,6 @@
1817
import time
1918

2019
from models import User, session
21-
from datetime import datetime
2220

2321

2422
class Beam:
@@ -294,134 +292,107 @@ def read_chat(self, handler=None):
294292
if callable(handler):
295293
handler(response)
296294

297-
def connect_to_liveloading(self, channel_id, user_id):
295+
def connect_to_constellation(self, channel_id, user_id):
298296
"""Connect to Beam liveloading."""
299297

300-
self.liveloading_connection_information = {
298+
self.constellation_connection_information = {
301299
"channel_id": channel_id,
302300
"user_id": user_id
303301
}
304302

305-
liveloading_websocket_connection = websocket_connect(
306-
"wss://realtime.beam.pro/socket.io/?EIO=3&transport=websocket")
307-
liveloading_websocket_connection.add_done_callback(
303+
constellation_websocket_connection = websocket_connect(
304+
"wss://constellation.beam.pro")
305+
constellation_websocket_connection.add_done_callback(
308306
partial(self.subscribe_to_liveloading, channel_id, user_id))
309307

310308
def subscribe_to_liveloading(self, channel_id, user_id, future):
311-
"""Subscribe to Beam liveloading."""
309+
"""Subscribe to Beam constellation."""
312310

313311
if future.exception() is None:
314-
self.liveloading_websocket = future.result()
312+
self.constellation_websocket = future.result()
315313

316314
self.logger.info(
317-
"Successfully connected to liveloading websocket.")
318-
319-
interfaces = (
320-
"channel:{channel_id}:update",
321-
"channel:{channel_id}:followed",
322-
"channel:{channel_id}:subscribed",
323-
"channel:{channel_id}:resubscribed",
324-
"channel:{channel_id}:hosted",
325-
"user:{user_id}:update"
326-
)
327-
self.subscribe_to_interfaces(
328-
*tuple(
329-
interface.format(channel_id=channel_id, user_id=user_id)
330-
for interface in interfaces
331-
)
332-
)
315+
"Successfully connected to constellation websocket.")
316+
317+
interfaces = [
318+
"channel:{channel}:update".format(channel=channel_id),
319+
"channel:{channel}:followed".format(channel=channel_id),
320+
"channel:{channel}:subscribed".format(channel=channel_id),
321+
"channel:{channel}:resubscribed".format(channel=channel_id),
322+
"channel:{channel}:hosted".format(channel=channel_id),
323+
"user:{user}:update".format(user=user_id)
324+
]
325+
self.subscribe_to_interfaces(interfaces)
333326

334327
self.logger.info(
335-
"Successfully subscribed to liveloading interfaces.")
328+
"Successfully subscribed to Constellation interfaces.")
336329

337-
self.watch_liveloading()
330+
self.watch_constellation()
338331
else:
339332
self.logger.warning(future.exception())
340-
self.connect_to_liveloading(channel_id, user_id)
341-
342-
def subscribe_to_interfaces(self, *interfaces):
343-
"""Subscribe to a Beam liveloading interface."""
344-
345-
packet = [
346-
"put",
347-
{
348-
"method": "put",
349-
"headers": {},
350-
"data": {
351-
"slug": interfaces
352-
},
353-
"url": "/api/v1/live"
354-
}
355-
]
356-
self.liveloading_websocket.write_message('420' + dumps(packet))
357-
358-
def parse_liveloading_message(self, message):
359-
"""Parse a message received from the Beam liveloading websocket."""
333+
self.connect_to_constellation(channel_id, user_id)
360334

361-
sections = re.match(r"(\d+)(.+)?$", message).groups()
335+
def subscribe_to_interfaces(self, interfaces: list):
336+
"""Subscribe to a Beam constellation interface."""
362337

363-
return {
364-
"code": sections[0],
365-
"data": loads(sections[1]) if sections[1] is not None else None
338+
packet = {
339+
"type": "method",
340+
"method": "livesubscribe",
341+
"params": {
342+
"events": interfaces
343+
},
344+
"id": 1
366345
}
346+
self.constellation_websocket.write_message(dumps(packet))
347+
348+
def parse_constellation_message(self, packet):
349+
try:
350+
packet = loads(packet)
351+
except:
352+
return ""
353+
else:
354+
if "data" in packet and "payload" in packet["data"]:
355+
return packet["data"]
356+
else:
357+
return ""
367358

368359
@coroutine
369-
def watch_liveloading(self, handler=None):
360+
def watch_constellation(self):
370361
"""Watch and handle packets from the Beam liveloading websocket."""
371362

372-
response = yield self.liveloading_websocket.read_message()
363+
response = yield self.constellation_websocket.read_message()
373364
if response is None:
374365
raise ConnectionError
375366

376-
packet = self.parse_liveloading_message(response)
377-
378-
PeriodicCallback(
379-
partial(self.liveloading_websocket.write_message, '2'),
380-
packet["data"]["pingInterval"]
381-
).start()
382-
383367
while True:
384-
message = yield self.liveloading_websocket.read_message()
385-
386-
if message is None:
387-
self.logger.info("Connection to Liveloading lost.")
388-
self.logger.info("Attempting to reconnect.")
389-
390-
return self.connect_to_liveloading(
391-
**self.liveloading_connection_information)
392-
393-
self.logger.info("Attempting to reconnect.")
394-
self.watch_liveloading()
395-
396-
packet = self.parse_liveloading_message(message)
397-
398-
if packet.get("data") is not None:
399-
self.logger.debug("LIVE: {}".format(packet))
400-
401-
if isinstance(packet["data"], list):
402-
if isinstance(packet["data"][0], str):
403-
if packet["data"][1].get("following"):
404-
self.logger.info("- {} followed.".format(
405-
packet["data"][1]["user"]["username"]))
406-
407-
user = session.query(User).filter_by(
408-
id=packet["data"][1]["user"]["id"]).first()
409-
if user and (datetime.now() - user.follow_date).days:
410-
self.send_message(
411-
"Thanks for the follow, @{}!".format(
412-
packet["data"][1]["user"]["username"]))
413-
user.follow_date = datetime.now()
414-
session.add(user)
415-
session.commit()
416-
elif packet["data"][1].get("subscribed"):
417-
self.logger.info("- {} subscribed.".format(
418-
packet["data"][1]["user"]["username"]))
419-
self.send_message(
420-
"Thanks for the subscription, @{}! <3".format(
421-
packet["data"][1]["user"]["username"]))
422-
elif packet["data"][1].get("hoster"):
423-
self.logger.info("- {} hosted the channel.".format(
424-
packet["data"][1]["hoster"]["token"]))
368+
message = yield self.constellation_websocket.read_message()
369+
message = self.parse_constellation_message(message)
370+
if message is None or message is "":
371+
pass
372+
else:
373+
self.logger.debug("LIVE: {}".format(message))
374+
if "followed" in message["channel"]:
375+
if message["payload"]["following"]:
425376
self.send_message(
426-
"Thanks for hosting the channel, @{}!".format(
427-
packet["data"][1]["hoster"]["token"]))
377+
"Thanks for the follow, @{} !".format(
378+
message["payload"]["user"]["username"]))
379+
self.logger.info("- {} followed.".format(
380+
message["payload"]["user"]["username"]))
381+
elif "subscribed" in message["channel"]:
382+
self.send_message("Thanks for subscribing, @{} !".format(
383+
message["payload"]["user"]["username"]
384+
))
385+
elif "resubscribed" in message["channel"]:
386+
self.send_message("Thanks for subscribing, @{} !".format(
387+
message["payload"]["user"]["username"]
388+
))
389+
390+
# if message is None:
391+
# self.logger.info("Connection to Constellation lost.")
392+
# self.logger.info("Attempting to reconnect.")
393+
394+
# return self.connect_to_constellation(
395+
# **self.constellation_connection_information)
396+
397+
# self.logger.info("Attempting to reconnect.")
398+
# self.watch_constellation()

cactus.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ def run(self, *args, **kwargs):
129129

130130
def connect_liveloading():
131131
try:
132-
self.connect_to_liveloading(
132+
self.connect_to_constellation(
133133
self.channel_data["id"],
134134
self.channel_data["userId"])
135135
except ConnectionError as e:

models.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -491,11 +491,14 @@ def __call__(self, args, data):
491491
if len(args) < 2:
492492
return "Not enough arguments."
493493
elif len(args) == 2:
494-
user = re.match(r'@?([\w_-]*[a-z][\w_-]*', args[1])
494+
user = re.match(r'@?([\w_-]*[a-z][\w_-])*', args[1], re.I)
495+
user = str(user.group()).replace("@", "")
496+
497+
# user = user.group().replace("@", "")
495498
if user is None:
496499
return "Invalid username '{}'.".format(args[1])
497500

498-
channel_id = self.get_channel(user.group())
501+
channel_id = self.get_channel(user)
499502

500503
if channel_id.get("statusCode") == 404:
501504
return "User has not entered this channel."
@@ -506,7 +509,7 @@ def __call__(self, args, data):
506509
query.friend = not query.friend
507510
session.commit()
508511
return "{}ed @{} as a friend.".format(
509-
["Remov", "Add"][query.friend], user.group())
512+
["Remov", "Add"][query.friend], user)
510513
else:
511514
return "User has not entered this channel."
512515
elif len(args) > 2:

0 commit comments

Comments
 (0)