def update_hints(request): jwt_token = request.data.get('token') places = [ ('banco', 'Banco'), ('bar', 'Bar'), ('penhores', 'Casa de penhores'), ('charutaria', 'Charutaria'), ('chaveiro', 'Chaveiro'), ('docas', 'Docas'), ('carruagens', 'Estação de carruagens'), ('farmacia', 'Farmácia'), ('hotel', 'Hotel'), ('livraria', 'Livraria'), ('museu', 'Museu'), ('parque', 'Parque'), ('syard', 'Scotland Yard'), ('teatro', 'Teatro'), ] try: jogador = make_jogador(jwt_token) except: return Response({'error': 'Usuário não identificado'}, status=HTTP_403_FORBIDDEN) try: sala = Sala.objects.get(id=jogador.sala_id) except Sala.DoesNotExist: return Response({'error': 'Usuário não está em uma sala'}, status=HTTP_403_FORBIDDEN) for place_code, place_name in places: hint_place = 'pista_{}'.format(place_code) try: status = request.data[hint_place] except: continue print(status) if (str(status).lower() == 'true'): setattr(jogador, hint_place, True) action = Action() action.text = '{} desbloqueou a pista do(a) {}.'.format( jogador.name, place_name) action.room = sala action.save() else: setattr(jogador, hint_place, False) action = Action() action.text = '{} bloqueou a pista do(a) {}.'.format( jogador.name, place_name) action.room = sala action.save() jogador.save() serializer = JogadorSerializer(jogador) return Response(data=serializer.data, status=HTTP_200_OK)
def criar_sala(request): jwt_token = request.data.get('token') case_id = request.data.get('case_id') try: jogador = make_jogador(jwt_token) except: return Response({'error': 'Usuário não identificado'}, status=HTTP_403_FORBIDDEN) try: if (not case_id): return Response({'error': 'Erro ao encontrar o caso'}, status=HTTP_400_BAD_REQUEST) caso = Caso.objects.get(id=case_id) except Caso.DoesNotExist: return Response({'error': 'Erro ao encontrar o caso'}, status=HTTP_400_BAD_REQUEST) sala = Sala() jogador.sala_id = sala.id jogador.save() sala.caso_id = caso.id update(sala) sala.save() action = Action() action.text = '{} entrou na sala.'.format(jogador.name) action.room = sala action.save() serializer = SalaSerializer(sala) return Response(data=serializer.data, status=HTTP_200_OK)
def do_clone_action( action: Action, new_workflow: Workflow = None, new_name: str = None, ): """Clone an action. Function that given an action clones it and changes workflow and name :param action: Object to clone :param new_workflow: New workflow object to point :param new_name: New name :return: Cloned object """ if new_name is None: new_name = action.name if new_workflow is None: new_workflow = action.workflow new_action = Action( name=new_name, description_text=action.description_text, workflow=new_workflow, last_executed_log=None, action_type=action.action_type, serve_enabled=action.serve_enabled, active_from=action.active_from, active_to=action.active_to, rows_all_false=copy.deepcopy(action.rows_all_false), text_content=action.text_content, target_url=action.target_url, shuffle=action.shuffle, ) new_action.save() try: # Clone the column/condition pairs field. for acc_tuple in action.column_condition_pair.all(): cname = acc_tuple.condition.name if acc_tuple.condition else None ActionColumnConditionTuple.objects.get_or_create( action=new_action, column=new_action.workflow.columns.get( name=acc_tuple.column.name), condition=new_action.conditions.filter(name=cname).first(), ) # Clone the conditions for condition in action.conditions.all(): do_clone_condition(condition, new_action) # Update new_action.save() except Exception as exc: new_action.delete() raise exc return new_action
def create(self, validated_data, **kwargs): """Create the action. :param validated_data: Validated data :param kwargs: Extra material :return: Create the action in the DB """ action_obj = None try: action_type = validated_data.get('action_type') if not action_type: if validated_data['is_out']: action_type = Action.personalized_text else: action_type = Action.survey action_obj = Action( workflow=self.context['workflow'], name=validated_data['name'], description_text=validated_data['description_text'], action_type=action_type, serve_enabled=validated_data['serve_enabled'], active_from=validated_data['active_from'], active_to=validated_data['active_to'], text_content=validated_data.get( 'content', validated_data.get('text_content'), # Legacy ), target_url=validated_data.get('target_url', ''), shuffle=validated_data.get('shuffle', False), ) action_obj.save() # Load the conditions pointing to the action condition_data = ConditionSerializer( data=validated_data.get('conditions', []), many=True, context={'action': action_obj}) if condition_data.is_valid(): condition_data.save() else: raise Exception(_('Invalid condition data')) # Process the fields columns (legacy) and column_condition_pairs self.create_column_condition_pairs( validated_data, action_obj, self.context['workflow'].columns.all(), ) except Exception: if action_obj and action_obj.id: ActionColumnConditionTuple.objects.filter( action=action_obj, ).delete() action_obj.delete() raise return action_obj
def create_action(user,verb,target=None): # 检查最后一分钟内的相同动作 now = timezone.now() last_minute = now - datetime.timedelta(seconds=60) # gte 大于等于 lte 小于等于 similar_actions = Action.objects.filter(user_id=user.id,verb=verb,created__gte=last_minute) if target: target_ct = ContentType.objects.get_for_model(target) similar_actions = similar_actions.filter(target_ct=target_ct,target_id=target.id) if not similar_actions: action = Action(user=user,verb=verb,target=target) action.save() return True return False
def send_solution(request): jwt_token = request.data.get('token') solution = request.data.get('solution') try: jogador = make_jogador(jwt_token) except: return Response({'error': 'Usuário não identificado'}, status=HTTP_403_FORBIDDEN) try: sala = Sala.objects.get(id=jogador.sala_id) except Sala.DoesNotExist: return Response({'error': 'Usuário não está em uma sala'}, status=HTTP_403_FORBIDDEN) jogador.sala_id = '' jogador.pista_banco = False jogador.pista_bar = False jogador.pista_penhores = False jogador.pista_charutaria = False jogador.pista_chaveiro = False jogador.pista_docas = False jogador.pista_carruagens = False jogador.pista_farmacia = False jogador.pista_hotel = False jogador.pista_livraria = False jogador.pista_museu = False jogador.pista_parque = False jogador.pista_syard = False jogador.pista_teatro = False jogador.save() update(sala) action = Action() action.text = '{} enviou uma solução para o caso:\n{}'.format( jogador.name, solution) action.room = sala action.save() caso = Caso.objects.get(id=sala.caso_id) if (sala.jogadores == 0): sala.delete() return Response({'solution': caso.solucao}, status=HTTP_200_OK)
def entrar_sala(request): jwt_token = request.data.get('token') sala_id = request.data.get('id') try: jogador = make_jogador(jwt_token) except: return Response({'error': 'Usuário não identificado'}, status=HTTP_403_FORBIDDEN) try: sala = Sala.objects.get(id=sala_id) except Sala.DoesNotExist: return Response({'error': 'A sala não foi encontrada'}, status=HTTP_400_BAD_REQUEST) jogador.sala_id = sala.id jogador.save() update(sala) action = Action() action.text = '{} entrou na sala.'.format(jogador.name) action.room = sala action.save() serializer = SalaSerializer(sala) return Response(data=serializer.data, status=HTTP_200_OK)
def sair_sala(request): jwt_token = request.data.get('token') try: jogador = make_jogador(jwt_token) except: return Response({'error': 'Usuário não identificado'}, status=HTTP_403_FORBIDDEN) try: sala = Sala.objects.get(id=jogador.sala_id) except Sala.DoesNotExist: return Response({'error': 'Usuário não está em uma sala'}, status=HTTP_403_FORBIDDEN) jogador.sala_id = '' jogador.pista_banco = False jogador.pista_bar = False jogador.pista_penhores = False jogador.pista_charutaria = False jogador.pista_chaveiro = False jogador.pista_docas = False jogador.pista_carruagens = False jogador.pista_farmacia = False jogador.pista_hotel = False jogador.pista_livraria = False jogador.pista_museu = False jogador.pista_parque = False jogador.pista_syard = False jogador.pista_teatro = False jogador.save() update(sala) action = Action() action.text = '{} saiu da sala.'.format(jogador.name) action.room = sala action.save() serializer = SalaSerializer(sala) if (sala.jogadores == 0): sala.delete() return Response(data=serializer.data, status=HTTP_200_OK)
def create(self, validated_data, **kwargs): # Process first the used_columns field to get a sense of how many # columns, their type how many of them new, etc. etc. new_columns = [] for citem in validated_data['used_columns']: cname = citem.get('name', None) if not cname: raise Exception('Incorrect column name {0}.'.format(cname)) col = Column.objects.filter(workflow=self.context['workflow'], name=cname).first() if not col: # new column if citem['is_key']: raise Exception('New action cannot have non-existing key ' 'column {0}'.format(cname)) # Accummulate the new columns just in case we have to undo # the changes new_columns.append(citem) continue # existing column if col.data_type != citem.get('data_type', None) or \ col.is_key != citem['is_key'] or \ set(col.categories) != set(citem['categories']): # The two columns are different raise Exception( 'Imported column {0} is different from existing ' 'one.'.format(cname)) new_column_names = [x['name'] for x in new_columns] action_obj = None try: # used_columns has been verified. action_obj = Action( workflow=self.context['workflow'], name=validated_data['name'], description_text=validated_data['description_text'], is_out=validated_data['is_out'], serve_enabled=validated_data['serve_enabled'], active_from=validated_data['active_from'], active_to=validated_data['active_to'], content=validated_data.get('content', '')) action_obj.save() if new_columns: # There are some new columns that need to be created column_data = ColumnSerializer(data=new_columns, many=True, context=self.context) # And save its content if column_data.is_valid(): column_data.save() workflow = self.context['workflow'] df = pandas_db.load_from_db(self.context['workflow'].id) if df is None: # If there is no data frame, there is no point on # adding columns. Column.objects.filter( workflow=self.context['workflow'], name__in=new_column_names).delete() action_obj.delete() raise Exception('Action cannot be imported with and ' 'empty data table') for col in Column.objects.filter( workflow=workflow, name__in=new_column_names): # Add the column with the initial value df = ops.data_frame_add_column(df, col, None) # Update the column position col.position = len(df.columns) col.save() # Store the df to DB ops.store_dataframe_in_db(df, workflow.id) else: raise Exception('Unable to create column data') # Load the conditions pointing to the action condition_data = ConditionSerializer( data=validated_data.get('conditions', []), many=True, context={'action': action_obj}) if condition_data.is_valid(): condition_data.save() else: raise Exception('Unable to create condition information') # Update the condition variables for each formula if not present for condition in action_obj.conditions.all(): if condition.columns.all().count() == 0: col_names = get_variables(condition.formula) # Add the corresponding columns to the condition condition.columns.set( self.context['workflow'].columns.filter( name__in=col_names)) # Load the columns field columns = ColumnNameSerializer(data=validated_data['columns'], many=True, required=False, context=self.context) if columns.is_valid(): for citem in columns.data: column = action_obj.workflow.columns.get( name=citem['name']) action_obj.columns.add(column) columns.save() else: raise Exception('Unable to create columns field') except Exception: if action_obj and action_obj.id: action_obj.delete() Column.objects.filter(workflow=self.context['workflow'], name__in=new_column_names).delete() raise return action_obj