Esempio n. 1
0
        def fileslist_message():
            def path_to_dict(path):
                d = {'text': os.path.basename(path), 'path': path}
                if os.path.isdir(path):
                    d['nodes'] = [
                        path_to_dict(os.path.join(path, x))
                        for x in sorted(os.listdir(path))
                    ]
                    d['backColor'] = "#EEE"
                    d['selectable'] = False
                else:
                    d['selectable'] = True
                    d['text'] += ' <div class="media-edit float-right">'
                    d['text'] += '  <span class="badge badge-success" onClick="playlistAdd(\'' + path + '\'); event.stopPropagation();"> <i class="fas fa-plus"></i> </span>'
                    # d['text'] += '  <span class="badge badge-danger ml-2"><i class="far fa-trash-alt"></i> </span>';
                    d['text'] += ' </div>'
                return d

            liste = []
            for bp in self.player.basepath:
                liste.append(path_to_dict(bp))

            if len(liste) > 0 and 'nodes' in liste[0]:
                socketio.emit('files', liste)
            else:
                socketio.emit('files', None)
Esempio n. 2
0
def get_owner(channel):
    owner = ''
    data = get_json('channels.json')
    for i in data['channel']:
        if(i['cn'] == channel):
            owner = i['owner']
    socketio.emit('set_delete_button', owner)
 def emit(self, data) -> None:
     if not self.is_init:
         self.connect()
     try:
         socketio.emit('buffered_data', data, namespace='/binder')
     except Exception as e:
         print('socketio emit error ', e)
Esempio n. 4
0
        def fileslist_message():
            def path_to_dict(path):
                if os.path.basename(path).startswith('.'):
                    return None
                d = {'text': os.path.basename(path), 'path': path}
                if os.path.isdir(path):
                    n = filter(None, [
                        path_to_dict(os.path.join(path, x))
                        for x in sorted(os.listdir(path))
                    ])
                    d['nodes'] = [x for x in n if x is not None]
                    d['backColor'] = "#EEE"
                    d['selectable'] = False
                else:
                    d['selectable'] = True
                    d['text'] += ' <div class="media-edit float-right">'
                    d['text'] += '  <span class="badge badge-success" onClick="playlistAdd(\'' + path + '\'); event.stopPropagation();"> <i class="fas fa-plus"></i> </span>'
                    # d['text'] += '  <span class="badge badge-danger ml-2"><i class="far fa-trash-alt"></i> </span>';
                    d['text'] += ' </div>'
                return d

            liste = []
            for bp in self.http2interface.hplayer.files.root_paths:
                br = path_to_dict(bp)
                if br is not None:
                    # print(br)
                    liste.append(br)

            if len(liste) > 0 and 'nodes' in liste[0]:
                socketio.emit('files', liste)
            else:
                socketio.emit('files', None)
Esempio n. 5
0
def background_thread2(threadname, q):
    count = 0
    while True:
        time.sleep(1)
        count += 1
        paisa = q.get()
        socketio.emit('my_response2', {'data': paisa})
    def worker(task_queue, socketio):

        alive = True

        sleep = 1

        log.info("worker starts!")

        while True:

            try:

                task = task_queue.get(block=True, timeout=1)

                log.info("emitting task: %s", task)

                sleep = 1
                socketio.emit("pong", f"task: {task}")

            except queue.Empty:

                sleep = 1

                log.info("Emitting pong, then sleeping for %s", sleep)

                socketio.emit("pong", "empty")

            time.sleep(sleep)

        log.info("worker finished")
Esempio n. 7
0
def set_message(message_json):
    data={}
    channel_name = 'json/'+message_json['channel']+'.json'
    if path.exists(channel_name) and os.stat(channel_name).st_size!=0:
        with open(channel_name) as json_file:
            data = json.load(json_file)
        with open(channel_name, 'w') as json_file:
            print('length: ' + str(len(data['messages'])))
            if(len(data['messages']) == 100):
                data['messages'].pop(0)
            data['messages'].append({
                'message': message_json['message'],
                'sender': message_json['sender'],
                'date' : message_json['date'],
                'time' : message_json['time'] 
            })
            json.dump(data, json_file)
            socketio.emit('new_message_json', (data, message_json['channel']))
    else:
        with open(channel_name, 'w') as json_file:
            data = {}
            data['messages']=[]
            data['messages'].append({
                'message': message_json['message'],
                'sender': message_json['sender'],
                'date' : message_json['date'],
                'time' : message_json['time'] 
            })
            json.dump(data, json_file)
            socketio.emit('new_message_json', (data, message_json['channel']))
