Example #1
0
 def task_initial(self, grab, task):
     self.request_item.title = grab.doc.select('//title').text()
     for elem in grab.xpath_list('//a[not(contains(@href, "http"))]'):
         if (self.result_counter >= self.total):
             self.result_status = 'success'
             self.info = 'All images grabbed'
             self.request_item.status = self.result_status
             self.request_item.info = self.info
             db.session.commit()
             with app.app_context():
                 socketio.emit('finish', 'finish', namespace='/main')
             eventlet.sleep(0)
             self.stop()
             return
         else:
             if elem.get('href') not in self.urls:
                 self.urls.append(elem.get('href'))
                 yield Task('link', url=elem.get('href'))
     if (self.result_counter != self.total):
         self.result_status = 'error'
         self.info = 'Not of all images grabbed'
     else:
         self.request_item.status = self.result_status
         self.request_item.info = self.info
         db.session.commit()
         with app.app_context():
             socketio.emit('finish', 'finish', namespace='/main')
         eventlet.sleep(0)
         self.stop()
Example #2
0
	def cycle_switches(self):

		self.log.info("Emitting message: %s, %s", self.rollup_time, time.time())

		with app.app_context():
			exp = config.CYCLE_EXPERIMENTS[self.experiment_idx]
			self.experiment_idx = (self.experiment_idx + 1) % len(config.CYCLE_EXPERIMENTS)

			npts          = EXPERIMENT_CONFIGS[exp]['npts']
			startf, stopf = EXPERIMENT_CONFIGS[exp]['start'], EXPERIMENT_CONFIGS[exp]['stop']


			msg = {
				"src-guid"      : "nooooooope",
				"switch-matrix" :
				{
					"experiment-1" : exp == 1,
					"experiment-2" : exp == 2,
					"experiment-3" : exp == 3,
					"experiment-4" : exp == 4,
				},
				'start-stop' : [startf, stopf],
				'no-points'  : npts,
			}

			app.config['ARBITER'].set_experiment(msg["switch-matrix"])
			app.config['ARBITER'].set_num_points(npts)
			app.config['ARBITER'].set_start_stop_freq(startf, stopf)

			socketio.emit('config', msg, broadcast=True, namespace='/vna_interface')
Example #3
0
def winner(picture):
    user = User.query.filter_by(id=session['user-info']['id']).first()
    game = user.game
    if game is None:
        flash('You\'re not in a game!', 'warning')
        return redirect(url_for('.index'))
    if game.current_player != user.id:
        flash('You\'re not the current picker!', 'warning')
        return redirect(url_for('.index'))
    game.current_round += 1
    pic = Picture.query.filter_by(id=picture).first()
    playerWinner = game.users.filter_by(id=pic.user_id).first()
    playerWinner.current_streak += 1
    playerWinner.experience += playerWinner.current_streak
    playerWinner.best_streak = max(playerWinner.current_streak,
            playerWinner.best_streak)
    for player in game.users:
        if player != playerWinner and player != user:
            player.current_streak = 0

    if game.current_round <= game.rounds:
        #go on to next round
        game.phrase = ""
        for picture in game.pictures:
            picture.game_id = None
            db.session.delete(picture)
        users = getPlayerOrder(game)
        game.current_player = users[game.current_round % len(users)].id
    flash('%s was the winner!' % playerWinner.username, 'success')
    socketio.emit('anything', broadcast=True)
    db.session.commit()
    return redirect(url_for('.index'))
Example #4
0
 def task_link(self, grab, task):
     for image in grab.doc.select('//img'):
         try:
             if (self.result_counter >= self.total):
                 self.result_status = 'success'
                 self.info = 'All images grabbed'
                 self.request_item.status = self.result_status
                 self.request_item.info = self.info
                 db.session.commit()
                 with app.app_context():
                     socketio.emit('finish', 'finish', namespace='/main')
                 eventlet.sleep(0)
                 self.stop()
                 return
             src = image.attr('src')
             res = urllib.urlopen(src)
             http_message = res.info()
             if self.image_type != 'all' and self.image_type != http_message.type:
                 continue
             hash = os.urandom(16).encode('hex')
             filename = hash + src.split('/')[-1]
             self.downloader.retrieve(src, 'app/static/images/' + filename)
             self.result_counter += 1
             image_item = Image(
                 self.request_item,
                 src,
                 filename)
             db.session.add(image_item)
             with app.app_context():
                 socketio.emit('grabed_count', self.result_counter, namespace='/main')
             eventlet.sleep(0)
         except Exception as e:
             continue
Example #5
0
def game(game_id):
    name = session['name']
    print name

    if request.method == 'POST':
        move = request.form['data']
        sender_id = request.form['sender_id']
        if game_id not in games:
            return ""
        if sender_id not in games[game_id].keys():
            return ""

        if -2 == sum(player['move'] for player in games[game_id].values() if player['move'] == -1):
            games[game_id][sender_id]['move'] = move
        else:
            games[game_id][sender_id]['move'] = move
            for player in games[game_id].values():
                socketio.emit('submittedMove', {'msg': player['move']}, namespace='/game', room=player['opp_id'])

            games.pop(game_id, None)

        print games[game_id][sender_id]
        return 'Received'

    return render_template('game.html', name=name, game_id=game_id, id=session[game_id])
