Exemplo n.º 1
0
def project_accept_submission_requirements(request, project_uuid):
    try:
        project = limsfm_get_project(project_uuid)
    except requests.HTTPError as e:
        handle_limsfm_http_exception(request, e)
    except requests.RequestException as e:
        handle_limsfm_request_exception(request, e)

    if request.method == 'POST':
        form = ProjectAcceptTermsForm(request.POST)
        if form.is_valid():
            try:
                limsfm_update_project(project_uuid, form.cleaned_data)
            except requests.HTTPError as e:
                handle_limsfm_http_exception(request, e)
            except requests.RequestException as e:
                handle_limsfm_request_exception(request, e)
            else:
                slack_message('portal/slack/limsfm_project_accepted_submission_requirements.slack',
                              {'uuid': project_uuid, 'form': form})
                gmo_flag_to_file(
                    project['reference'],
                    form.cleaned_data['submission_requirements_name'],
                    form.cleaned_data['gmo_samples']
                )
                return HttpResponseRedirect(reverse(project_detail, args=[project_uuid]))
    else:
        form = ProjectAcceptTermsForm()
    # GET request, or invalid/failed POST
    return render(
        request, 'portal/accept_submission_requirements.html',
        {
            'project': project,
            'terms_form': form,
        })
Exemplo n.º 2
0
def confirm_order(order, charge_id, charge_created):
    logger.info('confirm_order', order=order.order_id, charge_id=charge_id)
    with transaction.atomic():
        order.confirm(charge_id, charge_created)
    send_receipt(order)
    send_ticket_invitations(order)
    slack_message('tickets/order_created.slack', {'order': order})
Exemplo n.º 3
0
def post_create(request):
    author = get_object_or_404(RedditAccount, owner_id=request.user.id)
    if request.method == "POST":
        form = PostForm(request.POST, user=request.user, initial={'author': author.id})
        if form.is_valid():
            post = form.save(commit=False)
            post.modified_time = datetime.datetime.now()
            if not request.user.is_staff:
                post.author_id = author.id
            slack_message('slack/postCreateRich.slack', {
                'author': author,
                'post': post,
            },
                [{
                    'title': post.title,
                    'text': post.body,
                },])
            post = form.save()
            return redirect('post_list')
    else:
        form = PostForm(user=request.user, initial={'author': author})

    template = loader.get_template('postEdit.html')
    context = {
        'title': "New Post",
        'form': form,
    }
    return HttpResponse(template.render(context, request))
Exemplo n.º 4
0
    def process_response(self, request, response):
        """
        Send broken link emails for relevant 404 NOT FOUND responses.
        """
        if response.status_code == 404 and not settings.DEBUG:
            domain = request.get_host()
            path = request.get_full_path()
            referer = force_text(request.META.get('HTTP_REFERER', ''),
                                 errors='replace')

            if not self.is_ignorable_request(request, path, domain, referer):
                ua = request.META.get('HTTP_USER_AGENT', '<none>')
                ip = request.META.get('REMOTE_ADDR', '<none>')

                subject = "Broken %slink on %s" % (
                    ('INTERNAL ' if self.is_internal_request(domain, referer)
                     else ''), domain)
                message = ("Referrer: %s\nRequested URL: %s\nUser agent: %s\n"
                           "IP address: %s\n" % (referer, path, ua, ip))
                attachments = {
                    'subject': subject,
                    'text': message,
                    'color': 'warning',
                }
                template = 'django_slack/exception.slack'

                slack_message(template, {'text': subject}, [attachments])
        return response
Exemplo n.º 5
0
 def test_backend_override(self):
     """
     Ensure the backend can be overridden.
     """
     with override_settings(SLACK_BACKEND='tests.backends.RaisingBackend'):
         with self.assertRaises(RaisingBackend.RaisedException):
             slack_message('test.slack', {'text': 'test'})
Exemplo n.º 6
0
def project_accept_submission_requirements(request, project_uuid):
    if request.method == 'POST':
        form = ProjectAcceptTermsForm(request.POST)
        if form.is_valid():
            try:
                limsfm_update_project(project_uuid, form.cleaned_data)
            except requests.HTTPError as e:
                handle_limsfm_http_exception(request, e)
            except requests.RequestException as e:
                handle_limsfm_request_exception(request, e)
            else:
                slack_message('portal/slack/limsfm_project_accepted_submission_requirements.slack',
                              {'uuid': project_uuid, 'form': form})
                return HttpResponseRedirect(reverse(project_detail, args=[project_uuid]))
    else:
        form = ProjectAcceptTermsForm()
    # GET request, or invalid/failed POST
    try:
        project = limsfm_get_project(project_uuid)
    except requests.HTTPError as e:
        handle_limsfm_http_exception(request, e)
    except requests.RequestException as e:
        handle_limsfm_request_exception(request, e)
    return render(
        request, 'portal/accept_submission_requirements.html',
        {
            'project': project,
            'terms_form': form,
        })
Exemplo n.º 7
0
def new_nomination(request):
    if request.user.is_authenticated and request.user.get_nomination():
        messages.warning(request, 'You have already submitted a nomination')
        return redirect(request.user.get_nomination())

    if request.method == 'POST':
        if not request.user.is_authenticated:
            return redirect(settings.LOGIN_URL)

        form = NominationForm(request.POST)
        if form.is_valid():
            nomination = form.save(commit=False)
            nomination.nominee = request.user
            nomination.save()
            messages.success(request,
                             'Thank you for submitting your nomination')
            slack_message('ukpa/nomination_created.slack',
                          {'nomination': nomination})
            return redirect(nomination)
    else:
        form = NominationForm()

    context = {
        'form': form,
    }
    return render(request, 'ukpa/new_nomination.html', context)