Esempio n. 8
0
def send_server(run_string):
    global socketio
    print(run_string)
    no_errors = ''.join(filter(lambda x: x in string.printable, run_string))
    if socketio is not None:
        socketio.emit('run_log', no_errors)

    print("Emmtted:" + no_errors)
Esempio n. 9
0
 def client_connect():
     socketio.emit('settings', self.player.settings())
     socketio.emit('name', self.player.name)
     global thread
     with thread_lock:
         if thread is None:
             thread = socketio.start_background_task(
                 target=background_thread)
Esempio n. 10
0
def connect(data):
    #stories.append(data)
    print data
    if session.get('user') not in users:
        return
    storyList[data["name"]] = (Story.Story(data["storyText"], data["name"],
                                           data["name"], data["storyImage"]))
    newStories = [x.__dict__ for x in list(storyList.values())]
    socketio.emit('updateStories', list(reversed(newStories)))
Esempio n. 11
0
def send2Q8i(msgType, msgJson, func=None):
    if msgJson['communityID']:
        logger.info("BEGIN: msgType=[%s],msgJson=[%s]", msgType, msgJson)
        socketio.emit(msgType,
                      msgJson,
                      room=msgJson['communityID'],
                      callback=func,
                      namespace='/sio_q8i')
        logger.info("END  : msgType=[%s],msgJson=[%s]", msgType, msgJson)
Esempio n. 12
0
def image():
    if 'image' in request.files:
        file = request.files['image']
        file_path = 'static/recent.jpg'
        file.save(file_path)
        socketio.emit('new_image', {}, broadcast=True)
        return jsonify({'path': 'recent.jpg'})
    else:
        return jsonify({'path': ''})
Esempio n. 13
0
 def background_thread():
     while True:
         try:
             task = self.sendBuffer.get_nowait()
             if len(task) > 1: socketio.emit(task[0], task[1])
             else: socketio.emit(task[0], None)
             self.sendBuffer.task_done()
         except queue.Empty:
             socketio.sleep(0.1)
Esempio n. 14
0
def update_resources():
    sleep_time = 2
    while True:
        time.sleep(sleep_time)
        for user in User.users().values():
            for resource in user.resources:
                resource.set_amount(resource.get_amount() +
                                    resource.get_speed() * sleep_time)
            socketio.emit("resources", user.resources, room=user.client)
Esempio n. 15
0
def connect(data):
    #stories.append(data)
    print("New story", data)
    if data["ownerID"] not in users:
        return
    stories[data["ownerID"]] = (Story.Story(data["storyName"], data["ownerID"],
                                            data["storyText"],
                                            data["storyImage"]))
    newStories = [x.__dict__ for x in list(stories.values())]
    socketio.emit('updateStories', list(reversed(newStories)))
Esempio n. 16
0
def background_thread2(q):
    count = 0
    while True:
        time.sleep(1)
        count += 1
        print(q)
        paisa = q
        #qx =Queue()
        #qx.put(q)
        socketio.emit('my_response2', {'data': paisa})