Example #6
0
def postSong(url=None):
    data = {
        "success": False
    }
    if url is None:
        url = request.json.get('url')
    title = findTitle(url)
    if title is None:
        data["message"] = "Invalid URL!"
        return data
    else:
        if "youtube" in url:
            url = "//www.youtube.com/embed/" + getYoutubeId(url)
        newSong = Song(url=url, title=title)
        db.session.add(newSong)
        try:
            db.session.commit()
        except:
            data["message"] = "Song already in playlist!"
            db.session.rollback()
            return data
        data = {
            "success": True,
            "data": {
                "id": newSong.id,
                "url": newSong.url,
                "title": newSong.title
                }
        }
    socketio.emit('new-song', data['data'])
    return data
    def create_game(cls):
        #create row in game table
        game = Game(game_started=True)
        db.session.add(game)
        db.session.commit()

        #randomly passing order that will be assigned when we create scoresheets
        positions = range(0, number_of_players)
        random.shuffle(positions)

        #create a scoresheet for each player TODO: this is currently making a game from all players in the db
        players = Player.query.all()
        for player in players:
            p = Scoresheet(player=player.name, game_id=game.id, position=positions.pop())
            db.session.add(p)
            db.session.commit()

            for i in range(0,number_of_rounds):
                r = Round(scoresheet_id=p.id, round_number=i+1)
                db.session.add(r)
        db.session.commit()

        # assemble data to be sent
        send_data = {'logMessage': 'game started','players': game.get_players()}
        socketio.emit('start_game', send_data, namespace=namespace)

        #play the first round
        game.play_round()
Example #8
0
    def file_failed(file):
        """
        will be called whenever a File fails
        :param file: the File object of the File that has failed
        """

        # delete from "processes"
        ProcessRepository.processes.pop(file.id)

        # update status and set attributes to zero
        file = db.session.query(File).filter_by(id=file.id).first()
        file.status = StatusMap.failed.value
        file.clear()
        db.session.commit()

        # check if it's necessary to start new processes
        ProcessRepository.check_and_start_processes()

        # notify client
        socketio.emit("file_done", {
            "data": {
                "id": file.id,
                "count_active": ProcessRepository.count_processes_active(),
                "count_queued": ProcessRepository.count_processes_queued(),
                "count_total": ProcessRepository.count_processes_total(),
            }
        })
    def receive_play_card(self, card):
        card = card[-1]+card[:-1]
        turn_index = self.get_turn_index()
        players = self.get_players()
        player = players[turn_index]
        player_stat = self.get_scoresheets()[turn_index].get_stats(self.round)
        player_stat.played_cards += (card + ',')

        # log who played what card
        msg = {'message': player + " played " + card}
        socketio.emit('server_message', msg, namespace=namespace)

        #add it to the player's played card space
        send_data = {'player': player, 'suit': card[:1], 'rank': card[1:]}
        socketio.emit('card_played', send_data, namespace=namespace)

        # increase the turn counter
        self.cards_played_counter += 1
        self.turn += 1
        db.session.commit()

        # if trick isn't over, get the next players card
        if self.cards_played_counter % number_of_players != 0:
            self.request_play_card()
        # if trick is over, score the trick
        else:
            self.score_trick()
 def emit_message(self, *args, **kwargs):
     username = kwargs.get('room')
     if username:
         user = Player.query.filter_by(name=username)
         if user.bot:
             Bot(self.game)
     socketio.emit(*args, **kwargs)
Example #11
0
def rt_feed(self):
    print("FEED")
    feeds_collection = mongo.db.feed
    now = datetime.utcnow()
    from_ = now - timedelta(minutes=now.minute % 5 + app.config["FEED_REFRESH"], seconds=now.second, microseconds=now.microsecond)
    feeds = feeds_collection.find()
    socketio.emit("update", dumps(feeds), namespace=rt_feed_namespace)
Example #12
0
def rt_map(self):
    print("MAP")
    assets_collection = mongo.db.assets
    now = datetime.utcnow()
    from_ = now - timedelta(minutes=now.minute % 5 + app.config["RTMAP_REFRESH"], seconds=now.second, microseconds=now.microsecond)
    assets = assets_collection.find({"ipmeta.country": {"$ne": "unknown"}}, {"ipmeta.iso_code": 1, "ipmeta.city": 1, "ipmeta.country": 1, "ipmeta.geo": 1})
    socketio.emit("update", dumps(assets), namespace=rt_map_namespace)
