Python django.core.handlers.wsgi.WSGIRequest() Examples

The following are 30 code examples of django.core.handlers.wsgi.WSGIRequest(). 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 also want to check out all available functions/classes of the module django.core.handlers.wsgi , or try the search function .
Example #1
Source File: suggestions.py    From raveberry with 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 #2
Source File: system.py    From raveberry with 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 #3
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def reorder(self, request: WSGIRequest) -> HttpResponse:
        """Reorders the queue.
        The song specified by element is inserted between prev and next."""
        prev_key = request.POST.get("prev")
        cur_key = request.POST.get("element")
        next_key = request.POST.get("next")
        if not cur_key:
            return HttpResponseBadRequest()
        if not prev_key:
            iprev_key = None
        else:
            iprev_key = int(prev_key)
        icur_key = int(cur_key)
        if not next_key:
            inext_key = None
        else:
            inext_key = int(next_key)
        try:
            self.playback.queue.reorder(iprev_key, icur_key, inext_key)
        except ValueError:
            return HttpResponseBadRequest("request on old state")
        return HttpResponse() 
Example #4
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def remove(self, request: WSGIRequest) -> HttpResponse:
        """Removes a song identified by the given key from the queue."""
        key = request.POST.get("key")
        if key is None:
            return HttpResponseBadRequest()
        ikey = int(key)
        try:
            removed = self.playback.queue.remove(ikey)
            self.playback.queue_semaphore.acquire(blocking=False)
            # if we removed a song and it was added by autoplay,
            # we want it to be the new basis for autoplay
            if not removed.manually_requested:
                self.playback.handle_autoplay(removed.external_url or removed.title)
            else:
                self.playback.handle_autoplay()
        except models.QueuedSong.DoesNotExist:
            return HttpResponseBadRequest("song does not exist")
        return HttpResponse() 
Example #5
Source File: sound.py    From raveberry with 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 #6
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def set_volume(self, request: WSGIRequest) -> None:
        """Sets the playback volume.
        value has to be a float between 0 and 1."""
        self.volume = float(request.POST.get("value"))  # type: ignore
        try:
            # Try to set the volume via the pulse server.
            # This is faster and does not impact visualization
            subprocess.run(
                f"pactl set-sink-volume @DEFAULT_SINK@ {round(self.volume*100)}%".split(),
                env={"PULSE_SERVER": "127.0.0.1"},
                check=True,
            )
        except (FileNotFoundError, subprocess.CalledProcessError):
            # pulse is not installed or there is no server running.
            # change mopidy's volume
            with self.playback.mopidy_command() as allowed:
                if allowed:
                    self.playback.player.mixer.set_volume(round(self.volume * 100)) 
Example #7
Source File: library.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def scan_library(self, request: WSGIRequest) -> HttpResponse:
        """Scan the folder at the given path and add all its sound files to the database."""
        library_path = request.POST.get("library_path")
        if library_path is None:
            return HttpResponseBadRequest("library path was not supplied.")

        if not os.path.isdir(library_path):
            return HttpResponseBadRequest("not a directory")
        library_path = os.path.abspath(library_path)

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

        self._scan_library(library_path)

        return HttpResponse(
            f"started scanning in {library_path}. This could take a while"
        ) 
Example #8
Source File: system.py    From raveberry with 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 #9
Source File: system.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def upgrade_raveberry(self, _request: WSGIRequest) -> HttpResponse:
        """Performs an upgrade of raveberry."""

        @background_thread
        def do_upgrade() -> None:
            subprocess.call(
                [
                    "sudo",
                    "/usr/local/sbin/raveberry/upgrade_raveberry",
                    os.path.join(settings.BASE_DIR, "config/raveberry.ini"),
                ]
            )

        do_upgrade()

        return HttpResponse("Upgrading... Look for logs in /var/www/") 
Example #10
Source File: settings.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def option(
        func: Callable[[T, WSGIRequest], Optional[HttpResponse]]
    ) -> Callable[[T, WSGIRequest], HttpResponse]:
        """A decorator that makes sure that only the admin changes a setting."""

        def _decorator(self: T, request: WSGIRequest) -> HttpResponse:
            # don't allow option changes during alarm
            if request.user.username != "admin":
                return HttpResponseForbidden()
            response = func(self, request)
            self.base.settings.update_state()
            if response is not None:
                return response
            return HttpResponse()

        return wraps(func)(_decorator) 
Example #11
Source File: controller.py    From raveberry with GNU Lesser General Public License v3.0 6 votes vote down vote up
def disabled_when_voting(func: Callable) -> Callable:
    """A decorator for controls that are disabled during voting.
    Only users with appropriate privileges are still able to perform this action."""

    def _decorator(
        self: "Controller", request: WSGIRequest, *args, **kwargs
    ) -> HttpResponse:
        if (
            self.musiq.base.settings.basic.voting_system
            and not self.musiq.base.user_manager.has_controls(request.user)
        ):
            return HttpResponseForbidden()
        func(self, request, *args, **kwargs)
        self.musiq.update_state()
        return HttpResponse()

    return wraps(func)(_decorator) 
