<commit_before><?php namespace Icebreath\Modules;

use Icebreath\Module;
use Icebreath\Response;

class icecast extends Module {

    private $VERSION = "0.1.0";

    /**
     * Asks the module to handle a PUT (Create) request
     *
     * @param $view
     * @param $args
     * @return Response
     */
    protected function handlePut($view, $args)
    {
        return new Response(null, 404, "This module doesn't support this HTTP method");
    }

    /**
     * Asks the module to handle a POST (Update) request
     *
     * @param $view
     * @param $args
     * @return Response
     */
    protected function handlePost($view, $args)
    {
        return new Response(null, 404, "This module doesn't support this HTTP method");
    }

    /**
     * Asks the module to handle a DELETE (Well duh, Delete) request
     *
     * @param $view
     * @param $args
     * @return Response
     */
    protected function handleDelete($view, $args)
    {
        return new Response(null, 404, "This module doesn't support this HTTP method");
    }

    /************************************* REAL CODE ***********************************/

    /**
     * Asks the module to handle a GET (Read) request
     *
     * @param $view
     * @param $args
     * @return Response
     */
    protected function handleGet($view, $args)
    {
        if(!isset($view))
            return new Response(array(
                'message' => "Icecast module version $this->VERSION for Icebreath",
                'usage' => 'icecast/[stats]/{mount}'
            ));
        else {
            if(count($args) >= 1) {
                return $this->getStats($args[0]);
            } else {
                return $this->getStats();
            }
        }
    }

    /**
     * Generates a URL address for the Icecast server
     * using the settings defined in the modules config
     *
     * @param $uri
     * @return string
     */
    private function getServerURL($uri) {
        return "http://" .
               \Config::get("icebreath.icecast.username") . ":" . \Config::get("icebreath.icecast.password") .
               "@" . \Config::get("icebreath.icecast.hostname") . ":" . \Config::get("icebreath.icecast.port") . $uri;
    }

    /**
     * Opens a cURL connection to the URL to retrieve and
     * return the data from the address
     *
     * Throws a RuntimeException when it fails to connect
     * to the server or returns a non-OK http response code
     *
     * @param $url
     * @return mixed
     * @throws RuntimeException
     */
    private function getDataFromServer($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Icebreath/Icecast (Firefox cURL emulated)');

        $data = curl_exec($curl);
        $http_resp = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if(empty($data) || $http_resp != "200")
            throw new \RuntimeException("Failed to connect to the requested server ***MASKED***, got HTTP response code [$http_resp]");

        return curl_exec($curl);
    }