Example #13
0
def notify_object_updated(target, ignore_classes=None):
    if not ignore_classes:
        ignore_classes = set()
    target_class = target.__class__
    target.last_updated = datetime.utcnow()
    string_mapping = table_to_string_mapping[target_class]


    # for attr in bidirectional_relationships.get(target_class, []):
    #     related_objs = getattr(target, attr)
    #     try:
    #         _related_objs = related_objs.all()
    #         related_objs = _related_objs
    #     except AttributeError:
    #         continue
    #
    #     if related_objs:
    #         print("Updating Related objs", related_objs)
    #         try:
    #             for obj in related_objs:
    #                 if obj.__class__ not in ignore_classes:
    #                     ignore_classes.add(target_class)
    #                     _notify_object_updated(obj, ignore_classes)
    #
    #         except TypeError:
    #             if related_objs.__class__ not in ignore_classes:
    #                 ignore_classes.add(target_class)
    #                 _notify_object_updated(related_objs, ignore_classes)

    socketio.emit('updated', update_msg_schema.dump({
        'last_updated': target.last_updated,
        'model': string_mapping,
        'id': str(target.id)
    }), namespace=make_namespace(string_mapping), broadcast=True)
Example #14
0
def get_genotypes(json):
    ids = extract_ids(json)
    for id_subset in subset(ids, 500):
        genotypes = []
        for id in id_subset:
            genotype = next(Genotype.query.filter(Genotype.id == id).values(
                Genotype.id, Genotype.project_id, Genotype.sample_annotations_id, Genotype.locus_id,
                Genotype.annotated_peaks, Genotype.reference_run_id, Genotype.flags, Genotype.comments,
                Genotype.last_updated, Genotype.alleles
            ))
            genotypes.append(genotype)
        # genotypes = Genotype.query.filter(Genotype.id.in_(id_subset)).values(
        #     Genotype.id, Genotype.project_id, Genotype.sample_annotations_id, Genotype.locus_id,
        #     Genotype.annotated_peaks, Genotype.reference_run_id, Genotype.flags, Genotype.comments,
        #     Genotype.last_updated, Genotype.alleles
        # )
        res = []
        for s in genotypes:
            g = {
                'id': s[0],
                'project': s[1],
                'sample_annotations': s[2],
                'locus': s[3],
                'annotated_peaks': s[4],
                'reference_run': s[5],
                'flags': s[6],
                'comments': s[7],
                'last_updated': s[8],
                'alleles': s[9]
            }
            res.append(g)

        genotypes_dump = schema.dumps(res, many=True)
        socketio.emit('get_updated', {JSON_NAMESPACE: genotypes_dump.data}, namespace=make_namespace(JSON_NAMESPACE))
        socketio.sleep()
Example #15
0
 def emit_task_success(self, message=None, callback=None):
     socketio.emit(self.task, {
         'task_args': self.task_args,
         'status': 'success',
         'id': self.task_id,
         'payload': message
     }, namespace=self.namespace, callback=callback)
     socketio.sleep()
Example #16
0
def notify_created(_, __, target):
    target_class = target.__class__
    string_mapping = table_to_string_mapping[target_class]
    # print("Inserting class {} with id {}".format(string_mapping, str(target.id)))
    socketio.emit('created', {
        'model': string_mapping,
        'id': str(target.id)
    }, namespace=make_namespace(string_mapping), broadcast=True)
Example #17
0
 def emit_task_progress(self, progress, callback=None):
     socketio.emit(self.task, {
         'task_args': self.task_args,
         'status': 'in_progress',
         'id': self.task_id,
         'payload': progress
     }, namespace=self.namespace, callback=callback)
     socketio.sleep()
Example #18
0
 def emit_task_start(self, data=None, callback=None):
     socketio.emit(self.task, {
         'task_args': self.task_args,
         'status': 'start',
         'id': self.task_id,
         'payload': data
     }, namespace=self.namespace, callback=callback)
     socketio.sleep()
Example #19
0
def start_helper(tc):
    try:
        sopen = tc.start();
        flash('Trying to start the tempcontrol')
    except SerialException as e:
        flash('SerialException: Could not open serial connection', 'error')
    socketio.emit('open_conn',{'data': tc.conn_str()})
    return redirect(url_for('main.index'))
Example #20
0
def background_thread():
    count = 0
    while True:
        time.sleep(10)
        count += 1
        socketio.emit('my response',
                {'data': 'Server generated event', 'count': count},
                namespace='/chat')
Example #21
0
 def log(self, message):
     post = ConferenceLog(conference=self, message=message)
     db.session.add(post)
     db.session.commit()
     socketio.emit('log_message', {
         'data': message,
         'room': 'conference-%s' % self.id
     })
Example #22
0
def notify_locus_parameter_locked(_, __):
    locus_parameter_subsets = defaultdict(list)
    for target in db.session.dirty:
        if isinstance(target, ProjectLocusParams):
            locus_parameter_subsets[table_to_string_mapping[target.__class__]].append((target.id, target.locked))
    for subset_label in locus_parameter_subsets:
        locus_parameters = locus_parameter_subsets[subset_label]
        socketio.emit('locked', locus_parameters, namespace=make_namespace(subset_label), broadcast=True)
def create_question():
    toid = request.args.get("to", "")
    if not toid == "":
        question = Question(submitter_id=current_user().id, to_id=int(toid), description=request.form["description"])
        db.session.add(question)
        db.session.commit()
        socketio.emit("question_added", "question created", room="consultants", namespace="/consultants")
        return redirect("/questions/by/" + str(current_user().id))