Example #12
Source File: musiq.py    From raveberry with 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 #13
Source File: musiq.py    From raveberry with 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 #14
Source File: library.py    From raveberry with 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 #15
Source File: platforms.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_spotify_suggestions(self, request: WSGIRequest):
        """Sets the number of online suggestions from spotify to be shown."""
        value = int(request.POST.get("value"))  # type: ignore
        Setting.objects.filter(key="spotify_suggestions").update(value=value)
        self.spotify_suggestions = value 
Example #16
Source File: lights.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_ring_brightness(self, request: WSGIRequest) -> None:
        """Updates the ring brightness."""
        # raises ValueError on wrong input, caught in option decorator
        value = float(request.POST.get("value"))  # type: ignore
        self.ring.brightness = value 
Example #17
Source File: lights.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_ring_monochrome(self, request: WSGIRequest) -> None:
        """Sets whether the ring should be in one color only."""
        enabled = request.POST.get("value") == "true"  # type: ignore
        self.ring.monochrome = enabled 
Example #18
Source File: lights.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_ring_program(self, request: WSGIRequest) -> None:
        """Updates the ring program."""
        program_name = request.POST.get("program")
        if not program_name:
            return
        program = self.led_programs[program_name]
        if program == self.ring_program:
            # the program doesn't change, return immediately
            return
        self._set_ring_program(program) 
Example #19
Source File: wifi.py    From raveberry with 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 #20
Source File: basic.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_online_suggestions(self, request: WSGIRequest) -> None:
        """Enables or disables the voting system based on the given value."""
        enabled = request.POST.get("value") == "true"
        Setting.objects.filter(key="online_suggestions").update(value=enabled)
        self.online_suggestions = enabled 
Example #21
Source File: basic.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_logging_enabled(self, request: WSGIRequest) -> None:
        """Enables or disables logging of requests and play logs based on the given value."""
        enabled = request.POST.get("value") == "true"
        Setting.objects.filter(key="logging_enabled").update(value=enabled)
        self.logging_enabled = enabled 
Example #22
Source File: basic.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_voting_system(self, request: WSGIRequest) -> None:
        """Enables or disables the voting system based on the given value."""
        enabled = request.POST.get("value") == "true"
        Setting.objects.filter(key="voting_system").update(value=enabled)
        self.voting_system = enabled 
Example #23
Source File: platforms.py    From raveberry with 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 #24
Source File: platforms.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_soundcloud_suggestions(self, request: WSGIRequest):
        """Sets the number of online suggestions from soundcloud to be shown."""
        value = int(request.POST.get("value"))  # type: ignore
        Setting.objects.filter(key="soundcloud_suggestions").update(value=value)
        self.soundcloud_suggestions = value 
Example #25
Source File: platforms.py    From raveberry with 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 #26
Source File: platforms.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_spotify_enabled(self, request: WSGIRequest) -> HttpResponse:
        """Enables or disables spotify to be used as a song provider.
        Makes sure mopidy has correct spotify configuration."""
        enabled = request.POST.get("value") == "true"
        return self._set_extension_enabled("spotify", enabled) 
Example #27
Source File: lights.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_fixed_color(self, request: WSGIRequest) -> None:
        """Updates the static color used for some programs."""
        hex_col = request.POST.get("value").lstrip("#")  # type: ignore
        # raises IndexError on wrong input, caught in option decorator
        color = tuple(int(hex_col[i : i + 2], 16) / 255 for i in (0, 2, 4))
        # https://github.com/python/mypy/issues/5068
        color = cast(Tuple[float, float, float], color)
        self.fixed_color = color 
Example #28
Source File: platforms.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_youtube_suggestions(self, request: WSGIRequest):
        """Sets the number of online suggestions from youtube to be shown."""
        value = int(request.POST.get("value"))  # type: ignore
        Setting.objects.filter(key="youtube_suggestions").update(value=value)
        self.youtube_suggestions = value 
Example #29
Source File: platforms.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_youtube_enabled(self, request: WSGIRequest):
        """Enables or disables youtube to be used as a song provider."""
        enabled = request.POST.get("value") == "true"
        Setting.objects.filter(key="youtube_enabled").update(value=enabled)
        self.youtube_enabled = enabled 
Example #30
Source File: settings.py    From raveberry with GNU Lesser General Public License v3.0 5 votes vote down vote up
def index(self, request: WSGIRequest) -> HttpResponse:
        """Renders the /settings page. Only admin is allowed to see this page."""
        if not self.base.user_manager.is_admin(request.user):
            raise PermissionDenied
        context = self.base.context(request)
        library_path = os.path.abspath(
            os.path.join(settings.SONGS_CACHE_DIR, "local_library")
        )
        if os.path.islink(library_path):
            context["local_library"] = os.readlink(library_path)
        else:
            context["local_library"] = "/"
        context["version"] = settings.VERSION
        return render(request, "settings.html", context)