Python django.http.HttpResponseBadRequest() Examples

The following are 30 code examples for showing how to use django.http.HttpResponseBadRequest(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.http , or try the search function .

Example 1
Project: crowdata   Author: crowdata   File: views.py    License: MIT License 6 votes vote down vote up
def form_detail(request, slug, template="forms/form_detail.html"):
    form = get_object_or_404(models.DocumentSetForm, slug=slug)
    request_context = RequestContext(request)
    args = (form, request_context, request.POST or None)

    form_for_form = forms.DocumentSetFormForForm(*args)

    if request.method == 'POST':
        if not form_for_form.is_valid():
            form_invalid.send(sender=request, form=form_for_form)
            return HttpResponseBadRequest(json.dumps(form_for_form.errors), content_type='application/json')
        else:
            entry = form_for_form.save()
            form_valid.send(sender=request, form=form_for_form, entry=entry, document_id=request.session['document_id_for_entry'])
            return HttpResponse('')
    return render_to_response(template, { 'form': form }, request_context) 
Example 2
Project: raveberry   Author: raveberry   File: suggestions.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def random_suggestion(cls, request: WSGIRequest) -> HttpResponse:
        """This method returns a random suggestion from the database.
        Depending on the value of :param playlist:,
        either a previously pushed playlist or song is returned."""
        suggest_playlist = request.GET["playlist"] == "true"
        if not suggest_playlist:
            if ArchivedSong.objects.count() == 0:
                return HttpResponseBadRequest("No songs to suggest from")
            index = random.randint(0, ArchivedSong.objects.count() - 1)
            song = ArchivedSong.objects.all()[index]
            return JsonResponse({"suggestion": song.displayname(), "key": song.id})

        # exclude radios from suggestions
        remaining_playlists = (
            ArchivedPlaylist.objects.all()
            .exclude(list_id__startswith="RD")
            .exclude(list_id__contains="&list=RD")
        )
        if remaining_playlists.count() == 0:
            return HttpResponseBadRequest("No playlists to suggest from")
        index = random.randint(0, remaining_playlists.count() - 1)
        playlist = remaining_playlists.all()[index]
        return JsonResponse({"suggestion": playlist.title, "key": playlist.id}) 
Example 3
Project: raveberry   Author: raveberry   File: musiq.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def request_radio(self, request: WSGIRequest) -> HttpResponse:
        """Endpoint to request radio for the current song."""
        # only get ip on user requests
        if self.base.settings.basic.logging_enabled:
            request_ip, _ = ipware.get_client_ip(request)
            if request_ip is None:
                request_ip = ""
        else:
            request_ip = ""

        try:
            current_song = CurrentSong.objects.get()
        except CurrentSong.DoesNotExist:
            return HttpResponseBadRequest("Need a song to play the radio")
        provider = SongProvider.create(self, external_url=current_song.external_url)
        return provider.request_radio(request_ip) 
Example 4
Project: raveberry   Author: raveberry   File: musiq.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def post_song(self, request: WSGIRequest) -> HttpResponse:
        """This endpoint is part of the API and exempt from CSRF checks.
        Shareberry uses this endpoint."""
        # only get ip on user requests
        if self.base.settings.basic.logging_enabled:
            request_ip, _ = ipware.get_client_ip(request)
            if request_ip is None:
                request_ip = ""
        else:
            request_ip = ""
        query = request.POST.get("query")
        if not query:
            return HttpResponseBadRequest("No query to share.")
        # Set the requested platform to 'spotify'.
        # It will automatically fall back to Youtube
        # if Spotify is not enabled or a youtube link was requested.
        successful, message, _ = self.do_request_music(
            request_ip, query, None, False, "spotify"
        )
        if not successful:
            return HttpResponseBadRequest(message)
        return HttpResponse(message) 
Example 5
Project: raveberry   Author: raveberry   File: system.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def enable_streaming(self, _request: WSGIRequest) -> HttpResponse:
        """Enable icecast streaming."""
        icecast_exists = False
        for line in subprocess.check_output(
            "systemctl list-unit-files --full --all".split(), universal_newlines=True
        ).splitlines():
            if "icecast2.service" in line:
                icecast_exists = True
                break

        if not icecast_exists:
            return HttpResponseBadRequest("Please install icecast2")

        subprocess.call(["sudo", "/usr/local/sbin/raveberry/enable_streaming"])
        config_file = os.path.join(settings.BASE_DIR, "setup/mopidy_icecast.conf")
        self.update_mopidy_config(config_file)
        return HttpResponse() 
Example 6
Project: raveberry   Author: raveberry   File: system.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def get_latest_version(self, _request: WSGIRequest) -> HttpResponse:
        """Looks up the newest version number from PyPi and returns it."""
        try:
            subprocess.run(
                "pip3 install raveberry==nonexistingversion".split(),
                stdout=subprocess.DEVNULL,
                stderr=subprocess.PIPE,
                universal_newlines=True,
                check=True,
            )
        except subprocess.CalledProcessError as e:
            # parse the newest verson from pip output
            for line in e.stderr.splitlines():
                if "from versions" in line:
                    versions = [re.sub(r"[^0-9.]", "", token) for token in line.split()]
                    versions = [version for version in versions if version]
                    latest_version = versions[-1]
                    return HttpResponse(latest_version)
        return HttpResponseBadRequest("Could not determine latest version.") 
Example 7
Project: raveberry   Author: raveberry   File: library.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def list_subdirectories(self, request: WSGIRequest) -> HttpResponse:
        """Returns a list of all subdirectories for the given path."""
        path = request.GET.get("path")
        if path is None:
            return HttpResponseBadRequest("path was not supplied.")
        basedir, subdirpart = os.path.split(path)
        if path == "":
            suggestions = ["/"]
        elif os.path.isdir(basedir):
            suggestions = [
                os.path.join(basedir, subdir + "/")
                for subdir in next(os.walk(basedir))[1]
                if subdir.lower().startswith(subdirpart.lower())
            ]
            suggestions.sort()
        else:
            suggestions = ["not a valid directory"]
        if not suggestions:
            suggestions = ["not a valid directory"]
        return JsonResponse(suggestions, safe=False) 
Example 8
Project: raveberry   Author: raveberry   File: platforms.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def _set_extension_enabled(self, extension, enabled) -> HttpResponse:
        if enabled:
            if settings.DOCKER:
                response = HttpResponse(
                    "Make sure you provided mopidy with correct credentials."
                )
            else:
                extensions = self.base.settings.system.check_mopidy_extensions()
                functional, message = extensions[extension]
                if not functional:
                    return HttpResponseBadRequest(message)
                response = HttpResponse(message)
        else:
            response = HttpResponse("Disabled extension")
        Setting.objects.filter(key=f"{extension}_enabled").update(value=enabled)
        setattr(self, f"{extension}_enabled", enabled)
        return response 
Example 9
Project: raveberry   Author: raveberry   File: sound.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_output_device(self, request: WSGIRequest) -> HttpResponse:
        """Sets the given device as default output device."""
        device = request.POST.get("device")
        if not device:
            return HttpResponseBadRequest("No device selected")

        try:
            subprocess.run(
                ["pactl", "set-default-sink", device],
                stdout=subprocess.DEVNULL,
                stderr=subprocess.PIPE,
                env={"PULSE_SERVER": "127.0.0.1"},
                check=True,
            )
        except subprocess.CalledProcessError as e:
            return HttpResponseBadRequest(e.stderr)
        # restart mopidy to apply audio device change
        subprocess.call(["sudo", "/usr/local/sbin/raveberry/restart_mopidy"])
        return HttpResponse(
            f"Set default output. Restarting the current song might be necessary."
        ) 
Example 10
Project: open-synthesis   Author: twschiller   File: teams.py    License: GNU General Public License v3.0 6 votes vote down vote up
def decide_invitation(request, invite_id):
    invite = get_object_or_404(TeamRequest, pk=invite_id)
    team = invite.team

    if team.owner_id is None or team.owner_id != request.user.id:
        raise SuspiciousOperation(_('User is not the owner of the team'))
    elif 'accept' in request.POST:
        invite.team.members.add(invite.invitee)
        invite.team.save()
        notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='accept', action_object=team, target=invite.invitee)
        messages.success(request, _('Added {name} to the team').format(name=invite.invitee.username))
    elif 'reject' in request.POST:
        notify.send(request.user, recipient=invite.invitee, actor=request.user, verb='reject', action_object=team, target=invite.invitee)
        messages.success(request, _('Ignored {name}\'s team membership request').format(name=invite.invitee.username))
    else:
        return HttpResponseBadRequest(_('POST request must include either "{accept}" or "{reject}"').format(accept='accept', reject='reject'))

    invite.delete()
    return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example 11