Exemplo n.º 8
0
 def test_backend_override(self):
     """
     Ensure the backend can be overridden.
     """
     with override_settings(SLACK_BACKEND='tests.backends.RaisingBackend'):
         with self.assertRaises(RaisingBackend.RaisedException):
             slack_message('test.slack', {'text': 'test'})
Exemplo n.º 9
0
def update_previous_day_reports(day=None):
    """
    Complete all report data for the previous day.

    :arg day: An optional datetime object representing a day.
    """
    start_date, _ = _get_day(day)

    if not day:
        # If not specified,
        # do the previous day now that the day is complete
        start_date -= datetime.timedelta(days=1)

    # Do all reports
    daily_update_geos(start_date)
    daily_update_placements(start_date)
    daily_update_impressions(start_date)
    daily_update_keywords(start_date)
    daily_update_uplift(start_date)
    daily_update_regiontopic(start_date)

    if not day:
        # Send notification to Slack about previous day's reports
        # Don't send this notification if run manually
        slack_message(
            "adserver/slack/generic-message.slack",
            {
                "text": f"Completed aggregating report data for yesterday ({start_date:%Y-%m-%d}). :page_with_curl:"
            },
        )
Exemplo n.º 10
0
def new_application(request):
    if not _can_submit(request):
        return _new_application_after_cfp_closes(request)

    if request.user.is_authenticated and request.user.get_grant_application():
        messages.warning(request, 'You have already submitted an application')
        return redirect(request.user.get_grant_application())

    if request.method == 'POST':
        if not request.user.is_authenticated:
            return redirect(settings.LOGIN_URL)

        form = ApplicationForm(request.POST)
        if form.is_valid():
            application = form.save(commit=False)
            for day in DAYS:
                if day in form.cleaned_data['days']:
                    setattr(application, day, True)
                else:
                    setattr(application, day, False)
            application.applicant = request.user
            application.save()
            messages.success(request,
                             'Thank you for submitting your application')
            slack_message('grants/application_created.slack',
                          {'application': application})
            return redirect(application)
    else:
        form = ApplicationForm()

    context = {
        'form': form,
        'js_paths': ['grants/application_form.js'],
    }
    return render(request, 'grants/new_application.html', context)
Exemplo n.º 11
0
 def send_messages(self, email_messages):
     for message in email_messages:
         attachments = [
             {
                 'fallback':
                 'メール',
                 'fields': [
                     {
                         'title': 'From',
                         'value': message.from_email
                     },
                     {
                         'title': 'To',
                         'value': ','.join(message.to)
                     },
                     {
                         'title': '件名',
                         'value': message.subject,
                     },
                     {
                         'title': '本文',
                         'value': message.body,
                     },
                 ],
             },
         ]
         slack_message('slacks/slack_email.slack',
                       {'slack': settings.SLACK_EMAIL_CHANNEL}, attachments)
Exemplo n.º 12
0
def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            team_name = form.cleaned_data.get('team_name')
            user.team.name = team_name
            captain = form.cleaned_data.get('team_captain')
            user.team.captain = captain
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
            messages.success(request, f'{team_name} successfully registered!')

            slack_message('users/reg.slack', {
                'captain': captain,
                'team': team_name,
                'emoji': 'squirrel',
            })

            return redirect('hunt20-home')

    else:
        form = UserRegisterForm()
    return render(request, 'users/register.html', {'form': form})
Exemplo n.º 13
0
def new_user_manager_notification(request, user, **kwargs):
    """
    Sends an email notification and a slack message upon successful user signup.
    The Email is sent to the site managers.
    The slack message is sent to the default slack channel from the project settings.
    :param request:
    :param user:
    :param kwargs:
    :return:
    """
    # manager_group, created_group = Group.objects.get_or_create(name="managers")
    # managers = [user.email for user in manager_group.user_set.all()]
    # TODO: Switch to managers group as soon as it is stable
    managers = ['*****@*****.**']
    username = str(user.username)
    reply_email = user.email
    subject = "New user: {}".format(username)
    message = "Hurray! {} has joined the circle of legends.".format(username)

    email = EmailMessage(subject=subject,
                         body=message,
                         to=managers,
                         reply_to=reply_email)
    email.send(fail_silently=True)

    slack_message('slack/message.slack', {
        'message': '@channel: {}'.format(message),
    },
                  fail_silently=False)
Exemplo n.º 14
0
    def send_message(self, message, recipient, source, **kwargs):
        target_rooms = self.slack_channels(source, **kwargs)

        if not any(target_rooms) or not settings.SLACK_TOKEN:
            errors = list()
            if not target_rooms:
                errors.append('Room ID')
            if not settings.SLACK_TOKEN:
                errors.append('Slack Token')
            return 'Missing configuration: {}'.format(', '.join(errors))

        message = ' '.join([recipient, message]).strip()

        data = {
            "message": message,
        }
        for room in target_rooms:
            try:
                slack_message('messages/slack_message.html',
                              data,
                              channel=room)
            except Exception as e:
                logger.exception(e)
                return '400: Bad Request'
        return '200: OK'
Exemplo n.º 15
0
def publish(request):
    try:
        pk = int(request.GET.get('pk'))

        page_type = request.GET.get('type')

        if request.GET.get('lessons') == 'true':
            children = True
        else:
            children = False

        klass = globals()[page_type]

        obj = klass.objects.get(pk=pk)

        if request.GET.get('pdf') == 'true':
            as_pdf = True
            pub_func = obj.publish_pdfs
        else:
            as_pdf = False
            pub_func = obj.publish

        slack_message('slack/message.slack', {
            'message': 'kicked off a publish of %s %s \n With children: %s\n As pdf: %s'
                       % (page_type, obj.title, children, as_pdf),
            'user': request.user,
        })

    except Exception, e:
        logger.exception('Publishing failed')

        return HttpResponse(e.message, content_type='application/json', status=500)