Esempio n. 17
0
    def get_offer_from_server(data):
        src_socket_id = data["src_socket_id"]
        offer = data["pack"]["offer"]
        peer_name = data["pack"]["peer_name"]
        network = data["pack"]["network"]
        route_list = data["pack"]["route"]
        print_debug_log("Get offer from client {}.".format(src_socket_id))

        rtc_list[src_socket_id] = WebRTCVPN()
        rtc = rtc_list[src_socket_id]
        answer = loop.run_until_complete(
            rtc_list[src_socket_id].create_answer(offer))

        emit_data = dict()
        emit_data["dst_socket_id"] = src_socket_id

        emit_data["pack"] = dict()
        emit_data["pack"]["answer"] = answer
        emit_data["pack"]["peer_name"] = args.name
        emit_data["pack"]["route"] = args.route

        socketio.emit("require_answer_from_client", emit_data)
        print_debug_log("Send answer to client {}.".format(src_socket_id))

        name = "tun-{}".format(peer_name)
        local_address = "{}.{}".format(network, "2")
        peer_address = "{}.{}".format(network, "1")

        pc = rtc.get_pc()

        @pc.on("datachannel")
        def on_datachannel(channel):
            print_log("VPN channel connected.")

            rtc.create_tuntap(name, local_address, mtu, channel)
            print_log("Create new TUN/TAP.")
            print_msg = "Name: {} Local_adderss: {} Peer_address: {} MTU: {}."
            print_log(print_msg.format(name, local_address, peer_address, mtu))

            if not route_list == None:
                print_log("Add new route.")
                for route in route_list:
                    rtc.set_route(route, peer_address)
                    print_log("Network: {} Dst: {}.".format(
                        route, peer_address))

        channel_state = loop.run_until_complete(
            rtc_list[src_socket_id].monitor())

        print_log("VPN channel closed.")
        print_log("Remove new TUN/TAP.")
        print_msg = "Name: {} Local_adderss: {} Peer_address: {} MTU: {}."
        print_log(print_msg.format(name, local_address, peer_address, mtu))

        del rtc_list[src_socket_id]
Esempio n. 18
0
def delete_channel(channel):
    os.remove('json/'+channel['channel']+'.json')
    data_copy = {}
    data_copy['channel']=[]
    data = get_json('channels.json')
    for i in data['channel']:
        if i['cn'] != channel['channel']:
            data_copy['channel'].append(i)
    with open('channels.json', 'w') as json_file:
            json.dump(data_copy, json_file)
    socketio.emit('delete_channel_message', channel['channel'])
    socketio.emit('delete_channel_ret')
Esempio n. 19
0
def background_thread(threadname, q):
    """Example of how to send server generated events to clients."""
    count = 0
    while True:
        time.sleep(1)

        count += 1
        q.put(count)
        socketio.emit('my_response', {
            'data': 'Server generated event',
            'count': count
        })
Esempio n. 20
0
def search_to_json(file_name, object_name, key, find):
    with open(file_name) as json_file:
        data = json.load(json_file)
            
        for user in data[object_name]:
            if user[key] == find:
                #if found
                ret_val = 0
                socketio.emit('ret_avail', ret_val)
                return ret_val
       
        return data
Esempio n. 21
0
def internet_on():
    while True:
        list = [
            'http://apptec.cl', 'https://google.com', 'https://facebook.com',
            'https://reddit.com', 'https://twitter.com'
        ]
        try:
            urlopen(random.choice(list), timeout=3)
            socketio.emit('InternetConnection', {'status': True})
            time.sleep(3)
        except:
            socketio.emit('InternetConnection', {'status': False})
            time.sleep(2)
Esempio n. 22
0
def handle_send_message_event(data):
    app.logger.info("{} has sent message to the room {}: {}".format(
        data['username'], data['room'], data['message']))
    socketio.emit('receive_message', data, room=data['room'])

    # Stores the room and message in a variable
    outbound_number = data['room']
    outbound_message = data['message']

    # Sends the message back to the user via SMS
    client.messages.create(to=outbound_number,
                           from_="+16479058445",
                           body=outbound_message)
Esempio n. 23
0
def getPidByName():
    global all_dead
    global crash_time

    init_supervisor()
    result_list = []
    m, s = divmod(int(time.time()) - start_time_stamp, 60)
    h, m = divmod(m, 60)
    time_interval_str = "%d:%02d:%02d" % (h, m, s)
    time_str = time.strftime("%Y-%m-%d %H:%M:%S",
                             time.localtime(int(time.time())))

    post_obj = {"data": [], "ip": my_ip}
    json_str = "Empty"

    for item in window_hwnd:
        client_info = item[:2]
        if (win32gui.GetWindowText(int(item[0])) == item[1]):
            all_dead = False

            client_info.append(True)
            client_info.append(time_interval_str)
            result_list.append(client_info)
        else:
            client_info.append(False)
            if (item[-1] == False):
                item[-1] = True
                crash_time[client_info[0]] = time_str

            if (crash_time[client_info[0]]):
                client_info.append(crash_time[client_info[0]])
            result_list.append(client_info)

    json_str = json.dumps(result_list)
    post_obj = {"data": result_list, "ip": my_ip}
    try:
        sio.emit("sendMonitor", post_obj)
        print(json_str)
        f_log = open(Superviser_Log, "a+")
        f_log.write(json_str + "\n")
        f_log.close()
        sio.on("pingServer")
    except Exception as e:
        print("Server error! " + e.__str__() + "\n")

    sendNotify(result_list)

    global t2
    t2.cancel()
    newtimer()
    t2.start()
