def publish_message(self, cname, messagetoclient): # Wait and then publish a message to the subscribed channel: time.sleep(10) grippub = GripPubControl({'control_uri': 'http://pushpin-svc:5561'}) logger.info("Publishing the message " + messagetoclient) print("Publishing the message " + messagetoclient) grippub.publish(cname, Item(WebSocketMessageFormat(messagetoclient)))
def _get_pubcontrol(): global _pubcontrol _lock.acquire() if _pubcontrol is None: _pubcontrol = GripPubControl() _pubcontrol.apply_grip_config(_get_proxies()) _lock.release() return _pubcontrol
def logs(): camera_id = request.args.get('cam') # pushpin private control pub = GripPubControl({'control_uri': 'http://proxy:5561'}) pub.publish_http_response(camera_id + '_channel', '{"event": "USER_REQUESTED"}') # wait receive_log() to finish updating current_log # FIXME: This part need be optimized time.sleep(0.4) return json.dumps(cache.get('current_log')), 200, {'ContentType': 'application/json'}
def send(): if request.method == 'POST': # obtain sent message message = request.form.get('message') message = 'event: ranstr\ndata: ' + message + '\n\n' # send sent message to be published to a channel on pushpin pub = GripPubControl({'control_uri': 'http://pushpin:5561'}) pub.publish_http_stream('test', message) return render_template('send.html') elif request.method == 'GET': return render_template('send.html') else: return redirect(url_for('stream_bp.home'))
def connect(self, **kwargs): variables = self.variables.copy() variables.update(kwargs) host = variables.get("host") port = variables.get("port") control_uri = f"http://{host}:{port}" self.pubctrl = GripPubControl({"control_uri": control_uri}) is_active = self.publish_on_stream("admin", "Connection test", sync=True) if not is_active: raise ServiceUnavailable(f"Pushpin unavailable on {control_uri}") return self
def _get_pubcontrol(): global _pubcontrol _lock.acquire() if _pubcontrol is None: _pubcontrol = GripPubControl() _pubcontrol.apply_config(getattr(settings, 'PUBLISH_SERVERS', [])) _pubcontrol.apply_grip_config(getattr(settings, 'GRIP_PROXIES', [])) _lock.release() return _pubcontrol
def custom_connection(self, **kwargs): if len(kwargs) > 0: variables = kwargs else: variables = self.variables host = variables.get('host') port = variables.get('port') control_uri = 'http://{}:{}'.format(host, port) pubctrl = GripPubControl({'control_uri': control_uri}) client = PushpinClient(pubctrl) is_active = client.publish_on_stream('admin', 'Connection test', sync=True) if is_active: return client raise ServiceUnavailable( "Pushpin unavailable on {}".format(control_uri))
def _create(self): return GripPubControl({'control_uri': current_app.config.get('GRIP_URI'), 'control_iss': current_app.config.get('GRIP_REALM'), 'key': current_app.config.get('GRIP_KEY')})
import sys import socket import threading import subprocess from pubcontrol import Item from gripcontrol import GripPubControl, HttpStreamFormat pub = GripPubControl({'control_uri': 'http://localhost:5561'}) def publish_worker(): sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(('127.0.0.1', 5004)) while True: data, addr = sock.recvfrom(65536) pub.publish('music', Item(HttpStreamFormat(data))) thread = threading.Thread(target=publish_worker) thread.daemon = True thread.start() subprocess.check_call([ 'gst-launch-1.0', 'filesrc', 'location=%s' % sys.argv[1], '!', 'decodebin', '!', 'queue', '!', 'lamemp3enc', '!', 'udpsink', 'clients=localhost:5004' ])
s3_client = boto3.client('s3') logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) # NOTE: localhost will not work as hostname, even in dev PUSHPIN_HOSTNAME = os.getenv('PUSHPIN_HOSTNAME') PUSHPIN_PORT = os.getenv('PUSHPIN_PORT', '5561') RESTREAM_LAMBDA_PREFIX = 'restreamable' KEYS_BUCKET = os.getenv('KEYS_BUCKET', 'restream-data') KEYS_OBJECT = os.getenv('KEYS_OBJECT', 'keys.json') ITEM_TABLE = os.getenv('MESSAGE_CACHE_TABLE', 'RestreamMessageCache') CONNECTION_TTL = int(os.getenv( 'CONNECTION_TTL', 1800)) # 30 minute default TTL on each connection pub = GripPubControl( {'control_uri': 'http://{}:{}'.format(PUSHPIN_HOSTNAME, PUSHPIN_PORT)}) channel_counts = {} channel_processors = {} global channel_keys channel_keys = {} connection_channels = {} connection_lastseen = {} FETCH_UPDATE_TIMEOUT = 600 # seconds def increment_channel_count(channel_id): count = channel_counts.get(channel_id, 0) channel_counts[channel_id] = count + 1 logger.debug('{} count inc to {}'.format(channel_id,
def publish_message(self): time.sleep(3) message = 'Please connect with Websocket. Http-stream is not supported yet!' print(message) grippub = GripPubControl({'control_uri': 'http://localhost:5561'}) grippub.publish(self.cname, Item(WebSocketMessageFormat(message)))
class PushpinExt(Connector): def get_connection_exception(self): return ServiceUnavailable def connect(self, **kwargs): variables = self.variables.copy() variables.update(kwargs) host = variables.get("host") port = variables.get("port") control_uri = f"http://{host}:{port}" self.pubctrl = GripPubControl({"control_uri": control_uri}) is_active = self.publish_on_stream("admin", "Connection test", sync=True) if not is_active: raise ServiceUnavailable(f"Pushpin unavailable on {control_uri}") return self def disconnect(self) -> None: self.disconnected = True def is_connected(self) -> bool: log.warning("pushpin.is_connected method is not implemented") return not self.disconnected @staticmethod def callback(result, message): if result: log.debug("Message successfully published on pushpin") else: # pragma: no cover log.error("Publish failed on pushpin: {}", message) def publish_on_stream(self, channel, message, sync=False): if not sync: self.pubctrl.publish_http_stream(channel, message, callback=PushpinExt.callback) return True try: self.pubctrl.publish_http_stream(channel, message, blocking=True) log.debug("Message successfully published on pushpin") return True except BaseException as e: log.error("Publish failed on pushpin: {}", message) log.error(e) return False def publish_on_socket(self, channel, message, sync=False): item = Item(WebSocketMessageFormat(message, binary=False)) if not sync: self.pubctrl.publish(channel, item, callback=self.callback) return True try: self.pubctrl.publish(channel, item, blocking=True) log.debug("Message successfully published on pushpin") return True except BaseException as e: # pragma: no cover log.error("Publish failed on pushpin: {}", message) log.error(e) return False
import sys import json from pubcontrol import Item from gripcontrol import GripPubControl, WebSocketEvent, \ WebSocketMessageFormat, decode_websocket_events, encode_websocket_events pub = GripPubControl({'control_uri': 'http://localhost:5561'}) opening = False out_headers = [] out = [] for e in decode_websocket_events(sys.stdin.read()): if e.type == 'OPEN': if not opening: opening = True # enable GRIP out_headers.append(('Sec-WebSocket-Extensions', 'grip')) # ack the open out.append(e) # subscribe connection to channel cm = {'type': 'subscribe', 'channel': 'room'} out.append(WebSocketEvent('TEXT', 'c:%s' % json.dumps(cm))) elif e.type == 'CLOSE': out.append(e) # ack break elif e.type == 'TEXT': # broadcast to everyone pub.publish('room', Item(WebSocketMessageFormat(e.content)))