Exemplo n.º 16
0
def notify_of_completed_flights():
    """Send a note and close flights which completed in the last day."""
    cutoff = get_ad_day() - datetime.timedelta(days=1)
    for flight in Flight.objects.filter(live=True):
        if (
            flight.clicks_remaining() == 0
            and flight.views_remaining() == 0
            and AdImpression.objects.filter(
                date__gte=cutoff, advertisement__flight=flight
            ).exists()
        ):
            log.info("Flight %s finished in the last day.", flight)

            # Send notification about this flight
            slack_message(
                "adserver/slack/flight-complete.slack",
                {
                    "flight": flight,
                    "flight_url": generate_absolute_url(flight.get_absolute_url()),
                },
            )

            # Mark the flight as no longer live. It is complete
            flight.live = False
            flight.save()
Exemplo n.º 17
0
def new_user_notification(request, user, **kwargs):
    """
    Sends an email notification and a chat message upon successful user signup.

    The Email is sent to the site managers.
    The chat message is sent to the default slack channel from the project settings.
    :param request:
    :param user:
    :param kwargs:
    :return:
    """
    # manager_group, created_group = Group.objects.get_or_create(name="managers")
    # managers = [user.email for user in manager_group.user_set.all()]
    # TODO: Switch to managers group as soon as it is stable
    managers = ['*****@*****.**']
    reply_emails = [user.email]
    subject = f"New user: {user.username}"
    message = f"Hurray! {user.name} has joined the circle of legends."

    email = EmailMessage(subject=subject, body=message, to=managers, reply_to=reply_emails)
    email.send()

    embed = {
        'author': {
            'name': user.name,
            'icon_url': user.get_avatar()
        },
        'description': f'I want us to make {user.name} feel welcome here. ;)'
    }
    send_chat_message.delay(message, embeds=[embed], channel=Channel.COMMUNITY.value)

    slack_message('slack/message.slack', {'message': '@channel: {}'.format(message), }, fail_silently=False)
Exemplo n.º 18
0
def unit_pjspdf(request, slug, unit_slug):

    output = PdfFileWriter()
    unit = get_object_or_404(Unit, curriculum__slug=slug, slug=unit_slug)

    data = {
        "url": get_url_for_pdf(request, unit.get_absolute_url(), True),
        "renderType": "pdf"
    }

    url = 'http://PhantomJScloud.com/api/browser/v2/%s/' % settings.PHANTOMJS_KEY
    headers = {'content-type': 'application/json'}

    req = Request(url, json.dumps(data), headers)
    response = urlopen(req)
    results = response.read()
    print '\nresponse status code'
    print response.code
    print '\nresponse headers (pay attention to pjsc-* headers)'
    print response.headers

    memoryPDF = StringIO(results)
    localPDF = PdfFileReader(memoryPDF)
    output.appendPagesFromReader(localPDF)

    pdfresponse = HttpResponse(content_type='application/pdf')
    output.write(pdfresponse)
    pdfresponse['Content-Disposition'] = 'inline;filename=unit%s.pdf' % unit.number

    slack_message('slack/message.slack', {
        'message': 'created a PDF from %s %s' % (slug, unit_slug),
        'user': request.user,
    })

    return pdfresponse
Exemplo n.º 19
0
def task_postrun_slack(signal=None,
                       sender=None,
                       task_id=None,
                       task=None,
                       args=None,
                       retval=None,
                       state=None,
                       **kwargs):
    if settings.SLACK_CHANNEL:
        ttask = models.TatlTask.objects.get(celery_uuid=task_id)
        slack_message('slack/blank', {}, [{
            "mrkdwn_in": ["text", "pretext", "fields"],
            "title":
            "Task ended",
            "title_link":
            "",
            "text":
            "Task %s (`%s`) for `%s` finished with state *%s*" %
            (task.name, task_id,
             ttask.user.username if ttask.user else 'unknown', state),
            "footer":
            "Task end spotted by Majora",
            "footer_icon":
            "https://avatars.slack-edge.com/2019-05-03/627972616934_a621b7d3a28c2b6a7bd1_512.jpg",
            "ts":
            int(timezone.now().timestamp()),
        }])
Exemplo n.º 20
0
def gong(request):
    user = "******" % request.POST.get("user_name", "somebody")
    reason = request.POST.get("text", "Gonged stuff!")

    slack_message('slack/gonged.slack', {
        'user': user,
        'reason': reason
    })

    attachments = [
        {
            'author_name': user,
            'title': reason,
            'image_url': 'https://curriculum.code.org/images/gong.gif',
            'color': '#00adbc'
        }
    ]
    payload = {
        "response_type": "in_channel",
        "attachments": attachments,
    }

    record = Record(user=user, reason=reason)
    record.save()

    return Response(payload, content_type='application/json')
Exemplo n.º 21
0
def announce_perm_flex(sender, instance, **kwargs):
    if settings.SLACK_CHANNEL_TATL:
        ext = ''
        if instance.extra_context:
            try:
                ext = "\n```%s```" % json.dumps(json.loads(
                    instance.extra_context),
                                                indent=4,
                                                sort_keys=True)
            except Exception as e:
                pass

        try:
            slack_message('slack/permflex', {
                "channel": settings.SLACK_CHANNEL_TATL,
            }, [{
                "text":
                "User `%s` flexed their `%s` permission on `%s` at %s %s" % (
                    instance.user,
                    instance.used_permission,
                    str(instance.content_object),
                    str(instance.timestamp),
                    ext,
                ),
            }])
        except:
            pass
Exemplo n.º 22
0
    def send_message(self,
                     message,
                     request,
                     recipients=None,
                     related=None,
                     **kwargs):
        if not self.destination or not self.target_room or not settings.SLACK_TOKEN:
            errors = list()
            if not self.destination:
                errors.append('Destination URL')
            if not self.target_room:
                errors.append('Room ID')
            if not settings.SLACK_TOKEN:
                errors.append('Slack Token')
            return 'Missing configuration: {}'.format(', '.join(errors))

        slack_users = self.slack_users(recipients) if recipients else ''

        slack_link = self.slack_link(request, related, **
                                     kwargs) if related else ''

        message = ' '.join([slack_users, message, slack_link]).strip()

        data = {
            "message": message,
        }
        try:
            slack_message('messages/slack_message.html',
                          data,
                          channel=self.target_room)
            return '200: OK'
        except Exception as e:
            logger.exception(e)
            return '400: Bad Request'