Example #24
0
def queuewall():
	previous_images = set(os.listdir(flapp.config['QUEUE_DIR']))
	previous_images = map(lambda f: flapp.config['QUEUE_DIR'] + f, previous_images) 
	for img in previous_images:
		add_image_to_wall_q(img)
	images = get_queue_wall_images()
	print images
	socketio.emit('images', {'images':images}, namespace = '/queue')
	return render_template('queue.html')
Example #25
0
def pickingPhase(user, game):
    form = PickAWordForm(request.form)
    words = getWord(adjs, 5)
    picker_id = game.current_player
    picker = User.query.filter_by(id=picker_id).first()
    socketio.emit('anything', broadcast=True)
    return render_template('pickaword.html', form=form, 
        isPicker=picker_id == user.id, words=words, picker=picker.username,
        game_round=game.current_round)
Example #26
0
def add_processing_files():
    """
    send client information about all currently processing Files
    """
    files = FileRepository.get_processing_query().all()

    for file in files:
        # emit the file_started event for *every* file that is currently being processed
        socketio.emit("file_started", {"data": formatted_file_data(file)})
Example #27
0
def leaveGame():
    user = User.query.filter_by(id=session['user-info']['id']).first()
    if user.game is None:
        flash('You aren\'t in a game!', 'warning')
        return redirect(url_for('.index'))
    user.game = None
    socketio.emit('anything', broadcast=True)
    db.session.commit()
    return redirect(url_for('.index'))
Example #28
0
def stop_wtc(ard_nr):
    '''
    The main function for rendering the principal site.
    '''
    tc = WebTempControl.query.get(ard_nr);
    tc.stop()
    flash('Stopped the thermocontrol')
    socketio.emit('close_conn',{'data': tc.conn_str()})
    return redirect(url_for('main.index'))
Example #29
0
def background_thread():
    """Example of how to send server generated events to clients."""
    count = 0
    while True:
        time.sleep(120)
        count += 1
        socketio.emit('my response',
                      {'data': 'Server generated event', 'count': count, 'nickname': 'Server'},
                      namespace='/chat')
Example #30
0
def leave_conference(conf_number, callerid):
    if not asterisk_is_authenticated():
        return 'NOTAUTH'
    message = gettext('Number %(num)s has left the conference.', num=callerid)
    conference = Conference.query.filter_by(number=conf_number).first_or_404()
    conference.log(message)
    socketio.emit('update_participants', {
        'room': 'conference-%s' % conference.id
    })
    return 'OK'
Example #31
0
    def cancel_process(file_id):
        """
        cancel a specific Process
        :param file_id: the id of the file corresponding to the Process
        """

        # stop thread
        ProcessRepository.processes[file_id].stop()
        # update status
        file = File.query.filter_by(id=file_id).first()
        file.status = StatusMap.failed.value
        file.clear()
        db.session.commit()

        # emit file_done event
        socketio.emit("file_done", {"data": formatted_file_data(file)})

        # remove from processes dict
        ProcessRepository.processes.pop(file_id)
Example #32
0
def send_message(data):
    user_ = User.query.filter_by(username=data['username']).first()
    thread_ = thread.query.filter_by(subject=data['room']).first()
    p = post(message=data['message'], user_id=user_.id, thread_id=thread_.id)
    db.session.add(p)
    db.session.commit()
    p = post.query.filter_by(message=data['message'],
                             user_id=user_.id,
                             thread_id=thread_.id).first()
    socketio.emit('received_message', {
        'room': data['room'],
        'user_id': p.user_id,
        'username': user_.username,
        'msg': p.message,
        'post_id': p.id,
        'thread_id': thread_.id
    },
                  room=data['room'],
                  dif_user=p.user_id)
def switchClick_ack(data=None):

    # if the callback is called with no data then just pass
    if data is None:
        return

    parsed = json.loads(data)
    oActuator = Actuator.query.filter_by(id=parsed['id']).first()
    if oActuator is not None:
        # Update database
        oActuator.state_current = parsed['state']       
        db.session.commit()
        # Update client-user's button state
        aux = {
            'id' : parsed['id'],
            'state' : parsed['state'],
            'class' : 'switch-onoff'
        }
        socketio.emit('updateState', data=aux, namespace='/client-user')
Example #34
0
    def picture(self):
        """Sends the last picture saved by the streaming
        through a socket.
        """

        pictures = sorted([f for f in os.listdir(self.stream_path)])

        if len(pictures):
            p = pictures[-1]
            picture_path = os.path.join(self.stream_path, p)
            while os.stat(picture_path).st_size == 0:
                pass
            return picture_path
        else:
            socketio.emit('msg2user', {'type': 'warning',
                                       'msg': 'There is no picture to send'}, namespace='/car')
            if self.verbose:
                print('There is no picture to send')
            return None
