diff --git a/Controller/LaguController.php b/Controller/LaguController.php index 4ba5f423d6a2c8253ba5739ce618601776477cea..fdb5bfbf1a9d5a2ad4afc3b0d50000173410a5b3 100644 --- a/Controller/LaguController.php +++ b/Controller/LaguController.php @@ -4,9 +4,9 @@ namespace Controller; use Exception; use Lib\Interfaces\Routing\IRequest; - use Lib\Interfaces\Routing\IResponse; - use Lib\Interfaces\Model\IDatabase; - use Lib\Enums\Model\SortOrder; +use Lib\Interfaces\Routing\IResponse; +use Lib\Interfaces\Model\IDatabase; +use Lib\Enums\Model\SortOrder; use Lib\Enums\Request\HttpStatus; use Lib\Service\Storage\LocalStorage; use Model\Relations\Album; @@ -15,645 +15,660 @@ use PDO; use Throwable; const SONG_sIZE = 10; - class LaguController { - static function getLagu(IRequest $req,IResponse $res){ - //cek session - if(!$req->auth){ - if(!isset($req->session->get_array()["occurence"])){ - $req->session->occurence = 0; - } - if(!isset($req->session->get_array()["bannedUntil"])){ - $req->session->bannedUntil = date("Y/m/d",0); - } - if(date('Y/m/d') >= $req->session->bannedUntil && $req->session->occurence>3){ - $req->session->occurence = 0; - $req->session->bannedUntil = date("Y/m/d",0); - } - // echo $req->session->occurence ; - $req->session->occurence +=1; - if($req->session->occurence>3) { - $req->session->bannedUntil = date("Y/m/d",strtotime(date('Y/m/d'). ' +1 day')); - $res->redirect("/",403); - } +class LaguController +{ + static function getLagu(IRequest $req, IResponse $res) + { + //cek session + if (!$req->auth) { + if (!isset($req->session->get_array()["occurence"])) { + $req->session->occurence = 0; } - - - $idLagu = $req->getParam("/lagu/:id","id"); - $lagu_db = new Song($req->db); - $transaction = $lagu_db->transaction(); - $lagu = $transaction->select(["*"])->where("song_id =?",[$idLagu])->all(); - //print_r($lagu); - if(count($lagu)===0){ - return LaguController::searchLagu($req,$res); + if (!isset($req->session->get_array()["bannedUntil"])) { + $req->session->bannedUntil = date("Y/m/d", 0); + } + if (date('Y/m/d') >= $req->session->bannedUntil && $req->session->occurence > 3) { + $req->session->occurence = 0; + $req->session->bannedUntil = date("Y/m/d", 0); + } + // echo $req->session->occurence ; + $req->session->occurence += 1; + if ($req->session->occurence > 3) { + $req->session->bannedUntil = date("Y/m/d", strtotime(date('Y/m/d') . ' +1 day')); + $res->redirect("/", 403); } - //cek type audio - $subTitle = explode('.',$lagu[0]["audio_path"]); - $type = "audio/".$subTitle[count($subTitle)-1]; - //proses release date - $date = LaguController::formatDate($lagu[0]["release_date"]); - //proses durasi - $duration = LaguController::formatDuration($lagu[0]["duration"]); - - return $res->view("Pages/Lagu", - [ - "id"=> $idLagu, - "image_path"=> $lagu[0]["image_path"], - "title"=>$lagu[0]["title"], - "singer_name"=>$lagu[0]["singer_name"], - "audio_path"=>$lagu[0]["audio_path"], - "sound_type"=>$type, - "release_date"=>$date, - "genre"=>$lagu[0]["genre"], - "duration"=>$duration, - "auth"=>$req->auth, - "date"=>$lagu[0]["release_date"] - ] - ); } - - static function formatDate(string $date):string{ - $dates = explode('-',$date); - $day = $dates[2]; - $year = $dates[0]; - $month = match($dates[1]){ - "01"=>"Januari", - "02"=>"Februari", - "03"=>"Maret", - "04"=>"April", - "05"=>"Mei", - "06"=>"Juni", - "07"=>"Juli", - "08"=>"Agustus", - "09"=>"September", - "10"=>"Oktober", - "11"=>"November", - "12"=>"Desember" - }; - return $day . " ". $month. " ". $year; + + + $idLagu = $req->getParam("/lagu/:id", "id"); + $lagu_db = new Song($req->db); + $transaction = $lagu_db->transaction(); + $lagu = $transaction->select(["*"])->where("song_id =?", [$idLagu])->all(); + //print_r($lagu); + if (count($lagu) === 0) { + return LaguController::searchLagu($req, $res); } + //cek type audio + $subTitle = explode('.', $lagu[0]["audio_path"]); + $type = "audio/" . $subTitle[count($subTitle) - 1]; + //proses release date + $date = LaguController::formatDate($lagu[0]["release_date"]); + //proses durasi + $duration = LaguController::formatDuration($lagu[0]["duration"]); - static function formatDuration(int $duration):string{ - $jam = 0; - $menit= 0; - $detik = 0; - $strJam = ""; - if($duration>=3600){ - $jam = floor($duration/3600); - if($jam<10){ - $jam = "0".$jam; - } - if($jam>0){ - $strJam = $jam.":"; - } - } - //echo $strJam; - $duration = $duration %3600; - if($duration>=60){ - $menit = floor($duration/60); - if($menit<10){ - $menit = "0".$menit; - } - $strJam = $strJam . $menit.":"; + return $res->view( + "Pages/Lagu", + [ + "id" => $idLagu, + "image_path" => $lagu[0]["image_path"], + "title" => $lagu[0]["title"], + "singer_name" => $lagu[0]["singer_name"], + "audio_path" => $lagu[0]["audio_path"], + "sound_type" => $type, + "release_date" => $date, + "genre" => $lagu[0]["genre"], + "duration" => $duration, + "auth" => $req->auth, + "date" => $lagu[0]["release_date"] + ] + ); + } + + static function formatDate(string $date): string + { + $dates = explode('-', $date); + $day = $dates[2]; + $year = $dates[0]; + $month = match ($dates[1]) { + "01" => "Januari", + "02" => "Februari", + "03" => "Maret", + "04" => "April", + "05" => "Mei", + "06" => "Juni", + "07" => "Juli", + "08" => "Agustus", + "09" => "September", + "10" => "Oktober", + "11" => "November", + "12" => "Desember" + }; + return $day . " " . $month . " " . $year; + } + + static function formatDuration(int $duration): string + { + $jam = 0; + $menit = 0; + $detik = 0; + $strJam = ""; + if ($duration >= 3600) { + $jam = floor($duration / 3600); + if ($jam < 10) { + $jam = "0" . $jam; } - $detik = $duration % 60; - //echo $strJam; - if($detik<10){ - $detik = "0".$detik; + if ($jam > 0) { + $strJam = $jam . ":"; } - if($detik>=0){ - $strJam = $strJam . $detik; + } + //echo $strJam; + $duration = $duration % 3600; + if ($duration >= 60) { + $menit = floor($duration / 60); + if ($menit < 10) { + $menit = "0" . $menit; } - return $strJam; + $strJam = $strJam . $menit . ":"; } + $detik = $duration % 60; + //echo $strJam; + if ($detik < 10) { + $detik = "0" . $detik; + } + if ($detik >= 0) { + $strJam = $strJam . $detik; + } + return $strJam; + } + + static function redirectSearchLagu(IRequest $req, IResponse $res) + { + $sortType = $req->getQuery("sortsType") !== null ? $req->getQuery("sortsType") : "titleASC"; + $genre = $req->getQuery("filteredGenre") !== null ? $req->getQuery("filteredGenre") : "nofilter"; + $filteredGenre = strtolower($genre); + $queryString = strtolower($req->getQuery("q")); + return $res->redirect("/search?sortsType=$sortType&q=$queryString+&filteredGenre=$filteredGenre"); + } - static function redirectSearchLagu(IRequest $req, IResponse $res){ - $sortType = $req->getQuery("sortsType")!==null?$req->getQuery("sortsType"):"titleASC"; - $genre = $req->getQuery("filteredGenre")!==null?$req->getQuery("filteredGenre"):"nofilter"; - $filteredGenre = strtolower($genre); - $queryString = strtolower($req->getQuery("q")); - return $res->redirect("/search?sortsType=$sortType&q=$queryString+&filteredGenre=$filteredGenre"); + static function searchLagu(IRequest $req, IResponse $res) + { + $lagu_db = new Song($req->db); + $transaction = $lagu_db->transaction(); + $sortType = $req->getQuery("sortsType") !== null ? $req->getQuery("sortsType") : "titleASC"; + $genre = $req->getQuery("filteredGenre") !== null ? $req->getQuery("filteredGenre") : "nofilter"; + $filteredGenre = strtolower($genre); + $lagu = $transaction->select(["*"]); + $queryString = strtolower($req->getQuery("q")) ?? ""; + if ($req->getHeader("accept") === "text/html") { + $res->setHeader("content-type", "text/html"); + return $res->redirect("/search?sortsType=$sortType&q=$queryString+&filteredGenre=$filteredGenre"); } - static function searchLagu(IRequest $req,IResponse $res){ - $lagu_db = new Song($req->db); - $transaction = $lagu_db->transaction(); - $sortType = $req->getQuery("sortsType")!==null?$req->getQuery("sortsType"):"titleASC"; - $genre = $req->getQuery("filteredGenre")!==null?$req->getQuery("filteredGenre"):"nofilter"; - $filteredGenre = strtolower($genre); - $lagu = $transaction->select(["*"]); - $queryString = strtolower($req->getQuery("q")) ??""; - if($req->getHeader("accept")==="text/html"){ - $res->setHeader("content-type","text/html"); - return $res->redirect("/search?sortsType=$sortType&q=$queryString+&filteredGenre=$filteredGenre"); - } - - if(!is_null($queryString) && strlen($queryString)>0){ - if(is_numeric($queryString)){ - $lagu->where("LOWER(title) LIKE ? OR + if (!is_null($queryString) && strlen($queryString) > 0) { + if (is_numeric($queryString)) { + $lagu->where( + "LOWER(title) LIKE ? OR EXTRACT(year FROM release_date) = ? OR LOWER(singer_name) LIKE ?", - ["%".$queryString."%" ,$queryString,"%".$queryString."%"]); - } - else{ - $lagu->where("LOWER(title) LIKE ? OR + ["%" . $queryString . "%", $queryString, "%" . $queryString . "%"] + ); + } else { + $lagu->where( + "LOWER(title) LIKE ? OR LOWER(singer_name) LIKE ?", - ["%".$queryString."%" , "%".$queryString."%"]); - } - } - else{ - $queryString = ""; - } - if(!is_null($filteredGenre) && $filteredGenre!=="nofilter"){ - $lagu->where("LOWER(genre) = ?",[$filteredGenre]); - } - if($sortType===NULL){ - $sortType = "titleASC"; - } - match($sortType){ - "titleASC"=>$lagu->sortBy("title",SortOrder::Ascending), - "titleDSC"=>$lagu->sortBy("title",SortOrder::Descending), - "yearOLD"=>$lagu->sortBy("release_date",SortOrder::Ascending), - "yearNEW"=>$lagu->sortBy("release_date",SortOrder::Descending), - }; - - //dapetin list genre - $genreList = $transaction->select(["DISTINCT genre"])->all(); - - $page = $req->getQuery("page") ?? 1; - - if (!is_numeric($page)) { - return $res->redirect("/"); + ["%" . $queryString . "%", "%" . $queryString . "%"] + ); } - + } else { + $queryString = ""; + } + if (!is_null($filteredGenre) && $filteredGenre !== "nofilter") { + $lagu->where("LOWER(genre) = ?", [$filteredGenre]); + } + if ($sortType === NULL) { + $sortType = "titleASC"; + } + match ($sortType) { + "titleASC" => $lagu->sortBy("title", SortOrder::Ascending), + "titleDSC" => $lagu->sortBy("title", SortOrder::Descending), + "yearOLD" => $lagu->sortBy("release_date", SortOrder::Ascending), + "yearNEW" => $lagu->sortBy("release_date", SortOrder::Descending), + }; - $hasil_ = $lagu->all(); - // print_r($hasil_); + //dapetin list genre + $genreList = $transaction->select(["DISTINCT genre"])->all(); + + $page = $req->getQuery("page") ?? 1; + + if (!is_numeric($page)) { + return $res->redirect("/"); + } + + + $hasil_ = $lagu->all(); + // print_r($hasil_); //$hasil = $lagu->all(); $total = count($hasil_); $total_page = ceil($total / SONG_sIZE); - $hasil = $lagu->paginate(SONG_sIZE,$page - 1)->all(); - + $hasil = $lagu->paginate(SONG_sIZE, $page - 1)->all(); + if ($page < 1) { - return $res->redirect("/"); + return $res->redirect("/"); } - + if ($page > $total_page) { - if($total_page>0){ - return $res->redirect("/search?sortsType=$sortType&q=$queryString&filteredGenre=$filteredGenre&page=1"); - } - else{ - return $res->view("Pages/SearchLagu", - [ "songs" =>[], - "sortsType"=>$sortType, - "query"=> $queryString, - "auth"=>$req->auth, - "selectedGenre" => $filteredGenre, - "genreList"=>$genreList, - "page" => $page, - "next_page" => null, - "prev_page" => null, - ]); - } + if ($total_page > 0) { + return $res->redirect("/search?sortsType=$sortType&q=$queryString&filteredGenre=$filteredGenre&page=1"); + } else { + return $res->view( + "Pages/SearchLagu", + [ + "songs" => [], + "sortsType" => $sortType, + "query" => $queryString, + "auth" => $req->auth, + "selectedGenre" => $filteredGenre, + "genreList" => $genreList, + "page" => $page, + "next_page" => null, + "prev_page" => null, + ] + ); + } + } + + $transaction->commit(); + if ($req->getHeader("accept") === "application/json") { + $res->setHeader("content-type", "application/json"); + return $res->json(["hasil" => $hasil, "page" => $page, "total_page" => $total_page]); + } + // print_r($hasil); + // print_r($total_page); + // print_r($filteredGenre); + return $res->view( + "Pages/SearchLagu", + [ + "songs" => $hasil, + "sortsType" => $sortType, + "query" => $queryString, + "auth" => $req->auth, + "selectedGenre" => $filteredGenre, + "genreList" => $genreList, + "page" => $page, + "next_page" => $page < $total_page ? $page + 1 : null, + "prev_page" => $page > 1 ? $page - 1 : null, + ] + ); + } + static function addLagu(IRequest $req, IResponse $res) + { + $lagu_db = new Song($req->db); + $transaction = $lagu_db->transaction(); + //dapetin data + $formData = $req->formData(); + // print_r($formData); + //datanya + $title = $formData["title"]; + $release_date = $formData["release_date"]; + $singer_name = $formData["singer_name"]; + $genre = $formData["genre"]; + //proses file + //lagu + $target_path_audio = "/"; + $target_dir = "audio/"; + $file = $formData["file_lagu"]["name"]; + $path = pathinfo($file); + $filename = $path['filename']; + $ext = $path['extension']; + $target_path_audio = $target_dir . time() . "-" . $filename . "." . $ext; + $temp_name = $formData['file_lagu']['tmp_name']; + // echo $temp_name."tawarmenawar"; + //echo $target_path; + //move_uploaded_file($temp_name,$target_path); + $storage = new LocalStorage(); + if (isset($file)) { + $storage->copy($temp_name, $target_path_audio); } - + $duration = LaguController::getDuration("/app/storage/" . $target_path_audio); + $target_path_audio = "/storage/" . $target_path_audio; + //gambar + $target_dir = "image/"; + $file = $formData["image_file"]["name"]; + $target_path_image = "/"; + if (isset($file) && strlen($file) > 0) { + $path = pathinfo($file); + $filename = $path['filename']; + $ext = $path['extension']; + $target_path_image = $target_dir . "music-" . time() . "-" . $filename . "." . $ext; + $temp_name = $formData['image_file']['tmp_name']; + $storage->copy($temp_name, $target_path_image); + $target_path_image = "/storage/" . $target_path_image; + } + //$query = $transaction->insert([]) + //insert + try { + $transaction->insert( + [ + "title" => $title, + "release_date" => $release_date, + "duration" => $duration, + "audio_path" => $target_path_audio, + "singer_name" => $singer_name ?? "", + "genre" => $genre, + "image_path" => $target_path_image + ] + ); $transaction->commit(); - if($req->getHeader("accept")==="application/json"){ - $res->setHeader("content-type","application/json"); - return $res->json(["hasil"=>$hasil,"page"=>$page,"total_page"=>$total_page]); - } - // print_r($hasil); - // print_r($total_page); - // print_r($filteredGenre); - return $res->view("Pages/SearchLagu", - [ "songs" =>$hasil, - "sortsType"=>$sortType, - "query"=> $queryString, - "auth"=>$req->auth, - "selectedGenre" => $filteredGenre, - "genreList"=>$genreList, - "page" => $page, - "next_page" => $page < $total_page ? $page + 1 : null, - "prev_page" => $page > 1 ? $page - 1 : null, - ]); - } - static function addLagu(IRequest $req, IResponse $res){ - $lagu_db = new Song($req->db); - $transaction = $lagu_db->transaction(); - //dapetin data - $formData = $req->formData(); - // print_r($formData); - //datanya - $title = $formData["title"]; - $release_date = $formData["release_date"]; - $singer_name = $formData["singer_name"]; - $genre = $formData["genre"]; - //proses file - //lagu - $target_path_audio = "/"; - $target_dir = "audio/"; - $file = $formData["file_lagu"]["name"]; + } catch (Throwable $err) { + $transaction->rollback(); + throw $err; + } + return $res->view("Pages/AddSong", [ + "auth" => $req->auth, + "added" => true + ]); + } + + static function updateLagu(IRequest $req, IResponse $res) + { + $data = $req->formData(); + //print_r($data); + $id = $data["id"]; + unset($data["id"]); + //simpan files + $storage = new LocalStorage(); + $audio = $data["audio"] ?? null; + $target_dir = "audio/"; + $file = $audio["name"] ?? null; + if (isset($file)) { $path = pathinfo($file); $filename = $path['filename']; $ext = $path['extension']; - $target_path_audio = $target_dir.time()."-".$filename.".".$ext; - $temp_name = $formData['file_lagu']['tmp_name']; - // echo $temp_name."tawarmenawar"; - //echo $target_path; - //move_uploaded_file($temp_name,$target_path); - $storage = new LocalStorage(); - if(isset($file)){ - $storage->copy($temp_name,$target_path_audio); - } - $duration = LaguController::getDuration("/app/storage/".$target_path_audio); - $target_path_audio = "/storage/".$target_path_audio; - //gambar - $target_dir = "image/"; - $file = $formData["image_file"]["name"]; - $target_path_image = "/"; - if(isset($file) && strlen($file)>0){ - $path = pathinfo($file); - $filename = $path['filename']; - $ext = $path['extension']; - $target_path_image = $target_dir."music-".time()."-".$filename.".".$ext; - $temp_name = $formData['image_file']['tmp_name']; - $storage->copy($temp_name,$target_path_image); - $target_path_image = "/storage/".$target_path_image; - } - //$query = $transaction->insert([]) - //insert - try{ - $transaction->insert( - [ - "title"=>$title, - "release_date"=>$release_date, - "duration"=>$duration, - "audio_path"=>$target_path_audio, - "singer_name"=>$singer_name ?? "", - "genre"=>$genre, - "image_path"=>$target_path_image - ] - ); - $transaction->commit(); - }catch(Throwable $err){ - $transaction->rollback(); - throw $err; - } - return $res->view("Pages/AddSong",[ - "auth"=>$req->auth, - "added"=>true - ]); + $target_path_audio = $target_dir . time() . "-" . $filename . "." . $ext; + $temp_name = $audio['tmp_name']; + $storage->copy($temp_name, $target_path_audio); + unset($data["audio"]); + $target_path_audio = "/storage/" . $target_path_audio; + $data["audio_path"] = $target_path_audio; } - static function updateLagu(IRequest $req ,IResponse $res){ - $data = $req->formData(); - //print_r($data); - $id = $data["id"]; - unset($data["id"]); - //simpan files - $storage = new LocalStorage(); - $audio = $data["audio"] ??null; - $target_dir = "audio/"; - $file = $audio["name"]?? null; - if(isset($file)){ - $path = pathinfo($file); - $filename = $path['filename']; - $ext = $path['extension']; - $target_path_audio = $target_dir.time()."-".$filename.".".$ext; - $temp_name = $audio['tmp_name']; - $storage->copy($temp_name,$target_path_audio); - unset($data["audio"]); - $target_path_audio = "/storage/".$target_path_audio; - $data["audio_path"] = $target_path_audio; - } - - //gambar - $image = $data["image"] ??null; - $target_dir = "image/"; - $file = $image["name"] ??null; - $target_path_image = "/"; - if(isset($file) && strlen($file)>0){ - - $path = pathinfo($file); - $filename = $path['filename']; - $ext = $path['extension']; - $target_path_image = $target_dir."music-".time()."-".$filename.".".$ext; - $temp_name = $image['tmp_name']; - $storage->copy($temp_name,$target_path_image); - $target_path_image = "/storage/".$target_path_image; - unset($data["image"]); - - $data["image_path"] = $target_path_image; - } - //$data["audio_path"] = $audio[""] - //print_r($data); - //ganti file - $lagu_db = new Song($req->db); - $transaction = $lagu_db->transaction(); - try{ - $paths = $transaction->select(["audio_path,image_path"])->where("song_id =?",[$id])->all()[0]; - //print_r($paths); - //hapus file - if($paths["audio_path"]!=="/" && $paths["audio_path"]!=="" && $paths["audio_path"]!==null &&$audio!==null){ - $storage->delete("/app".$paths["audio_path"]); + //gambar + $image = $data["image"] ?? null; + $target_dir = "image/"; + $file = $image["name"] ?? null; + $target_path_image = "/"; + if (isset($file) && strlen($file) > 0) { + + $path = pathinfo($file); + $filename = $path['filename']; + $ext = $path['extension']; + $target_path_image = $target_dir . "music-" . time() . "-" . $filename . "." . $ext; + $temp_name = $image['tmp_name']; + $storage->copy($temp_name, $target_path_image); + $target_path_image = "/storage/" . $target_path_image; + unset($data["image"]); + + $data["image_path"] = $target_path_image; + } + //$data["audio_path"] = $audio[""] + //print_r($data); + //ganti file + $lagu_db = new Song($req->db); + $transaction = $lagu_db->transaction(); + try { + $paths = $transaction->select(["audio_path,image_path"])->where("song_id =?", [$id])->all()[0]; + //print_r($paths); + //hapus file + if ($paths["audio_path"] !== "/" && $paths["audio_path"] !== "" && $paths["audio_path"] !== null && $audio !== null) { + $storage->delete("/app" . $paths["audio_path"]); } - if($paths["image_path"]!=="/" && $paths["image_path"]!=="" && $paths["image_path"]!==null && $image!==null){ - $storage->delete("/app".$paths["image_path"]); + if ($paths["image_path"] !== "/" && $paths["image_path"] !== "" && $paths["image_path"] !== null && $image !== null) { + $storage->delete("/app" . $paths["image_path"]); } - // print_r($data); - $transaction->update("song_id= ?",[$id],$data)->commit(); - }catch(Exception ){ + // print_r($data); + $transaction->update("song_id= ?", [$id], $data)->commit(); + } catch (Exception) { $transaction->rollback(); - } - //update data - $lagu = $transaction->select(["*"])->where("song_id =?",[$id])->all(); - //print_r($lagu); - if(count($lagu)===0){ - return LaguController::searchLagu($req,$res); - } - //cek type audio - $subTitle = explode('.',$lagu[0]["audio_path"]); - $type = "audio/".$subTitle[count($subTitle)-1]; - //proses release date - $date = LaguController::formatDate($lagu[0]["release_date"]); - - return $res->json([ - "image_path"=> $lagu[0]["image_path"], - "title"=>$lagu[0]["title"], - "audio_path"=>$lagu[0]["audio_path"], - "sound_type"=>$type, - "release_date"=>$date, - "genre"=>$lagu[0]["genre"], - "date"=>$lagu[0]["release_date"], - "status"=>"Perubahan berhasil disimpan!" - ]); } - static function hapusLagu(IRequest $req, IResponse $res){ - $lagu_db = new Song($req->db); - $transaction = $lagu_db->transaction(); - $id = $req->getParam("/lagu/delete/:id","id"); - //hapus file - $storage = new LocalStorage(); - $paths = $transaction->select(["audio_path,image_path"])->where("song_id =?",[$id])->all()[0]; - $transaction->commit(); - if($paths["audio_path"]!=="/" && $paths["audio_path"]!=="" && $paths["audio_path"]!==null){ - $storage->delete("/app".$paths["audio_path"]); - } - if($paths["image_path"]!=="/" && $paths["image_path"]!=="" && $paths["image_path"]!==null){ - $storage->delete("/app".$paths["image_path"]); - } - //hapus record - // try{ - - $transaction->delete("song_id = ?",[$id]); - // } - // catch(Exception){ - // $transaction->rollback(); - // } - - return $res->json([ - "deleted"=>true - ]); - + //update data + $lagu = $transaction->select(["*"])->where("song_id =?", [$id])->all(); + //print_r($lagu); + if (count($lagu) === 0) { + return LaguController::searchLagu($req, $res); } + //cek type audio + $subTitle = explode('.', $lagu[0]["audio_path"]); + $type = "audio/" . $subTitle[count($subTitle) - 1]; + //proses release date + $date = LaguController::formatDate($lagu[0]["release_date"]); - //credit: http://www.zedwood.com/article/php-calculate-duration-of-mp3 - static function getDuration(string $filename){ - $fd = fopen($filename, "rb"); - $duration=0; - $block = fread($fd, 100); - $offset = LaguController::skipID3v2Tag($block); - fseek($fd, $offset, SEEK_SET); - while (!feof($fd)) - { - $block = fread($fd, 10); - if (strlen($block)<10) { break; } - //looking for 1111 1111 111 (frame synchronization bits) - else if ($block[0]=="\xff" && (ord($block[1])&0xe0) ) - { - $info = self::parseFrameHeader(substr($block, 0, 4)); - if (empty($info['Framesize'])) { return $duration; } //some corrupt mp3 files - fseek($fd, $info['Framesize']-10, SEEK_CUR); - $duration += ( $info['Samples'] / $info['Sampling Rate'] ); - } - else if (substr($block, 0, 3)=='TAG') - { - fseek($fd, 128-10, SEEK_CUR);//skip over id3v1 tag size - } - else - { - fseek($fd, -9, SEEK_CUR); - } + return $res->json([ + "image_path" => $lagu[0]["image_path"], + "title" => $lagu[0]["title"], + "audio_path" => $lagu[0]["audio_path"], + "sound_type" => $type, + "release_date" => $date, + "genre" => $lagu[0]["genre"], + "date" => $lagu[0]["release_date"], + "status" => "Perubahan berhasil disimpan!" + ]); + } + static function hapusLagu(IRequest $req, IResponse $res) + { + $lagu_db = new Song($req->db); + $transaction = $lagu_db->transaction(); + $id = $req->getParam("/lagu/delete/:id", "id"); + //hapus file + $storage = new LocalStorage(); + $paths = $transaction->select(["audio_path,image_path"])->where("song_id =?", [$id])->all()[0]; + $transaction->commit(); + if ($paths["audio_path"] !== "/" && $paths["audio_path"] !== "" && $paths["audio_path"] !== null) { + $storage->delete("/app" . $paths["audio_path"]); + } + if ($paths["image_path"] !== "/" && $paths["image_path"] !== "" && $paths["image_path"] !== null) { + $storage->delete("/app" . $paths["image_path"]); + } + //hapus record + // try{ + + $transaction->delete("song_id = ?", [$id]); + // } + // catch(Exception){ + // $transaction->rollback(); + // } + + return $res->json([ + "deleted" => true + ]); + } + + //credit: http://www.zedwood.com/article/php-calculate-duration-of-mp3 + static function getDuration(string $filename) + { + $fd = fopen($filename, "rb"); + $duration = 0; + $block = fread($fd, 100); + $offset = LaguController::skipID3v2Tag($block); + fseek($fd, $offset, SEEK_SET); + while (!feof($fd)) { + $block = fread($fd, 10); + if (strlen($block) < 10) { + break; + } + //looking for 1111 1111 111 (frame synchronization bits) + else if ($block[0] == "\xff" && (ord($block[1]) & 0xe0)) { + $info = self::parseFrameHeader(substr($block, 0, 4)); + if (empty($info['Framesize'])) { + return $duration; + } //some corrupt mp3 files + fseek($fd, $info['Framesize'] - 10, SEEK_CUR); + $duration += ($info['Samples'] / $info['Sampling Rate']); + } else if (substr($block, 0, 3) == 'TAG') { + fseek($fd, 128 - 10, SEEK_CUR); //skip over id3v1 tag size + } else { + fseek($fd, -9, SEEK_CUR); } - return round($duration); } - //credit: http://www.zedwood.com/article/php-calculate-duration-of-mp3 - static function skipID3v2Tag(&$block) - { - if (substr($block, 0,3)=="ID3") - { - $id3v2_major_version = ord($block[3]); - $id3v2_minor_version = ord($block[4]); - $id3v2_flags = ord($block[5]); - $flag_unsynchronisation = $id3v2_flags & 0x80 ? 1 : 0; - $flag_extended_header = $id3v2_flags & 0x40 ? 1 : 0; - $flag_experimental_ind = $id3v2_flags & 0x20 ? 1 : 0; - $flag_footer_present = $id3v2_flags & 0x10 ? 1 : 0; - $z0 = ord($block[6]); - $z1 = ord($block[7]); - $z2 = ord($block[8]); - $z3 = ord($block[9]); - if ( (($z0&0x80)==0) && (($z1&0x80)==0) && (($z2&0x80)==0) && (($z3&0x80)==0) ) - { - $header_size = 10; - $tag_size = (($z0&0x7f) * 2097152) + (($z1&0x7f) * 16384) + (($z2&0x7f) * 128) + ($z3&0x7f); - $footer_size = $flag_footer_present ? 10 : 0; - return $header_size + $tag_size + $footer_size;//bytes to skip - } + return round($duration); + } + //credit: http://www.zedwood.com/article/php-calculate-duration-of-mp3 + static function skipID3v2Tag(&$block) + { + if (substr($block, 0, 3) == "ID3") { + $id3v2_major_version = ord($block[3]); + $id3v2_minor_version = ord($block[4]); + $id3v2_flags = ord($block[5]); + $flag_unsynchronisation = $id3v2_flags & 0x80 ? 1 : 0; + $flag_extended_header = $id3v2_flags & 0x40 ? 1 : 0; + $flag_experimental_ind = $id3v2_flags & 0x20 ? 1 : 0; + $flag_footer_present = $id3v2_flags & 0x10 ? 1 : 0; + $z0 = ord($block[6]); + $z1 = ord($block[7]); + $z2 = ord($block[8]); + $z3 = ord($block[9]); + if ((($z0 & 0x80) == 0) && (($z1 & 0x80) == 0) && (($z2 & 0x80) == 0) && (($z3 & 0x80) == 0)) { + $header_size = 10; + $tag_size = (($z0 & 0x7f) * 2097152) + (($z1 & 0x7f) * 16384) + (($z2 & 0x7f) * 128) + ($z3 & 0x7f); + $footer_size = $flag_footer_present ? 10 : 0; + return $header_size + $tag_size + $footer_size; //bytes to skip } - return 0; } + return 0; + } - //credit: http://www.zedwood.com/article/php-calculate-duration-of-mp3 - static function parseFrameHeader($fourbytes) - { - static $versions = array( - 0x0=>'2.5',0x1=>'x',0x2=>'2',0x3=>'1', // x=>'reserved' - ); - static $layers = array( - 0x0=>'x',0x1=>'3',0x2=>'2',0x3=>'1', // x=>'reserved' - ); - static $bitrates = array( - 'V1L1'=>array(0,32,64,96,128,160,192,224,256,288,320,352,384,416,448), - 'V1L2'=>array(0,32,48,56, 64, 80, 96,112,128,160,192,224,256,320,384), - 'V1L3'=>array(0,32,40,48, 56, 64, 80, 96,112,128,160,192,224,256,320), - 'V2L1'=>array(0,32,48,56, 64, 80, 96,112,128,144,160,176,192,224,256), - 'V2L2'=>array(0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160), - 'V2L3'=>array(0, 8,16,24, 32, 40, 48, 56, 64, 80, 96,112,128,144,160), - ); - static $sample_rates = array( - '1' => array(44100,48000,32000), - '2' => array(22050,24000,16000), - '2.5' => array(11025,12000, 8000), - ); - static $samples = array( - 1 => array( 1 => 384, 2 =>1152, 3 =>1152, ), //MPEGv1, Layers 1,2,3 - 2 => array( 1 => 384, 2 =>1152, 3 => 576, ), //MPEGv2/2.5, Layers 1,2,3 - ); - //$b0=ord($fourbytes[0]);//will always be 0xff - $b1=ord($fourbytes[1]); - $b2=ord($fourbytes[2]); - $b3=ord($fourbytes[3]); - - $version_bits = ($b1 & 0x18) >> 3; - $version = $versions[$version_bits]; - $simple_version = ($version=='2.5' ? 2 : $version); - - $layer_bits = ($b1 & 0x06) >> 1; - $layer = $layers[$layer_bits]; - - $protection_bit = ($b1 & 0x01); - $bitrate_key = sprintf('V%dL%d', $simple_version , $layer); - $bitrate_idx = ($b2 & 0xf0) >> 4; - $bitrate = isset($bitrates[$bitrate_key][$bitrate_idx]) ? $bitrates[$bitrate_key][$bitrate_idx] : 0; - - $sample_rate_idx = ($b2 & 0x0c) >> 2;//0xc => b1100 - $sample_rate = isset($sample_rates[$version][$sample_rate_idx]) ? $sample_rates[$version][$sample_rate_idx] : 0; - $padding_bit = ($b2 & 0x02) >> 1; - $private_bit = ($b2 & 0x01); - $channel_mode_bits = ($b3 & 0xc0) >> 6; - $mode_extension_bits = ($b3 & 0x30) >> 4; - $copyright_bit = ($b3 & 0x08) >> 3; - $original_bit = ($b3 & 0x04) >> 2; - $emphasis = ($b3 & 0x03); - - $info = array(); - $info['Version'] = $version;//MPEGVersion - $info['Layer'] = $layer; - //$info['Protection Bit'] = $protection_bit; //0=> protected by 2 byte CRC, 1=>not protected - $info['Bitrate'] = $bitrate; - $info['Sampling Rate'] = $sample_rate; - //$info['Padding Bit'] = $padding_bit; - //$info['Private Bit'] = $private_bit; - //$info['Channel Mode'] = $channel_mode_bits; - //$info['Mode Extension'] = $mode_extension_bits; - //$info['Copyright'] = $copyright_bit; - //$info['Original'] = $original_bit; - //$info['Emphasis'] = $emphasis; - $info['Framesize'] = self::framesize($layer, $bitrate, $sample_rate, $padding_bit); - $info['Samples'] = $samples[$simple_version][$layer]; - return $info; - } + //credit: http://www.zedwood.com/article/php-calculate-duration-of-mp3 + static function parseFrameHeader($fourbytes) + { + static $versions = array( + 0x0 => '2.5', 0x1 => 'x', 0x2 => '2', 0x3 => '1', // x=>'reserved' + ); + static $layers = array( + 0x0 => 'x', 0x1 => '3', 0x2 => '2', 0x3 => '1', // x=>'reserved' + ); + static $bitrates = array( + 'V1L1' => array(0, 32, 64, 96, 128, 160, 192, 224, 256, 288, 320, 352, 384, 416, 448), + 'V1L2' => array(0, 32, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, 384), + 'V1L3' => array(0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320), + 'V2L1' => array(0, 32, 48, 56, 64, 80, 96, 112, 128, 144, 160, 176, 192, 224, 256), + 'V2L2' => array(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160), + 'V2L3' => array(0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160), + ); + static $sample_rates = array( + '1' => array(44100, 48000, 32000), + '2' => array(22050, 24000, 16000), + '2.5' => array(11025, 12000, 8000), + ); + static $samples = array( + 1 => array(1 => 384, 2 => 1152, 3 => 1152,), //MPEGv1, Layers 1,2,3 + 2 => array(1 => 384, 2 => 1152, 3 => 576,), //MPEGv2/2.5, Layers 1,2,3 + ); + //$b0=ord($fourbytes[0]);//will always be 0xff + $b1 = ord($fourbytes[1]); + $b2 = ord($fourbytes[2]); + $b3 = ord($fourbytes[3]); - //credit: http://www.zedwood.com/article/php-calculate-duration-of-mp3 - static function framesize($layer, $bitrate,$sample_rate,$padding_bit) - { - if ($layer==1) - return intval(((12 * $bitrate*1000 /$sample_rate) + $padding_bit) * 4); - else //layer 2, 3 - return intval(((144 * $bitrate*1000)/$sample_rate) + $padding_bit); - } + $version_bits = ($b1 & 0x18) >> 3; + $version = $versions[$version_bits]; + $simple_version = ($version == '2.5' ? 2 : $version); - //credit: https://www.daniweb.com/programming/web-development/threads/428301/getting-video-duration-without-ffmpeg - static function multi_getDuration($file){ + $layer_bits = ($b1 & 0x06) >> 1; + $layer = $layers[$layer_bits]; - if (file_exists($file)){ - ## open and read video file + $protection_bit = ($b1 & 0x01); + $bitrate_key = sprintf('V%dL%d', $simple_version, $layer); + $bitrate_idx = ($b2 & 0xf0) >> 4; + $bitrate = isset($bitrates[$bitrate_key][$bitrate_idx]) ? $bitrates[$bitrate_key][$bitrate_idx] : 0; + + $sample_rate_idx = ($b2 & 0x0c) >> 2; //0xc => b1100 + $sample_rate = isset($sample_rates[$version][$sample_rate_idx]) ? $sample_rates[$version][$sample_rate_idx] : 0; + $padding_bit = ($b2 & 0x02) >> 1; + $private_bit = ($b2 & 0x01); + $channel_mode_bits = ($b3 & 0xc0) >> 6; + $mode_extension_bits = ($b3 & 0x30) >> 4; + $copyright_bit = ($b3 & 0x08) >> 3; + $original_bit = ($b3 & 0x04) >> 2; + $emphasis = ($b3 & 0x03); + + $info = array(); + $info['Version'] = $version; //MPEGVersion + $info['Layer'] = $layer; + //$info['Protection Bit'] = $protection_bit; //0=> protected by 2 byte CRC, 1=>not protected + $info['Bitrate'] = $bitrate; + $info['Sampling Rate'] = $sample_rate; + //$info['Padding Bit'] = $padding_bit; + //$info['Private Bit'] = $private_bit; + //$info['Channel Mode'] = $channel_mode_bits; + //$info['Mode Extension'] = $mode_extension_bits; + //$info['Copyright'] = $copyright_bit; + //$info['Original'] = $original_bit; + //$info['Emphasis'] = $emphasis; + $info['Framesize'] = self::framesize($layer, $bitrate, $sample_rate, $padding_bit); + $info['Samples'] = $samples[$simple_version][$layer]; + return $info; + } + + //credit: http://www.zedwood.com/article/php-calculate-duration-of-mp3 + static function framesize($layer, $bitrate, $sample_rate, $padding_bit) + { + if ($layer == 1) + return intval(((12 * $bitrate * 1000 / $sample_rate) + $padding_bit) * 4); + else //layer 2, 3 + return intval(((144 * $bitrate * 1000) / $sample_rate) + $padding_bit); + } + + //credit: https://www.daniweb.com/programming/web-development/threads/428301/getting-video-duration-without-ffmpeg + static function multi_getDuration($file) + { + + if (file_exists($file)) { + ## open and read video file $handle = fopen($file, "r"); ## read video file size $contents = fread($handle, filesize($file)); - + fclose($handle); - $make_hexa = hexdec(bin2hex(substr($contents,strlen($contents)-3))); - - if (strlen($contents) > $make_hexa){ - - $pre_duration = hexdec(bin2hex(substr($contents,strlen($contents)-$make_hexa,3))) ; - $post_duration = $pre_duration/1000; - $timehours = $post_duration/3600; - $timeminutes =($post_duration % 3600)/60; - $timeseconds = ($post_duration % 3600) % 60; - $timehours = explode(".", $timehours); - $timeminutes = explode(".", $timeminutes); - $timeseconds = explode(".", $timeseconds); - $duration = $timehours[0]. ":" . $timeminutes[0]. ":" . $timeseconds[0];} - return $duration; - + $make_hexa = hexdec(bin2hex(substr($contents, strlen($contents) - 3))); + + if (strlen($contents) > $make_hexa) { + + $pre_duration = hexdec(bin2hex(substr($contents, strlen($contents) - $make_hexa, 3))); + $post_duration = $pre_duration / 1000; + $timehours = $post_duration / 3600; + $timeminutes = ($post_duration % 3600) / 60; + $timeseconds = ($post_duration % 3600) % 60; + $timehours = explode(".", $timehours); + $timeminutes = explode(".", $timeminutes); + $timeseconds = explode(".", $timeseconds); + $duration = $timehours[0] . ":" . $timeminutes[0] . ":" . $timeseconds[0]; } - else { - + return $duration; + } else { + return false; - } } + } - static function changeSongAlbum(IRequest $req, IResponse $res) { - $song = new Song($req->db); - $album = new Album($req->db); - - $idLagu = $req->getParam("/admin/lagu/:id/album", "id"); - $data = $req->jsonData(); - - $album_id = $data["album_id"]; - - $album_transaction = $album->transaction(); - $count = $album_transaction->select(["COUNT(album_id) cnt"])->where("album_id = ?", [$album_id])->all()[0]; - $album_transaction->commit(); - - if(isset($count["cnt"]) && $count["cnt"] == 0 || !isset($count["cnt"])) { - $res->setHttpStatus(HttpStatus::BadRequest); - return $res->json([ - "status" => "failed", - "message" => "No such album_id = $album_id found", - "data" => null, - ]); - } + static function changeSongAlbum(IRequest $req, IResponse $res) + { + $song = new Song($req->db); + $album = new Album($req->db); - $song_transaction = $song->transaction(); - $count = $song_transaction->select(["COUNT(song_id) cnt"])->where("song_id = ?", [$idLagu])->all()[0]; + $idLagu = $req->getParam("/admin/lagu/:id/album", "id"); + $data = $req->jsonData(); - if(isset($count["cnt"]) && $count["cnt"] == 0 || !isset($count["cnt"])) { - $res->setHttpStatus(HttpStatus::BadRequest); - return $res->json([ - "status" => "failed", - "message" => "No such song_id = $idLagu found", - "data" => null, - ]); - } + $album_id = $data["album_id"]; + + $album_transaction = $album->transaction(); + $count = $album_transaction->select(["COUNT(album_id) cnt"])->where("album_id = ?", [$album_id])->all()[0]; + $album_transaction->commit(); - $song_transaction->update("song_id = ?", [$idLagu], [ - "album_id" => $album_id, + if (isset($count["cnt"]) && $count["cnt"] == 0 || !isset($count["cnt"])) { + $res->setHttpStatus(HttpStatus::BadRequest); + return $res->json([ + "status" => "failed", + "message" => "No such album_id = $album_id found", + "data" => null, ]); + } - $song_transaction->commit(); + $song_transaction = $song->transaction(); + $count = $song_transaction->select(["COUNT(song_id) cnt"])->where("song_id = ?", [$idLagu])->all()[0]; + if (isset($count["cnt"]) && $count["cnt"] == 0 || !isset($count["cnt"])) { + $res->setHttpStatus(HttpStatus::BadRequest); return $res->json([ - "status" => "success", - "message" => "success", + "status" => "failed", + "message" => "No such song_id = $idLagu found", "data" => null, ]); } - static function deleteSongAlbum(IRequest $req, IResponse $res) { - $song = new Song($req->db); - $idLagu = $req->getParam("/admin/lagu/:id/album", "id"); + $song_transaction->update("song_id = ?", [$idLagu], [ + "album_id" => $album_id, + ]); - $song_transaction = $song->transaction(); - $count = $song_transaction->select(["COUNT(song_id) cnt"])->where("song_id = ?", [$idLagu])->all()[0]["cnt"]; + $song_transaction->commit(); - if($count == 0) { - $res->setHttpStatus(HttpStatus::BadRequest); - return $res->json([ - "status" => "failed", - "message" => "No such song_id = $idLagu found", - "data" => null, - ]); - } + return $res->json([ + "status" => "success", + "message" => "success", + "data" => null, + ]); + } - $song_transaction->update("song_id = ?", [$idLagu], [ - "album_id" => null, - ]); + static function deleteSongAlbum(IRequest $req, IResponse $res) + { + $song = new Song($req->db); + $idLagu = $req->getParam("/admin/lagu/:id/album", "id"); - $song_transaction->commit(); + $song_transaction = $song->transaction(); + $count = $song_transaction->select(["COUNT(song_id) cnt"])->where("song_id = ?", [$idLagu])->all()[0]["cnt"]; + + if ($count == 0) { + $res->setHttpStatus(HttpStatus::BadRequest); + return $res->json([ + "status" => "failed", + "message" => "No such song_id = $idLagu found", + "data" => null, + ]); } - } \ No newline at end of file + + $song_transaction->update("song_id = ?", [$idLagu], [ + "album_id" => null, + ]); + + $song_transaction->commit(); + } +} diff --git a/Controller/SubsciberController.php b/Controller/SubsciberController.php index 7c443466bbe21ec372b13557ffd3a02ba783c08f..7bda4601cb179a2f62ee1b503f58ce7462d8ed47 100644 --- a/Controller/SubsciberController.php +++ b/Controller/SubsciberController.php @@ -9,18 +9,20 @@ use Lib\Interfaces\Routing\IResponse; use Model\Relations\Subscription; use Lib\Service\Api\FetchAPI; -class SubsciberController { +class SubsciberController +{ const DEFAULT_PAGE = 1; const DEFAULT_LIMIT = 10; - static function setStatus(IRequest $req, IResponse $res) { + static function setStatus(IRequest $req, IResponse $res) + { $subscriber = new Subscription($req->db); $transaction = $subscriber->transaction(); - - try{ + + try { $payload = $req->jsonData(); $errors = []; - - if(!is_null(getenv("API_KEY")) && $req->getHeader("X-API-KEY") !== getenv("API_KEY")) { + + if (!is_null(getenv("API_KEY")) && $req->getHeader("X-API-KEY") !== getenv("API_KEY")) { $transaction->rollback(); return $res->setHttpStatus(HttpStatus::Forbidden)->json([ "status" => "failed", @@ -28,24 +30,26 @@ class SubsciberController { "data" => null, ]); } - - if(!isset($payload["subscriber_id"]) || is_null($payload["subscriber_id"])) { + + if (!isset($payload["subscriber_id"]) || is_null($payload["subscriber_id"])) { $errors[] = "Subscriber id is required"; } - - if(!isset($payload["creator_id"]) || is_null($payload["creator_id"])) { + + if (!isset($payload["creator_id"]) || is_null($payload["creator_id"])) { $errors[] = "Creator id is required"; } - - if(!isset($payload["status"])) { + + if (!isset($payload["status"])) { $errors[] = "Status is required"; - } else if (strtoupper($payload["status"]) !== "PENDING" && + } else if ( + strtoupper($payload["status"]) !== "PENDING" && strtoupper($payload["status"]) !== "ACCEPTED" && - strtoupper($payload["status"]) !== "REJECTED") { + strtoupper($payload["status"]) !== "REJECTED" + ) { $errors[] = "Status value is invalid"; } - - if(count($errors) > 0) { + + if (count($errors) > 0) { $transaction->rollback(); return $res->setHttpStatus(HttpStatus::BadRequest)->json([ "status" => "failed", @@ -53,13 +57,13 @@ class SubsciberController { "data" => $errors, ]); } - + $result = $transaction->select(["COUNT(*) as cnt"])->where("creator_id = ? AND subscriber_id = ?", [ $payload["creator_id"], $payload["subscriber_id"], ])->all(); - - if($result[0]["cnt"] === 0) { + + if ($result[0]["cnt"] === 0) { $transaction->insert( [ "creator_id" => $payload["creator_id"], @@ -67,7 +71,7 @@ class SubsciberController { "status" => strtoupper($payload["status"]), ] ); - }else{ + } else { $transaction->update("creator_id = ? AND subscriber_id = ?", [ $payload["creator_id"], $payload["subscriber_id"], @@ -75,17 +79,16 @@ class SubsciberController { "status" => strtoupper($payload["status"]), ]); } - - + + $transaction->commit(); - + return $res->json([ "status" => "success", "message" => "success", "data" => null, ]); - - }catch(Exception $e){ + } catch (Exception $e) { $transaction->rollback(); return $res->setHttpStatus(HttpStatus::InternalServerError)->json([ "status" => "failed", @@ -97,19 +100,20 @@ class SubsciberController { } } - static function getStatus(IRequest $req, IResponse $res) { + static function getStatus(IRequest $req, IResponse $res) + { $payload = $req->jsonData(); $errors = []; - if(!isset($payload["subscriber_id"])) { + if (!isset($payload["subscriber_id"])) { $errors[] = "Subscriber id is required"; } - - if(!isset($payload["creator_id"])) { + + if (!isset($payload["creator_id"])) { $errors[] = "Creator id is required"; } - - if(count($errors) > 0) { + + if (count($errors) > 0) { return $res->setHttpStatus(HttpStatus::BadRequest)->json([ "status" => "failed", "message" => "Input is invalid", @@ -127,13 +131,13 @@ class SubsciberController { $transaction->commit(); - if(count($result) > 0) { + if (count($result) > 0) { return $res->json([ "status" => "success", "message" => "success", "data" => $result[0], ]); - }else{ + } else { return $res->setHttpStatus(HttpStatus::NotFound)->json([ "status" => "failed", "message" => "Data not found", @@ -142,70 +146,70 @@ class SubsciberController { } } - static function fetchSubscriptions(int $page,int $limit, int $user_id,$db){ + static function fetchSubscriptions(int $page, int $limit, int $user_id, $db) + { $fetcher = new FetchAPI(getenv("REST_HOST")); $param = [ - "page"=>$page, - "limit"=>$limit, + "page" => $page, + "limit" => $limit, ]; $rest_key = getenv("REST_KEY"); $headers = [ - "X-API-KEY"=> $rest_key + "X-API-KEY" => $rest_key ]; - $output = $fetcher->get("/singers",$param,$headers); + $output = $fetcher->get("/singers", $param, $headers); - if(!$output){ + if (!$output) { return false; } - $data = json_decode($output,true)["data"]; - + $data = json_decode($output, true)["data"]; + //tambahin status berlangganan $subscriber = new Subscription($db); $transaction = $subscriber->transaction(); - try{ - foreach($data as $index=>$value){ - $data[$index] = array(); - $data[$index]["name"] = $value["name"]; - $data[$index]["singer_id"] = $value["singer_id"]; - - if($user_id > -1){ - //fetch data - $result = $transaction->select(["*"])->where("creator_id = ? AND subscriber_id = ?", [ - $value["singer_id"], - $user_id, - ])->all(); - // print_r("3"); - // print_r($data[$index]); - - if(count($result) > 0) { - $data[$index]["isSubscribe"] = $result[0]["status"]==="ACCEPTED"?1:0; + try { + foreach ($data as $index => $value) { + $data[$index] = array(); + $data[$index]["name"] = $value["name"]; + $data[$index]["singer_id"] = $value["singer_id"]; + + if ($user_id > -1) { + //fetch data + $result = $transaction->select(["*"])->where("creator_id = ? AND subscriber_id = ?", [ + $value["singer_id"], + $user_id, + ])->all(); + // print_r("3"); + // print_r($data[$index]); + + if (count($result) > 0) { + $data[$index]["isSubscribe"] = $result[0]["status"] === "ACCEPTED" ? 1 : 0; + } else { + $data[$index]["isSubscribe"] = 0; + } + } } - else{ - $data[$index]["isSubscribe"] = 0; - } - } - } $transaction->commit(); - } - catch(Exception $e){ - // $transaction->rollback(); - print_r($e->getMessage()); - } + } catch (Exception $e) { + // $transaction->rollback(); + print_r($e->getMessage()); + } return $data; } - static function getPremiumSinger(IRequest $req, IResponse $res){ + static function getPremiumSinger(IRequest $req, IResponse $res) + { //data ada - $user_id = $req->auth?$req->auth->user_id:-1; - $page = $req->getQuery("page") ? - ($req->getQuery("page")>0 ? $req->getQuery("page") : SubsciberController::DEFAULT_PAGE) + $user_id = $req->auth ? $req->auth->user_id : -1; + $page = $req->getQuery("page") ? + ($req->getQuery("page") > 0 ? $req->getQuery("page") : SubsciberController::DEFAULT_PAGE) : SubsciberController::DEFAULT_PAGE; - $limit = $req->getQuery("limit") ? - ($req->getQuery("limit")>0?$req->getQuery("limit"):SubsciberController::DEFAULT_LIMIT) - :SubsciberController::DEFAULT_LIMIT; - $data = SubsciberController::fetchSubscriptions($page,$limit,$user_id,$req->db); - if($data===false){ + $limit = $req->getQuery("limit") ? + ($req->getQuery("limit") > 0 ? $req->getQuery("limit") : SubsciberController::DEFAULT_LIMIT) + : SubsciberController::DEFAULT_LIMIT; + $data = SubsciberController::fetchSubscriptions($page, $limit, $user_id, $req->db); + if ($data === false) { // return $res->json([ // "status"=>"failed", // "message"=>"fetch operations failed", @@ -215,25 +219,25 @@ class SubsciberController { return $res->redirect("/", 500); } - // $data = json_decode($output,true)["data"]; + // $data = json_decode($output,true)["data"]; //fetch max page $fetcher = new FetchAPI(getenv("REST_HOST")); $param = [ - "page-size"=>$limit, + "page-size" => $limit, ]; $rest_key = getenv("REST_KEY"); $headers = [ - "X-API-KEY"=> $rest_key + "X-API-KEY" => $rest_key ]; - $output = $fetcher->get("/singers/max-page",$param,$headers); + $output = $fetcher->get("/singers/max-page", $param, $headers); $total_page = 1; - if($output){ - $total_page = json_decode($output,true)["data"]; + if ($output) { + $total_page = json_decode($output, true)["data"]; } return $res->view("Pages/PremiumSinger", [ "singers" => $data, "page" => $page, - "limit"=>$limit, + "limit" => $limit, "next_page" => $page < $total_page ? $page + 1 : null, "prev_page" => $page > 1 ? $page - 1 : null, "auth" => $req->auth, diff --git a/static/js/modifylagu.js b/static/js/modifylagu.js index 38d3d66147cb29fa4d7015636705d5b5e986fcf9..95001d74d256891d7c7f7a1b875e831f9973796c 100644 --- a/static/js/modifylagu.js +++ b/static/js/modifylagu.js @@ -1,10 +1,10 @@ const editButton = document.querySelector("button#edit"); const image = document.querySelector("#image") const audio = document.querySelector("#audio") -const title= document.querySelector("#title") -const singer_name= document.querySelector("#singer_name") -const release_date= document.querySelector("#release_date") -const genre= document.querySelector("#genre") +const title = document.querySelector("#title") +const singer_name = document.querySelector("#singer_name") +const release_date = document.querySelector("#release_date") +const genre = document.querySelector("#genre") const imageContainer = document.querySelector("#imageContainer") const audioPlayer = document.querySelector("audio") const duration = document.querySelector("#duration") @@ -12,186 +12,186 @@ const content_div = title.parentNode let initialData = {} let modifiedData = {} -function getContent(parent){ - let text = parent.innerHTML.split(" ") - parent.innerHTML= text.shift() - let contentText = "" - if(text.length>1){ - contentText = text.join(" ") +function getContent(parent) { + let text = parent.innerHTML.split(" ") + parent.innerHTML = text.shift() + let contentText = "" + if (text.length > 1) { + contentText = text.join(" ") + } + else if (text.length === 1) { + contentText = text[0] + } + return contentText; +} +editButton.onclick = (e) => { + //edit gambar + const inputGambar = document.createElement("input") + inputGambar.type = "file" + inputGambar.accept = "image/*" + imageContainer.appendChild(inputGambar) + let srcc = image.src.split('/') + for (i = 0; i < 3; i++) { + srcc.shift() + } + initialData["image_path"] = ('/' + srcc.join("/")).replace("%20", " ") + //edit lagu + const inputLagu = document.createElement("input") + inputLagu.accept = "audio/*" + inputLagu.type = "file" + audioPlayer.parentNode.insertBefore(inputLagu, audioPlayer.nextSibling) + srcc = audio.src.split('/') + for (i = 0; i < 3; i++) { + srcc.shift() + } + initialData["audio_path"] = ('/' + srcc.join("/")).replace("%20", " ") + //edit judul + let titleText = getContent(title) + const ubahJudul = document.createElement("input") + ubahJudul.type = "text" + ubahJudul.value = titleText + title.parentNode.insertBefore(ubahJudul, title.nextSibling) + + initialData["title"] = titleText + + //edit tanggal rilis + let dateText = release_date.getAttribute("data-date-type") + console.log(dateText) + const ubahDate = document.createElement("input") + ubahDate.type = "date" + ubahDate.value = dateText + release_date.parentNode.insertBefore(ubahDate, release_date.nextSibling) + initialData["release_date"] = dateText + //edit genre + let genreText = getContent(genre) + const ubahGenre = document.createElement("input") + ubahGenre.type = "text" + ubahGenre.value = genreText + genre.parentNode.insertBefore(ubahGenre, genre.nextSibling) + initialData["genre"] = genreText + //tambahin tombol cancel dan update + let buttonsList = document.createElement("div") + buttonsList.id = "list__button" + duration.parentNode.insertBefore(buttonsList, duration.nextSibling) + //button cancel + let cancelButton = document.createElement("button") + cancelButton.innerText = "Batalkan" + cancelButton.onclick = (e) => { + status.innerHTML = '' + title.innerHTML = title.innerHTML + " " + initialData["title"] + genre.innerHTML = genre.innerHTML + " " + initialData["genre"] + //hapus input field + imageContainer.removeChild(inputGambar) + audioPlayer.parentNode.removeChild(inputLagu) + content_div.removeChild(ubahJudul) + content_div.removeChild(ubahDate) + content_div.removeChild(ubahGenre) + //hapus tombol + buttonsList.innerHTML = '' + buttonsList.parentNode.removeChild(buttonsList) + //tampilin lagi edit button + editButton.style.display = "inline-block" + } + + buttonsList.appendChild(cancelButton) + //button update + let updateButton = document.createElement("button") + updateButton.innerText = "Ubah" + buttonsList.appendChild(updateButton) + + updateButton.onclick = async (e) => { + modifiedData["title"] = ubahJudul.value + modifiedData["release_date"] = ubahDate.value + modifiedData["genre"] = ubahGenre.value + modifiedData["id"] = document.querySelector("input[name='id'").value + modifiedData["audio"] = inputLagu.files[0]; + modifiedData["image"] = inputGambar.files[0]; + + console.log(modifiedData) + //bikin form data + let formData = new FormData() + if (modifiedData["title"] !== initialData["title"]) { + formData.append("title", modifiedData["title"]) } - else if(text.length===1){ - contentText = text[0] + if (modifiedData["release_date"] !== initialData["release_date"]) { + formData.append("release_date", modifiedData["release_date"]) } - return contentText; -} -editButton.onclick = (e)=>{ - //edit gambar - const inputGambar = document.createElement("input") - inputGambar.type = "file" - inputGambar.accept = "image/*" - imageContainer.appendChild(inputGambar) - let srcc = image.src.split('/') - for(i=0;i<3;i++){ - srcc.shift() + if (modifiedData["genre"] !== initialData["genre"]) { + formData.append("genre", modifiedData["genre"]) } - initialData["image_path"] = ('/'+srcc.join("/")).replace("%20"," ") - //edit lagu - const inputLagu = document.createElement("input") - inputLagu.accept = "audio/*" - inputLagu.type = "file" - audioPlayer.parentNode.insertBefore(inputLagu,audioPlayer.nextSibling) - srcc = audio.src.split('/') - for(i=0;i<3;i++){ - srcc.shift() + formData.append("id", modifiedData["id"]) + if (modifiedData["release_date"] !== initialData["release_date"]) { + formData.append("release_date", modifiedData["release_date"]) } - initialData["audio_path"] = ('/'+srcc.join("/")).replace("%20"," ") - //edit judul - let titleText = getContent(title) - const ubahJudul = document.createElement("input") - ubahJudul.type = "text" - ubahJudul.value = titleText - title.parentNode.insertBefore(ubahJudul,title.nextSibling) - - initialData["title"] = titleText - - //edit tanggal rilis - let dateText = release_date.getAttribute("data-date-type") - console.log(dateText) - const ubahDate = document.createElement("input") - ubahDate.type = "date" - ubahDate.value = dateText - release_date.parentNode.insertBefore(ubahDate,release_date.nextSibling) - initialData["release_date"] = dateText - //edit genre - let genreText = getContent(genre) - const ubahGenre = document.createElement("input") - ubahGenre.type = "text" - ubahGenre.value = genreText - genre.parentNode.insertBefore(ubahGenre,genre.nextSibling) - initialData["genre"] = genreText - //tambahin tombol cancel dan update - let buttonsList = document.createElement("div") - buttonsList.id = "list__button" - duration.parentNode.insertBefore(buttonsList,duration.nextSibling) - //button cancel - let cancelButton = document.createElement("button") - cancelButton.innerText = "Batalkan" - cancelButton.onclick = (e)=>{ - status.innerHTML = '' - title.innerHTML = title.innerHTML + " "+ initialData["title"] - genre.innerHTML = genre.innerHTML + " " + initialData["genre"] - //hapus input field - imageContainer.removeChild(inputGambar) - audioPlayer.parentNode.removeChild(inputLagu) - content_div.removeChild(ubahJudul) - content_div.removeChild(ubahDate) - content_div.removeChild(ubahGenre) - //hapus tombol - buttonsList.innerHTML = '' - buttonsList.parentNode.removeChild(buttonsList) - //tampilin lagi edit button - editButton.style.display = "inline-block" + if (modifiedData["image"] !== null && modifiedData["image"] !== undefined) { + formData.append("image", modifiedData["image"]) } - - buttonsList.appendChild(cancelButton) - //button update - let updateButton = document.createElement("button") - updateButton.innerText = "Ubah" - buttonsList.appendChild(updateButton) - - updateButton.onclick = async (e)=>{ - modifiedData["title"] = ubahJudul.value - modifiedData["release_date"] = ubahDate.value - modifiedData["genre"] = ubahGenre.value - modifiedData["id"] = document.querySelector("input[name='id'").value - modifiedData["audio"] = inputLagu.files[0]; - modifiedData["image"] = inputGambar.files[0]; - - console.log(modifiedData) - //bikin form data - let formData = new FormData() - if(modifiedData["title"]!==initialData["title"]){ - formData.append("title",modifiedData["title"]) - } - if(modifiedData["release_date"]!==initialData["release_date"]){ - formData.append("release_date",modifiedData["release_date"]) - } - if(modifiedData["genre"]!==initialData["genre"]){ - formData.append("genre",modifiedData["genre"]) - } - formData.append("id",modifiedData["id"]) - if(modifiedData["release_date"]!==initialData["release_date"]){ - formData.append("release_date",modifiedData["release_date"]) - } - if(modifiedData["image"]!==null && modifiedData["image"]!==undefined){ - formData.append("image",modifiedData["image"]) - } - if(modifiedData["audio"]!==null && modifiedData["audio"]!==undefined){ - formData.append("audio",modifiedData["audio"]) - } - console.log(formData) - console.log("/lagu/"+document.querySelector("input[name='id'").value) - const status_update = await http.post("/lagu/"+document.querySelector("input[name='id'").value,formData,{ - json: false, - // headers: { - // "Content-Type": "multipart/form-data" - // }, - }); - let data = status_update["data"] - console.log(status_update) - console.log(data) - //update - audio.src = data["audio_path"] - audio.type = data["sound_type"] - image.src = data["image_path"] - title.innerHTML= title.innerHTML + " "+ data["title"] - getContent(release_date) - release_date.innerHTML = "Tanggal Rilis: "+data["release_date"] - genre.innerHTML = genre.innerHTML + " "+data["genre"] - release_date.dataset.dateType = data["date"] - let status_ = document.querySelector("#status") - status_.innerText = data["status"] - status_.classList.add("success__added") - //hapus input field - imageContainer.removeChild(inputGambar) - audioPlayer.parentNode.removeChild(inputLagu) - content_div.removeChild(ubahJudul) - content_div.removeChild(ubahDate) - content_div.removeChild(ubahGenre) - //hapus tombol - buttonsList.innerHTML = '' - buttonsList.parentNode.removeChild(buttonsList) - //tampilin lagi edit button - editButton.style.display = "inline-block" - + if (modifiedData["audio"] !== null && modifiedData["audio"] !== undefined) { + formData.append("audio", modifiedData["audio"]) } - //button delete - let deleteButton = document.createElement("button") - deleteButton.innerText = "Hapus Lagu" - deleteButton.classList.add("remove__button") - deleteButton.style.backgroundColor = "red" - buttonsList.appendChild(deleteButton) - deleteButton.onclick = async (e)=>{ - let status = await http.delete("/lagu/delete/"+document.querySelector("input[name='id'").value) - console.log(status) - let sta = status["data"]["deleted"] - if(sta===true){ - let contess =document.querySelector(".content") - contess.innerHTML = ` + console.log(formData) + console.log("/lagu/" + document.querySelector("input[name='id'").value) + const status_update = await http.post("/lagu/" + document.querySelector("input[name='id'").value, formData, { + json: false, + // headers: { + // "Content-Type": "multipart/form-data" + // }, + }); + let data = status_update["data"] + console.log(status_update) + console.log(data) + //update + audio.src = data["audio_path"] + audio.type = data["sound_type"] + image.src = data["image_path"] + title.innerHTML = title.innerHTML + " " + data["title"] + getContent(release_date) + release_date.innerHTML = "Tanggal Rilis: " + data["release_date"] + genre.innerHTML = genre.innerHTML + " " + data["genre"] + release_date.dataset.dateType = data["date"] + let status_ = document.querySelector("#status") + status_.innerText = data["status"] + status_.classList.add("success__added") + //hapus input field + imageContainer.removeChild(inputGambar) + audioPlayer.parentNode.removeChild(inputLagu) + content_div.removeChild(ubahJudul) + content_div.removeChild(ubahDate) + content_div.removeChild(ubahGenre) + //hapus tombol + buttonsList.innerHTML = '' + buttonsList.parentNode.removeChild(buttonsList) + //tampilin lagi edit button + editButton.style.display = "inline-block" + + } + //button delete + let deleteButton = document.createElement("button") + deleteButton.innerText = "Hapus Lagu" + deleteButton.classList.add("remove__button") + deleteButton.style.backgroundColor = "red" + buttonsList.appendChild(deleteButton) + deleteButton.onclick = async (e) => { + let status = await http.delete("/lagu/delete/" + document.querySelector("input[name='id'").value) + console.log(status) + let sta = status["data"]["deleted"] + if (sta === true) { + let contess = document.querySelector(".content") + contess.innerHTML = ` <h1> Lagu Berhasil Dihapus!</h1> <a href="/"> <button id="returnButton"> Kembali ke halaman awal</button> </a> ` - } - } - //tulisan kalau lagi di mode edit - let status = document.querySelector("#status") - status.innerText = "Edit Lagu" - imageContainer.parentNode.insertBefore(status,imageContainer) + } + } + //tulisan kalau lagi di mode edit + let status = document.querySelector("#status") + status.innerText = "Edit Lagu" + imageContainer.parentNode.insertBefore(status, imageContainer) - //hapus edit button - //editButton.parentElement.removeChild(editButton) - editButton.style.display = "none" - console.log(initialData) - } \ No newline at end of file + //hapus edit button + //editButton.parentElement.removeChild(editButton) + editButton.style.display = "none" + console.log(initialData) +} \ No newline at end of file diff --git a/static/js/searchlagu.js b/static/js/searchlagu.js index 9fbbd27244f80d052b087fd58e128004055a69b0..e77bf13689732fc5aa1b2f5e69831a8371246f16 100644 --- a/static/js/searchlagu.js +++ b/static/js/searchlagu.js @@ -5,8 +5,10 @@ const searchBar = document.querySelector(".header__search-bar > input") const genreFilter = document.querySelector("#filteredGenre") const pagination_number = document.querySelector(".pagination__page") //const searchButton = document.querySelector("#searchButton") +const prevButton = document.querySelector("#next_button") +const nextButton = document.querySelector("#prev_button") -function regenerateData(data){ +function regenerateData(data) { html = '' data.forEach(song => { imagePath = song["image_path"]; @@ -32,30 +34,30 @@ function regenerateData(data){ container.innerHTML = html } -async function resortPage(type){ +async function resortPage(type) { let page = pagination_number.innerText.split(" ")[1] let url = `/search?sortsType=${type}&q=${searchBar.value}&filteredGenre=${genreFilter.value}&page=${page}` await http.get(url, {}); window.location = url } -async function searchResult(query){ +async function searchResult(query) { console.log("a") - console.log("/search?query="+query) - const data = await http.get("/search?q="+query+"&sortsType="+sort_type_selector.value+"&filteredGenre="+genreFilter.value,{ - json:true, + console.log("/search?query=" + query) + const data = await http.get("/search?q=" + query + "&sortsType=" + sort_type_selector.value + "&filteredGenre=" + genreFilter.value, { + json: true, headers: { "Accept": "application/json" } }) const lagu = data["data"]["hasil"] - document.querySelector(".pagination__page").innerHTML = "Page "+data["data"]["page"] + document.querySelector(".pagination__page").innerHTML = "Page " + data["data"]["page"] page = data["data"]["page"] let total_page = data["data"]["total_page"] - if(page>total_page){ + if (page > total_page) { document.querySelector("#next_button").display = "hidden"; } - if(page<=1){ + if (page <= 1) { document.querySelector("#prev_button").display = "hidden"; } //console.log(data) @@ -64,47 +66,67 @@ async function searchResult(query){ regenerateData(lagu) } -async function filterSearch(genre){ +async function filterSearch(genre) { let page = pagination_number.innerText.split(" ")[1] let url = `/search?sortsType=${sort_type_selector.value}&q=${searchBar.value}&filteredGenre=${genre}&page=${page}` await http.get(url, {}); window.location = url - - // console.log("/search?sortsType="+sort_type_selector.value+"&q="+searchBar.value+"&filteredGenre="+genre) - // const data = await http.get("/search?sortsType="+sort_type_selector.value+"&q="+searchBar.value+"&filteredGenre="+genre, { - // json: true, - // headers: { - // "Accept": "application/json" - // }, - // }); - // const lagu = data["data"]["hasil"] - // document.querySelector(".pagination__page").innerHTML = "Page "+data["data"]["page"] - // page = data["data"]["page"] - // let total_page = data["data"]["total_page"] - // if(page>total_page){ - // document.querySelector("#next_button").display = "hidden"; - // } - // if(page<=1){ - // document.querySelector("#prev_button").display = "hidden"; - // } - // console.log(lagu) - // container.innerHTML = '' - // console.log(container) - // console.log(lagu) - // regenerateData(lagu) } -sort_type_selector.onchange = -(e)=>{ - type = e.target.value; - setTimeout(() => { - resortPage(type) - }, 100); +async function movePage(page){ + const data = await http.get(`/search?q=${searchBar.value}&sortsType=${sort_type_selector.value} + &filteredGenre=${genreFilter.value}&page=${page}`, { + json: true, + headers: { + "Accept": "application/json" + } + }) + const lagu = data["data"]["hasil"] + document.querySelector(".pagination__page").innerHTML = "Page " + data["data"]["page"] + page = data["data"]["page"] + let total_page = data["data"]["total_page"] + if (page > total_page) { + document.querySelector("#next_button").display = "hidden"; + } + if (page <= 1) { + document.querySelector("#prev_button").display = "hidden"; + } + //console.log(data) + container.innerHTML = '' + //console.log(container) + regenerateData(lagu) } -genreFilter.onchange = (e)=>{ - genre = e.target.value; - setTimeout(()=>{ - filterSearch(genre) - },100) +if (sort_type_selector) { + sort_type_selector.onchange = + (e) => { + type = e.target.value; + setTimeout(() => { + resortPage(type) + }, 100); + } +} +if (genreFilter) { + genreFilter.onchange = (e) => { + genre = e.target.value; + setTimeout(() => { + filterSearch(genre) + }, 100) + } +} +if (nextButton) { + nextButton.onclick = (e) => { + let page = pagination_number.innerText.split(" ")[1] + setTimeout(() => { + movePage(page + 1) + }, 100) + } +} +if (prevButton) { + prevButton.onclick = (e) => { + let page = pagination_number.innerText.split(" ")[1] + setTimeout(() => { + movePage(page - 1) + }, 100) + } } \ No newline at end of file