Esempio n. 24
0
def check_cn_availability(channel_json, methods=['GET', 'POST']):
    data={}
    if path.exists('channels.json') and os.stat('channels.json').st_size!=0:
        data = search_to_json('channels.json', 'channel', 'cn', channel_json['cn'])
        if data != 0:
            print(data)
            with open('channels.json', 'w') as json_file:
                data['channel'].append({
                    'cn': str(channel_json['cn']),
                    'owner': str(channel_json['owner'])
                })
                json.dump(data, json_file)
                socketio.emit('ret_cn_avail', 1)
                socketio.emit('new_channel_json', data)
    else:
        #if messageme.txt is empty
        with open('channels.json', 'w') as json_file:
            data = {}
            data['channel']=[]
            data['channel'].append({
                'cn': str(channel_json['cn']),
                'owner': str(channel_json['owner'])
            })
            json.dump(data, json_file)
            socketio.emit('ret_cn_avail', 1)
            socketio.emit('new_channel_json', data)
Esempio n. 25
0
def setTimer():
    data = request.get_json()
    try:
        time = int(data.get('time'))
    except:
        return Response(500)

    global timer

    timer = time
    print(timer)
    socketio.emit("timerUpdate", timer)

    return Response(200)
Esempio n. 26
0
def connect(username):
    print("Username joined:", username)
    userBal = random.randint(100, 1000)
    global poolMoney
    poolMoney += 100
    socketio.emit("updatedMoney", poolMoney)

    #adding user to state
    tempUser = User.User(name=username['val'], balance=userBal - 100)
    users[tempUser.getID()] = tempUser
    userID = tempUser.getID()
    emit("registered", userID)
    print('USERS', users)
    allUsers = [x.getName() for x in users.values()]
    socketio.emit("newUser", allUsers)
Esempio n. 27
0
def custom_emit(event, *args, **kwargs):
    """Emit a SocketIO event.
    This function emits a user-specific SocketIO event to one or more connected
    clients. A JSON blob can be attached to the event as payload. This is a
    function that can only be called from a SocketIO event handler. Example::
        @socketio.on('my event')
        def handle_my_custom_event(json):
            emit('my response', {'data': 42})
    :param event: The name of the user event to emit.
    :param args: A dictionary with the JSON data to send as payload.
    :param namespace: The namespace under which the message is to be sent.
                      Defaults to the namespace used by the originating event.
                      An empty string can be used to use the global namespace.
    :param callback: Callback function to invoke with the client's
                     acknowledgement.
    :param broadcast: ``True`` to send the message to all connected clients, or
                      ``False`` to only reply to the sender of the originating
                      event.
    :param room: Send the message to all the users in the given room.
    """
    broadcast = kwargs.get('broadcast')
    room = kwargs.get('room')
    namespace = "/spotirooms"
    callback = kwargs.get('callback')
    if room is None and not broadcast:
        room = flask.request.sid

    socketio = flask.current_app.extensions['socketio']
    return socketio.emit(event, *args, namespace=namespace, room=room,
                         callback=callback)