Example #35
0
def RequestStation(data):
    print("i am in")
    try:
        if (data['action'] == "drop"):
            action = "D"
        elif (data['action'] == "pick"):
            action = "P"

        msgToSend = "ST," + str(data['station_id']) + ",R," + str(
            data['job_id']) + "," + str(
                data['position']) + "|" + action + "|" + str(
                    data['bin_id']) + ";"
        reply = checkRequest(data['station_id'], msgToSend)
        if type(reply) is list:
            if (reply[2] == 'A'):
                requestReply = jsonFormat(
                    {
                        "station_id": data['station_id'],
                        "job_id": data['job_id'],
                        "status": "true",
                        "message": "Approved"
                    }, "")
            else:
                requestReply = jsonFormat(
                    {
                        "station_id": data['station_id'],
                        "job_id": data['job_id'],
                        "status": "false",
                        "message": "Denied"
                    }, "")
        else:
            requestReply = jsonFormat(
                {
                    "station_id": data['station_id'],
                    "job_id": data['job_id'],
                    "status": "false",
                    "message": "Denied"
                }, reply)
        socketio.emit("request", requestReply, namespace='/station')
        # emit("request", requestReply)
    except Exception as e:
        print(redBright(e))
Example #36
0
 def post(self, room_id):
     song_file = request.files["song"]
     if song_file.filename == "":
         return {"status": "error", 'message': "Please select a file"}, 400
     elif not (song_file and allowed_file(song_file.filename)):
         return {
             "status": "error",
             'message': "Files must be in mp3 format."
         }, 400
     elif Room.query.filter_by(id=room_id).first() is None:
         return {"status": "error", "message": "Room does not exist."}, 400
     else:
         link = None
         try:
             song_name = secure_filename(song_file.filename)
             link = upload_file_to_s3(song_file, config.S3_BUCKET)
             new_song = Song(name=song_name, link=link, room_id=room_id)
             db.session.add(new_song)
         except Exception as e:
             if link is not None:
                 s3.delete_object(Bucket=config.S3_BUCKET,
                                  Key=link[len(config.S3_LOCATION):])
             db.session.rollback()
             print(repr(e))
             return {
                 "status":
                 "error",
                 'message':
                 "Something wrong happen while uploading new song. Please try again."
             }, 400
         db.session.commit()
         result = song_schema.dump(new_song)
         socketio.emit('playlist', {
             'data': {
                 'room_id': room_id,
                 'action': 'song_added',
                 'data': result,
                 'message': 'Song ' + song_name + ' has been added.'
             }
         },
                       room=room_id)
         return {"status": "success", "data": result}, 200
Example #37
0
    def end_turn(cls, game):
        app.logger.debug(
            'Ending turn for the game {game_id}'.format(game_id=game.game_id))

        # End current turn
        game.end_current_turn()

        # Rank answers
        ranked_players = game.get_current_turn_ranks()
        player_count = len(ranked_players)

        # Send the end of turn signal and the correct and best answer to every players in the game
        city = game.get_current_city()
        turn_results = {
            'correct_answer': {
                'name': city['name'],
                'lat': city['latitude'],
                'lng': city['longitude']
            }
        }

        if player_count > 0:
            turn_results['best_answer'] = {
                'distance':
                ranked_players[0].get_result(game.turn_number).distance,
                'lat': ranked_players[0].get_answer(game.turn_number).latitude,
                'lng': ranked_players[0].get_answer(game.turn_number).longitude
            }

        socketio.emit('end_of_turn', turn_results, room=game.game_id)

        # Then send individual player results
        for rank, player in enumerate(ranked_players):
            socketio.emit('player_results', {
                'rank': rank + 1,
                'total': player_count,
                'distance': player.get_result(game.turn_number).distance,
                'score': player.get_result(game.turn_number).score,
                'lat': player.get_answer(game.turn_number).latitude,
                'lng': player.get_answer(game.turn_number).longitude
            },
                          room=player.sid)
Example #38
0
def create_chat_message(raw_message):
    chat = Chat.query.get(raw_message['chatId'])
    user = User.query.get(raw_message['userId'])

    if (user and chat):
        message = Message(chat_id=chat.id,
                          user_id=user.id,
                          text=raw_message['text'])
        db.session.add(message)
        db.session.commit()

    socketio.emit(
        'new-message',
        json.dumps({
            **prepare_message_to_send(message), 'isUnread': True
        }))
    socketio.emit('lastMessageUpdate', {
        'chatId': chat.id,
        'body': str(message)
    })
def handle_join_room(data):
    user = User.objects(username=data['username']).first()
    # update point of user
    point = user.point - 50
    user.update(set__point=point)

    # save sid of player
    gameroom = get_gameroom(data['room'])
    member0 = gameroom.members[0]
    member1 = gameroom.members[1]
    if member0.name == data['username']:
        member0.sid = request.sid
    else:
        member1.sid = request.sid
    gameroom.save()

    join_room(data['room'])

    data['info'] = 'connected'
    socketio.emit('join-room-info', data, data['room'])