Project: open-synthesis   Author: twschiller   File: teams.py    License: GNU General Public License v3.0 6 votes vote down vote up
def join_team(request, team_id):
    team = get_object_or_404(Team, pk=team_id)

    if team.members.filter(id=request.user.id).exists():
        raise SuspiciousOperation(_('User is already a member of the team'))
    elif TeamRequest.objects.filter(invitee=request.user, inviter__isnull=False, team=team).exists() or not team.invitation_required:
        team.members.add(request.user)
        team.save()
        TeamRequest.objects.filter(invitee=request.user, team=team).delete()
        messages.success(request, _('Joined team {name}').format(name=team.name))
        return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,)))
    elif TeamRequest.objects.filter(invitee=request.user, team=team).exists():
        return HttpResponseBadRequest(_('User already has a membership request with the team'))
    else:
        TeamRequest.objects.create(invitee=request.user, team=team)
        if team.owner:
            notify.send(request.user, recipient=team.owner, actor=request.user, verb='request_membership', target=team)
        messages.success(request, _('Requested invitation to team {name}').format(name=team.name))
        return HttpResponseRedirect(reverse('openach:view_team', args=(team.id,))) 
Example 12
Project: browserscope   Author: elsigh   File: util.py    License: Apache License 2.0 6 votes vote down vote up
def GvizTableData(request):
    """Returns a string formatted for consumption by a Google Viz table."""
    #def throw_deadline():
    #    logging.info('MANUAL THROW!! DeadlineExceededError DeadlineExceededError')
    #    raise DeadlineExceededError
    #t = Timer(15.0, throw_deadline)

    test_set = None
    category = request.GET.get('category')
    if not category:
        return http.HttpResponseBadRequest('Must pass category=something')

    test_set = all_test_sets.GetTestSet(category)
    if not test_set:
        return http.HttpResponseBadRequest(
            'No test set was found for category=%s' % category)

    formatted_gviz_table_data = GetStats(request, test_set, 'gviz_table_data')
    return http.HttpResponse(formatted_gviz_table_data) 