Esempio n. 28
0
def custom_emit(event, *args, **kwargs):
    """Emit a SocketIO event.
    This function emits a user-specific SocketIO event to one or more connected
    clients. A JSON blob can be attached to the event as payload. This is a
    function that can only be called from a SocketIO event handler. Example::
        @socketio.on('my event')
        def handle_my_custom_event(json):
            emit('my response', {'data': 42})
    :param event: The name of the user event to emit.
    :param args: A dictionary with the JSON data to send as payload.
    :param namespace: The namespace under which the message is to be sent.
                      Defaults to the namespace used by the originating event.
                      An empty string can be used to use the global namespace.
    :param callback: Callback function to invoke with the client's
                     acknowledgement.
    :param broadcast: ``True`` to send the message to all connected clients, or
                      ``False`` to only reply to the sender of the originating
                      event.
    :param room: Send the message to all the users in the given room.
    """
    broadcast = kwargs.get('broadcast')
    room = kwargs.get('room')
    namespace = "/spotirooms"
    callback = kwargs.get('callback')
    if room is None and not broadcast:
        room = flask.request.sid

    socketio = flask.current_app.extensions['socketio']
    return socketio.emit(event,
                         *args,
                         namespace=namespace,
                         room=room,
                         callback=callback)
Esempio n. 29
0
def emit(event, *args, **kwargs):
    """Emit a SocketIO event.

    This function emits a SocketIO event to one or more connected clients. A
    JSON blob can be attached to the event as payload. This is a function that
    can only be called from a SocketIO event handler, as in obtains some
    information from the current client context. Example::

        @socketio.on('my event')
        def handle_my_custom_event(json):
            emit('my response', {'data': 42})

    :param event: The name of the user event to emit.
    :param args: A dictionary with the JSON data to send as payload.
    :param namespace: The namespace under which the message is to be sent.
                      Defaults to the namespace used by the originating event.
                      A ``'/'`` can be used to explicitly specify the global
                      namespace.
    :param callback: Callback function to invoke with the client's
                     acknowledgement.
    :param broadcast: ``True`` to send the message to all clients, or ``False``
                      to only reply to the sender of the originating event.
    :param to: Send the message to all the users in the given room. If this
               argument is not set and ``broadcast`` is ``False``, then the
               message is sent only to the originating user.
    :param include_self: ``True`` to include the sender when broadcasting or
                         addressing a room, or ``False`` to send to everyone
                         but the sender.
    :param skip_sid: The session id of a client to ignore when broadcasting
                     or addressing a room. This is typically set to the
                     originator of the message, so that everyone except
                     that client receive the message. To skip multiple sids
                     pass a list.
    :param ignore_queue: Only used when a message queue is configured. If
                         set to ``True``, the event is emitted to the
                         clients directly, without going through the queue.
                         This is more efficient, but only works when a
                         single server process is used, or when there is a
                         single addressee. It is recommended to always leave
                         this parameter with its default value of ``False``.
    """
    if 'namespace' in kwargs:
        namespace = kwargs['namespace']
    else:
        namespace = flask.request.namespace
    callback = kwargs.get('callback')
    broadcast = kwargs.get('broadcast')
    to = kwargs.pop('to', kwargs.pop('room', None))
    if to is None and not broadcast:
        to = flask.request.sid
    include_self = kwargs.get('include_self', True)
    skip_sid = kwargs.get('skip_sid')
    ignore_queue = kwargs.get('ignore_queue', False)

    socketio = flask.current_app.extensions['socketio']
    return socketio.emit(event, *args, namespace=namespace, to=to,
                         include_self=include_self, skip_sid=skip_sid,
                         callback=callback, ignore_queue=ignore_queue)
Esempio n. 30
0
    def request_offer_from_server(data):
        src_socket_id = data["src_socket_id"]
        print_debug_log("Request offer from client {}.".format(src_socket_id))

        rtc_list[src_socket_id] = WebRTCVPN()
        rtc = rtc_list[src_socket_id]
        offer = loop.run_until_complete(rtc_list[src_socket_id].create_offer())

        emit_data = dict()
        emit_data["dst_socket_id"] = src_socket_id

        emit_data["pack"] = dict()
        emit_data["pack"]["offer"] = offer
        emit_data["pack"]["peer_name"] = args.name
        emit_data["pack"]["route"] = args.route

        socketio.emit("require_offer_from_client", emit_data)
        print_debug_log("Require offer to client {}.".format(src_socket_id))