Exemplo n.º 23
0
    def form_valid(self, form):
        # 作成者を登録
        form.instance.create_user = self.request.user

        # Contact のインスタンスを作成
        response = super().form_valid(form)

        # 初期閲覧部署を登録
        form.instance.department_list.set(
            form.instance.contact_kind.department_list.all())

        # お問い合わせ作成者にメールを送信
        penguin_send_mail('お問い合わせを送信しました', [self.request.user],
                          'communication/mails/contact_create.txt',
                          {'contact': form.instance})

        # 事務局員に slack を送信
        slack_message('communication/slacks/contact_create.slack',
                      {'slack': form.instance.contact_kind.slack},
                      form.instance.get_slack_attachments)

        # メッセージを追加
        messages.success(self.request, 'お問い合わせを事務局員に送信しました!')

        return response
Exemplo n.º 24
0
def handle_limsfm_request_exception(request, e):
    ERROR_MESSAGE = ("The MicrobesNG customer portal is temporarily "
                     "unavailable. Please try again later.")
    messages.error(request, ERROR_MESSAGE)
    slack_message('portal/slack/limsfm_request_exception.slack',
                  {'e': e, 'path': request.path})
    print(e)
    return 503  # http status
Exemplo n.º 25
0
    def send_slack_message(template, context=None, attachments=None):

        try:
            slack_message(template, context, attachments)
        except Exception as err:
            logging.getLogger('common').error(
                "Slack message failed, raised exception: {0}, with stack trace: {1}"
                .format(err, traceback.format_exc()))
Exemplo n.º 26
0
    def test_escape_chars(self):
        """
        Test the characters Slack wants escaped.

        See <https://api.slack.com/docs/formatting#how_to_escape_characters>
        """
        slack_message('escape.slack', {'text': '< > &'})
        self.assertMessage(text='&lt; &gt; &amp;')
Exemplo n.º 27
0
    def test_escape_chars(self):
        """
        Test the characters Slack wants escaped.

        See <https://api.slack.com/docs/formatting#how_to_escape_characters>
        """
        slack_message('escape.slack', {'text': '< > &'})
        self.assertMessage(text='&lt; &gt; &amp;')
Exemplo n.º 28
0
 def test_escaped(self):
     """
     Simple test of the Django escaping to illustrate problem.
     """
     slack_message('test.slack', {'text': '< > & " \''})
     if django.VERSION[0] >= 3:
         self.assertMessage(text='&lt; &gt; &amp; &quot; &#x27;')
     else:
         self.assertMessage(text='&lt; &gt; &amp; &quot; &#39;')
Exemplo n.º 29
0
def activity_save_receiver(sender, instance, *args, **kwargs):
	if instance.type == DEBIT:
		instance.user.bank_balance -= instance.value
	elif instance.type == CREDIT:
		instance.user.bank_balance += instance.value
		slack_message('slack/gain_credit.slack', {
		    'obj': instance,
		})
	instance.user.save()
Exemplo n.º 30
0
def orderitem_save_receiver(sender, instance, created, *args, **kwargs):
	if created:
		total = instance.cost()
		instance.order.value += total
		instance.order.save()
		Activity.objects.create(user=instance.order.user, type=DEBIT, value=total)
		slack_message('slack/buy_item.slack', {
		    'obj': instance,
		})
Exemplo n.º 31
0
def project_detail(request, project_uuid):
    # Fetch project from lims
    project = None
    try:
        project = limsfm_get_project(project_uuid)
    except requests.HTTPError as e:
        handle_limsfm_http_exception(request, e)
    except requests.RequestException as e:
        handle_limsfm_request_exception(request, e)
    if not project:
        # Template will report error messages
        return render(request, 'portal/project.html', {'project': project})

    # Check whether user needs to accept submission requirements
    if not (project['submission_requirements_name']
            or project['meta_data_status'] == 'Accepted'
            or project['all_content_received_date']
            ):  # Redirect to accept submission requirements
        return HttpResponseRedirect(
            reverse(project_accept_submission_requirements,
                    args=[project_uuid]))

    context = {
        'project': project,
        'project_add_collaborator_form': ProjectAddCollaboratorForm(),
        'project_ena_form': ProjectEnaForm(initial=project),
        'upload_sample_sheet_form': UploadSampleSheetForm()
    }

    if project['is_confidential'] or project['ena_title']:
        # Render full project portal
        if request_should_post_to_slack(request):
            slack_message('portal/slack/limsfm_project_detail_access.slack', {
                'request': request,
                'project': project
            })
        return render(request, 'portal/project.html', context)
    else:
        # Collect ena title/abstract before proceeding to portal
        if project['meta_data_status'] == 'Accepted':
            messages.warning(
                request,
                "We did not previously collect your project title & description as part of our initial setup process, "
                "so we need to request this data retrospectively. We appreciate your cooperation."
            )
        else:
            messages.warning(
                request,
                "Please complete your project title & description in order to proceed to your portal."
            )
        if request_should_post_to_slack(request):
            slack_message('portal/slack/limsfm_project_setup_access.slack', {
                'request': request,
                'project': project
            })
        return HttpResponseRedirect(
            reverse(project_ena_details, args=[project_uuid]))
Exemplo n.º 32
0
    def form_valid(self, form):

        slack_message('my_message.slack', {
            'message': form.cleaned_data.get('contacter_message'),
            'name': form.cleaned_data.get('contacter_name'),
            'mail': form.cleaned_data.get('contacter_mail')
        })

        return super(ContactMe, self).form_valid(form)