Example 13
Project: GTDWeb   Author: lanbing510   File: defaults.py    License: GNU General Public License v2.0 6 votes vote down vote up
def bad_request(request, template_name='400.html'):
    """
    400 error handler.

    Templates: :template:`400.html`
    Context: None
    """
    try:
        template = loader.get_template(template_name)
    except TemplateDoesNotExist:
        return http.HttpResponseBadRequest('<h1>Bad Request (400)</h1>', content_type='text/html')
    return http.HttpResponseBadRequest(template.render())


# This can be called when CsrfViewMiddleware.process_view has not run,
# therefore need @requires_csrf_token in case the template needs
# {% csrf_token %}. 
Example 14
Project: django-register-sample   Author: naritotakizawa   File: views.py    License: MIT License 6 votes vote down vote up
def get(self, request, **kwargs):
        token = kwargs.get('token')
        try:
            new_email = loads(token, max_age=self.timeout_seconds)

        # 期限切れ
        except SignatureExpired:
            return HttpResponseBadRequest()

        # tokenが間違っている
        except BadSignature:
            return HttpResponseBadRequest()

        # tokenは問題なし
        else:
            User.objects.filter(email=new_email, is_active=False).delete()
            request.user.email = new_email
            request.user.save()
            return super().get(request, **kwargs) 
Example 15
Project: anytask   Author: znick   File: views.py    License: MIT License 6 votes vote down vote up
def check_user(request):
    ya_login = request.GET.get('ya_login')
    if not ya_login:
        return HttpResponseBadRequest()

    try:
        profile = UserProfile.objects.select_related('user').get(ya_passport_login=ya_login)
    except UserProfile.DoesNotExist:
        return HttpResponseNotFound('No profile found')

    user = profile.user

    return HttpResponse(json.dumps({
        'id': user.id,
        'ya_passport_login': ya_login,
        'active': user.is_active,
        'is_staff': user.is_staff or user.is_superuser,
        'is_teacher': user.course_teachers_set.exists(),
    }), content_type="application/json") 