Example #40
0
def get_model_detail_period(mid, sid, uids):
    while sid in all_background_thread:
        model_info = redis_func.get_model_status(mid)
        device_info = []
        for uid in uids:
            res = redis_func.get_device_status(uid)
            res["times"] = redis_func.get_device_model_contribute_time(
                uid, mid)
            res["status"] = redis_func.get_device_model_status(uid, mid)

            device_info.append(res)

        ret = {"model_info": model_info, "device_info": device_info}
        socketio.emit('push_task_info',
                      ret,
                      namespace='/dashboard',
                      json=True,
                      room=sid)

        socketio.sleep(5)
Example #41
0
def languageChange(data):
    LoadDB(data['language'])

    global db

    a = db.get_toml_data('Buildin')
    
    stg = ''
    for item in a:
        stg += "<li><a class='dropdown-item' href='#' onClick='dropClicked(this)' data-value='" + item + "'>" + item + "</a></li>"

    stg += "<li><div class='dropdown-divider'></div></li>"

    a = db.get_toml_data('Custom')
  
    for item in a:
        stg += "<li><a class='dropdown-item' href='#' onClick='dropClicked(this)' data-value='" + item + "'>" + item + "</a></li>"
      

    socketio.emit('lang_changed', stg, namespace='/generator')
Example #42
0
def serious_chat(user1, user2, topic):
    serious_queue.pop(0)
    serious_queue.pop(0)
    id1 = username[user1]
    id2 = username[user2]
    chats[id1] = id2
    chats[id2] = id1
    opinions = get_opinions()
    socketio.emit('okay', {
        'name': user1,
        'topic': topic,
        'opinion': opinions[0]
    },
                  room=id1)
    socketio.emit('okay', {
        'name': user2,
        'topic': topic,
        'opinion': opinions[1]
    },
                  room=id2)
Example #43
0
def handle_channel(chn):
    global profane
    name = chn['name']
    content = chn['message']

    name_cleaned = profanity.censor(name)
    content_cleaned = profanity.censor(content)

    now = datetime.now().strftime('%A %I:%M:%S %p').lstrip("0").replace(
        " 0", " ")

    message_object = Channel(name=name_cleaned,
                             content=content_cleaned,
                             date_posted=now)
    database.session.add(message_object)
    database.session.commit()

    json_chan = {'name': name_cleaned, 'content': content_cleaned, 'date': now}

    socketio.emit('channel', json_chan)
Example #44
0
def pco_set(data):
    g = freeplay_games[data['gameid']]
    player = g.get_player_from_session(current_user)
    print('Client {}, event {}: {}'.format(get_stable_user(), 'PCO SET', data))
    if not g.confirm_or_destroy_id(data['obj_id']):
        return False
    obj = g.all_movables[data['obj_id']]
    obj.offset_per_dependent = [int(data['pco_x']), int(data['pco_y'])]
    return_data = {
        'movables_info': [{
            'id': obj.id,
            'offset_per_dependent': obj.offset_per_dependent
        }]
    }
    socketio.emit('UPDATE',
                  return_data,
                  broadcast=True,
                  room=data['gameid'],
                  namespace='/freeplay')
    g.time_of_last_update = time()
Example #45
0
def right_to_eraser(data):
    comment = ProjectComment.query.get(data['comment_id'])

    print(sid_rooms.get(str(comment.author.id)), comment.author.id, sid_rooms)
    # for sid in [request.sid, *list(map(lambda x: sid_rooms.get(x.id), comment.project.authors))]:
    #
    #     if sid is None:
    #         continue
    #
    #     print (sid)
    #     socketio.emit("right_to_eraser", {
    #         "project_id": data['project_id'],
    #         "comment_id": data['comment_id'],
    #     }, room=sid)

    socketio.emit("right_to_eraser", {
        "project_id": data['project_id'],
        "comment_id": data['comment_id'],
    },
                  room=request.sid)
Example #46
0
    def update_legend(self):
        app.logger.debug('Updating legend')

        legend_changes = []

        ranks = self.game.get_current_turn_ranks()
        for p in ranks:
            p_name, p_color = self.game.colors_mapped[p.sid]
            legend_changes.append(
                (p_name, p_color,
                 p.get_result(self.game.turn_number).distance))

        # for player_sid, player_name_and_color in self.game.colors_mapped.items():
        #     legend_item = [player_name_and_color[1], player_name_and_color[0]]
        #     if len(current_turn_players_results) > 0:
        #         legend_item.append(current_turn_players_results[player_sid])
        #     else:
        #         legend_item.append(0)
        #     legend_changes.append(legend_item)
        socketio.emit('legend_changes', legend_changes)
Example #47
0
def like(postID):
    print(postID)
    # chatroom = Chatroom.query.get_or_404(room_id)
    post = Post.query.get_or_404(postID)
    user = db.session.query(User).get(current_user.id)
    if (not user.has_liked(post)):
        user.like(post)
        db.session.commit()
    likedUsers = len(post.LikedUsers.all())
    socketio.emit("likedUsers", {"likedUsers": likedUsers})
    # user.ChatroomId = chatroom.id
    # chatroom.Members.append(user)
    # db.session.commit()
    # flask_socketio.join_room(room_id)
    # socketio.emit("join_b", {"ProfilePicture": current_user.ProfilePicture,
    #                          "FirstName": current_user.FirstName,
    #                          "Members" : getMembersAsList(chatroom.Members)
    #                          }
    #               , room=room_id)
    print(user.has_liked(post))
