Ejemplo n.º 1
0
def add_action(request):
    '''
    新增操作模板
    '''    
    if request.POST:
        action_type = request.POST.get('action_type', None)  # 类型。如,apache,lse
        name = request.POST.get('name', None)  # 名称。如,LSE4部署。
        run_os = request.POST.get('run_os', None)  # 操作模板正常执行所需的操作系统
        action_cmd = request.POST.get('action_cmd', None)  # 操作
        if action_cmd == None or action_cmd == '':
            if request.FILES:
                f = request.FILES['file']           
                sh = f.read()       
                try:
                    action_cmd = sh.decode('utf-8-sig')
                except:           
                    action_cmd = sh.decode('gb2312')
                f.close()
        
        action = Action.objects.filter(action_type__iexact=action_type, name__iexact=name)
        if action:
            return HttpResponse(simplejson.dumps({"statusCode": 302,
                                                  "navTabId": request.POST.get('navTabId', 'actionindex'),
                                                  "callbackType": request.POST.get('callbackType', None),
                                                  "message": u'此操作模板已存在,不能添加',
                                                  "info": u'此操作模板已存在,不能添加',
                                                  "result": u'此操作模板已存在,不能添加'}),
                                mimetype='application/json')
        action = Action(action_type=action_type, name=name,
                        run_os=run_os, action_cmd=action_cmd)
        action.save()
        Log(username=request.user.username,
            content=u"操作模板添加成功,服务名称是:" + name).save()          
        return render_to_response('action/uploadsuccess.html', {'name': action.name})
    return render_to_response('action/add_action.html', context_instance=RequestContext(request))
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
    def is_subscription_over(user):
        over = False

        try:
            subscription = Subscription.objects.get(user=user)
            if subscription.days_left == 0:
                over = True

                try:
                    action = Action.objects.get(_for=user.email, what="subscription_almost_over")
                    action.delete()
                except Action.DoesNotExist:
                    pass

            if over:
                try:
                    action = Action.objects.get(_for=user.email, what="subscription_over")
                except Action.DoesNotExist:
                    action = Action(_for=user.email, what="subscription_over", created_by=user)
                    action.save()
            else:
                try:
                    action = Action.objects.get(_for=user.email, what="subscription_over")
                    action.delete()
                except Action.DoesNotExist:
                    pass

        except Subscription.DoesNotExist:
            pass
Ejemplo n.º 5
0
    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
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
0
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
Ejemplo n.º 8
0
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)
Ejemplo n.º 9
0
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)
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
def edit_action_out(
    request: HttpRequest,
    workflow: Workflow,
    action: Action,
) -> HttpResponse:
    """Edit action out.

    :param request: Request object
    :param workflow: The workflow with the action
    :param action: Action
    :return: HTML response
    """
    # Create the form
    form = EditActionOutForm(request.POST or None, instance=action)

    form_filter = FilterForm(
        request.POST or None,
        instance=action.get_filter(),
        action=action
    )

    # Processing the request after receiving the text from the editor
    if request.method == 'POST' and form.is_valid() and form_filter.is_valid():
        # Get content
        text_content = form.cleaned_data.get('text_content')

        # Render the content as a template and catch potential problems.
        if text_renders_correctly(text_content, action, form):
            # Log the event
            Log.objects.register(
                request.user,
                Log.ACTION_UPDATE,
                action.workflow,
                {'id': action.id,
                 'name': action.name,
                 'workflow_id': workflow.id,
                 'workflow_name': workflow.name,
                 'content': text_content})

            # Text is good. Update the content of the action
            action.set_text_content(text_content)

            if action.action_type == Action.personalized_json:
                # Update the target_url field
                action.target_url = form.cleaned_data['target_url']

            action.save()

            if request.POST['Submit'] == 'Submit':
                return redirect(request.get_full_path())

            return redirect('action:index')

    # This is a GET request or a faulty POST request

    # Get the filter or None
    filter_condition = action.get_filter()

    # Context to render the form
    context = {
        'filter_condition': filter_condition,
        'action': action,
        'load_summernote': action.action_type == Action.personalized_text,
        'conditions': action.conditions.filter(is_filter=False),
        'other_conditions': Condition.objects.filter(
            action__workflow=workflow, is_filter=False,
        ).exclude(action=action),
        'query_builder_ops': workflow.get_query_builder_ops_as_str(),
        'attribute_names': [
            attr for attr in list(workflow.attributes.keys())
        ],
        'columns': workflow.columns.all(),
        'stat_columns': workflow.columns.filter(is_key=False),
        'selected_rows':
            filter_condition.n_rows_selected
            if filter_condition else -1,
        'has_data': action.workflow.has_table(),
        'all_false_conditions': any(
            cond.n_rows_selected == 0
            for cond in action.conditions.all()),
        'rows_all_false': action.get_row_all_false_count(),
        'total_rows': workflow.nrows,
        'form': form,
        'form_filter': form_filter,
        'vis_scripts': PlotlyHandler.get_engine_scripts(),
    }

    # Return the same form in the same page
    return render(request, 'action/edit_out.html', context=context)
Ejemplo n.º 12
0
    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