Example 16
Project: silverstrike   Author: agstrike   File: api.py    License: MIT License 6 votes vote down vote up
def get_balances(request, dstart, dend):
    try:
        dstart = datetime.datetime.strptime(dstart, '%Y-%m-%d').date()
        dend = datetime.datetime.strptime(dend, '%Y-%m-%d').date()
    except ValueError:
        return HttpResponseBadRequest(_('Invalid date format, expected yyyy-mm-dd'))
    balance = Split.objects.personal().exclude_transfers().filter(date__lt=dstart).aggregate(
            models.Sum('amount'))['amount__sum'] or 0
    splits = Split.objects.personal().exclude_transfers().date_range(dstart, dend).order_by('date')
    data_points = []
    labels = []
    days = (dend - dstart).days
    if days > 50:
        step = days / 50 + 1
    else:
        step = 1
    for split in splits:
        while split.date > dstart:
            data_points.append(balance)
            labels.append(datetime.datetime.strftime(dstart, '%Y-%m-%d'))
            dstart += datetime.timedelta(days=step)
        balance += split.amount
    data_points.append(balance)
    labels.append(datetime.datetime.strftime(dend, '%Y-%m-%d'))
    return JsonResponse({'labels': labels, 'data': data_points}) 
Example 17
Project: django-webmention   Author: easy-as-python   File: views.py    License: MIT License 6 votes vote down vote up
def receive(request):
    if "source" in request.POST and "target" in request.POST:
        source = request.POST.get("source")
        target = request.POST.get("target")
        webmention = None

        if not url_resolves(target):
            return HttpResponseBadRequest("Target URL did not resolve to a resource on the server")

        try:
            try:
                webmention = WebMentionResponse.objects.get(source=source, response_to=target)
            except WebMentionResponse.DoesNotExist:
                webmention = WebMentionResponse()

            response_body = fetch_and_validate_source(source, target)
            webmention.update(source, target, response_body)
            return HttpResponse("The webmention was successfully received", status=202)
        except (SourceFetchError, TargetNotFoundError) as e:
            webmention.invalidate()
            return HttpResponseBadRequest(str(e))
        except Exception as e:
            return HttpResponseServerError(str(e))
    else:
        return HttpResponseBadRequest("webmention source and/or target not in request") 
Example 18
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def webhook(request, build_key):
    if request.method != 'POST':
        return HttpResponseNotAllowed(['POST'])

    try:
        data = json.loads(request.body)
    except ValueError:
        err_str = "Bad json in github webhook request"
        logger.warning(err_str)
        return HttpResponseBadRequest(err_str)

    user = models.GitUser.objects.filter(build_key=build_key).first()
    if not user:
        logger.warning("No user with build key %s" % build_key)
        return HttpResponseBadRequest("Error")

    if user.recipes.count() == 0:
        logger.warning("User '%s' does not have any recipes" % user)
        return HttpResponseBadRequest("Error")

    return process_event(user, data) 
Example 19
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def process_event(user, json_data):
    ret = HttpResponse('OK')
    try:
        logger.info('Webhook called:\n{}'.format(json.dumps(json_data, indent=2)))

        if 'pull_request' in json_data:
            process_pull_request(user, json_data)
        elif 'commits' in json_data:
            process_push(user, json_data)
        elif 'release' in json_data:
            process_release(user, json_data)
        elif 'zen' in json_data:
            # this is a ping that gets called when first
            # installing a hook. Just log it and move on.
            logger.info('Got ping for user {}'.format(user.name))
        else:
            err_str = 'Unknown post to github hook'
            logger.warning(err_str)
            ret = HttpResponseBadRequest(err_str)
    except Exception:
        err_str ="Invalid call to github/webhook for user %s. Error: %s" % (user, traceback.format_exc())
        logger.warning(err_str)
        ret = HttpResponseBadRequest(err_str)
    return ret 