Example #48
0
def creer_publication():
    jeton = request.json["jeton"]
    corps = request.json["corps"]

    print(jeton)
    print(corps)
    print("publier un nouveau message: " + corps)
    u = Utilisateur.query.filter_by(jeton=jeton).first_or_404()
    publication = Publication(corps=corps, auteur=u)
    db.session.add(publication)
    db.session.commit()

    id = publication.utilisateur_id
    socketio.emit('nouvelle_publication', {
        'id': id,
        'corps': publication.corps
    },
                  namespace='/chat')

    return jsonify(publication.to_dict())
def ledClick_ack(data=None):

    # if the callback is called with no data then just pass
    if data is None:
        return

    parsed = json.loads(data)
    oControllerLed = ControllerLed.query.filter_by(id=parsed['id']).first()
    if oControllerLed is not None:
        # Update database
        oControllerLed.state_current = parsed['state']
        db.session.commit()
        # Update client-user's button state
        aux = {
            'id' : parsed['id'],
            'state' : parsed['state'],
            'state_colorshift' : oControllerLed.state_colorshift,
            'class' : 'controller-onoff'
        }
        socketio.emit('updateState', data=aux, namespace='/client-user')
Example #50
0
def test_connect():
    app.data.console_queue.put("connected")
    app.data.console_queue.put(request.sid)
    if app.uithread == None:
        app.uithread = socketio.start_background_task(
            app.UIProcessor.start, current_app._get_current_object()
        )
        app.uithread.start()

    if not app.data.connectionStatus:
        app.data.console_queue.put("Attempting to re-establish connection to controller")
        app.data.serialPort.openConnection()

    socketio.emit("my response", {"data": "Connected", "count": 0})
    address = app.data.hostAddress
    data = json.dumps({"hostAddress": address})
    print(data)
    socketio.emit("message", {"command": "hostAddress", "data": data, "dataFormat":"json"}, namespace="/MaslowCNC",)
    if app.data.pyInstallUpdateAvailable:
        app.data.ui_queue1.put("Action", "pyinstallUpdate", "on")
Example #51
0
    def logout(self, name=-1):
        resp = {
            'status': 1,
            'msg': ''
        }
        if request.method == 'POST':
            if name and name != -1:
                line_id = name
            else:
                line_id = get_line_id_by_current_user(self.datamodel.session)
            socketio.emit('message', {
                'action': 'logout',
                'p': ''
            },
                          namespace='/canary',
                          room=name)
            resp = {
                'status': 0,
                'msg': 'logout success'
            }

            _datamodel = SQLAInterface(ProjectFiles, self.datamodel.session)
            filters = _datamodel.get_filters()
            filters.add_filter('name', FilterEqual, name)
            count, item = _datamodel.query(filters=filters)
            for i in item:
                #g['is_logout'][name] = -2
                i.status = -2
                _datamodel.add(i)

                global g
                g['status'][i.me_id][name]['status'] = -1

            #return redirect(self.route_base)

        widgets = self._list()
        return self.render_template('line_function.html',
                                    title=self.list_title,
                                    widgets=widgets,
                                    is_logout=True,
                                    resp=resp)
    def play_round(self):
        # increase round counter - round is 1 indexed, 1 == rd1
        self.round += 1

        # set who's turn it is to index 1 (dealer is index 0, so it's left of the dealer)
        self.turn = self.round
        self.trick_counter = 0
        db.session.commit()

        # let everyone know the round started
        socketio.emit('server_message',
                      {'message': 'Round' + str(self.round) + "...FIGHT!!!"},
                      namespace=namespace)
        socketio.emit('update_round_and_dealer', {
            'round': self.round,
            'dealer': self.get_dealer_name(self.round)
        },
                      namespace=namespace)

        # shuffle up n deal
        self.deal()
Example #53
0
 def flip(self, no_update=False):
     if (len(self.images) == 2):
         if not isinstance(self, Dice):
             self.show_face_number = 0 if self.show_face_number == 1 else 1
         if not no_update:
             self.game.thread_lock.acquire()
             data = {
                 "movables_info": [{
                     "id":
                     self.id,
                     "show_face_number":
                     self.show_face_number,
                 }]
             }
             with app.test_request_context('/'):
                 socketio.emit('UPDATE',
                               data,
                               broadcast=True,
                               room=self.game.gameid,
                               namespace='/freeplay')
             self.game.thread_lock.release()
Example #54
0
def create_new_categ():
    if not current_user or not current_user.is_authenticated or current_user.role_id != 2:
        return json.dumps({"success": False})

    new_categ = request.get_json(True)

    categ = Categ(name=new_categ['name'],
                  color=new_categ['color'],
                  text_color=new_categ['textColor'],
                  params=new_categ['params'])
    try:
        db.session.add(categ)
        db.session.commit()
    except sqlalchemy.exc.IntegrityError:
        db.session.rollback()
        return json.dumps({
            "success": False,
            "message": 'Category already exists'
        })
    socketio.emit('reload')
    return json.dumps({"success": True})