Esempio n. 31
0
def addUser():
    username = request.get_json()
    global users
    if username["uname"] in users.keys():
        return Response(500)
    global poolMoney
    #poolMoney += 5
    socketio.emit("updatedMoney", poolMoney)

    #adding user to state
    tempUser = User.User(username['fname'], username['lname'],
                         username['uname'], username['pass'])
    users[tempUser.getUname()] = tempUser
    session['user'] = username["uname"]

    socketio.emit("newUser", tempUser.getName())
    #return Response(status=200)
    return url_for("getStories")
Esempio n. 32
0
def emit(event, *args, **kwargs):
    """Emit a SocketIO event.

    This function emits a SocketIO event to one or more connected clients. A
    JSON blob can be attached to the event as payload. This is a function that
    can only be called from a SocketIO event handler, as in obtains some
    information from the current client context. Example::

        @socketio.on('my event')
        def handle_my_custom_event(json):
            emit('my response', {'data': 42})

    :param event: The name of the user event to emit.
    :param args: A dictionary with the JSON data to send as payload.
    :param namespace: The namespace under which the message is to be sent.
                      Defaults to the namespace used by the originating event.
                      A ``'/'`` can be used to explicitly specify the global
                      namespace.
    :param callback: Callback function to invoke with the client's
                     acknowledgement.
    :param broadcast: ``True`` to send the message to all clients, or ``False``
                      to only reply to the sender of the originating event.
    :param room: Send the message to all the users in the given room. If this
                 argument is set, then broadcast is implied to be ``True``.
    :param include_self: ``True`` to include the sender when broadcasting or
                         addressing a room, or ``False`` to send to everyone
                         but the sender.
    :param ignore_queue: Only used when a message queue is configured. If
                         set to ``True``, the event is emitted to the
                         clients directly, without going through the queue.
                         This is more efficient, but only works when a
                         single server process is used, or when there is a
                         single addresee. It is recommended to always leave
                         this parameter with its default value of ``False``.
    """
    if 'namespace' in kwargs:
        namespace = kwargs['namespace']
    else:
        namespace = flask.request.namespace
    callback = kwargs.get('callback')
    broadcast = kwargs.get('broadcast')
    room = kwargs.get('room')
    if room is None and not broadcast:
        room = flask.request.sid
    include_self = kwargs.get('include_self', True)
    ignore_queue = kwargs.get('ignore_queue', False)

    socketio = flask.current_app.extensions['socketio']
    return socketio.emit(event, *args, namespace=namespace, room=room,
                         include_self=include_self, callback=callback,
                         ignore_queue=ignore_queue)
Esempio n. 33
0
def emit(event, *args, **kwargs):
    """Emit a SocketIO event.

    This function emits a SocketIO event to one or more connected clients. A
    JSON blob can be attached to the event as payload. This is a function that
    can only be called from a SocketIO event handler, as in obtains some
    information from the current client context. Example::

        @socketio.on('my event')
        def handle_my_custom_event(json):
            emit('my response', {'data': 42})

    :param event: The name of the user event to emit.
    :param args: A dictionary with the JSON data to send as payload.
    :param namespace: The namespace under which the message is to be sent.
                      Defaults to the namespace used by the originating event.
                      A ``'/'`` can be used to explicitly specify the global
                      namespace.
    :param callback: Callback function to invoke with the client's
                     acknowledgement.
    :param broadcast: ``True`` to send the message to all clients, or ``False``
                      to only reply to the sender of the originating event.
    :param room: Send the message to all the users in the given room. If this
                 argument is set, then broadcast is implied to be ``True``.
    :param include_self: ``True`` to include the sender when broadcasting or
                         addressing a room, or ``False`` to send to everyone
                         but the sender.
    """
    if "namespace" in kwargs:
        namespace = kwargs["namespace"]
    else:
        namespace = flask.request.namespace
    callback = kwargs.get("callback")
    broadcast = kwargs.get("broadcast")
    room = kwargs.get("room")
    if room is None and not broadcast:
        room = flask.request.sid
    include_self = kwargs.get("include_self", True)

    socketio = flask.current_app.extensions["socketio"]
    return socketio.emit(event, *args, namespace=namespace, room=room, include_self=include_self, callback=callback)
def emit(event, data, use_socket=True, **kwargs):
    if use_socket:
        return socketio.emit(event, data, **kwargs)
    else:
        return data