Exemplo n.º 33
0
def send_chat_notification(file, text, data):
    from django_slack import slack_message
    text = ("{text}\n{data}\n-- {file}").format(file=file, text=text, data=data)
    if getattr(settings, 'SLACK_BACKEND', None) in (None, 'django_slack.backends.DisabledBackend'):
        print "-- SLACK MESSAGE"
        print text
        print "----"
    else:
        slack_message('django-slack/text.slack', {"text": text})
Exemplo n.º 34
0
def home(request):
    region = request.user.userprofile.current_region
    invite = InvitationForm(request.user)
    teams = Team.objects.filter(teammember__user=request.user)

    regionform = RegionSelectForm()
    regionform.initial['region'] = region

    for t in teams:
        team_member = TeamMember.objects.get(team=t, user=request.user)
        if request.user == t.creator or team_member.is_admin:
            t.is_admin = True
        t.active = True

        ## check if region is available
        if region.disabled:
            messages.error(request, 'The %s region is currently unavailable. Check the community forum for service status.' % (region.name))
            t.active = False
            continue

        tenant = get_tenant_for_team(t, region)
        if not tenant:
            t.active = False
            slack_message(
                'home/slack/no_tenant_for_region.slack',
                {'team': t, 'region': region, 'user': request.user})
            continue

        if region.name == 'bham':
            t.horizon_endpoint = 'https://birmingham.climb.ac.uk'
        elif region.name == 'cardiff':
            t.horizon_endpoint = 'https://cardiff.climb.ac.uk'
        elif region.name == 'warwick':
            t.horizon_endpoint = 'http://stack.warwick.climb.ac.uk'
        elif region.name == 'swansea':
            t.horizon_endpoint = 'https://swansea.climb.ac.uk'

        try:
            t.launch_form = LaunchServerForm(tenant.get_flavors())
            available_keys = [key for key in tenant.get_keys() if key[0] != "cloudman"]
            t.launch_custom_form = LaunchImageServerForm(tenant.get_images(),tenant.get_flavors(), available_keys)
            t.tenant_access = tenant
            t.instances = list_instances(tenant)
        except Exception, e:
            messages.error(
                request,
                'The %s region is currently unavailable. Check the community '
                'forum for service status.' % (region.name))
            slack_message(
                'home/slack/region_api_exception.slack',
                {
                    'team': t,
                    'region': region,
                    'user': request.user,
                    'e': e
                })
Exemplo n.º 35
0
 def test_fail_silently(self):
     """
     Ensure fail silently can be overridden.
     """
     # Note that this will fail if test_backend_override ever fails.
     with override_settings(
         SLACK_FAIL_SILENTLY=True,
         SLACK_BACKEND='tests.backends.RaisingBackend',
     ):
         slack_message('test.slack', {'text': 'test'})
Exemplo n.º 36
0
 def test_fail_silently(self):
     """
     Ensure fail silently can be overridden.
     """
     # Note that this will fail if test_backend_override ever fails.
     with override_settings(
             SLACK_FAIL_SILENTLY=True,
             SLACK_BACKEND='tests.backends.RaisingBackend',
     ):
         slack_message('test.slack', {'text': 'test'})
Exemplo n.º 37
0
def log(message):
    """
    Generic helper for logging information from the sync process. Message is
    logged to the console mostly for debugging purposes, and is logged to slack
    for actual use.
    """
    print(message) # pylint: disable=superfluous-parens
    slack_message('slack/message.slack', {
        'message': message
    })
Exemplo n.º 38
0
def handle_limsfm_request_exception(request, e):
    ERROR_MESSAGE = ("The MicrobesNG customer portal is temporarily "
                     "unavailable. Please try again later.")
    messages.error(request, ERROR_MESSAGE)
    slack_message('portal/slack/limsfm_request_exception.slack', {
        'e': e,
        'path': request.path
    })
    print(e)
    return 503  # http status
Exemplo n.º 39
0
def todo_add(request):
    if request.method == "POST":
        form = TodoForm(request.POST)
        if form.is_valid():
            todo = form.save(commit=False)
            slack_message('blog/message.slack', {"message": todo.content}) 
            todo.save()
            return redirect('list')
    else:
        form = TodoForm()
    return render(request, "blog/forms.html", {"form": form})
Exemplo n.º 40
0
def handle_limsfm_http_exception(request, e):
    ERROR_MESSAGE = ("An unexpected error has occured. "
                     "Please contact [email protected]")
    if e.response.status_code == 404:
        raise Http404
    else:
        messages.error(request, ERROR_MESSAGE)
        slack_message('portal/slack/limsfm_http_exception.slack',
                      {'e': e, 'path': request.path})
    print(e)
    return 500  # http status
Exemplo n.º 41
0
def recv_new_sample(sender, sample_id, submitter, **kwargs):
    if settings.SLACK_CHANNEL:
        slack_message(
            'slack/blank',
            {},
            [{
                "text": "Sample %s uploaded from %s" % (sample_id, submitter),
                #"footer": "New sample spotted by Majora",
                #"footer_icon": "https://avatars.slack-edge.com/2019-05-03/627972616934_a621b7d3a28c2b6a7bd1_512.jpg",
                #"ts": int(time.time()),
            }])
Exemplo n.º 42
0
def start_guiding_process(request, user, **kwargs):
    # Create a new guide relation
    relation = user.guiderelation
    # Notify potential guides
    username = user.username
    location = reverse('guides:list')
    url = request.build_absolute_uri(location)
    message = "{} is looking for a guide: {}".format(username, url)
    # TODO: Fix backend isse: https://app.getsentry.com/eraldo/colegend-staging/issues/102969964/
    # Then remove fail_silently
    slack_message('slack/message.slack', {'message': '@channel: {}'.format(message), 'channel': 'cloudguide'},
                  fail_silently=True)