Example #55
0
def sendMessageViaSocketIO(senderID, receiverID, message):
    sender = User.objects.get(id=senderID)

    messageDocument = Message(sender_id=sender,
                              receiver_id=receiverID,
                              message=message,
                              create_time=datetime.datetime.utcnow())
    messageDocument.save()

    data = {
        "sender_id": {
            "$oid": senderID,
            "name": sender.name
        },
        "message": message,
        "messageID": str(messageDocument.id),
        "isRead": messageDocument.isRead
    }
    if receiverID != senderID:
        socketio.emit(senderID + 'To' + receiverID, data, broadcast=True)
        socketio.emit('messageTo' + receiverID, data, broadcast=True)
Example #56
0
def handle_worker_action(msg, methods=['GET', 'POST']):
    print('received worker action: ' + str(msg))
    try:
        worker_to_remove = msg['remove_']
        print("removing worker %s ..." % worker_to_remove)
        resp = json.dumps(
            {'response': job_manager.delete_worker(worker_to_remove)})
        socketio.emit('deletion_respone', resp)
    except KeyError:
        pass
    try:
        worker_to_add = int(msg['add_'])
        print("adding %d workers ..." % worker_to_add)
        spawn_success = [
            job_manager.spawn_worker() for i in range(worker_to_add)
        ]
        resp = json.dumps(
            {'response': (sum(spawn_success) == len(spawn_success))})
        socketio.emit('creation_respone', resp)
    except KeyError:
        pass
Example #57
0
def getSlotDropdownList(data):
    global db

    #save the new slot info that came in
    if data:
        savenewslot(data)
    
    a = db.get_toml_data('Buildin')
    
    stg = ''
    for item in a:
        stg += "<li><a class='dropdown-item' href='#' onClick='dropClicked(this)' data-value='" + item + "'>" + item + "</a></li>"

    stg += "<li><div class='dropdown-divider'></div></li>"

    a = db.get_toml_data('Custom')
  
    for item in a:
        stg += "<li><a class='dropdown-item' href='#' onClick='dropClicked(this)' data-value='" + item + "'>" + item + "</a></li>"

    socketio.emit('slotsDropDownList', {"html":stg}, namespace='/generator')
Example #58
0
def index():
    formulaire = FormulairePublication()
    if formulaire.validate_on_submit():
        publication = Publication(corps = formulaire.publication.data, auteur= current_user)
        db.session.add(publication)
        db.session.commit()
        id = publication.id
        socketio.emit('nouvelle_publication', {'id':id}, namespace='/chat')
        flash('Votre publication est en ligne')
        return redirect(url_for('index'))   
             
    utilisateur =current_user
    page = request.args.get('page',1,type=int)
    publication = current_user.Liste_publications_dont_je_suis_partisans().paginate(page,app.config['PUBLICATIONS_PAR_PAGE'],False)
    #utilisateur = Utilisateur.query.all()
    suivant = url_for('index',page= publication.next_num) \
        if publication.has_next else None
    precedent = url_for('index',page = publication.prev_num) \
        if publication.has_prev else None

    return render_template('index.html', titre='Accueil',suivant=suivant,precedent=precedent, utilisateur=utilisateur,publication=publication.items,formulaire=formulaire) 
Example #59
0
def background_thread(registrationToken, windowToken):

    while mongoClient["tmpPatientToken"].count_documents({
            'id': registrationToken,
            'synced': False
    }) == 1:
        socketio.sleep(1)

    #If a token has been marked as synced, redirect to index. If not, the user has pressed cancel
    if mongoClient["tmpPatientToken"].count_documents({
            'id': registrationToken,
            'synced': True
    }) == 1:
        cursorRegistrationToken = mongoClient["tmpPatientToken"].find_one(
            {'id': registrationToken})
        insertPatient(windowToken, cursorRegistrationToken["name"], cursorRegistrationToken["surname1"], \
            cursorRegistrationToken["surname2"], cursorRegistrationToken["age"], cursorRegistrationToken["gender"], \
            cursorRegistrationToken["groups"], True)
        mongoClient["tmpPatientToken"].delete_one({'id': registrationToken})

        socketio.emit('redirect', namespace='/registerPatient')
Example #60
0
 def parse(self, response):
     print("parsing")
     page = Page()
     page['url'] = response.url
     page['content'] = response.xpath('//div[@id="mw-content-text"]')
     page['content'] = page['content'].xpath(
         '//div[@class="mw-parser-output"]//p//text()').extract()
     #filter content
     text_to_send = filter_text_from_content(page, query)
     #print(text_to_send)
     try:
         print("socket")
         socketio.emit("content", {
             'data': text_to_send,
             "_id": content_id
         },
                       broadcast=True)
         print("socket emit")
     except Exception as e:
         traceback.print_exc()
         print("Exception", e)