    /**
     * Gets the current nowplaying stats from Icecast server
     * and formats in JSON for easy access
     *
     * @param string $mount_point_name
     * @return Response
     */
    private function getStats($mount_point_name="")
    {
        $data = null;
        try {
            $data = $this->getDataFromServer($this->getServerURL("/admin/stats"));
        } catch(\RuntimeException $ex) {
            return new Response(null, 500, $ex->getMessage());
        }

        $data = new \SimpleXMLElement($data);

        $server_data = new ServerStruct();
        $server_data->server_version = (string)$data->server_id;
        $server_data->server_admin = (string)$data->admin;
        $server_data->server_location = \Config::get('icebreath.icecast.location');
        $server_data->server_listeners_total = (int)$data->listeners;
        $server_data->server_listeners_unique = 0;
        $server_data->server_listeners_peak = 0;
        $server_data->server_listeners_max = 0;
        $server_data->server_streams = array();

        foreach($data->source as $mount_point)
        {
            $server_data->server_listeners_peak += (int)$mount_point->listener_peak;
            if($mount_point->max_listeners == "unlimited")
                $server_data->server_listeners_max =  -1;
            else
                $server_data->server_listeners_max += (int)$mount_point->max_listeners;
            $unique_listeners = $this->getUniqueListenersOnMount((string)$mount_point["mount"]);
            $server_data->server_listeners_unique += $unique_listeners;

            $ignore_this_mount = false;
            foreach(\Config::get('icebreath.icecast.mount_point_ignore') as $id => $ignore_mount) {
                if((string)$mount_point["mount"] == $ignore_mount) {
                    $ignore_this_mount = true;
                }
            }

            if($ignore_this_mount) {
                continue;
            }

            if(!empty($mount_point_name) && str_replace('/', '', $mount_point["mount"]) != $mount_point_name)
                continue;

            if($mount_point->source_ip == null)
            {
                $stream = new StreamStruct();
                $stream->stream_online = false;
                $stream->stream_name = (string)$mount_point["mount"];
                $stream->stream_error = "Stream is offline! It has no connected source!";
                array_push($server_data->server_streams, $stream);
                continue;
            }

            $stream = new StreamStruct();
            $stream->stream_online = true;
            $stream->stream_title = (string)$mount_point->server_name;
            $stream->stream_description = (string)$mount_point->server_description;
            $stream->stream_name = (string)$mount_point["mount"];
            $stream->stream_genre = (string)$mount_point->genre;

            $stream->stream_audio_info = new AudioInfoStruct();
            $audio_info = explode(';', (string)$mount_point->audio_info);
            foreach($audio_info as $info)<commit_msg>Fix some issue with incorrect stats #30<commit_after><?php namespace Icebreath\Modules;

use Icebreath\Module;
use Icebreath\Response;

class icecast extends Module {

    private $VERSION = "0.1.0";

    /**
     * Asks the module to handle a PUT (Create) request
     *
     * @param $view
     * @param $args
     * @return Response
     */
    protected function handlePut($view, $args)
    {
        return new Response(null, 404, "This module doesn't support this HTTP method");
    }

    /**
     * Asks the module to handle a POST (Update) request
     *
     * @param $view
     * @param $args
     * @return Response
     */
    protected function handlePost($view, $args)
    {
        return new Response(null, 404, "This module doesn't support this HTTP method");
    }

    /**
     * Asks the module to handle a DELETE (Well duh, Delete) request
     *
     * @param $view
     * @param $args
     * @return Response
     */
    protected function handleDelete($view, $args)
    {
        return new Response(null, 404, "This module doesn't support this HTTP method");
    }

    /************************************* REAL CODE ***********************************/

    /**
     * Asks the module to handle a GET (Read) request
     *
     * @param $view
     * @param $args
     * @return Response
     */
    protected function handleGet($view, $args)
    {
        if(!isset($view))
            return new Response(array(
                'message' => "Icecast module version $this->VERSION for Icebreath",
                'usage' => 'icecast/[stats]/{mount}'
            ));
        else {
            if(count($args) >= 1) {
                return $this->getStats($args[0]);
            } else {
                return $this->getStats();
            }
        }
    }

    /**
     * Generates a URL address for the Icecast server
     * using the settings defined in the modules config
     *
     * @param $uri
     * @return string
     */
    private function getServerURL($uri) {
        return "http://" .
               \Config::get("icebreath.icecast.username") . ":" . \Config::get("icebreath.icecast.password") .
               "@" . \Config::get("icebreath.icecast.hostname") . ":" . \Config::get("icebreath.icecast.port") . $uri;
    }

    /**
     * Opens a cURL connection to the URL to retrieve and
     * return the data from the address
     *
     * Throws a RuntimeException when it fails to connect
     * to the server or returns a non-OK http response code
     *
     * @param $url
     * @return mixed
     * @throws RuntimeException
     */
    private function getDataFromServer($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.2) Icebreath/Icecast (Firefox cURL emulated)');

        $data = curl_exec($curl);
        $http_resp = curl_getinfo($curl, CURLINFO_HTTP_CODE);

        if(empty($data) || $http_resp != "200")
            throw new \RuntimeException("Failed to connect to the requested server ***MASKED***, got HTTP response code [$http_resp]");

        return curl_exec($curl);
    }

    /**
     * Gets the current nowplaying stats from Icecast server
     * and formats in JSON for easy access
     *
     * @param string $mount_point_name
     * @return Response
     */
    private function getStats($mount_point_name="")
    {
        $data = null;
        try {
            $data = $this->getDataFromServer($this->getServerURL("/admin/stats"));
        } catch(\RuntimeException $ex) {
            return new Response(null, 500, $ex->getMessage());
        }

        $data = new \SimpleXMLElement($data);

        $server_data = new ServerStruct();
        $server_data->server_version = (string)$data->server_id;
        $server_data->server_admin = (string)$data->admin;
        $server_data->server_location = \Config::get('icebreath.icecast.location');
        $server_data->server_listeners_total = (int)$data->listeners;
        $server_data->server_listeners_unique = 0;
        $server_data->server_listeners_peak = 0;
        $server_data->server_listeners_max = 0;
        $server_data->server_streams = array();

        foreach($data->source as $mount_point)
        {
 
            $ignore_this_mount = false;
            foreach(\Config::get('icebreath.icecast.mount_point_ignore') as $id => $ignore_mount) {
                if((string)$mount_point["mount"] == $ignore_mount) {
                    $ignore_this_mount = true;
                }
            }

            if($ignore_this_mount) {
                continue;
            }

            if(!empty($mount_point_name) && str_replace('/', '', $mount_point["mount"]) != $mount_point_name)
                continue;

           $server_data->server_listeners_peak += (int)$mount_point->listener_peak;
            if($mount_point->max_listeners == "unlimited")
                $server_data->server_listeners_max =  -1;
            else
                $server_data->server_listeners_max += (int)$mount_point->max_listeners;
            $unique_listeners = $this->getUniqueListenersOnMount((string)$mount_point["mount"]);
            $server_data->server_listeners_unique += $unique_listeners;

            if($mount_point->source_ip == null)
            {
                $stream = new StreamStruct();
                $stream->stream_online = false;
                $stream->stream_name = (string)$mount_point["mount"];
                $stream->stream_error = "Stream is offline! It has no connected source!";
                array_push($server_data->server_streams, $stream);
                continue;
            }

            $stream = new StreamStruct();
            $stream->stream_online = true;
            $stream->stream_title = (string)$mount_point->server_name;
            $stream->stream_description = (string)$mount_point->server_description;
            $stream->stream_name = (string)$mount_point["mount"];
            $stream->stream_genre = (string)$mount_point->genre;

            $stream->stream_audio_info = new AudioInfoStruct();
            $audio_info = explode(';', (string)$mount_point->audio_info);
            foreach($audio_info as $info)
{'fraction_non_alphanumeric': 0.13665130088288147, 'fraction_numerical': 0.005469177279474959, 'mean_word_length': 2.250380904012189, 'pattern_counts': {'":': 4, '<': 5, '<?xml version=': 0, '>': 93, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 2, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1756900', 'n_tokens_mistral': 3789, 'n_tokens_neox': 3606, 'n_words': 819}