Example 20
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def process_event(user, json_data):
    ret = HttpResponse('OK')
    try:
        logger.info('Webhook called:\n{}'.format(json.dumps(json_data, indent=2)))
        object_kind = json_data.get("object_kind")
        if object_kind == 'merge_request':
            process_pull_request(user, json_data)
        elif object_kind == "push":
            if json_data.get("commits"):
                process_push(user, json_data)
        else:
            err_str = 'Unknown post to gitlab hook'
            logger.warning(err_str)
            ret = HttpResponseBadRequest(err_str)
    except Exception:
        err_str = "Invalid call to gitlab/webhook for user %s. Error: %s" % (user, traceback.format_exc())
        logger.warning(err_str)
        ret = HttpResponseBadRequest(err_str)
    return ret 
Example 21
Project: civet   Author: idaholab   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def check_job_finished_post(request, build_key, client_name, job_id):
    data, response = check_post(request, ['seconds', 'complete'])

    if response:
        return response, None, None, None

    try:
        client = models.Client.objects.get(name=client_name, ip=get_client_ip(request))
    except models.Client.DoesNotExist:
        return HttpResponseBadRequest('Invalid client'), None, None, None

    try:
        job = models.Job.objects.get(pk=job_id, client=client, event__build_user__build_key=build_key)
    except models.Job.DoesNotExist:
        return HttpResponseBadRequest('Invalid job/build_key'), None, None, None

    return None, data, client, job 
Example 22
Project: django-payfast   Author: PiDelport   File: views.py    License: MIT License 5 votes vote down vote up
def notify_handler(request):
    """
    Notify URL handler.

    On successful access 'payfast.signals.notify' signal is sent.
    Orders should be processed in signal handler.
    """
    m_payment_id = request.POST.get('m_payment_id', None)
    order = get_object_or_404(PayFastOrder, m_payment_id=m_payment_id)

    form = NotifyForm(request, request.POST, instance=order)
    if not form.is_valid():
        errors = form.plain_errors()[:255]
        order.request_ip = form.ip
        order.debug_info = errors
        order.trusted = False
        order.save()

        # XXX: Any possible data leakage here?
        return HttpResponseBadRequest(
            content_type='application/json',
            content=form.errors.as_json(),
        )

    order = form.save()
    signals.notify.send(sender=notify_handler, order=order)
    return HttpResponse() 
Example 23
Project: raveberry   Author: raveberry   File: musiq.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def request_music(self, request: WSGIRequest) -> HttpResponse:
        """Endpoint to request music. Calls internal function."""
        key = request.POST.get("key")
        query = request.POST.get("query")
        playlist = request.POST.get("playlist") == "true"
        platform = request.POST.get("platform")

        if query is None or not platform:
            return HttpResponseBadRequest(
                "query, playlist and platform have to be specified."
            )
        ikey = None
        if key:
            ikey = int(key)

        # only get ip on user requests
        if self.base.settings.basic.logging_enabled:
            request_ip, _ = ipware.get_client_ip(request)
            if request_ip is None:
                request_ip = ""
        else:
            request_ip = ""

        successful, message, queue_key = self.do_request_music(
            request_ip, query, ikey, playlist, platform
        )
        if not successful:
            return HttpResponseBadRequest(message)
        return JsonResponse({"message": message, "key": queue_key}) 
Example 24
Project: raveberry   Author: raveberry   File: base.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def submit_hashtag(cls, request: WSGIRequest) -> HttpResponse:
        """Add the given hashtag to the database."""
        hashtag = request.POST.get("hashtag")
        if hashtag is None or len(hashtag) == 0:
            return HttpResponseBadRequest()

        if hashtag[0] != "#":
            hashtag = "#" + hashtag
        models.Tag.objects.create(text=hashtag)

        return HttpResponse() 
Example 25
Project: raveberry   Author: raveberry   File: wifi.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def connect_to_wifi(self, request: WSGIRequest) -> HttpResponse:
        """Connect to a given ssid with the given password."""
        ssid = request.POST.get("ssid")
        password = request.POST.get("password")
        if ssid is None or password is None or ssid == "" or password == "":
            return HttpResponseBadRequest("Please provide both SSID and password")
        try:
            output = subprocess.check_output(
                ["sudo", "/usr/local/sbin/raveberry/connect_to_wifi", ssid, password]
            ).decode()
            return HttpResponse(output)
        except subprocess.CalledProcessError as e:
            output = e.output.decode()
            return HttpResponseBadRequest(output) 