Exemplo n.º 43
0
def send_chat_notification(file, text, data):
    from django_slack import slack_message
    text = ("{text}\n{data}\n-- {file}").format(file=file,
                                                text=text,
                                                data=data)
    if getattr(settings, 'SLACK_BACKEND',
               None) in (None, 'django_slack.backends.DisabledBackend'):
        print "-- SLACK MESSAGE"
        print text
        print "----"
    else:
        slack_message('django-slack/text.slack', {"text": text})
Exemplo n.º 44
0
def unit_resources_pdf(request, slug, unit_slug):
    merger = PdfFileMerger()
    unit = get_object_or_404(Unit, curriculum__slug=slug, slug=unit_slug)
    for lesson in unit.lessons.exclude(keywords__keyword__slug="optional"):
        lesson_string = render_to_string("curricula/lesson_title.html", {'unit': unit, 'lesson': lesson},
                                         request=request)
        lesson_page = pdfkit.from_string(lesson_string, False, options=settings.WKHTMLTOPDF_CMD_OPTIONS, configuration=pdfkit_config)
        lesson_page_pdf = StringIO(lesson_page)
        merger.append(PdfFileReader(lesson_page_pdf))
        for resource in lesson.resources.all():
            if resource.gd:
                try:
                    remotePDF = urlopen(Request(resource.gd_pdf())).read()
                    memoryPDF = StringIO(remotePDF)
                    localPDF = PdfFileReader(memoryPDF)
                    merger.append(localPDF)
                except Exception:

                    attachments = [
                        {
                            'color': 'danger',
                            'title': 'URL',
                            'text': resource.url,
                        },
                        {
                            'color': 'danger',
                            'title': 'Related Lesson',
                            'text': lesson.get_absolute_url(),
                        },
                    ]

                    ip = get_real_ip(request)

                    slack_message('slack/message.slack', {
                        'message': "tried and failed to publish resource %s - %s (pk %s). "
                                   "Check to ensure that it's a publicly accessible Google Doc"
                                   % (resource.name, resource.type, resource.pk),
                        'user': request.user.get_username() or ip,
                    }, attachments)
                    return HttpResponse('PDF Generation Failed', status=500)

    response = HttpResponse(content_type='application/pdf')
    merger.write(response)
    response['Content-Disposition'] = 'inline;filename=unit%s_resources.pdf' % unit.number

    ip = get_real_ip(request)
    slack_message('slack/message.slack', {
        'message': 'created a resource PDF from %s %s' % (slug, unit_slug),
        'user': request.user.get_username() or ip,
    })

    return response
Exemplo n.º 45
0
    def send_feeback(sender, subject='', message=''):
        # TODO: Getting managers via dynamic role filtering.
        managers = ['*****@*****.**']

        if subject:
            message = '{subject}\n{message}'.format(subject=subject, message=message)

        subject = 'Feedback from {name} ({username})'.format(name=sender.name, username=sender.username)

        email = EmailMessage(subject=subject, body=message, to=managers, reply_to=[sender.email])
        email.send()

        slack_message('slack/message.slack', {'message': '@channel: {}'.format(message), }, fail_silently=True)
Exemplo n.º 46
0
def handle_limsfm_http_exception(request, e):
    ERROR_MESSAGE = ("An unexpected error has occured. "
                     "Please contact [email protected]")
    if e.response.status_code == 404:
        raise Http404
    else:
        messages.error(request, ERROR_MESSAGE)
        slack_message('portal/slack/limsfm_http_exception.slack', {
            'e': e,
            'path': request.path
        })
    print(e)
    return 500  # http status
Exemplo n.º 47
0
 def publish_pdfs(self, *args, **kwargs):
     if self.jackfrost_can_build():
         try:
             read, written = build_single(self.get_pdf_url())
             slack_message('slack/message.slack', {
                 'message': 'published %s %s' % (self.content_model, self.title),
                 'color': '#00adbc'
             })
             yield json.dumps(written)
             yield '\n'
         except Exception, e:
             yield json.dumps(e.message)
             yield '\n'
             logger.exception('Failed to publish PDF for %s' % self)
Exemplo n.º 48
0
def send_slack_message(request, menu):
    """
    Utility function that send a notification message via the Slack channel specified in the
    settings file through a Celery backend (which means is done asynchronously).
    The message contains the link to the new menu.

    Arguments:
    **menu**
        A Menu model object which will be used to form the message's menu link
    """
    slack_message('slack/new_menu_notification.slack', {
        'menu': menu,
        'host': Site.objects.get_current().domain
    })
Exemplo n.º 49
0
    def perform_create(self, serializer):
        ride = Ride.objects.get(id=self.kwargs.get('id'))
        user = self.request.user

        registration = serializer.save(
            user=user,
            ride=ride,
            paid=False,
            status=RideRiders.PENDING)

        slack_message('slack/new_registration.slack', {
            'user': user,
            'ride': ride,
            'reg': registration
        })
Exemplo n.º 50
0
    def perform_update(self, serializer):
        """
        Charge the user for the ride fee and then update the status of
        their RideRider entry. The current status must be 'accepted'
        and the logged in user must be the owner of the record.
        """
        request = self.request
        ride = Ride.objects.get(id=self.kwargs.get('id'))
        amount = request.data.get('amount')

        # Check that there is actually space left on the ride
        # People shouldn't get here if there isn't but let's make sure we don't
        # charge anyone if there isn't enough space on the ride
        if ride.spaces_left == 0:
            raise ValidationError("This ride is already at full capacity")

        # Determine how much we are charging this user (either the minimum
        # contribution or more if they have explicitely specified more)
        if amount is None:
            amount = ride.price
        else:
            amount = float(amount)

        if amount < ride.price:
            raise ValidationError("The amount can't be less than the price of the ride.")

        # Go ahead and charge them!
        if ride.price > 0:
            try:
                sale = Sale.charge(
                    request.data.get('token'),
                    ride.chapter.private_key,
                    int(amount * 100),
                    ride.currency,
                    "Techbikers {0}: {1}".format(ride.name, request.user.email),
                    request.user.email)
            except stripe.error.CardError, e:
                raise ValidationError(e.json_body['error'])
            sale.rider_id = request.user.id
            sale.save()

            slack_message('slack/completed_registration.slack', {
                'user': request.user,
                'ride': ride,
                'amount': amount
            })

            serializer.save(status=RideRiders.REGISTERED, paid=True, sale=sale)
