<?php
ini_set('error_reporting', E_ALL);
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);


$url = urldecode($_SERVER['REQUEST_URI']);

if ($url[0] . $url[1] . $url[2] . $url[3] . $url[4] == '/mp3/') {


$id = explode('.mp3',explode('mp3/',$url)[1])[0];
$mp3_file = 'mp3/'.$id.'.mp3';


    if (!file_exists($mp3_file) or filesize($mp3_file)<100) {

        $api_key = 'f1cdc046dae52ddd3a6af3ee30212b20';
        $url = 'https://www.ru-music.com/song/' . $id;


        $head = array_change_key_case(get_headers($url, TRUE));

        if(isset($head['location'])) {
            $url = 'https://www.ru-music.com'.$head['location'];
        }
        $id_hash =  @file_get_contents($url);
        $id = explode('||',$id_hash)[0];
        $hash = explode('||',$id_hash)[1];

        //var_dump($http_response_header);


        $api = file_get_contents('http://185.162.92.71/api.php?method=get.audio&ids=' . $id . '&hash='.$hash.'&key=' . $api_key);
        $api = json_decode($api);
        $mp3 = $api[0][2];


        if (!empty($mp3)) {

            file_put_contents($mp3_file, file_get_contents($mp3));
            header("Location:/".$mp3_file);
            die();
        }


        die();
    }
}
