Python django.db.models 模块,ObjectDoesNotExist() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.ObjectDoesNotExist()

项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def cancel_rq_scheduler_jobs(ticket_id=None, status='answered'):
    """
        Cancel all rq scheduler jobs for given `abuse.models.Ticket`

        :param int ticket_id: The id of the `abuse.models.Ticket`
        :param str status: The `abuse.models.Ticket.TICKET_STATUS' reason of the cancel
    """
    try:
        ticket = Ticket.objects.get(id=ticket_id)
    except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
        Logger.error(unicode('Ticket %d cannot be found in DB. Skipping...' % (ticket)))
        return

    for job in ticket.jobs.all():
        if job.asynchronousJobId in utils.scheduler:
            utils.scheduler.cancel(job.asynchronousJobId)
            job.status = 'cancelled by %s' % status
            job.save()

    for job in utils.scheduler.get_jobs():
        if job.func_name in ASYNC_JOB_TO_CANCEL and job.kwargs['ticket_id'] == ticket.id:
            utils.scheduler.cancel(job.id)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def get_action_for_timeout(ticket):
        """
            Returns action to apply when ticket timeout

            :param `abuse.models.Ticket` ticket: A Cerberus Ticket instance
            :rtype: `abuse.models.ServiceAction`
            :return: The `abuse.models.ServiceAction` to apply
        """
        if not isinstance(ticket, Ticket):
            try:
                ticket = Ticket.objects.get(id=ticket)
            except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
                raise ActionServiceException(
                    'Ticket %s cannot be found in DB. Skipping...' % (str(ticket))
                )

        action = None
        if ServiceAction.objects.count():
            action = ServiceAction.objects.all()[:1][0]

        return action
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def list_actions_for_ticket(ticket):
        """
            List all available `abuse.models.ServiceAction` for a Cerberus ticket

            :param `abuse.models.Ticket` ticket: A Cerberus `abuse.models.Ticket` instance
            :rtype list:
            :return: The list of possible `abuse.models.ServiceAction` for given ticket
        """
        if not isinstance(ticket, Ticket):
            try:
                ticket = Ticket.objects.get(id=ticket)
            except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
                raise ActionServiceException(
                    'Ticket %s cannot be found in DB. Skipping...' % (str(ticket))
                )

        actions = ServiceAction.objects.all()
        return actions
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update_order(user, body):
    """
        Update groupId/orderId for preset display
    """
    group_id = 0
    try:
        for group in body:
            order_id = 0
            for preset_dict in group['presets']:
                preset = TicketWorkflowPreset.objects.get(id=preset_dict['id'])
                preset.orderId = order_id
                preset.groupId = group_id
                preset.save()
                order_id += 1
            group_id += 1
    except (AttributeError, KeyError, ObjectDoesNotExist, ValueError):
        raise BadRequest('Bad Request')
    return index(user)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def get_ticket_attachments(ticket_id):
    """
        Get ticket attachments..
    """
    try:
        ticket = Ticket.objects.get(id=ticket_id)
    except (IndexError, ObjectDoesNotExist, ValueError):
        raise NotFound('Ticket not found')

    ticket_reports_id = ticket.reportTicket.all().values_list(
        'id',
        flat=True
    ).distinct()

    attachments = AttachedDocument.objects.filter(report__id__in=ticket_reports_id).distinct()
    attachments = list(attachments)
    attachments.extend(ticket.attachments.all())
    attachments = list(set(attachments))
    attachments = [model_to_dict(attach) for attach in attachments]
    return attachments
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def get_providers(ticket_id):
    """ Get ticket's providers
    """
    try:
        ticket = Ticket.objects.get(id=ticket_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Ticket not found')

    emails = ticket.reportTicket.all().values_list('provider__pk', flat=True).distinct()
    providers = [ProvidersController.show(email) for email in emails]

    for prov in providers:
        prov['contacted'] = ContactedProvider.objects.filter(
            ticket=ticket,
            provider__email=prov['email']
        ).exists()

    return providers
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update_proof(ticket_id, proof_id, body, user):
    """ Update proof
    """
    ticket = None
    try:
        ticket = Ticket.objects.get(id=ticket_id)
        Proof.objects.get(id=proof_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Not Found')

    try:
        body.pop('id', None)
        body.pop('ticket', None)
        ticket.proof.update(**body)
        ticket.save()
        database.log_action_on_ticket(
            ticket=ticket,
            action='update_proof',
            user=user
        )
    except (KeyError, FieldDoesNotExist, FieldError, IntegrityError, TypeError, ValueError) as ex:
        raise BadRequest(str(ex.message))
    return {'message': 'Proof successfully updated'}
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def add_tag(ticket_id, body, user):
    """ Add ticket tag
    """
    try:
        tag = Tag.objects.get(**body)
        ticket = Ticket.objects.get(id=ticket_id)

        if ticket.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for ticket')

        ticket.tags.add(tag)
        ticket.save()
        database.log_action_on_ticket(
            ticket=ticket,
            action='add_tag',
            user=user,
            tag_name=tag.name
        )
    except MultipleObjectsReturned:
        raise BadRequest('Please use tag id')
    except (KeyError, FieldError, IntegrityError, ObjectDoesNotExist, ValueError):
        raise NotFound('Tag or ticket not found')
    return {'message': 'Tag successfully added'}
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def remove_tag(ticket_id, tag_id, user):
    """ Remove ticket tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
        ticket = Ticket.objects.get(id=ticket_id)

        if ticket.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for ticket')

        ticket.tags.remove(tag)
        ticket.save()
        database.log_action_on_ticket(
            ticket=ticket,
            action='remove_tag',
            user=user,
            tag_name=tag.name
        )

    except (ObjectDoesNotExist, FieldError, IntegrityError, ValueError):
        raise NotFound('Not Found')
    return {'message': 'Tag successfully removed'}
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def get_jobs_status(ticket_id):
    """
        Get actions todo status
    """
    try:
        ticket = Ticket.objects.get(id=ticket_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Ticket not found')

    resp = []
    jobs = ticket.jobs.all().order_by('creationDate')
    for job in jobs:
        info = model_to_dict(job)
        if info.get('action'):
            info['action'] = model_to_dict(ServiceAction.objects.get(id=info['action']))
        resp.append(info)

    return resp
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update(news_id, body, user):
    """ Update news
    """
    try:
        if user.is_superuser:
            news = News.objects.get(id=news_id)
        else:
            news = News.objects.get(id=news_id, author__id=user.id)
    except (ObjectDoesNotExist, ValueError):
        return NotFound('News not found')
    try:
        body = {k: v for k, v in body.iteritems() if k not in ['author', 'date', 'tags']}
        News.objects.filter(pk=news.pk).update(**body)
        news = News.objects.get(pk=news.pk)
    except (KeyError, FieldError, IntegrityError):
        raise BadRequest('Invalid fields in body')
    return model_to_dict(news)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def create(body, user):
    """
        Create a new report item
    """
    try:
        resp = __get_item_infos(body, user)
        item, created = ReportItem.objects.get_or_create(**resp)
        if resp['report'].ticket:
            database.log_action_on_ticket(
                ticket=resp['report'].ticket,
                action='add_item',
                user=user
            )
    except (AttributeError, FieldError, IntegrityError, KeyError, ObjectDoesNotExist) as ex:
        raise BadRequest(str(ex.message))
    if not created:
        raise BadRequest('Report items already exists')
    return show(item.id)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update(item_id, body, user):
    """
        Update a report item
    """
    try:
        item = ReportItem.objects.get(id=item_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Item not found')

    try:
        resp = __get_item_infos(body, user)
        ReportItem.objects.filter(pk=item.pk).update(**resp)
        item = ReportItem.objects.get(pk=item.pk)
        if resp['report'].ticket:
            database.log_action_on_ticket(
                ticket=resp['report'].ticket,
                action='update_item',
                user=user
            )
    except (AttributeError, FieldError, IntegrityError, KeyError, ObjectDoesNotExist):
        raise BadRequest('Invalid fields in body')
    return show(item_id)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def delete_from_report(item_id, rep, user):
    """ Delete an item
    """
    try:
        item = ReportItem.objects.get(id=item_id)
        ReportItem.objects.filter(report=rep, rawItem=item.rawItem).delete()
        report = Report.objects.get(id=rep)
        if report.ticket:
            database.log_action_on_ticket(
                ticket=report.ticket,
                action='delete_item',
                user=user
            )
        return {'message': 'Item successfully removed'}
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Item not found')
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def get_screenshot(item_id, report_id):
    """
        Get screenshot for item
    """
    try:
        item = ReportItem.objects.get(id=item_id, report__id=report_id)
        if item.itemType != 'URL':
            raise BadRequest('Item is not an URL')
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Item not found')

    try:
        screenshots = ImplementationFactory.instance.get_singleton_of(
            'PhishingServiceBase'
        ).get_screenshots(item.rawItem)
        schema.valid_adapter_response('PhishingServiceBase', 'get_screenshots', screenshots)
        results = {
            'rawItem': item.rawItem,
            'screenshots': screenshots,
        }
        return results
    except (PhishingServiceException, schema.InvalidFormatError, schema.SchemaNotFound):
        raise InternalServerError('Error while loading screenshots')
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def unblock_item(item_id, report_id=None, ticket_id=None):
    """
        Unblock given `abuse.models.ReportItem`
    """
    try:
        item = ReportItem.objects.get(id=item_id)
        if report_id:
            report = Report.objects.get(id=report_id)
            if item.report.id != report.id:
                raise BadRequest('Given item not attached to given report')
        if ticket_id:
            ticket = Ticket.objects.get(id=ticket_id)
            if item.report.id not in ticket.reportTicket.all().values_list('id', flat=True):
                raise BadRequest('Given item not attached to given ticket')
    except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
        raise NotFound('Item not found')

    utils.default_queue.enqueue(
        'phishing.unblock_url',
        url=item.rawItem,
    )
    return {'message': 'Unblocking job successfully scheduled'}
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def remove_tag(defendant_id, tag_id, user):
    """ Remove defendant tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
        defendant = Defendant.objects.get(id=defendant_id)

        for defendt in Defendant.objects.filter(customerId=defendant.customerId):
            defendt.tags.remove(tag)
            defendt.save()

            for ticket in defendt.ticketDefendant.all():
                database.log_action_on_ticket(
                    ticket=ticket,
                    action='remove_tag',
                    user=user,
                    tag_name=tag.name
                )

    except (ObjectDoesNotExist, FieldError, IntegrityError, ValueError):
        raise NotFound('Defendant or tag not found')

    return show(defendant_id)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def create(body):
    """ Create provider
    """
    if 'email' not in body:
        raise BadRequest('Email field required')
    if len(Provider.objects.filter(email=body['email'])) > 1:
        raise BadRequest('Provider already exists')

    try:
        cat = None
        if body.get('defaultCategory'):
            cat = Category.objects.get(name=body['defaultCategory'])
        body.pop('defaultCategory', None)
        body = {k: v for k, v in body.iteritems() if k in PROVIDER_FIELDS}
        provider = Provider.objects.create(defaultCategory=cat, **body)
        return model_to_dict(provider)
    except (FieldError, IntegrityError, ObjectDoesNotExist) as ex:
        raise BadRequest(str(ex.message))
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update(prov, body):
    """ Update provider infos
    """
    try:
        provider = Provider.objects.get(email=prov)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Provider does not exist')
    try:
        body = {k: v for k, v in body.iteritems() if k in PROVIDER_FIELDS}
        cat = None
        if body.get('defaultCategory'):
            cat = Category.objects.get(name=body['defaultCategory'])
        body.pop('defaultCategory', None)
        Provider.objects.filter(pk=provider.pk).update(defaultCategory=cat, **body)
        provider = Provider.objects.get(pk=provider.pk)
    except (FieldError, IntegrityError, ObjectDoesNotExist) as ex:
        raise BadRequest(str(ex.message))
    return model_to_dict(provider)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def remove_tag(provider_email, tag_id):
    """ Remove defendant tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
        provider = Provider.objects.get(email=provider_email)

        if provider.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for provider')

        provider.tags.remove(tag)
        provider.save()

    except (ObjectDoesNotExist, FieldError, IntegrityError, ValueError):
        raise NotFound('Provider or tag not found')
    return model_to_dict(provider)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def get_raw(report_id):
    """ Get raw email of report
    """
    report = None
    try:
        report = Report.objects.get(id=report_id)
        if not report.filename:
            return {'raw': report.body}

        raw = None
        try:
            with ImplementationFactory.instance.get_instance_of('StorageServiceBase', settings.GENERAL_CONFIG['email_storage_dir']) as cnx:
                raw = cnx.read(report.filename)
        except StorageServiceException:
            pass

        if not raw:
            raise NotFound('Raw not found')

        return {'raw': raw.decode('utf-8')}
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Report not found')
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def get_attachment(report_id, attachment_id):
    """ Get attachment
    """
    try:
        report = Report.objects.get(id=report_id)
        attachment = report.attachments.get(id=attachment_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Report or attachment not found')

    resp = None
    try:
        with ImplementationFactory.instance.get_instance_of('StorageServiceBase', settings.GENERAL_CONFIG['email_storage_dir']) as cnx:
            raw = cnx.read(attachment.filename)
            resp = {
                'raw': b64encode(raw),
                'filetype': str(attachment.filetype),
                'filename': attachment.name.encode('utf-8'),
            }
    except StorageServiceException:
        pass

    if not resp:
        raise NotFound('Raw attachment not found')

    return resp
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def add_tag(report_id, body):
    """ Add report tag
    """
    try:
        tag = Tag.objects.get(**body)
        report = Report.objects.get(id=report_id)

        if report.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for report')

        report.tags.add(tag)
        report.save()
    except MultipleObjectsReturned:
        raise BadRequest('Please use tag id')
    except (KeyError, FieldError, IntegrityError, ObjectDoesNotExist, ValueError):
        raise NotFound('Report or tag not found')
    return {'message': 'Tag successfully added'}
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def remove_tag(report_id, tag_id):
    """ Remove report tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
        report = Report.objects.get(id=report_id)

        if report.__class__.__name__ != tag.tagType:
            raise BadRequest('Invalid tag for report')

        report.tags.remove(tag)
        report.save()

    except (ObjectDoesNotExist, FieldError, IntegrityError, ValueError):
        raise NotFound('Report or tag not found')
    return {'message': 'Tag successfully removed'}
项目:intel-manager-for-lustre    作者:intel-hpdd    | 项目源码 | 文件源码
def __get__(self, instance, instance_type=None):
        if instance is None:
            return self

        try:
            return getattr(instance, self.cache_attr)
        except AttributeError:
            rel_obj = None

            # Make sure to use ContentType.objects.get_for_id() to ensure that
            # lookups are cached (see ticket #5570). This takes more code than
            # the naive ``getattr(instance, self.ct_field)``, but has better
            # performance when dealing with GFKs in loops and such.
            ct_id = getattr(instance, self.ct_field, None)
            if ct_id:
                ct = self.get_content_type(id=ct_id, using=instance._state.db)
                try:
                    rel_obj = ct.get_object_for_this_type(pk=getattr(instance, self.fk_field))
                except models.ObjectDoesNotExist:
                    pass
            setattr(instance, self.cache_attr, rel_obj)
            return rel_obj
项目:pyconjp-website    作者:pyconjp    | 项目源码 | 文件源码
def label_from_instance(self, obj):
        """
        ????????????????????????
        """
        labels = []
        try:
            labels.append(obj.presentation.pk)
        except ObjectDoesNotExist:
            labels.append('?')

        labels.append(obj.pk)

        try:
            labels.append(obj.result.status)
        except ObjectDoesNotExist:
            labels.append('unknown status')

        try:
            if obj.presentation.slot:
                labels.append(obj.presentation.slot.day.date)
                labels.append(obj.presentation.slot.start)
                for room in obj.presentation.slot.rooms:
                    labels.append(room.name)
        except ObjectDoesNotExist:
            pass
        labels.extend([obj.speaker.name, unicode(obj)])
        return ", ".join(unicode(l) for l in labels)
项目:shuup-wishlist    作者:shuup    | 项目源码 | 文件源码
def test_delete_own_wishlist_product(rf, regular_user):
    shop = get_default_shop()
    person = get_person_contact(regular_user)
    product = get_default_product()

    wishlist = Wishlist.objects.create(shop=shop, customer=person, name='foo', privacy=WishlistPrivacy.PUBLIC)
    wishlist.products.add(product)

    view_func = WishlistProductDeleteView.as_view()
    request = apply_request_middleware(rf.post("/"), customer=person)
    response = view_func(request, pk=wishlist.pk, product_pk=product.pk)

    assert response.status_code == 302
    with pytest.raises(ObjectDoesNotExist):
        Wishlist.objects.get(pk=wishlist.pk).products.get(pk=product.pk)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def _add_mass_contact_tag(ticket, campaign_name):
    """
        Add mass contact tag to report
    """
    try:
        tag, _ = Tag.objects.get_or_create(tagType='Ticket', name=campaign_name)
        ticket.tags.add(tag)
        ticket.save()
    except ObjectDoesNotExist:
        pass
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def delay_jobs(ticket=None, delay=None, back=True):
    """
        Delay pending jobs for given `abuse.models.Ticket`

        :param `abuse.models.Ticket` ticket: The Cerberus ticket
        :param int delay: Postpone duration
        :param bool back: In case of unpause, reschedule jobs with effectively elapsed time
    """
    if not delay:
        raise AssertionError('Missing delay')

    if not isinstance(ticket, Ticket):
        try:
            ticket = Ticket.objects.get(id=ticket)
        except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
            Logger.error(unicode('Ticket %d cannot be found in DB. Skipping...' % (ticket)))
            return

    # a job is here a tuple (Job instance, datetime instance)
    pending_jobs = utils.scheduler.get_jobs(until=timedelta(days=7), with_times=True)
    pending_jobs = {job[0].id: job for job in pending_jobs}

    for job in ticket.jobs.all():
        if pending_jobs.get(job.asynchronousJobId):
            current_date = pending_jobs[job.asynchronousJobId][1]
            new_date = current_date - delay if back else current_date + delay
            utils.scheduler.change_execution_time(
                pending_jobs[job.asynchronousJobId][0],
                new_date
            )
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def close_emails_thread(ticket_id=None):
    """
        Close emails thread for given `abuse.models.Ticket`

        :param int ticket_id: The id of the `abuse.models.Ticket`
    """
    try:
        ticket = Ticket.objects.get(id=ticket_id)
    except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
        raise AssertionError('Ticket %d cannot be found in DB. Skipping...' % (ticket))

    implementations.instance.get_singleton_of(
        'MailerServiceBase'
    ).close_thread(ticket)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def _check_auto_unassignation(ticket):

    history = ticket.ticketHistory.filter(
        actionType='ChangeStatus'
    ).order_by('-date').values_list(
        'ticketStatus',
        flat=True
    )[:3]

    try:
        models_config = ticket.treatedBy.operator.role.modelsAuthorizations
        unassigned_on_multiple_alarm = models_config['ticket']['unassignedOnMultipleAlarm']
        if (unassigned_on_multiple_alarm and len(history) == 3 and
                all([STATUS_SEQUENCE[i] == history[i] for i in xrange(3)])):
            database.log_action_on_ticket(
                ticket=ticket,
                action='change_treatedby',
                previous_value=ticket.treatedBy
            )
            database.log_action_on_ticket(
                ticket=ticket,
                action='update_property',
                property='escalated',
                previous_value=ticket.escalated,
                new_value=True,
            )
            ticket.treatedBy = None
            ticket.escalated = True
            ticket.save()
    except (AttributeError, KeyError, ObjectDoesNotExist, ValueError):
        pass
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def check_if_all_down(report=None, last=5, try_screenshot=True):
    """
        Check if all urls items for a report (phishing for example) are 'down'.

        :param `abuse.models.Report` report: A Cerberus `abuse.models.Report` instance to ping
        :param int last: Look for the n last record in db
        :param bool try_screenshot: Try to take a screenshot for the url
        :return: the result
        :rtype: bool
    """
    if not isinstance(report, Report):
        try:
            report = Report.objects.get(id=report)
        except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
            raise AssertionError('Report %d cannot be found in DB')

    # Check if report has URL items
    items = report.reportItemRelatedReport.all()
    items = list(set([item for item in items if item.itemType == 'URL']))
    if not items:  # No urls items found
        return False

    # Get current items score
    items_score = _get_items_score(report, items, last, try_screenshot)

    if all(v >= DOWN_THRESHOLD for v in items_score.itervalues()):
        Logger.error(unicode('All urls are down for report %d' % (report.id)))
        return True

    Logger.error(unicode('Some url are still up for report %d' % (report.id)))
    return False
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def close_because_all_down(report=None, denied_by=None):
    """
        Get or create a ticket and close it because all report's items are down

        :param `abuse.models.Report` report: A Cerberus `abuse.models.Report` instance
        :param int denied_by: The id of the `abuse.models.User`
            who takes the decision to close the ticket
    """
    if not isinstance(report, Report):
        try:
            report = Report.objects.get(id=report)
        except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
            raise AssertionError('Report %d cannot be found in DB' % (report))

    if not report.ticket:
        report.ticket = common.create_ticket(report, denied_by)
        report.save()

    inject_proof = not bool(report.ticket.proof.count())

    # Send email to provider
    common.send_email(
        report.ticket,
        [report.provider.email],
        settings.CODENAMES['no_more_content'],
        inject_proof=inject_proof
    )

    # Close ticket
    common.close_ticket(
        report.ticket,
        resolution_codename=settings.CODENAMES['no_more_content']
    )

    # Add tag
    report.ticket.tags.add(Tag.objects.get(
        name=settings.TAGS['phishing_autoclosed'],
        tagType='Ticket'
    ))
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def get_emails(self, ticket):
        """
            Get all emails for the given ticket

            :param 'abuse.models.Ticket` ticket: A Cerberus 'abuse.models.Ticket` instance.
            :return: A list of Email object
            :rtype: list
            :raises `adapters.services.mailer.abstract.MailerServiceException`: if any error occur
        """
        if not isinstance(ticket, Ticket):
            try:
                ticket = Ticket.objects.get(id=ticket)
            except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
                raise MailerServiceException(
                    'Ticket %s cannot be found in DB. Skipping...' % (str(ticket))
                )

        self._check_ticket_emails(ticket)

        cursor = self._db_conn.cursor()
        param = (ticket.publicId,)
        emails = []
        try:
            for row in cursor.execute('SELECT sender, recipient, subject, body, category, timestamp FROM emails WHERE publicid=?', param):
                body = self._html_parser.handle(row[3].replace('<br>\n', '\n').replace('\n', '<br>\n'))
                emails.append(Email(
                    sender=row[0],
                    recipient=row[1],
                    subject=row[2],
                    body=re.sub(r'^(\s*\n){2,}', '\n', body, flags=re.MULTILINE),
                    category=row[4],
                    created=row[5],
                    attachments=[],
                ))
        except (KeyError, ValueError) as ex:
            raise MailerServiceException(ex)

        emails = sorted(emails, key=lambda k: k.created)
        return emails
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def identify_ticket_from_meta(provider, recipients, subject):
    """
        Try to identify an answer to a Cerberus ticket with email meta
    """
    tickets_infos = []
    if not all((provider, recipients, subject)):
        return tickets_infos

    # Trying each recipients
    for recipient in recipients:

        ticket = category = None
        search = regexp.RECIPIENT.search(str(recipient).lower())
        if search is not None:
            public_id = str(search.group(1)).lower()
            try:
                ticket = Ticket.objects.get(publicId__iexact=public_id)
                extract = recipient.split('@')[0].split('.')[1].title()
                if extract in EMAIL_VALID_CATEGORIES:
                    category = extract
            except (AttributeError, IndexError, TypeError, ValueError, ObjectDoesNotExist):
                continue
        if all((ticket, category, recipient)):
            tickets_infos.append((ticket, category, recipient))

    return tickets_infos
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def apply_action_on_service(ticket, action, ip_addr=None, user=None):
        """
            Apply given action on service

            :param int ticket: The id of the Cerberus `abuse.models.Ticket`
            :param int action: The id of the Cerberus `abuse.models.ServiceAction`
            :param str ip_addr: The IP address
            :param int user: The id of the Cerberus `User`
            :raises `adapters.services.action.abstract.ActionServiceException`: if any error occur
        """
        if not isinstance(ticket, Ticket):
            try:
                ticket = Ticket.objects.get(id=ticket)
            except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
                raise ActionServiceException(
                    'Ticket %s cannot be found in DB. Skipping...' % (str(ticket))
                )

        if not isinstance(action, ServiceAction):
            try:
                action = ServiceAction.objects.get(id=action)
            except (AttributeError, ObjectDoesNotExist, TypeError, ValueError):
                raise ActionServiceException(
                    'Action %s cannot be found in DB. Skipping...' % (str(action))
                )

        return ActionResult(todo_id='123456', status='ok', comment='ok')
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def show(threshold_id):
    """ Get infos for specified threshold
    """
    try:
        threshold = ReportThreshold.objects.get(id=threshold_id)
        return model_to_dict(threshold)
    except ValueError:
        raise BadRequest('Not a valid threshold id')
    except ObjectDoesNotExist:
        raise NotFound('Threshold not found')
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def create(body):
    """ Create threshold
    """
    try:
        category = Category.objects.get(name=body['category'])
        if ReportThreshold.objects.filter(category=category).exists():
            raise BadRequest('Threshold already exists for this category')
        body['category'] = category
        threshold, created = ReportThreshold.objects.get_or_create(**body)
    except (KeyError, FieldError, IntegrityError, ObjectDoesNotExist):
        raise BadRequest('Missing or invalid fields in body')
    if not created:
        raise BadRequest('Threshold already exists')
    return model_to_dict(threshold)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update(threshold_id, body):
    """ Update threshold
    """
    try:
        threshold = ReportThreshold.objects.get(id=threshold_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Threshold not found')
    try:
        body = {k: v for k, v in body.iteritems() if k in ['threshold', 'interval']}
        ReportThreshold.objects.filter(pk=threshold.pk).update(**body)
        threshold = ReportThreshold.objects.get(pk=threshold.pk)
    except (KeyError, FieldError, IntegrityError):
        raise BadRequest('Missing or invalid fields in body')
    return model_to_dict(threshold)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def destroy(threshold_id):
    """ Remove threshold
    """
    try:
        threshold = ReportThreshold.objects.get(id=threshold_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Threshold not found')

    threshold.delete()
    return {'message': 'Threshold successfully removed'}
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def show(tag_id):
    """ Get tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Tag not found')
    return model_to_dict(tag)
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def destroy(tag_id):
    """ Remove tag
    """
    try:
        tag = Tag.objects.get(id=tag_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Tag not found')
    try:
        tag.delete()
        return {'message': 'Tag successfully removed'}
    except ProtectedError:
        raise Forbidden('Tag still referenced in reports/tickets')
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def get_prefetch_preset(user, ticket_id, preset_id, lang=None):
    """
        Prefetch preset with ticket infos
    """
    action = params = None
    try:
        ticket = Ticket.objects.get(id=ticket_id)
        preset = TicketWorkflowPreset.objects.get(id=preset_id, roles=user.operator.role)
        if preset.config:
            action = model_to_dict(preset.config.action)
            if preset.config.params:
                params = {param.codename: param.value for param in preset.config.params.all()}
        preset = model_to_dict(preset)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Ticket or preset not found')

    preset['templates'] = []
    templates_codename = MailTemplate.objects.filter(
        ticketworkflowpreset=preset['id']
    ).values_list(
        'codename',
        flat=True
    )
    templates_codename = list(set(templates_codename))

    for codename in templates_codename:
        template = MailTemplate.objects.get(codename=codename)
        resp = TemplatesController.get_prefetch_template(ticket.id, template.id, lang=lang)
        preset['templates'].append(resp)

    preset['action'] = action
    if action and params:
        preset['action']['params'] = params

    return preset
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def show(user, preset_id):
    """
        Get given preset
    """
    try:
        preset = TicketWorkflowPreset.objects.get(id=preset_id, roles=user.operator.role)
    except (IndexError, ObjectDoesNotExist, ValueError, TypeError):
        raise NotFound('Preset not found')

    action = params = None
    if preset.config:
        action = model_to_dict(preset.config.action)
        if preset.config.params:
            params = {param.codename: param.value for param in preset.config.params.all()}

    preset = model_to_dict(preset)
    preset['templates'] = MailTemplate.objects.filter(ticketworkflowpreset=preset['id'])
    preset['templates'] = [model_to_dict(m) for m in preset['templates']]
    preset['action'] = action
    if action and params:
        preset['action']['params'] = params

    preset['roles'] = list(TicketWorkflowPreset.objects.get(
        id=preset['id']
    ).roles.all().values_list(
        'codename',
        flat=True
    ).distinct())

    return preset
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update(user, preset_id, body):
    """
        Update preset
    """
    try:
        preset = TicketWorkflowPreset.objects.get(id=preset_id, roles=user.operator.role)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Preset not found')

    if TicketWorkflowPreset.objects.filter(~Q(id=preset_id), name=body['name']).count():
        raise BadRequest('Preset with same name already exists')

    if body.get('action'):
        try:
            preset.config = __get_preset_config(body)
        except (AttributeError, KeyError, ObjectDoesNotExist, TypeError, ValueError):
            raise BadRequest('Invalid or missing params in action')

    if body.get('templates') is not None:
        preset.templates.clear()
        for template_id in body['templates']:
            try:
                template = MailTemplate.objects.get(id=template_id)
                preset.templates.add(template)
            except (AttributeError, KeyError, ObjectDoesNotExist, ValueError):
                raise BadRequest('Invalid template id')

    preset.roles.clear()
    for role_codename in body['roles']:
        try:
            role = Role.objects.get(codename=role_codename)
            preset.roles.add(role)
        except (AttributeError, KeyError, ObjectDoesNotExist, ValueError):
            raise BadRequest('Invalid role codename')

    preset.name = body['name']
    preset.save()
    resp = show(user, preset.id)
    return resp
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def show(ticket_id, user):
    """ Get a ticket
    """
    try:
        ticket = Ticket.objects.get(id=ticket_id)
        just_assigned = False
        if not ticket.treatedBy:
            just_assigned = assign_if_not(ticket, user)
        ticket_dict = Ticket.objects.filter(id=ticket_id).values(*TICKET_FIELDS)[0]
    except (IndexError, ObjectDoesNotExist, ValueError):
        raise NotFound('Ticket not found')

    # Add related infos
    if ticket.treatedBy:
        ticket_dict['treatedBy'] = ticket.treatedBy.username
    if ticket.defendant:
        ticket_dict['defendant'] = DefendantsController.show(ticket.defendant.id)
    if ticket.action:
        ticket_dict['action'] = model_to_dict(ServiceAction.objects.get(id=ticket.action.id))
    if ticket.service:
        ticket_dict['service'] = model_to_dict(Service.objects.get(id=ticket.service.id))
    if ticket.jobs:
        ticket_dict['jobs'] = []
        for job in ticket.jobs.all():
            info = model_to_dict(job)
            ticket_dict['jobs'].append(info)

    ticket_reports_id = ticket.reportTicket.all().values_list('id', flat=True).distinct()

    ticket_dict['starredByMe'] = StarredTicket.objects.filter(
        ticket=ticket,
        user=user
    ).exists()

    ticket_dict['comments'] = _get_ticket_comments(ticket)
    ticket_dict['history'] = _get_ticket_history(ticket)
    ticket_dict['attachedReportsCount'] = ticket.reportTicket.count()
    ticket_dict['tags'] = _get_ticket_tags(ticket, ticket_reports_id)
    ticket_dict['justAssigned'] = just_assigned

    return ticket_dict
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def assign_if_not(ticket, user):
    """
        If ticket is not assigned and user not just set ticket owner to nobody
        assign ticket to current user
    """
    try:
        perm = AbusePermission.objects.get(user=user, category=ticket.category)
        if perm.profile.name == 'Read-only':
            return False
    except ObjectDoesNotExist:
        return False

    assigned = False
    delta = datetime.now() - timedelta(seconds=15)
    just_unassigned = ticket.ticketHistory.filter(
        date__gt=delta,
        action__icontains='to nobody'
    ).order_by('-date')[:1]
    if not ticket.treatedBy and not ticket.protected and not just_unassigned:
        ticket.treatedBy = user
        ticket.save()
        database.log_action_on_ticket(
            ticket=ticket,
            action='change_treatedby',
            user=user,
            new_value=user.username
        )
        assigned = True
    return assigned
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def update_pause_duration(ticket_id, body, user):
    """ Update ticket pause duration
    """
    try:
        ticket = Ticket.objects.get(id=ticket_id)
        if ticket.status != 'Paused':
            raise BadRequest('Ticket is not paused')
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Not Found')

    try:
        data = {'pauseDuration': body['pauseDuration']}
        if int(data['pauseDuration']) > 10000000:
            raise BadRequest('Invalid duration')

        # Delay jobs
        new_duration = int(data['pauseDuration'])
        if new_duration > ticket.pauseDuration:
            delay = new_duration - ticket.pauseDuration
            delay = timedelta(seconds=delay)
            utils.default_queue.enqueue(
                'ticket.delay_jobs',
                ticket=ticket.id,
                delay=delay,
                back=False
            )
        else:
            delay = ticket.pauseDuration - new_duration
            delay = timedelta(seconds=delay)
            utils.default_queue.enqueue(
                'ticket.delay_jobs',
                ticket=ticket.id,
                delay=delay,
                back=True
            )
        return _update_duration(ticket, data, user)
    except (KeyError, ValueError) as ex:
        raise BadRequest(str(ex.message))
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def get_proof(ticket_id):
    """ Get ticket proof
    """
    try:
        ticket = Ticket.objects.get(id=ticket_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Ticket not found')

    return [model_to_dict(p) for p in ticket.proof.all()]
项目:cerberus-core    作者:ovh    | 项目源码 | 文件源码
def add_proof(ticket_id, body, user):
    """ Add proof to ticket
    """
    try:
        ticket = Ticket.objects.get(id=ticket_id)
    except (ObjectDoesNotExist, ValueError):
        raise NotFound('Ticket not found')

    if isinstance(body, dict):
        body = [body]

    if not isinstance(body, list):
        raise BadRequest('Invalid body, expecting object or list')

    for param in body:
        try:
            ticket.proof.create(**param)
            ticket.save()
            database.log_action_on_ticket(
                ticket=ticket,
                action='add_proof',
                user=user
            )
        except (KeyError, FieldDoesNotExist, FieldError,
                IntegrityError, TypeError, ValueError) as ex:
            raise BadRequest(str(ex.message))

    return {'message': 'Proof successfully added to ticket'}