Exemplo n.º 51
0
 def publish(self, children=False, silent=False):
     if self.jackfrost_can_build():
         for url in self.jackfrost_urls():
             try:
                 read, written = build_single(url)
                 if not silent:
                     slack_message('slack/message.slack', {
                         'message': 'published %s %s' % (self.content_model, self.title),
                         'color': '#00adbc'
                     })
                 yield json.dumps(written)
                 yield '\n'
             except Exception, e:
                 yield json.dumps(e.message)
                 yield '\n'
                 logger.exception('Failed to publish %s' % url)
Exemplo n.º 52
0
def project_detail(request, project_uuid):
    # Fetch project from lims
    project = None
    try:
        project = limsfm_get_project(project_uuid)
    except requests.HTTPError as e:
        handle_limsfm_http_exception(request, e)
    except requests.RequestException as e:
        handle_limsfm_request_exception(request, e)
    if not project:
        # Template will report error messages
        return render(request, 'portal/project.html', {'project': project})

    # Check whether user needs to accept submission requirements
    if not (project['submission_requirements_name'] or
            project['meta_data_status'] == 'Accepted' or
            project['all_content_received_date']):  # Redirect to accept submission requirements
        return HttpResponseRedirect(reverse(project_accept_submission_requirements, args=[project_uuid]))

    context = {
        'project': project,
        'project_add_collaborator_form': ProjectAddCollaboratorForm(),
        'project_ena_form': ProjectEnaForm(initial=project),
        'upload_sample_sheet_form': UploadSampleSheetForm()
    }

    if project['is_confidential'] or project['ena_title']:
        # Render full project portal
        if request_should_post_to_slack(request):
            slack_message('portal/slack/limsfm_project_detail_access.slack',
                          {'request': request, 'project': project})
        return render(request, 'portal/project.html', context)
    else:
        # Collect ena title/abstract before proceeding to portal
        if project['meta_data_status'] == 'Accepted':
            messages.warning(request, "We did not previously collect your project title & description as part of our initial setup process, "
                                      "so we need to request this data retrospectively. We appreciate your cooperation.")
        else:
            messages.warning(request, "Please complete your project title & description in order to proceed to your portal.")
        if request_should_post_to_slack(request):
            slack_message('portal/slack/limsfm_project_setup_access.slack',
                          {'request': request, 'project': project})
        return HttpResponseRedirect(reverse(project_ena_details, args=[project_uuid]))
Exemplo n.º 53
0
def clone(request):
    try:
        pk = int(request.POST.get('pk'))
        page_type = request.POST.get('type')
        if request.POST.get('children') == 'true':
            children = True
        else:
            children = False

        klass = globals()[page_type]

        obj = klass.objects.get(pk=pk)

        cloneable = getattr(obj, "clone", None)
        if not callable(cloneable):
            logger.exception('%s is not cloneable' % obj.title)
            return HttpResponse("Not cloneable", content_type='application/json', status=500)

        attrs = request.POST.get('attrs', {})
        exclude = request.POST.get('exclude', [])

        duplicate = obj.clone(attrs=attrs, exclude=exclude, children=children)

        slack_message('slack/message.slack', {
            'message': 'cloned the %s %s'
                       % (page_type, obj.title),
            'user': request.user,
        })

        redirect_url = duplicate.get_absolute_url()
        if page_type in ['Block', 'Map', 'IDE']:
            redirect_url = "/documentation%s" % redirect_url

        payload = {'message': 'cloned to %s' % duplicate.title, 'redirect_url': redirect_url, 'status': 200}

        return HttpResponse(json.dumps(payload), content_type='application/json', status=payload.get('status', 200))

    except Exception, e:
        logger.exception('Cloning failed')

        return HttpResponse(e.message, content_type='application/json', status=500)
Exemplo n.º 54
0
def old_publish(request):
    try:
        pk = int(request.POST.get('pk'))

        page_type = request.POST.get('type')

        if request.POST.get('lessons') == 'true':
            children = True
        else:
            children = False

        klass = globals()[page_type]

        obj = klass.objects.get(pk=pk)

        if request.POST.get('pdf') == 'true':
            payload = obj.publish_pdfs()
        else:
            payload = obj.publish(children=children)

        attachments = [
            {
                'color': '#00adbc',
                'title': 'URL',
                'text': obj.get_absolute_url(),
            },
            {
                'color': '#00adbc',
                'title': 'Publishing Details',
                'text': json.dumps(payload),
            },
        ]

        slack_message('slack/message.slack', {
            'message': 'published %s %s' % (page_type, obj.title),
            'user': request.user,
        }, attachments)

    except Exception, e:
        payload = {'status': 500, 'error': 'failed', 'exception': e.message}
        logger.exception('Publishing failed')
Exemplo n.º 55
0
def projectline_update(request, project_uuid, projectline_uuid):
    form = ProjectLineForm(request.POST)
    if form.is_valid():
        try:
            limsfm_update_projectline(project_uuid, projectline_uuid,
                                      form.cleaned_data)
        except requests.HTTPError as e:
            status = handle_limsfm_http_exception(request, e)
            return JsonResponse(str(e))
        except requests.RequestException as e:
            status = handle_limsfm_request_exception(request, e)
            return JsonResponse(str(e))
        else:
            slack_message('portal/slack/limsfm_projectline_update.slack',
                          {'form': form})
            messages.success(request, "Saved")
            status = 200
        return JsonResponse(messages_to_json(request), status=status)
    else:
        json = form_errors_to_json(request, form)
        return JsonResponse(json, status=400)