Example 26
Project: raveberry   Author: raveberry   File: wifi.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_homewifi_ssid(self, request: WSGIRequest) -> HttpResponse:
        """Set the home network.
        The hotspot will not be created if connected to this wifi."""
        homewifi_ssid = request.POST.get("homewifi_ssid")
        if homewifi_ssid is None:
            return HttpResponseBadRequest("homewifi ssid was not supplied.")
        with open(os.path.join(settings.BASE_DIR, "config/homewifi"), "w+") as f:
            f.write(homewifi_ssid)
        return HttpResponse() 
Example 27
Project: raveberry   Author: raveberry   File: library.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def create_playlists(self, _request: WSGIRequest) -> HttpResponse:
        """Create a playlist for every folder in the library."""
        library_link = os.path.join(settings.SONGS_CACHE_DIR, "local_library")
        if not os.path.islink(library_link):
            return HttpResponseBadRequest("No library set")

        self.scan_progress = f"0 / 0 / 0"
        self.base.settings.update_state()

        self._create_playlists()

        return HttpResponse(f"started creating playlsts. This could take a while") 
Example 28
Project: raveberry   Author: raveberry   File: platforms.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_spotify_credentials(self, request: WSGIRequest) -> HttpResponse:
        """Update spotify credentials."""
        username = request.POST.get("username")
        password = request.POST.get("password")
        client_id = request.POST.get("client_id")
        client_secret = request.POST.get("client_secret")

        if not username or not password or not client_id or not client_secret:
            return HttpResponseBadRequest("All fields are required")

        self.spotify_username = username
        self.spotify_password = password
        self.spotify_client_id = client_id
        self.spotify_client_secret = client_secret

        Setting.objects.filter(key="spotify_username").update(
            value=self.spotify_username
        )
        Setting.objects.filter(key="spotify_password").update(
            value=self.spotify_password
        )
        Setting.objects.filter(key="spotify_client_id").update(
            value=self.spotify_client_id
        )
        Setting.objects.filter(key="spotify_client_secret").update(
            value=self.spotify_client_secret
        )

        self.base.settings.system.update_mopidy_config()
        return HttpResponse("Updated credentials") 
Example 29
Project: raveberry   Author: raveberry   File: platforms.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_soundcloud_credentials(self, request: WSGIRequest) -> HttpResponse:
        """Update soundcloud credentials."""
        auth_token = request.POST.get("auth_token")

        if not auth_token:
            return HttpResponseBadRequest("All fields are required")

        self.soundcloud_auth_token = auth_token

        Setting.objects.filter(key="soundcloud_auth_token").update(
            value=self.soundcloud_auth_token
        )

        self.base.settings.system.update_mopidy_config()
        return HttpResponse("Updated credentials") 
Example 30
Project: raveberry   Author: raveberry   File: sound.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_bluetooth_scanning(self, request: WSGIRequest) -> HttpResponse:
        """Enables scanning of bluetooth devices."""
        enabled = request.POST.get("value") == "true"
        if enabled:
            if self.bluetoothctl is not None:
                return HttpResponseBadRequest("Already Scanning")
            self.bluetooth_devices = []
            self.bluetoothctl = subprocess.Popen(
                ["bluetoothctl"], stdin=subprocess.PIPE, stdout=subprocess.PIPE
            )
            assert self.bluetoothctl.stdin

            self.bluetoothctl.stdin.write(b"devices\n")
            self.bluetoothctl.stdin.write(b"scan on\n")
            self.bluetoothctl.stdin.flush()
            while True:
                line = self._get_bluetoothctl_line()
                if not line:
                    break
                # match old devices
                match = re.match(r"Device (\S*) (.*)", line)
                # match newly scanned devices
                # We need the '.*' at the beginning of the line to account for control sequences
                if not match:
                    match = re.match(r".*\[NEW\] Device (\S*) (.*)", line)
                if match:
                    address = match.group(1)
                    name = match.group(2)
                    # filter unnamed devices
                    # devices named after their address are no speakers
                    if re.match("[A-Z0-9][A-Z0-9](-[A-Z0-9][A-Z0-9]){5}", name):
                        continue
                    self.bluetooth_devices.append({"address": address, "name": name})
                    self.base.settings.update_state()
        else:
            if self.bluetoothctl is None:
                return HttpResponseBadRequest("Currently not scanning")
            self._stop_bluetoothctl()
        return HttpResponse()