Ejemplo n.º 13
0
def serve_survey_row(
    request: HttpRequest,
    action: Action,
    user_attribute_name: str,
) -> HttpResponse:
    """Serve a request for action in.

    Function that given a request, and an action IN, it performs the lookup
     and data input of values.

    :param request: HTTP request

    :param action:  Action In

    :param user_attribute_name: The column name used to check for email

    :return:
    """
    # Get the attribute value depending if the user is managing the workflow
    # User is instructor, and either owns the workflow or is allowed to access
    # it as shared
    manager = has_access(request.user, action.workflow)
    user_attribute_value = None
    if manager:
        user_attribute_value = request.GET.get('uatv')
    if not user_attribute_value:
        user_attribute_value = request.user.email

    # Get the dictionary containing column names, attributes and condition
    # valuations:
    context = get_action_evaluation_context(
        action,
        get_row_values(
            action,
            (user_attribute_name, user_attribute_value),
        ),
    )

    if not context:
        # If the data has not been found, flag
        if not manager:
            return ontask_handler404(request, None)

        messages.error(
            request,
            _('Data not found in the table'))
        return redirect(reverse('action:run', kwargs={'pk': action.id}))

    # Get the active columns attached to the action
    colcon_items = extract_survey_questions(action, request.user)

    # Bind the form with the existing data
    form = EnterActionIn(
        request.POST or None,
        tuples=colcon_items,
        context=context,
        values=[context[colcon.column.name] for colcon in colcon_items],
        show_key=manager)

    keep_processing = (
        request.method == 'POST'
        and form.is_valid()
        and not request.POST.get('lti_version'))
    if keep_processing:
        # Update the content in the DB
        row_keys, row_values  = survey_update_row_values(
            action,
            colcon_items,
            manager,
            form.cleaned_data,
            'email',
            request.user.email,
            context)

        # Log the event and update its content in the action
        log_item = Log.objects.register(
            request.user,
            Log.SURVEY_INPUT,
            action.workflow,
            {'id': action.workflow.id,
             'name': action.workflow.name,
             'action': action.name,
             'action_id': action.id,
             'new_values': json.dumps(dict(zip(row_keys, row_values)))})

        # Modify the time of execution for the action
        action.last_executed_log = log_item
        action.save()

        # If not instructor, just thank the user!
        if not manager:
            return render(request, 'thanks.html', {})

        # Back to running the action
        return redirect(reverse('action:run', kwargs={'pk': action.id}))

    return render(
        request,
        'action/run_survey_row.html',
        {
            'form': form,
            'action': action,
            'cancel_url': reverse(
                'action:run', kwargs={'pk': action.id},
            ) if manager else None,
        },
    )
Ejemplo n.º 14
0
def invite_users(request, company):
    """ create a new Action entry """
    try:
        c = Company.objects.get(url_name=company)
    except Company.DoesNotExist:
        return JsonError(_("Company not found"))

    # permissions
    if not has_permission(request.user, c, 'user', 'edit'):
        return JsonError(_("You have no permissions to invite users"))

    # POST data:
    # emails is a list of dictionaries:
    # {'email': '*****@*****.**', 'permission': 'cashier'}
    try:
        data = JsonParse(request.POST.get('data'))
        if not data:
            raise KeyError
    except (ValueError, AttributeError, TypeError, KeyError):
        return JsonError(_("No data in request"))

    # check POSTed emails and permissions:
    errors = []
    valid_data = []

    for d in data:
        email = str(d.get('email'))
        if not email:
            continue

        # validate permission
        permission = str(d.get('permission'))
        if permission not in g.PERMISSION_TYPES:
            # this shouldn't happen, don't even translate
            errors.append("This permission type is not valid: " + email + ": " + permission)

        # validate this email
        try:
            validate_email(email)
            valid_data.append(d)
        except ValidationError:
            errors.append(email)

        # check if this user is already a member of this company
        if Permission.objects.filter(company=c, user__email=email).exists():
            errors.append(_("User with this email is already member of the group: ") + email)

    # do nothing if there are errors
    if len(errors) > 0:
        return JsonError(errors)

    # insert all emails as Actions
    for d in valid_data:
        email = d.get('email')
        permission = d.get('permission')

        # delete any waiting actions from the same company and for the same user;
        Action.objects.filter(company=c, receiver=email, type=g.ACTION_INVITATION, status=g.ACTION_WAITING).delete()

        # create new Action entries
        action_data = {"user_email": request.user.email,
                       "user_first_last_name": str(request.user),
                       "permission": permission}

        action = Action(
            created_by=request.user,
            company=c,
            sender=request.user.email,
            receiver=email,
            type=g.ACTION_INVITATION,
            status=g.ACTION_WAITING,
            data=json.dumps(action_data)
        )
        action.save()

        # send a different invite to non-registered users and registered users
        if BlocklogicUser.objects.filter(email=email).exists():
            template_html = 'email/invitation_for_registered_users.html'
            template_text = 'email/invitation_for_registered_users.txt'
        else:
            template_html = 'email/invitation_for_non_registered_users.html'
            template_text = 'email/invitation_for_non_registered_users.txt'

        # send email
        mail_context = {
            'company_name': c.name,
            'register_url': settings.SITE_URL + reverse('web:sign_up'),
            'login_url': settings.SITE_URL + reverse('web:select_company'),
        }

        message_html = render_to_string(template_html, mail_context)
        message_text = render_to_string(template_text, mail_context)

        if settings.DEBUG:
            print "============="
            print message_text
            print "============="
            print message_html
            print "============="
        else:
            send_email(settings.EMAIL_FROM, [email], None,
                       settings.EMAIL_SUBJECT_PREFIX + " " + _("Invitation to join company on") + " " + settings.SITE_URL,
                       message_text, message_html)

    return JsonOk()