Exemplo n.º 56
0
def project_ena_details(request, project_uuid):
    # Handle POST
    if request.method == 'POST':
        form = ProjectEnaForm(request.POST)
        if form.is_valid():
            try:
                limsfm_update_project(project_uuid, form.cleaned_data)
            except requests.HTTPError as e:
                status = handle_limsfm_http_exception(request, e)
            except requests.RequestException as e:
                status = handle_limsfm_request_exception(request, e)
            else:
                slack_message('portal/slack/limsfm_project_ena_update.slack',
                              {'uuid': project_uuid, 'form': form})
                messages.success(request, "Project ENA details saved.")
                status = 200
            if request.is_ajax():
                return JsonResponse(messages_to_json(request), status=status)
            else:
                return HttpResponseRedirect(reverse(project_detail, args=[project_uuid]))
        elif request.is_ajax():
            return JsonResponse(form_errors_to_json(request, project_ena_form), status=400)

    # GET request, or invalid/failed POST
    project = None
    try:
        project = limsfm_get_project(project_uuid)
    except requests.HTTPError as e:
        handle_limsfm_http_exception(request, e)
    except requests.RequestException as e:
        handle_limsfm_request_exception(request, e)
    else:
        form = ProjectEnaForm(initial=project)
        if request_should_post_to_slack(request):
            slack_message('portal/slack/limsfm_project_setup_access.slack',
                          {'request': request, 'project': project})
        context = {'project': project, 'project_ena_form': form}
        return render(request, 'portal/project_setup.html', context)
Exemplo n.º 57
0
    def show_me_the_money(cls, sender: PayPalIPN, **kwargs):
        from lindy.ticket.models import TicketAddOn

        try:
            ipn_obj = sender
            custom = cls.parse_custom(ipn_obj.custom)

            # super important do this first
            Ticket.objects.filter(pk=custom.ticket_id).update(is_pending=True, is_checkout_finalized=True)
            TicketAddOn.objects.filter(pk__in=custom.addon_ids).update(is_pending=True, is_checkout_finalized=True)

            ticket = cls.objects.get(pk=custom.ticket_id)

            logger.info(
                'show me the money\n\t--> ipn: %s\n\t--> custom: %s\n\t--> ticket_id: %s\n\t--> custom_id: %s',
                ipn_obj.id, ipn_obj.custom, ticket.id, custom.ticket_id
            )

            ticket.paypal_ipn_set.add(ipn_obj)

            if ipn_obj.recurring:
                ticket.is_subscription = True

            with as_robot_user():
                ticket.is_paid  # NOTE: is_paid property scribbles on t._is_paid database value. Just needs to be saved.
                ticket.save()

            # Do this last, as it may fail
            ipn_obj.admin_url = admin_url(ipn_obj)
            slack_message(
                'ticket/ipn.slack',
                {
                    'ticket': ticket,
                    'ipn_obj': ipn_obj,
                }
            )
        except Exception as e:
            logger.exception(e)
Exemplo n.º 58
0
def unit_pdf(request, slug, unit_slug):

    buffer = StringIO()
    c = pycurl.Curl()
    c.setopt(c.WRITEDATA, buffer)

    unit = get_object_or_404(Unit, curriculum__slug=slug, slug=unit_slug)

    try:
        c.setopt(c.URL, get_url_for_pdf(request, unit.get_compiled_url(), True))
        print unit.get_compiled_url()
        c.perform()

        c.close()
        compiled = buffer.getvalue()
    except Exception:
        logger.exception('PDF Curling Failed')
        return HttpResponse('PDF Curling Failed', status=500)

    if request.GET.get('html'):  # Allows testing the html output
        response = HttpResponse(compiled)
    else:
        try:
            pdf = pdfkit.from_string(compiled.decode('utf8'), False, options=settings.WKHTMLTOPDF_CMD_OPTIONS, configuration=pdfkit_config)
        except Exception:
            logger.exception('PDF Generation Failed')
            return HttpResponse('PDF Generation Failed', status=500)

        response = HttpResponse(pdf, content_type='application/pdf')
        response['Content-Disposition'] = 'inline;filename=unit%s.pdf' % unit.number

        ip = get_real_ip(request)
        slack_message('slack/message.slack', {
            'message': 'created a PDF from %s %s' % (slug, unit_slug),
            'user': request.user.get_username() or ip,
        })

    return response
Exemplo n.º 59
0
def daily_slack_update(request):
    """
    Posts to the Techbikers Slack with a daily update on the current rides
    """
    attachments = []
    rides = Ride.objects.filter(end_date__gte=datetime.now().date())

    # If we have some current or upcoming rides, bundle together the
    # stats for each one ready to send to Slack
    if rides.count() > 0:
        for ride in rides:
            attachment = {
                'color': 'good',
                'title': ride.name,
                'title_link': 'https://techbikers.com/rides/{0}/{1}'.format(ride.id, ride.slug),
                'fields': [{
                    'title': 'Rider Registrations',
                    'value': ':white_check_mark: {0} registered, :envelope: {1} invited, :clock1: {2} pending'.format(
                        ride.registered_riders.count(),
                        ride.invited_riders.count(),
                        ride.pending_riders.count()
                    ),
                    'short': False
                }, {
                    'title': 'Fundraising Total',
                    'value': ':moneybag: {0} {1}'.format(ride.currency.upper(), ride.fundraising_total),
                    'short': False
                }]
            }
            attachments.append(attachment)

        # Post the update to Slack
        slack_message('slack/daily_update.slack', { 'number_rides': rides.count() }, attachments)

        # Return all good
        return Response({'message': 'success'})