Last active
August 29, 2015 14:23
-
-
Save davidpeach/91bad583aeda03e36611 to your computer and use it in GitHub Desktop.
Contains the functionality for parsing a Google Play Music URL for keeping track of albums I listen to. See http://davidpea.ch/articles/671 for the full post.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Http\Controllers; | |
use App\Http\Requests; | |
use App\Http\Controllers\Controller; | |
use Illuminate\Http\Request; | |
use JonnyW\PhantomJs\Client; | |
use App\Listening; | |
use DB; | |
class ApiController extends Controller | |
{ | |
public function addListeningTo(Request $request) | |
{ | |
$initialUrl = $request->get('url'); | |
$initialUrl = trim($initialUrl, '/'); | |
$urlArray = explode('/', $initialUrl); | |
if ( ! empty($urlArray)) | |
{ | |
$urlToParse = env('GOOGLE_PLAY_MUSIC_BASE_URL') . end($urlArray); | |
} | |
else | |
{ | |
abort(500); | |
} | |
$client = Client::getInstance(); | |
$engine = $client->getEngine(); | |
$engine->setPath(env('PHANTOM_BIN_PATH')); | |
$req = $client->getMessageFactory()->createRequest(); | |
$res = $client->getMessageFactory()->createResponse(); | |
$req->setMethod('GET'); | |
$req->setUrl($urlToParse); | |
$client->send($req, $res); | |
$content = $res->content; | |
$html = new \SimpleHtmlDom\simple_html_dom(); | |
$html->load($content); | |
$infoText = $html->find('div[class=info-text]', 0); | |
if ( ! is_null($infoText)) | |
{ | |
$albumArtist = $infoText->find('div[class=album-artist]', 0); | |
if ( ! is_null($albumArtist)) | |
{ | |
$albumArtist = $albumArtist->plaintext; | |
} | |
$albumTitle = $infoText->find('div[class=title]', 0); | |
if ( ! is_null($albumTitle)) | |
{ | |
$albumTitle = $albumTitle->plaintext; | |
} | |
$albumStats = $infoText->find('div[class=stats]', 0); | |
if ( ! is_null($albumStats)) | |
{ | |
$albumStats = $albumStats->plaintext; | |
} | |
} | |
$albumArtwork = $html->find('img[class=album-art]', 0); | |
if ( ! is_null($albumArtwork)) | |
{ | |
$albumArtworkSrc = $albumArtwork->getAttribute('src'); | |
} | |
$listenedTo = Listening::where('artist', $albumArtist)->where('album', $albumTitle)->first(); | |
if (is_null($listenedTo)) | |
{ | |
$listenedTo = Listening::create([ | |
'artist' => $albumArtist, | |
'album' => $albumTitle, | |
'artwork' => $albumArtworkSrc, | |
'album_stats' => $albumStats, | |
'url' => $urlToParse | |
]); | |
} | |
DB::insert("insert into listenings_counts SET listenings_id = '" . $listenedTo->id . "', created_at = NOW(), updated_at = NOW()"); | |
// maybe redirect to another screen where i could perhaps write a note? | |
return redirect('/'); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment