Laravel 5.2 Update (#106)

* Adopt PSR-2 coding style

The Laravel framework adopts the PSR-2 coding style in version 5.1.
Laravel apps *should* adopt this coding style as well. Read the
[PSR-2 coding style guide][1] for more details and check out [PHPCS][2]
to use as a code formatting tool.

[1]: https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md
[2]: https://github.com/squizlabs/PHP_CodeSniffer

* Adopt PHP short array syntax

Laravel 5 adopted the short array syntax which became available in
PHP 5.4.

* Remove SelfHandling from Jobs

Jobs are self handling by default in Laravel 5.2.

* Add new exceptions to `$dontReport` property

* Shift core files

* Shift Middleware

Laravel 5.2 adjusts the `Guard` object used within middleware. In
addition, new `can` and `throttles` middleware were added.

* Shift Input to Request facade

Laravel 5.2 no longer registers the `Input` facade by default. Laravel
now prefers using the `Request` facade or the `$request` object within
*Controllers* instead. Review the [HTTP Requests][1] documentation for
more details.

[1]: https://laravel.com/docs/5.2/requests

* Shift configuration

Laravel 5.2 introduces the `env` app configuration option and removes
the `pretend` mail configuration option. In addition, a few of the
default `providers` and `aliases` bindings were removed.

* Shift Laravel dependencies

* Shift cleanup

* Updated composer.lock

* Updated Middleware to 5.2

* Config update for Laravel 5.2

* [Laravel 5.2] Updated validation strings

* Updated auth config

* Updated to use middleware groups

* Added laravel 5.2 sessions migration
This commit is contained in:
Laravel Shift 2016-09-29 18:26:31 -04:00 committed by Adam Lavin
parent 9b31b48f37
commit 00f24a5c12
244 changed files with 40326 additions and 40363 deletions

1
.gitignore vendored
View file

@ -3,6 +3,7 @@
/public/build /public/build
/logs /logs
Homestead.yaml Homestead.yaml
/public/storage
.env .env
.vagrant .vagrant
_ide_helper.php _ide_helper.php

View file

@ -45,7 +45,7 @@ class AlbumDownloader
public function download() public function download()
{ {
// Check whether the format is lossless yet not all master files are lossless // Check whether the format is lossless yet not all master files are lossless
$isLosslessFormatWithLossyTracks = in_array($this->_format, Track::$LosslessFormats) $isLosslessFormatWithLossyTracks = in_array($this->_format, Track::$LosslessFormats)
&& !$this->_album->hasLosslessTracksOnly() && !$this->_album->hasLosslessTracksOnly()
&& $this->_album->hasLosslessTracks(); && $this->_album->hasLosslessTracks();
@ -77,11 +77,15 @@ class AlbumDownloader
if ($isLosslessFormatWithLossyTracks && $track->isMasterLossy()) { if ($isLosslessFormatWithLossyTracks && $track->isMasterLossy()) {
$masterFormatName = $track->getMasterFormatName(); $masterFormatName = $track->getMasterFormatName();
$zip->addLargeFile($track->getFileFor($masterFormatName), $zip->addLargeFile(
$directory . $track->getDownloadFilenameFor($masterFormatName)); $track->getFileFor($masterFormatName),
$directory . $track->getDownloadFilenameFor($masterFormatName)
);
} else { } else {
$zip->addLargeFile($track->getFileFor($this->_format), $zip->addLargeFile(
$directory . $track->getDownloadFilenameFor($this->_format)); $track->getFileFor($this->_format),
$directory . $track->getDownloadFilenameFor($this->_format)
);
} }
$notes .= $notes .=

View file

@ -22,7 +22,7 @@ namespace Poniverse\Ponyfm\Commands;
abstract class CommandBase abstract class CommandBase
{ {
private $_listeners = array(); private $_listeners = [];
public function listen($listener) public function listen($listener)
{ {
@ -47,5 +47,5 @@ abstract class CommandBase
/** /**
* @return CommandResponse * @return CommandResponse
*/ */
public abstract function execute(); abstract public function execute();
} }

View file

@ -44,7 +44,6 @@ class CommandResponse
if (is_array($validatorOrMessages)) { if (is_array($validatorOrMessages)) {
$response->_messages = $validatorOrMessages; $response->_messages = $validatorOrMessages;
$response->_validator = null; $response->_validator = null;
} else { } else {
$response->_validator = $validatorOrMessages; $response->_validator = $validatorOrMessages;
} }
@ -102,7 +101,6 @@ class CommandResponse
{ {
if ($this->_validator !== null) { if ($this->_validator !== null) {
return $this->_validator->messages()->getMessages(); return $this->_validator->messages()->getMessages();
} else { } else {
return $this->_messages; return $this->_messages;
} }

View file

@ -100,16 +100,12 @@ class CreateCommentCommand extends CommandBase
// Recount the track's comments, if this is a track comment // Recount the track's comments, if this is a track comment
if ($this->_type === 'track') { if ($this->_type === 'track') {
$entity = Track::find($this->_id); $entity = Track::find($this->_id);
} elseif ($this->_type === 'album') { } elseif ($this->_type === 'album') {
$entity = Album::find($this->_id); $entity = Album::find($this->_id);
} elseif ($this->_type === 'playlist') { } elseif ($this->_type === 'playlist') {
$entity = Playlist::find($this->_id); $entity = Playlist::find($this->_id);
} elseif ($this->_type === 'user') { } elseif ($this->_type === 'user') {
$entity = User::find($this->_id); $entity = User::find($this->_id);
} else { } else {
App::abort(400, 'This comment is being added to an invalid entity!'); App::abort(400, 'This comment is being added to an invalid entity!');
} }

View file

@ -35,7 +35,8 @@ class DeleteGenreCommand extends CommandBase
private $_genreToDelete; private $_genreToDelete;
private $_destinationGenre; private $_destinationGenre;
public function __construct($genreId, $destinationGenreId) { public function __construct($genreId, $destinationGenreId)
{
$this->_genreToDelete = Genre::find($genreId); $this->_genreToDelete = Genre::find($genreId);
$this->_destinationGenre = Genre::find($destinationGenreId); $this->_destinationGenre = Genre::find($destinationGenreId);
} }
@ -43,7 +44,8 @@ class DeleteGenreCommand extends CommandBase
/** /**
* @return bool * @return bool
*/ */
public function authorize() { public function authorize()
{
return Gate::allows('delete', $this->_genreToDelete); return Gate::allows('delete', $this->_genreToDelete);
} }
@ -51,7 +53,8 @@ class DeleteGenreCommand extends CommandBase
* @throws \Exception * @throws \Exception
* @return CommandResponse * @return CommandResponse
*/ */
public function execute() { public function execute()
{
$rules = [ $rules = [
'genre_to_delete' => 'required', 'genre_to_delete' => 'required',
'destination_genre' => 'required', 'destination_genre' => 'required',

View file

@ -35,7 +35,8 @@ class DeleteShowSongCommand extends CommandBase
private $_songToDelete; private $_songToDelete;
private $_destinationSong; private $_destinationSong;
public function __construct($songId, $destinationSongId) { public function __construct($songId, $destinationSongId)
{
$this->_songToDelete = ShowSong::find($songId); $this->_songToDelete = ShowSong::find($songId);
$this->_destinationSong = ShowSong::find($destinationSongId); $this->_destinationSong = ShowSong::find($destinationSongId);
} }
@ -43,7 +44,8 @@ class DeleteShowSongCommand extends CommandBase
/** /**
* @return bool * @return bool
*/ */
public function authorize() { public function authorize()
{
return Gate::allows('delete', $this->_destinationSong); return Gate::allows('delete', $this->_destinationSong);
} }
@ -51,7 +53,8 @@ class DeleteShowSongCommand extends CommandBase
* @throws \Exception * @throws \Exception
* @return CommandResponse * @return CommandResponse
*/ */
public function execute() { public function execute()
{
$rules = [ $rules = [
'song_to_delete' => 'required', 'song_to_delete' => 'required',
'destination_song' => 'required', 'destination_song' => 'required',

View file

@ -100,7 +100,7 @@ class EditAlbumCommand extends CommandBase
$newid = User::where('username', $this->_input['username'])->first()->id; $newid = User::where('username', $this->_input['username'])->first()->id;
if ($this->_album->user_id != $newid) { if ($this->_album->user_id != $newid) {
$this->_album->user_id = $newid; $this->_album->user_id = $newid;
} }
} }

View file

@ -159,8 +159,8 @@ class EditTrackCommand extends CommandBase
$newid = User::where('username', $this->_input['username'])->first()->id; $newid = User::where('username', $this->_input['username'])->first()->id;
if ($track->user_id != $newid) { if ($track->user_id != $newid) {
$oldid = $track->user_id; $oldid = $track->user_id;
$track->user_id = $newid; $track->user_id = $newid;
} }
} }

View file

@ -84,13 +84,10 @@ class GenerateTrackFilesCommand extends CommandBase
if ($isLossyUpload) { if ($isLossyUpload) {
if ($codecString === 'mp3') { if ($codecString === 'mp3') {
$masterFormat = 'MP3'; $masterFormat = 'MP3';
} else if (Str::startsWith($codecString, 'aac')) { } else if (Str::startsWith($codecString, 'aac')) {
$masterFormat = 'AAC'; $masterFormat = 'AAC';
} else if ($codecString === 'vorbis') { } else if ($codecString === 'vorbis') {
$masterFormat = 'OGG Vorbis'; $masterFormat = 'OGG Vorbis';
} else { } else {
$this->track->delete(); $this->track->delete();
return CommandResponse::fail(['track' => "The track does not contain audio in a known lossy format. The format read from the file is: {$codecString}"]); return CommandResponse::fail(['track' => "The track does not contain audio in a known lossy format. The format read from the file is: {$codecString}"]);
@ -156,7 +153,6 @@ class GenerateTrackFilesCommand extends CommandBase
} }
$this->dispatch(new EncodeTrackFile($trackFile, false, false, $this->isForUpload, $this->isReplacingTrack)); $this->dispatch(new EncodeTrackFile($trackFile, false, false, $this->isForUpload, $this->isReplacingTrack));
} }
} catch (InvalidEncodeOptionsException $e) { } catch (InvalidEncodeOptionsException $e) {
// Only delete the track if the track is not being replaced // Only delete the track if the track is not being replaced
if ($this->isReplacingTrack) { if ($this->isReplacingTrack) {
@ -167,7 +163,6 @@ class GenerateTrackFilesCommand extends CommandBase
} }
return CommandResponse::fail(['track' => [$e->getMessage()]]); return CommandResponse::fail(['track' => [$e->getMessage()]]);
} }
} catch (\Exception $e) { } catch (\Exception $e) {
if ($this->isReplacingTrack) { if ($this->isReplacingTrack) {
$this->track->version_upload_status = Track::STATUS_ERROR; $this->track->version_upload_status = Track::STATUS_ERROR;

View file

@ -51,7 +51,7 @@ class MergeAccountsCommand extends CommandBase
*/ */
public function execute() public function execute()
{ {
DB::transaction(function() { DB::transaction(function () {
$accountIds = [$this->sourceAccount->id]; $accountIds = [$this->sourceAccount->id];
foreach (Album::whereIn('user_id', $accountIds)->get() as $album) { foreach (Album::whereIn('user_id', $accountIds)->get() as $album) {

View file

@ -35,7 +35,6 @@ use Poniverse\Ponyfm\Models\User;
use Symfony\Component\HttpFoundation\File\UploadedFile; use Symfony\Component\HttpFoundation\File\UploadedFile;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException; use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class ParseTrackTagsCommand extends CommandBase class ParseTrackTagsCommand extends CommandBase
{ {
private $track; private $track;
@ -107,7 +106,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param Track * @param Track
* @return Track * @return Track
*/ */
private function unsetNullVariables($track) { private function unsetNullVariables($track)
{
$vars = $track->getAttributes(); $vars = $track->getAttributes();
foreach ($vars as $key => $value) { foreach ($vars as $key => $value) {
@ -125,7 +125,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param string $genreName * @param string $genreName
* @return int * @return int
*/ */
protected function getGenreId(string $genreName) { protected function getGenreId(string $genreName)
{
$existingGenre = Genre::withTrashed() $existingGenre = Genre::withTrashed()
->where('name', $genreName)->first(); ->where('name', $genreName)->first();
@ -165,7 +166,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param integer|null $coverId * @param integer|null $coverId
* @return int|null * @return int|null
*/ */
protected function getAlbumId(int $artistId, $albumName, $coverId = null) { protected function getAlbumId(int $artistId, $albumName, $coverId = null)
{
if (null !== $albumName) { if (null !== $albumName) {
$album = Album::firstOrNew([ $album = Album::firstOrNew([
'user_id' => $artistId, 'user_id' => $artistId,
@ -194,7 +196,8 @@ class ParseTrackTagsCommand extends CommandBase
* @return array the "processed" and raw tags extracted from the file * @return array the "processed" and raw tags extracted from the file
* @throws \Exception * @throws \Exception
*/ */
protected function parseOriginalTags(\Symfony\Component\HttpFoundation\File\File $file, User $artist, string $audioCodec) { protected function parseOriginalTags(\Symfony\Component\HttpFoundation\File\File $file, User $artist, string $audioCodec)
{
//========================================================================================================== //==========================================================================================================
// Extract the original tags. // Extract the original tags.
//========================================================================================================== //==========================================================================================================
@ -208,16 +211,12 @@ class ParseTrackTagsCommand extends CommandBase
if ($audioCodec === 'mp3') { if ($audioCodec === 'mp3') {
list($parsedTags, $rawTags) = $this->getId3Tags($allTags); list($parsedTags, $rawTags) = $this->getId3Tags($allTags);
} elseif (Str::startsWith($audioCodec, ['aac', 'alac'])) { } elseif (Str::startsWith($audioCodec, ['aac', 'alac'])) {
list($parsedTags, $rawTags) = $this->getAtomTags($allTags); list($parsedTags, $rawTags) = $this->getAtomTags($allTags);
} elseif (in_array($audioCodec, ['vorbis', 'flac'])) { } elseif (in_array($audioCodec, ['vorbis', 'flac'])) {
list($parsedTags, $rawTags) = $this->getVorbisTags($allTags); list($parsedTags, $rawTags) = $this->getVorbisTags($allTags);
} elseif (Str::startsWith($audioCodec, ['pcm', 'adpcm'])) { } elseif (Str::startsWith($audioCodec, ['pcm', 'adpcm'])) {
list($parsedTags, $rawTags) = $this->getAtomTags($allTags); list($parsedTags, $rawTags) = $this->getAtomTags($allTags);
} else { } else {
// Assume the file is untagged if it's in an unknown format. // Assume the file is untagged if it's in an unknown format.
$parsedTags = [ $parsedTags = [
@ -255,7 +254,6 @@ class ParseTrackTagsCommand extends CommandBase
if ($genreName !== null) { if ($genreName !== null) {
$parsedTags['genre_id'] = $this->getGenreId($genreName); $parsedTags['genre_id'] = $this->getGenreId($genreName);
} else { } else {
$parsedTags['genre_id'] = null; $parsedTags['genre_id'] = null;
} }
@ -270,10 +268,8 @@ class ParseTrackTagsCommand extends CommandBase
if ($image['image_mime'] === 'image/png') { if ($image['image_mime'] === 'image/png') {
$extension = 'png'; $extension = 'png';
} elseif ($image['image_mime'] === 'image/jpeg') { } elseif ($image['image_mime'] === 'image/jpeg') {
$extension = 'jpg'; $extension = 'jpg';
} else { } else {
throw new BadRequestHttpException('Unknown cover format embedded in the track file!'); throw new BadRequestHttpException('Unknown cover format embedded in the track file!');
} }
@ -289,7 +285,6 @@ class ParseTrackTagsCommand extends CommandBase
$cover = Image::upload($imageFile, $artist); $cover = Image::upload($imageFile, $artist);
$coverId = $cover->id; $coverId = $cover->id;
} else { } else {
// no cover art was found - carry on // no cover art was found - carry on
} }
@ -318,7 +313,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param array $rawTags * @param array $rawTags
* @return array * @return array
*/ */
protected function getId3Tags($rawTags) { protected function getId3Tags($rawTags)
{
if (array_key_exists('tags', $rawTags) && array_key_exists('id3v2', $rawTags['tags'])) { if (array_key_exists('tags', $rawTags) && array_key_exists('id3v2', $rawTags['tags'])) {
$tags = $rawTags['tags']['id3v2']; $tags = $rawTags['tags']['id3v2'];
} elseif (array_key_exists('tags', $rawTags) && array_key_exists('id3v1', $rawTags['tags'])) { } elseif (array_key_exists('tags', $rawTags) && array_key_exists('id3v1', $rawTags['tags'])) {
@ -364,7 +360,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param array $rawTags * @param array $rawTags
* @return array * @return array
*/ */
protected function getAtomTags($rawTags) { protected function getAtomTags($rawTags)
{
if (array_key_exists('tags', $rawTags) && array_key_exists('quicktime', $rawTags['tags'])) { if (array_key_exists('tags', $rawTags) && array_key_exists('quicktime', $rawTags['tags'])) {
$tags = $rawTags['tags']['quicktime']; $tags = $rawTags['tags']['quicktime'];
} else { } else {
@ -379,7 +376,6 @@ class ParseTrackTagsCommand extends CommandBase
if (isset($tags['release_date'])) { if (isset($tags['release_date'])) {
$releaseDate = $this->parseDateString($tags['release_date'][0]); $releaseDate = $this->parseDateString($tags['release_date'][0]);
} elseif (isset($tags['creation_date'])) { } elseif (isset($tags['creation_date'])) {
$releaseDate = $this->parseDateString($tags['creation_date'][0]); $releaseDate = $this->parseDateString($tags['creation_date'][0]);
} else { } else {
@ -408,7 +404,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param array $rawTags * @param array $rawTags
* @return array * @return array
*/ */
protected function getVorbisTags($rawTags) { protected function getVorbisTags($rawTags)
{
if (array_key_exists('tags', $rawTags) && array_key_exists('vorbiscomment', $rawTags['tags'])) { if (array_key_exists('tags', $rawTags) && array_key_exists('vorbiscomment', $rawTags['tags'])) {
$tags = $rawTags['tags']['vorbiscomment']; $tags = $rawTags['tags']['vorbiscomment'];
} else { } else {
@ -452,7 +449,8 @@ class ParseTrackTagsCommand extends CommandBase
* @param string $dateString * @param string $dateString
* @return null|Carbon * @return null|Carbon
*/ */
protected function parseDateString(string $dateString) { protected function parseDateString(string $dateString)
{
switch (Str::length($dateString)) { switch (Str::length($dateString)) {
// YYYY // YYYY
case 4: case 4:
@ -475,7 +473,6 @@ class ParseTrackTagsCommand extends CommandBase
// If not, give up. // If not, give up.
try { try {
return Carbon::createFromFormat(Carbon::ISO8601, $dateString); return Carbon::createFromFormat(Carbon::ISO8601, $dateString);
} catch (\InvalidArgumentException $e) { } catch (\InvalidArgumentException $e) {
return null; return null;
} }

View file

@ -94,10 +94,8 @@ class SaveAccountSettingsCommand extends CommandBase
if (isset($this->_input['avatar_id'])) { if (isset($this->_input['avatar_id'])) {
$this->_user->avatar_id = $this->_input['avatar_id']; $this->_user->avatar_id = $this->_input['avatar_id'];
} elseif (isset($this->_input['avatar'])) { } elseif (isset($this->_input['avatar'])) {
$this->_user->avatar_id = Image::upload($this->_input['avatar'], $this->_user)->id; $this->_user->avatar_id = Image::upload($this->_input['avatar'], $this->_user)->id;
} else { } else {
$this->_user->avatar_id = null; $this->_user->avatar_id = null;
} }

View file

@ -25,7 +25,7 @@ use Carbon\Carbon;
use Config; use Config;
use Gate; use Gate;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Validator; use Validator;
@ -73,7 +73,7 @@ class UploadTrackCommand extends CommandBase
int $version = 1, int $version = 1,
$track = null $track = null
) { ) {
$userSlug = Input::get('user_slug', null); $userSlug = Request::get('user_slug', null);
$this->_artist = $this->_artist =
$userSlug !== null $userSlug !== null
? User::where('slug', $userSlug)->first() ? User::where('slug', $userSlug)->first()
@ -94,9 +94,9 @@ class UploadTrackCommand extends CommandBase
*/ */
public function execute() public function execute()
{ {
$trackFile = Input::file('track', null); $trackFile = Request::file('track', null);
if (!$this->_isReplacingTrack) { if (!$this->_isReplacingTrack) {
$coverFile = Input::file('cover', null); $coverFile = Request::file('cover', null);
} }
if (null === $trackFile) { if (null === $trackFile) {
@ -114,7 +114,7 @@ class UploadTrackCommand extends CommandBase
$this->_track->user_id = $this->_artist->id; $this->_track->user_id = $this->_artist->id;
// The title set here is a placeholder; it'll be replaced by ParseTrackTagsCommand // The title set here is a placeholder; it'll be replaced by ParseTrackTagsCommand
// if the file contains a title tag. // if the file contains a title tag.
$this->_track->title = Input::get('title', pathinfo($trackFile->getClientOriginalName(), PATHINFO_FILENAME)); $this->_track->title = Request::get('title', pathinfo($trackFile->getClientOriginalName(), PATHINFO_FILENAME));
// The duration/version of the track cannot be changed until the encoding is successful // The duration/version of the track cannot be changed until the encoding is successful
$this->_track->duration = $audio->getDuration(); $this->_track->duration = $audio->getDuration();
$this->_track->current_version = $this->_version; $this->_track->current_version = $this->_version;
@ -131,7 +131,7 @@ class UploadTrackCommand extends CommandBase
} }
$trackFile = $trackFile->move(Config::get('ponyfm.files_directory').'/queued-tracks', $this->_track->id . 'v' . $this->_version); $trackFile = $trackFile->move(Config::get('ponyfm.files_directory').'/queued-tracks', $this->_track->id . 'v' . $this->_version);
$input = Input::all(); $input = Request::all();
$input['track'] = $trackFile; $input['track'] = $trackFile;
if (!$this->_isReplacingTrack) { if (!$this->_isReplacingTrack) {
$input['cover'] = $coverFile; $input['cover'] = $coverFile;
@ -180,7 +180,7 @@ class UploadTrackCommand extends CommandBase
if (!$this->_isReplacingTrack) { if (!$this->_isReplacingTrack) {
// If json_decode() isn't called here, Laravel will surround the JSON // If json_decode() isn't called here, Laravel will surround the JSON
// string with quotes when storing it in the database, which breaks things. // string with quotes when storing it in the database, which breaks things.
$this->_track->metadata = json_decode(Input::get('metadata', null)); $this->_track->metadata = json_decode(Request::get('metadata', null));
} }
$autoPublish = (bool)($input['auto_publish'] ?? $this->_autoPublishByDefault); $autoPublish = (bool)($input['auto_publish'] ?? $this->_autoPublishByDefault);
$this->_track->source = $this->_customTrackSource ?? 'direct_upload'; $this->_track->source = $this->_customTrackSource ?? 'direct_upload';

View file

@ -108,8 +108,12 @@ class ClassifyMLPMA extends Command
if (Str::contains(Str::lower($track->filename), 'ingram')) { if (Str::contains(Str::lower($track->filename), 'ingram')) {
$this->info('This is an official song remix!'); $this->info('This is an official song remix!');
list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, true, list($trackType, $linkedSongIds) = $this->classifyTrack(
$parsedTags); $track->filename,
$officialSongs,
true,
$parsedTags
);
// If it has "remix" in the name, it's definitely a remix. // If it has "remix" in the name, it's definitely a remix.
@ -117,13 +121,21 @@ class ClassifyMLPMA extends Command
if (Str::contains(Str::lower($sanitizedTrackTitle), 'remix')) { if (Str::contains(Str::lower($sanitizedTrackTitle), 'remix')) {
$this->info('This is some kind of remix!'); $this->info('This is some kind of remix!');
list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, false, list($trackType, $linkedSongIds) = $this->classifyTrack(
$parsedTags); $track->filename,
$officialSongs,
false,
$parsedTags
);
// No idea what this is. Have the pony at the terminal figure it out! // No idea what this is. Have the pony at the terminal figure it out!
} else { } else {
list($trackType, $linkedSongIds) = $this->classifyTrack($track->filename, $officialSongs, false, list($trackType, $linkedSongIds) = $this->classifyTrack(
$parsedTags); $track->filename,
$officialSongs,
false,
$parsedTags
);
} }
} }
@ -144,7 +156,6 @@ class ClassifyMLPMA extends Command
echo PHP_EOL; echo PHP_EOL;
} }
} }
/** /**
@ -169,19 +180,15 @@ class ClassifyMLPMA extends Command
if ($isRemixOfOfficialTrack && sizeof($officialSongs) === 1) { if ($isRemixOfOfficialTrack && sizeof($officialSongs) === 1) {
$linkedSongIds = [$officialSongs[0]->id]; $linkedSongIds = [$officialSongs[0]->id];
} else { } else {
if ($isRemixOfOfficialTrack && sizeof($officialSongs) > 1) { if ($isRemixOfOfficialTrack && sizeof($officialSongs) > 1) {
$this->question('Multiple official songs matched! Please enter the ID of the correct one.'); $this->question('Multiple official songs matched! Please enter the ID of the correct one.');
} else { } else {
if (sizeof($officialSongs) > 0) { if (sizeof($officialSongs) > 0) {
$this->question('This looks like a remix of an official song!'); $this->question('This looks like a remix of an official song!');
$this->question('Press "r" if the match above is right!'); $this->question('Press "r" if the match above is right!');
} else { } else {
$this->question('Exactly what kind of track is this?'); $this->question('Exactly what kind of track is this?');
} }
} }
$this->question('If this is a medley, multiple song ID\'s can be separated by commas. '); $this->question('If this is a medley, multiple song ID\'s can be separated by commas. ');
@ -228,7 +235,7 @@ class ClassifyMLPMA extends Command
default: default:
$trackTypeId = TrackType::OFFICIAL_TRACK_REMIX; $trackTypeId = TrackType::OFFICIAL_TRACK_REMIX;
$linkedSongIds = explode(',', $input); $linkedSongIds = explode(',', $input);
$linkedSongIds = array_map(function($item) { $linkedSongIds = array_map(function ($item) {
return (int) $item; return (int) $item;
}, $linkedSongIds); }, $linkedSongIds);
} }

View file

@ -76,13 +76,10 @@ class ClearTrackCache extends Command
if (count($trackFiles) === 0) { if (count($trackFiles) === 0) {
$this->info('No tracks found. Exiting.'); $this->info('No tracks found. Exiting.');
} else { } else {
if ($this->option('force') || $this->confirm(count($trackFiles) . ' cacheable track files found. Proceed to delete their files if they exist? [y|N]', false)) { if ($this->option('force') || $this->confirm(count($trackFiles) . ' cacheable track files found. Proceed to delete their files if they exist? [y|N]', false)) {
$count = 0; $count = 0;
foreach ($trackFiles as $trackFile) { foreach ($trackFiles as $trackFile) {
// Set expiration to null (so can be re-cached upon request) // Set expiration to null (so can be re-cached upon request)
$trackFile->expires_at = null; $trackFile->expires_at = null;
$trackFile->update(); $trackFile->update();
@ -94,14 +91,11 @@ class ClearTrackCache extends Command
$this->info('Deleted ' . $trackFile->getFile()); $this->info('Deleted ' . $trackFile->getFile());
} }
} }
$this->info($count . ' files deleted. Deletion complete. Exiting.'); $this->info($count . ' files deleted. Deletion complete. Exiting.');
} else { } else {
$this->info('Deletion cancelled. Exiting.'); $this->info('Deletion cancelled. Exiting.');
} }
} }
} }
} }

View file

@ -144,7 +144,6 @@ class FixMLPMAImages extends Command
$imageFile = new UploadedFile($imageFilePath, $imageFilename, $image['image_mime']); $imageFile = new UploadedFile($imageFilePath, $imageFilename, $image['image_mime']);
$cover = Image::upload($imageFile, $artistId, true); $cover = Image::upload($imageFile, $artistId, true);
$coverId = $cover->id; $coverId = $cover->id;
} else { } else {
$this->comment('No cover art found!'); $this->comment('No cover art found!');
} }

View file

@ -101,8 +101,10 @@ class MigrateOldData extends Command
if (!$user->uses_gravatar) { if (!$user->uses_gravatar) {
try { try {
$coverFile = $this->getIdDirectory('users', $user->id).'/'.$user->id.'_.png'; $coverFile = $this->getIdDirectory('users', $user->id).'/'.$user->id.'_.png';
$coverId = Image::upload(new UploadedFile($coverFile, $coverId = Image::upload(new UploadedFile(
$user->id.'_.png'), $user->id)->id; $coverFile,
$user->id.'_.png'
), $user->id)->id;
DB::table('users')->where('id', $user->id)->update(['avatar_id' => $coverId]); DB::table('users')->where('id', $user->id)->update(['avatar_id' => $coverId]);
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could copy user avatar '.$user->id.' because '.$e->getMessage()); $this->error('Could copy user avatar '.$user->id.' because '.$e->getMessage());
@ -176,10 +178,14 @@ class MigrateOldData extends Command
$coverId = null; $coverId = null;
if ($track->cover) { if ($track->cover) {
try { try {
$coverFile = $this->getIdDirectory('tracks', $coverFile = $this->getIdDirectory(
$track->id).'/'.$track->id.'_'.$track->cover.'.png'; 'tracks',
$coverId = Image::upload(new UploadedFile($coverFile, $track->id
$track->id.'_'.$track->cover.'.png'), $track->user_id)->id; ).'/'.$track->id.'_'.$track->cover.'.png';
$coverId = Image::upload(new UploadedFile(
$coverFile,
$track->id.'_'.$track->cover.'.png'
), $track->user_id)->id;
} catch (\Exception $e) { } catch (\Exception $e) {
$this->error('Could copy track cover '.$track->id.' because '.$e->getMessage()); $this->error('Could copy track cover '.$track->id.' because '.$e->getMessage());
} }
@ -396,5 +402,4 @@ class MigrateOldData extends Command
return \Config::get('ponyfm.files_directory').'/'.$type.'/'.$dir; return \Config::get('ponyfm.files_directory').'/'.$type.'/'.$dir;
} }
} }

View file

@ -76,12 +76,10 @@ class PoniverseApiSetup extends Command
'auth' => [$username, $password], 'auth' => [$username, $password],
'query' => ['app' => 'Pony.fm'] 'query' => ['app' => 'Pony.fm']
]); ]);
} catch (ClientException $e) { } catch (ClientException $e) {
if ($e->getResponse()->getStatusCode() === 401) { if ($e->getResponse()->getStatusCode() === 401) {
$this->error('Incorrect username or password! Please try again.'); $this->error('Incorrect username or password! Please try again.');
exit(); exit();
} else { } else {
var_dump($e->getResponse()->getBody()); var_dump($e->getResponse()->getBody());
throw $e; throw $e;
@ -100,16 +98,20 @@ class PoniverseApiSetup extends Command
} }
protected function setEnvironmentVariable($key, $oldValue, $newValue) { protected function setEnvironmentVariable($key, $oldValue, $newValue)
{
$path = base_path('.env'); $path = base_path('.env');
// Detect the specific "null" value. // Detect the specific "null" value.
if ($oldValue === null) if ($oldValue === null) {
$oldValue = 'null'; $oldValue = 'null';
}
if (file_exists($path)) { if (file_exists($path)) {
file_put_contents($path, str_replace( file_put_contents($path, str_replace(
"$key=".$oldValue, "$key=".$newValue, file_get_contents($path) "$key=".$oldValue,
"$key=".$newValue,
file_get_contents($path)
)); ));
} else { } else {
$this->error('Please run `vagrant up`!'); $this->error('Please run `vagrant up`!');

View file

@ -59,7 +59,7 @@ class RebuildArtists extends Command
$bar = $this->output->createProgressBar($numberOfUsers); $bar = $this->output->createProgressBar($numberOfUsers);
foreach(User::with(['tracks' => function($query) { foreach (User::with(['tracks' => function ($query) {
$query->published()->listed(); $query->published()->listed();
}])->get() as $user) { }])->get() as $user) {
$bar->advance(); $bar->advance();

View file

@ -59,11 +59,12 @@ class RebuildFilesizes extends Command
{ {
$this->info('This will only rebuild the cache for track files which exist on disk; non-existent files will be skipped.'); $this->info('This will only rebuild the cache for track files which exist on disk; non-existent files will be skipped.');
if ($this->option('force') || $this->confirm('Are you sure you want to rebuild the filesize cache? [y|N]', if ($this->option('force') || $this->confirm(
false) 'Are you sure you want to rebuild the filesize cache? [y|N]',
false
)
) { ) {
TrackFile::chunk(200, function ($trackFiles) {
TrackFile::chunk(200, function($trackFiles) {
$this->info('========== Start Chunk =========='); $this->info('========== Start Chunk ==========');
@ -79,11 +80,9 @@ class RebuildFilesizes extends Command
} }
$this->info('=========== End Chunk ==========='); $this->info('=========== End Chunk ===========');
}); });
$this->info('Rebuild complete. Exiting.'); $this->info('Rebuild complete. Exiting.');
} else { } else {
$this->info('Rebuild cancelled. Exiting.'); $this->info('Rebuild cancelled. Exiting.');
} }

View file

@ -66,7 +66,7 @@ class RebuildSearchIndex extends Command
$trackProgress = $this->output->createProgressBar($totalTracks); $trackProgress = $this->output->createProgressBar($totalTracks);
$this->info("Processing tracks..."); $this->info("Processing tracks...");
Track::withTrashed()->chunk(200, function(Collection $tracks) use ($trackProgress) { Track::withTrashed()->chunk(200, function (Collection $tracks) use ($trackProgress) {
foreach ($tracks as $track) { foreach ($tracks as $track) {
/** @var Track $track */ /** @var Track $track */
$trackProgress->advance(); $trackProgress->advance();
@ -79,7 +79,7 @@ class RebuildSearchIndex extends Command
$albumProgress = $this->output->createProgressBar($totalAlbums); $albumProgress = $this->output->createProgressBar($totalAlbums);
$this->info("Processing albums..."); $this->info("Processing albums...");
Album::withTrashed()->chunk(200, function(Collection $albums) use ($albumProgress) { Album::withTrashed()->chunk(200, function (Collection $albums) use ($albumProgress) {
foreach ($albums as $album) { foreach ($albums as $album) {
/** @var Album $album */ /** @var Album $album */
$albumProgress->advance(); $albumProgress->advance();
@ -92,7 +92,7 @@ class RebuildSearchIndex extends Command
$playlistProgress = $this->output->createProgressBar($totalPlaylists); $playlistProgress = $this->output->createProgressBar($totalPlaylists);
$this->info("Processing playlists..."); $this->info("Processing playlists...");
Playlist::withTrashed()->chunk(200, function(Collection $playlists) use ($playlistProgress) { Playlist::withTrashed()->chunk(200, function (Collection $playlists) use ($playlistProgress) {
foreach ($playlists as $playlist) { foreach ($playlists as $playlist) {
/** @var Playlist $playlist */ /** @var Playlist $playlist */
$playlistProgress->advance(); $playlistProgress->advance();
@ -105,7 +105,7 @@ class RebuildSearchIndex extends Command
$userProgress = $this->output->createProgressBar($totalUsers); $userProgress = $this->output->createProgressBar($totalUsers);
$this->info("Processing users..."); $this->info("Processing users...");
User::chunk(200, function(Collection $users) use ($userProgress) { User::chunk(200, function (Collection $users) use ($userProgress) {
foreach ($users as $user) { foreach ($users as $user) {
/** @var User $user */ /** @var User $user */
$userProgress->advance(); $userProgress->advance();

View file

@ -59,7 +59,6 @@ class RebuildTags extends Command
if ($this->argument('trackId')) { if ($this->argument('trackId')) {
$track = Track::findOrFail($this->argument('trackId')); $track = Track::findOrFail($this->argument('trackId'));
$tracks = [$track]; $tracks = [$track];
} else { } else {
$tracks = Track::whereNotNull('published_at')->withTrashed()->orderBy('id', 'asc')->get(); $tracks = Track::whereNotNull('published_at')->withTrashed()->orderBy('id', 'asc')->get();
} }
@ -69,7 +68,7 @@ class RebuildTags extends Command
$this->info("Updating tags for ${numberOfTracks} tracks..."); $this->info("Updating tags for ${numberOfTracks} tracks...");
$bar = $this->output->createProgressBar($numberOfTracks); $bar = $this->output->createProgressBar($numberOfTracks);
foreach($tracks as $track) { foreach ($tracks as $track) {
/** @var $track Track */ /** @var $track Track */
$track->updateTags(); $track->updateTags();
$bar->advance(); $bar->advance();

View file

@ -66,7 +66,7 @@ class RebuildTrack extends Command
$track = Track::with('trackFiles')->withTrashed()->find((int) $this->argument('trackId')); $track = Track::with('trackFiles')->withTrashed()->find((int) $this->argument('trackId'));
$this->printTrackInfo($track); $this->printTrackInfo($track);
if($this->option('upload')) { if ($this->option('upload')) {
// The track would've been deleted if its original upload failed. // The track would've been deleted if its original upload failed.
// It should be restored so the user can publish the track! // It should be restored so the user can publish the track!
$track->restore(); $track->restore();
@ -81,7 +81,6 @@ class RebuildTrack extends Command
$this->error("Something went wrong!"); $this->error("Something went wrong!");
print_r($result->getMessages()); print_r($result->getMessages());
} }
} else { } else {
$this->info("Re-encoding this track's files - there should be a line of output for each format!"); $this->info("Re-encoding this track's files - there should be a line of output for each format!");
@ -94,7 +93,8 @@ class RebuildTrack extends Command
} }
} }
private function printTrackInfo(Track $track) { private function printTrackInfo(Track $track)
{
$this->comment("Track info:"); $this->comment("Track info:");
$this->comment(" Title: {$track->title}"); $this->comment(" Title: {$track->title}");
$this->comment(" Uploaded at: {$track->created_at}"); $this->comment(" Uploaded at: {$track->created_at}");

View file

@ -67,10 +67,11 @@ class RebuildTrackCache extends Command
$this->info('If this is your first time running this command, it is *highly* recommended that you ensure the file sizes for all track files have been populated.'); $this->info('If this is your first time running this command, it is *highly* recommended that you ensure the file sizes for all track files have been populated.');
$this->info('***'); $this->info('***');
if ($this->option('force') || $this->confirm('Are you sure you want to delete all to-be-cached track files and encode missing non-cached track files?', if ($this->option('force') || $this->confirm(
false) 'Are you sure you want to delete all to-be-cached track files and encode missing non-cached track files?',
false
)
) { ) {
//========================================================================================================== //==========================================================================================================
// Delete previously cached track files // Delete previously cached track files
//========================================================================================================== //==========================================================================================================
@ -83,7 +84,7 @@ class RebuildTrackCache extends Command
// Chunk track files which are cacheable and NOT master // Chunk track files which are cacheable and NOT master
TrackFile::where('is_cacheable', true) TrackFile::where('is_cacheable', true)
->where('is_master', false) ->where('is_master', false)
->chunk(200, function($trackFiles) use (&$count) { ->chunk(200, function ($trackFiles) use (&$count) {
// Delete chunked track files // Delete chunked track files
foreach ($trackFiles as $trackFile) { foreach ($trackFiles as $trackFile) {
// Clear expiration so will be re-cached on next request // Clear expiration so will be re-cached on next request
@ -115,7 +116,7 @@ class RebuildTrackCache extends Command
TrackFile::where('is_cacheable', false) TrackFile::where('is_cacheable', false)
->whereIn('format', Track::$CacheableFormats) ->whereIn('format', Track::$CacheableFormats)
->where('is_master', false) ->where('is_master', false)
->chunk(200, function($trackFiles) use (&$trackFileCount, &$formats) { ->chunk(200, function ($trackFiles) use (&$trackFileCount, &$formats) {
$this->output->newLine(1); $this->output->newLine(1);
$this->info('---------- Start Chunk ----------'); $this->info('---------- Start Chunk ----------');
@ -150,7 +151,7 @@ class RebuildTrackCache extends Command
// Chunk track files which are NOT meant to be cacheable, but currently cacheable // Chunk track files which are NOT meant to be cacheable, but currently cacheable
TrackFile::where('is_cacheable', true) TrackFile::where('is_cacheable', true)
->whereNotIn('format', Track::$CacheableFormats) ->whereNotIn('format', Track::$CacheableFormats)
->chunk(200, function($trackFiles) use (&$trackFileCount, &$formats) { ->chunk(200, function ($trackFiles) use (&$trackFileCount, &$formats) {
$this->output->newLine(1); $this->output->newLine(1);
$this->info('---------- Start Chunk ----------'); $this->info('---------- Start Chunk ----------');
@ -188,7 +189,7 @@ class RebuildTrackCache extends Command
// Find track files which are cacheable and NOT master // Find track files which are cacheable and NOT master
TrackFile::whereIn('format', Track::$CacheableFormats) TrackFile::whereIn('format', Track::$CacheableFormats)
->where('is_master', false) ->where('is_master', false)
->chunk(200, function($trackFiles) use (&$count, &$trackFileCount) { ->chunk(200, function ($trackFiles) use (&$count, &$trackFileCount) {
$this->output->newLine(1); $this->output->newLine(1);
$this->info('---------- Start Chunk ----------'); $this->info('---------- Start Chunk ----------');
@ -223,36 +224,35 @@ class RebuildTrackCache extends Command
// Chunk non-cacheable track files // Chunk non-cacheable track files
TrackFile::where('is_cacheable', false) TrackFile::where('is_cacheable', false)
->where('is_master', false) ->where('is_master', false)
->chunk(200, function($trackFiles) use (&$count) { ->chunk(200, function ($trackFiles) use (&$count) {
$this->output->newLine(1); $this->output->newLine(1);
$this->info('---------- Start Chunk ----------'); $this->info('---------- Start Chunk ----------');
// Record the track files which do not exist (i.e., have not been encoded yet) // Record the track files which do not exist (i.e., have not been encoded yet)
$emptyTrackFiles = []; $emptyTrackFiles = [];
foreach ($trackFiles as $trackFile) { foreach ($trackFiles as $trackFile) {
if (!File::exists($trackFile->getFile())) { if (!File::exists($trackFile->getFile())) {
$count++; $count++;
$emptyTrackFiles[] = $trackFile; $emptyTrackFiles[] = $trackFile;
}
} }
}
// Encode recorded track files // Encode recorded track files
foreach ($emptyTrackFiles as $emptyTrackFile) { foreach ($emptyTrackFiles as $emptyTrackFile) {
$this->info("Started encoding track file ID {$emptyTrackFile->id}"); $this->info("Started encoding track file ID {$emptyTrackFile->id}");
$this->dispatch(new EncodeTrackFile($emptyTrackFile, false)); $this->dispatch(new EncodeTrackFile($emptyTrackFile, false));
} }
$this->info('----------- End Chunk -----------'); $this->info('----------- End Chunk -----------');
$this->output->newLine(1); $this->output->newLine(1);
}); });
$this->info($count.' track files encoded.'); $this->info($count.' track files encoded.');
$this->output->newLine(1); $this->output->newLine(1);
$this->info('Rebuild complete. Exiting.'); $this->info('Rebuild complete. Exiting.');
} else { } else {
$this->info('Rebuild cancelled. Exiting.'); $this->info('Rebuild cancelled. Exiting.');
} }

View file

@ -61,7 +61,6 @@ class VersionFiles extends Command
$this->info('This will only version track files which exist on disk; non-existent files will be skipped.'); $this->info('This will only version track files which exist on disk; non-existent files will be skipped.');
if ($this->option('force') || $this->confirm('Are you sure you want to rename all unversioned track files? [y|N]', false)) { if ($this->option('force') || $this->confirm('Are you sure you want to rename all unversioned track files? [y|N]', false)) {
TrackFile::chunk(200, function ($trackFiles) { TrackFile::chunk(200, function ($trackFiles) {
$this->info('========== Start Chunk =========='); $this->info('========== Start Chunk ==========');
@ -81,15 +80,12 @@ class VersionFiles extends Command
} else { } else {
$this->error('ID ' . $trackFile->id . ' was unable to be renamed'); $this->error('ID ' . $trackFile->id . ' was unable to be renamed');
} }
} }
$this->info('=========== End Chunk ==========='); $this->info('=========== End Chunk ===========');
}); });
$this->info('Rebuild complete. Exiting.'); $this->info('Rebuild complete. Exiting.');
} else { } else {
$this->info('Rebuild cancelled. Exiting.'); $this->info('Rebuild cancelled. Exiting.');
} }

View file

@ -28,7 +28,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* *
* @package Poniverse\Ponyfm\Contracts * @package Poniverse\Ponyfm\Contracts
*/ */
interface Commentable extends GeneratesNotifications { interface Commentable extends GeneratesNotifications
{
/** /**
* This method returns an Eloquent relation to the entity's comments. * This method returns an Eloquent relation to the entity's comments.
* *

View file

@ -28,7 +28,8 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
* *
* @package Poniverse\Ponyfm\Contracts * @package Poniverse\Ponyfm\Contracts
*/ */
interface Favouritable extends GeneratesNotifications { interface Favouritable extends GeneratesNotifications
{
/** /**
* This method returns an Eloquent relation to the entity's favourites. * This method returns an Eloquent relation to the entity's favourites.
* *

View file

@ -29,11 +29,12 @@ use Poniverse\Ponyfm\Models\User;
* *
* @package Poniverse\Ponyfm\Contracts * @package Poniverse\Ponyfm\Contracts
*/ */
interface GeneratesNotifications { interface GeneratesNotifications
{
/** /**
* Returns a human-friendly string (lowercase & singular) representing this * Returns a human-friendly string (lowercase & singular) representing this
* type of resource. * type of resource.
* *
* @return string * @return string
*/ */
public function getResourceType():string; public function getResourceType():string;

View file

@ -28,12 +28,13 @@ use Poniverse\Ponyfm\Models\User;
/** /**
* Interface NotificationHandler * Interface NotificationHandler
* @package Poniverse\Ponyfm\Contracts * @package Poniverse\Ponyfm\Contracts
* *
* Each method in this interface represents a type of notification. To add a new * Each method in this interface represents a type of notification. To add a new
* type of notification, add a method for it to this interface and every class * type of notification, add a method for it to this interface and every class
* that implements it. Your IDE should be able to help with this. * that implements it. Your IDE should be able to help with this.
*/ */
interface NotificationHandler { interface NotificationHandler
{
/** /**
* @param Track $track * @param Track $track
* @return void * @return void

View file

@ -20,7 +20,8 @@
namespace Poniverse\Ponyfm\Contracts; namespace Poniverse\Ponyfm\Contracts;
interface Searchable { interface Searchable
{
/** /**
* Returns this model in Elasticsearch-friendly form. The array returned by * Returns this model in Elasticsearch-friendly form. The array returned by
* this method should match the current mapping for this model's ES type. * this method should match the current mapping for this model's ES type.

View file

@ -22,6 +22,8 @@ namespace Poniverse\Ponyfm\Exceptions;
use Exception; use Exception;
use Symfony\Component\HttpKernel\Exception\HttpException; use Symfony\Component\HttpKernel\Exception\HttpException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Validation\ValidationException;
use GrahamCampbell\Exceptions\ExceptionHandler as ExceptionHandler; use GrahamCampbell\Exceptions\ExceptionHandler as ExceptionHandler;
class Handler extends ExceptionHandler class Handler extends ExceptionHandler
@ -32,6 +34,8 @@ class Handler extends ExceptionHandler
* @var array * @var array
*/ */
protected $dontReport = [ protected $dontReport = [
AuthorizationException::class,
ValidationException::class,
HttpException::class, HttpException::class,
]; ];
@ -45,7 +49,7 @@ class Handler extends ExceptionHandler
*/ */
public function report(Exception $e) public function report(Exception $e)
{ {
return parent::report($e); parent::report($e);
} }
/** /**

View file

@ -29,4 +29,6 @@ use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
* This exception indicates that an access token we attempted to introspect * This exception indicates that an access token we attempted to introspect
* through the Poniverse API is expired or otherwise unusable. * through the Poniverse API is expired or otherwise unusable.
*/ */
class InvalidAccessTokenException extends AccessDeniedHttpException {}; class InvalidAccessTokenException extends AccessDeniedHttpException
{
};

View file

@ -22,4 +22,6 @@ namespace Poniverse\Ponyfm\Exceptions;
use InvalidArgumentException; use InvalidArgumentException;
class InvalidEncodeOptionsException extends InvalidArgumentException {} class InvalidEncodeOptionsException extends InvalidArgumentException
{
}

View file

@ -31,4 +31,6 @@ use Illuminate\Database\Eloquent\ModelNotFoundException;
* contain tracks for which no lossless master is available (and thus, lossless * contain tracks for which no lossless master is available (and thus, lossless
* `TrackFiles` don't exist for). * `TrackFiles` don't exist for).
*/ */
class TrackFileNotFoundException extends ModelNotFoundException {} class TrackFileNotFoundException extends ModelNotFoundException
{
}

View file

@ -19,10 +19,13 @@
*/ */
namespace Poniverse\Ponyfm\Facades; namespace Poniverse\Ponyfm\Facades;
use Illuminate\Support\Facades\Facade; use Illuminate\Support\Facades\Facade;
class Notification extends Facade { class Notification extends Facade
protected static function getFacadeAccessor() { {
protected static function getFacadeAccessor()
{
return 'notification'; return 'notification';
} }
} }

View file

@ -35,7 +35,7 @@ class TracksController extends Controller
->published() ->published()
->with('user', 'genre', 'cover', 'album', 'album.user')->take(10)->get(); ->with('user', 'genre', 'cover', 'album', 'album.user')->take(10)->get();
$tracks = $tracks->map(function(Track $track) { $tracks = $tracks->map(function (Track $track) {
return Track::mapPublicTrackSummary($track); return Track::mapPublicTrackSummary($track);
}); });

View file

@ -28,7 +28,8 @@ use Response;
class TracksController extends ApiControllerBase class TracksController extends ApiControllerBase
{ {
public function postUploadTrack() { public function postUploadTrack()
{
session_write_close(); session_write_close();
$response = $this->execute(new UploadTrackCommand(true, true, session('api_client_id'), true)); $response = $this->execute(new UploadTrackCommand(true, true, session('api_client_id'), true));
@ -53,13 +54,13 @@ class TracksController extends ApiControllerBase
} }
public function getUploadStatus($trackId) { public function getUploadStatus($trackId)
{
$track = Track::findOrFail($trackId); $track = Track::findOrFail($trackId);
$this->authorize('edit', $track); $this->authorize('edit', $track);
if ($track->status === Track::STATUS_PROCESSING) { if ($track->status === Track::STATUS_PROCESSING) {
return Response::json(['message' => 'Processing...'], 202); return Response::json(['message' => 'Processing...'], 202);
} elseif ($track->status === Track::STATUS_COMPLETE) { } elseif ($track->status === Track::STATUS_COMPLETE) {
return Response::json([ return Response::json([
'message' => $track->published_at 'message' => $track->published_at
@ -68,7 +69,6 @@ class TracksController extends ApiControllerBase
'edit_url' => action('ContentController@getTracks', ['id' => $trackId]), 'edit_url' => action('ContentController@getTracks', ['id' => $trackId]),
'track_url' => $track->url 'track_url' => $track->url
], 201); ], 201);
} else { } else {
// something went wrong // something went wrong
return Response::json(['error' => 'Processing failed! Please contact logic@pony.fm to figure out what went wrong.'], 500); return Response::json(['error' => 'Processing failed! Please contact logic@pony.fm to figure out what went wrong.'], 500);

View file

@ -26,7 +26,7 @@ use Poniverse\Ponyfm\Commands\SaveAccountSettingsCommand;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Gate; use Gate;
use Auth; use Auth;
use Input; use Illuminate\Support\Facades\Request;
use Response; use Response;
class AccountController extends ApiControllerBase class AccountController extends ApiControllerBase
@ -77,6 +77,6 @@ class AccountController extends ApiControllerBase
public function postSave(User $user) public function postSave(User $user)
{ {
return $this->execute(new SaveAccountSettingsCommand(Input::all(), $user)); return $this->execute(new SaveAccountSettingsCommand(Request::all(), $user));
} }
} }

View file

@ -30,7 +30,7 @@ use Poniverse\Ponyfm\Models\Image;
use Poniverse\Ponyfm\Models\ResourceLogItem; use Poniverse\Ponyfm\Models\ResourceLogItem;
use Auth; use Auth;
use Gate; use Gate;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Response; use Response;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
@ -39,12 +39,12 @@ class AlbumsController extends ApiControllerBase
{ {
public function postCreate() public function postCreate()
{ {
return $this->execute(new CreateAlbumCommand(Input::all())); return $this->execute(new CreateAlbumCommand(Request::all()));
} }
public function postEdit($id) public function postEdit($id)
{ {
return $this->execute(new EditAlbumCommand($id, Input::all())); return $this->execute(new EditAlbumCommand($id, Request::all()));
} }
public function postDelete($id) public function postDelete($id)
@ -55,7 +55,7 @@ class AlbumsController extends ApiControllerBase
public function getShow($id) public function getShow($id)
{ {
$album = Album::with([ $album = Album::with([
'tracks' => function($query) { 'tracks' => function ($query) {
$query->userDetails(); $query->userDetails();
}, },
'tracks.cover', 'tracks.cover',
@ -75,7 +75,7 @@ class AlbumsController extends ApiControllerBase
App::abort(404); App::abort(404);
} }
if (Input::get('log')) { if (Request::get('log')) {
ResourceLogItem::logItem('album', $id, ResourceLogItem::VIEW); ResourceLogItem::logItem('album', $id, ResourceLogItem::VIEW);
$album->view_count++; $album->view_count++;
} }
@ -96,7 +96,6 @@ class AlbumsController extends ApiControllerBase
try { try {
/** @var Album $album */ /** @var Album $album */
$album = Album::with('tracks.trackFiles')->findOrFail($id); $album = Album::with('tracks.trackFiles')->findOrFail($id);
} catch (ModelNotFoundException $e) { } catch (ModelNotFoundException $e) {
return $this->notFound('Album not found!'); return $this->notFound('Album not found!');
} }
@ -121,8 +120,8 @@ class AlbumsController extends ApiControllerBase
public function getIndex() public function getIndex()
{ {
$page = 1; $page = 1;
if (Input::has('page')) { if (Request::has('page')) {
$page = Input::get('page'); $page = Request::get('page');
} }
$query = Album::summary() $query = Album::summary()
@ -144,8 +143,10 @@ class AlbumsController extends ApiControllerBase
$albums[] = Album::mapPublicAlbumSummary($album); $albums[] = Album::mapPublicAlbumSummary($album);
} }
return Response::json(["albums" => $albums, "current_page" => $page, "total_pages" => ceil($count / $perPage)], return Response::json(
200); ["albums" => $albums, "current_page" => $page, "total_pages" => ceil($count / $perPage)],
200
);
} }
public function getOwned(User $user) public function getOwned(User $user)

View file

@ -31,7 +31,7 @@ use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Poniverse\Ponyfm\Models\Follower; use Poniverse\Ponyfm\Models\Follower;
use App; use App;
use Input; use Illuminate\Support\Facades\Request;
use Response; use Response;
use ColorThief\ColorThief; use ColorThief\ColorThief;
use Helpers; use Helpers;
@ -63,7 +63,7 @@ class ArtistsController extends ApiControllerBase
'album' => function ($query) { 'album' => function ($query) {
$query->userDetails(); $query->userDetails();
} }
])->get(); ])->get();
$tracks = []; $tracks = [];
$albums = []; $albums = [];
@ -209,8 +209,8 @@ class ArtistsController extends ApiControllerBase
public function getIndex() public function getIndex()
{ {
$page = 1; $page = 1;
if (Input::has('page')) { if (Request::has('page')) {
$page = Input::get('page'); $page = Request::get('page');
} }
$query = User::where('track_count', '>', 0); $query = User::where('track_count', '>', 0);
@ -227,12 +227,15 @@ class ArtistsController extends ApiControllerBase
$users[] = User::mapPublicUserSummary($user); $users[] = User::mapPublicUserSummary($user);
} }
return Response::json(["artists" => $users, "current_page" => $page, "total_pages" => ceil($count / $perPage)], return Response::json(
200); ["artists" => $users, "current_page" => $page, "total_pages" => ceil($count / $perPage)],
200
);
} }
public function postIndex() { public function postIndex()
$name = Input::json('username'); {
$name = Request::json('username');
return $this->execute(new CreateUserCommand($name, $name, null, true)); return $this->execute(new CreateUserCommand($name, $name, null, true));
} }
} }

View file

@ -24,14 +24,14 @@ use App;
use Poniverse\Ponyfm\Commands\CreateCommentCommand; use Poniverse\Ponyfm\Commands\CreateCommentCommand;
use Poniverse\Ponyfm\Models\Comment; use Poniverse\Ponyfm\Models\Comment;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Input; use Illuminate\Support\Facades\Request;
use Response; use Response;
class CommentsController extends ApiControllerBase class CommentsController extends ApiControllerBase
{ {
public function postCreate($type, $id) public function postCreate($type, $id)
{ {
return $this->execute(new CreateCommentCommand($type, $id, Input::all())); return $this->execute(new CreateCommentCommand($type, $id, Request::all()));
} }
public function getIndex($type, $id) public function getIndex($type, $id)

View file

@ -39,7 +39,7 @@ class DashboardController extends ApiControllerBase
->orderBy('published_at', 'desc') ->orderBy('published_at', 'desc')
->take(30); ->take(30);
$recentQuery->whereHas('user', function($q) { $recentQuery->whereHas('user', function ($q) {
$q->whereIsArchived(false); $q->whereIsArchived(false);
}); });

View file

@ -27,14 +27,14 @@ use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Poniverse\Ponyfm\Models\Playlist; use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use Auth; use Auth;
use Input; use Illuminate\Support\Facades\Request;
use Response; use Response;
class FavouritesController extends ApiControllerBase class FavouritesController extends ApiControllerBase
{ {
public function postToggle() public function postToggle()
{ {
return $this->execute(new ToggleFavouriteCommand(Input::get('type'), Input::get('id'))); return $this->execute(new ToggleFavouriteCommand(Request::get('type'), Request::get('id')));
} }
public function getTracks() public function getTracks()
@ -43,7 +43,7 @@ class FavouritesController extends ApiControllerBase
::whereUserId(Auth::user()->id) ::whereUserId(Auth::user()->id)
->whereNotNull('track_id') ->whereNotNull('track_id')
->with([ ->with([
'track' => function($query) { 'track' => function ($query) {
$query $query
->userDetails() ->userDetails()
->published(); ->published();
@ -58,8 +58,7 @@ class FavouritesController extends ApiControllerBase
$tracks = []; $tracks = [];
foreach ($query->get() as $fav) { foreach ($query->get() as $fav) {
if ($fav->track == null) // deleted track if ($fav->track == null) { // deleted track
{
continue; continue;
} }
@ -75,7 +74,7 @@ class FavouritesController extends ApiControllerBase
::whereUserId(Auth::user()->id) ::whereUserId(Auth::user()->id)
->whereNotNull('album_id') ->whereNotNull('album_id')
->with([ ->with([
'album' => function($query) { 'album' => function ($query) {
$query->userDetails(); $query->userDetails();
}, },
'album.user', 'album.user',
@ -86,8 +85,7 @@ class FavouritesController extends ApiControllerBase
$albums = []; $albums = [];
foreach ($query->get() as $fav) { foreach ($query->get() as $fav) {
if ($fav->album == null) // deleted album if ($fav->album == null) { // deleted album
{
continue; continue;
} }
@ -103,7 +101,7 @@ class FavouritesController extends ApiControllerBase
::whereUserId(Auth::user()->id) ::whereUserId(Auth::user()->id)
->whereNotNull('playlist_id') ->whereNotNull('playlist_id')
->with([ ->with([
'playlist' => function($query) { 'playlist' => function ($query) {
$query->userDetails(); $query->userDetails();
}, },
'playlist.user', 'playlist.user',
@ -115,8 +113,7 @@ class FavouritesController extends ApiControllerBase
$playlists = []; $playlists = [];
foreach ($query->get() as $fav) { foreach ($query->get() as $fav) {
if ($fav->playlist == null) // deleted playlist if ($fav->playlist == null) { // deleted playlist
{
continue; continue;
} }

View file

@ -22,12 +22,12 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Poniverse\Ponyfm\Commands\ToggleFollowingCommand; use Poniverse\Ponyfm\Commands\ToggleFollowingCommand;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Input; use Illuminate\Support\Facades\Request;
class FollowController extends ApiControllerBase class FollowController extends ApiControllerBase
{ {
public function postToggle() public function postToggle()
{ {
return $this->execute(new ToggleFollowingCommand(Input::get('type'), Input::get('id'))); return $this->execute(new ToggleFollowingCommand(Request::get('type'), Request::get('id')));
} }
} }

View file

@ -20,7 +20,7 @@
namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Commands\CreateGenreCommand; use Poniverse\Ponyfm\Commands\CreateGenreCommand;
use Poniverse\Ponyfm\Commands\DeleteGenreCommand; use Poniverse\Ponyfm\Commands\DeleteGenreCommand;
use Poniverse\Ponyfm\Commands\RenameGenreCommand; use Poniverse\Ponyfm\Commands\RenameGenreCommand;
@ -28,14 +28,13 @@ use Poniverse\Ponyfm\Models\Genre;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Response; use Response;
class GenresController extends ApiControllerBase class GenresController extends ApiControllerBase
{ {
public function getIndex() public function getIndex()
{ {
$this->authorize('access-admin-area'); $this->authorize('access-admin-area');
$genres = Genre::with(['trackCountRelation' => function($query) { $genres = Genre::with(['trackCountRelation' => function ($query) {
$query->withTrashed(); $query->withTrashed();
}]) }])
->orderBy('name', 'asc') ->orderBy('name', 'asc')
@ -48,20 +47,20 @@ class GenresController extends ApiControllerBase
public function postCreate() public function postCreate()
{ {
$command = new CreateGenreCommand(Input::get('name')); $command = new CreateGenreCommand(Request::get('name'));
return $this->execute($command); return $this->execute($command);
} }
public function putRename($genreId) public function putRename($genreId)
{ {
$command = new RenameGenreCommand($genreId, Input::get('name')); $command = new RenameGenreCommand($genreId, Request::get('name'));
return $this->execute($command); return $this->execute($command);
} }
public function deleteGenre($genreId) public function deleteGenre($genreId)
{ {
$command = new DeleteGenreCommand($genreId, Input::get('destination_genre_id')); $command = new DeleteGenreCommand($genreId, Request::get('destination_genre_id'));
return $this->execute($command); return $this->execute($command);
} }
} }

View file

@ -21,7 +21,7 @@
namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Auth; use Auth;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Poniverse\Ponyfm\Models\Notification; use Poniverse\Ponyfm\Models\Notification;
use Poniverse\Ponyfm\Models\Subscription; use Poniverse\Ponyfm\Models\Subscription;
@ -56,7 +56,7 @@ class NotificationsController extends ApiControllerBase
*/ */
public function putMarkAsRead() public function putMarkAsRead()
{ {
$notificationIds = Input::json('notification_ids'); $notificationIds = Request::json('notification_ids');
$numberOfUpdatedRows = Auth::user() $numberOfUpdatedRows = Auth::user()
->notifications() ->notifications()
->whereIn('id', $notificationIds) ->whereIn('id', $notificationIds)
@ -74,7 +74,7 @@ class NotificationsController extends ApiControllerBase
*/ */
public function postSubscribe() public function postSubscribe()
{ {
$input = json_decode(Input::json('subscription')); $input = json_decode(Request::json('subscription'));
if ($input != 'null') { if ($input != 'null') {
$existing = Subscription::where('endpoint', '=', $input->endpoint) $existing = Subscription::where('endpoint', '=', $input->endpoint)
->where('user_id', '=', Auth::user()->id) ->where('user_id', '=', Auth::user()->id)
@ -104,7 +104,7 @@ class NotificationsController extends ApiControllerBase
*/ */
public function postUnsubscribe() public function postUnsubscribe()
{ {
$input = json_decode(Input::json('subscription')); $input = json_decode(Request::json('subscription'));
$existing = Subscription::where('endpoint', '=', $input->endpoint) $existing = Subscription::where('endpoint', '=', $input->endpoint)
->where('user_id', '=', Auth::user()->id) ->where('user_id', '=', Auth::user()->id)

View file

@ -31,7 +31,7 @@ use Poniverse\Ponyfm\Models\Image;
use Poniverse\Ponyfm\Models\Playlist; use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\ResourceLogItem; use Poniverse\Ponyfm\Models\ResourceLogItem;
use Auth; use Auth;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Response; use Response;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
@ -40,12 +40,12 @@ class PlaylistsController extends ApiControllerBase
{ {
public function postCreate() public function postCreate()
{ {
return $this->execute(new CreatePlaylistCommand(Input::all())); return $this->execute(new CreatePlaylistCommand(Request::all()));
} }
public function postEdit($id) public function postEdit($id)
{ {
return $this->execute(new EditPlaylistCommand($id, Input::all())); return $this->execute(new EditPlaylistCommand($id, Request::all()));
} }
public function postDelete($id) public function postDelete($id)
@ -55,27 +55,29 @@ class PlaylistsController extends ApiControllerBase
public function postAddTrack($id) public function postAddTrack($id)
{ {
return $this->execute(new AddTrackToPlaylistCommand($id, Input::get('track_id'))); return $this->execute(new AddTrackToPlaylistCommand($id, Request::get('track_id')));
} }
public function postRemoveTrack($id) public function postRemoveTrack($id)
{ {
return $this->execute(new RemoveTrackFromPlaylistCommand($id, Input::get('track_id'))); return $this->execute(new RemoveTrackFromPlaylistCommand($id, Request::get('track_id')));
} }
public function getIndex() public function getIndex()
{ {
$page = Input::has('page') ? Input::get('page') : 1; $page = Request::has('page') ? Request::get('page') : 1;
$query = Playlist::summary() $query = Playlist::summary()
->with('user', ->with(
'user',
'user.avatar', 'user.avatar',
'tracks', 'tracks',
'tracks.cover', 'tracks.cover',
'tracks.user', 'tracks.user',
'tracks.user.avatar', 'tracks.user.avatar',
'tracks.album', 'tracks.album',
'tracks.album.user') 'tracks.album.user'
)
->userDetails() ->userDetails()
// A playlist with only one track is not much of a list. // A playlist with only one track is not much of a list.
->where('track_count', '>', 1) ->where('track_count', '>', 1)
@ -106,7 +108,7 @@ class PlaylistsController extends ApiControllerBase
'tracks.genre', 'tracks.genre',
'tracks.cover', 'tracks.cover',
'tracks.album', 'tracks.album',
'tracks' => function($query) { 'tracks' => function ($query) {
$query->userDetails(); $query->userDetails();
}, },
'tracks.trackFiles', 'tracks.trackFiles',
@ -117,7 +119,7 @@ class PlaylistsController extends ApiControllerBase
App::abort('404'); App::abort('404');
} }
if (Input::get('log')) { if (Request::get('log')) {
ResourceLogItem::logItem('playlist', $id, ResourceLogItem::VIEW); ResourceLogItem::logItem('playlist', $id, ResourceLogItem::VIEW);
$playlist->view_count++; $playlist->view_count++;
} }
@ -161,7 +163,7 @@ class PlaylistsController extends ApiControllerBase
$query = Playlist $query = Playlist
::userDetails() ::userDetails()
->with('tracks', 'tracks.cover', 'tracks.user', 'user') ->with('tracks', 'tracks.cover', 'tracks.user', 'user')
->join('pinned_playlists', function($join) { ->join('pinned_playlists', function ($join) {
$join->on('playlist_id', '=', 'playlists.id'); $join->on('playlist_id', '=', 'playlists.id');
}) })
->where('pinned_playlists.user_id', '=', Auth::user()->id) ->where('pinned_playlists.user_id', '=', Auth::user()->id)
@ -221,8 +223,8 @@ class PlaylistsController extends ApiControllerBase
*/ */
private function applyOrdering($query) private function applyOrdering($query)
{ {
if (Input::has('order')) { if (Request::has('order')) {
$order = \Input::get('order'); $order = \Request::get('order');
$parts = explode(',', $order); $parts = explode(',', $order);
$query->orderBy($parts[0], $parts[1]); $query->orderBy($parts[0], $parts[1]);
} }

View file

@ -22,7 +22,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Elasticsearch; use Elasticsearch;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Library\Search; use Poniverse\Ponyfm\Library\Search;
use Response; use Response;
@ -30,7 +30,7 @@ class SearchController extends ApiControllerBase
{ {
public function getSearch(Search $search) public function getSearch(Search $search)
{ {
$results = $search->searchAllContent(Input::query('query')); $results = $search->searchAllContent(Request::query('query'));
return Response::json([ return Response::json([
'results' => $results, 'results' => $results,

View file

@ -20,7 +20,7 @@
namespace Poniverse\Ponyfm\Http\Controllers\Api\Web; namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Commands\CreateShowSongCommand; use Poniverse\Ponyfm\Commands\CreateShowSongCommand;
use Poniverse\Ponyfm\Commands\DeleteShowSongCommand; use Poniverse\Ponyfm\Commands\DeleteShowSongCommand;
use Poniverse\Ponyfm\Commands\RenameShowSongCommand; use Poniverse\Ponyfm\Commands\RenameShowSongCommand;
@ -28,14 +28,13 @@ use Poniverse\Ponyfm\Models\ShowSong;
use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase; use Poniverse\Ponyfm\Http\Controllers\ApiControllerBase;
use Response; use Response;
class ShowSongsController extends ApiControllerBase class ShowSongsController extends ApiControllerBase
{ {
public function getIndex() public function getIndex()
{ {
$this->authorize('access-admin-area'); $this->authorize('access-admin-area');
$songs = ShowSong::with(['trackCountRelation' => function($query) { $songs = ShowSong::with(['trackCountRelation' => function ($query) {
$query->withTrashed(); $query->withTrashed();
}]) }])
->orderBy('title', 'asc') ->orderBy('title', 'asc')
@ -49,20 +48,20 @@ class ShowSongsController extends ApiControllerBase
public function postCreate() public function postCreate()
{ {
$command = new CreateShowSongCommand(Input::get('title')); $command = new CreateShowSongCommand(Request::get('title'));
return $this->execute($command); return $this->execute($command);
} }
public function putRename($songId) public function putRename($songId)
{ {
$command = new RenameShowSongCommand($songId, Input::get('title')); $command = new RenameShowSongCommand($songId, Request::get('title'));
return $this->execute($command); return $this->execute($command);
} }
public function deleteSong($songId) public function deleteSong($songId)
{ {
$command = new DeleteShowSongCommand($songId, Input::get('destination_song_id')); $command = new DeleteShowSongCommand($songId, Request::get('destination_song_id'));
return $this->execute($command); return $this->execute($command);
} }
} }

View file

@ -32,7 +32,8 @@ use Carbon\Carbon;
class StatsController extends ApiControllerBase class StatsController extends ApiControllerBase
{ {
private function getStatsData($id, $hourly = false) { private function getStatsData($id, $hourly = false)
{
$playRange = "'1 MONTH'"; $playRange = "'1 MONTH'";
if ($hourly) { if ($hourly) {
@ -51,7 +52,8 @@ class StatsController extends ApiControllerBase
return $statQuery; return $statQuery;
} }
private function sortTrackStatsArray($query, $hourly = false) { private function sortTrackStatsArray($query, $hourly = false)
{
$now = Carbon::now(); $now = Carbon::now();
$playsArray = []; $playsArray = [];
$output = []; $output = [];
@ -104,8 +106,9 @@ class StatsController extends ApiControllerBase
} }
} }
public function getTrackStats($id) { public function getTrackStats($id)
$cachedOutput = Cache::remember('track_stats'.$id, 5, function() use ($id) { {
$cachedOutput = Cache::remember('track_stats'.$id, 5, function () use ($id) {
try { try {
$track = Track::published()->findOrFail($id); $track = Track::published()->findOrFail($id);
} catch (ModelNotFoundException $e) { } catch (ModelNotFoundException $e) {

View file

@ -37,12 +37,18 @@ class TaxonomiesController extends ApiControllerBase
->orderBy('name') ->orderBy('name')
->get() ->get()
->toArray(), ->toArray(),
'track_types' => TrackType::select('track_types.*', 'track_types' => TrackType::select(
DB::raw('(SELECT COUNT(id) FROM tracks WHERE tracks.track_type_id = track_types.id AND tracks.published_at IS NOT NULL) AS track_count')) 'track_types.*',
DB::raw('(SELECT COUNT(id) FROM tracks WHERE tracks.track_type_id = track_types.id AND tracks.published_at IS NOT NULL) AS track_count')
)
->where('id', '!=', TrackType::UNCLASSIFIED_TRACK) ->where('id', '!=', TrackType::UNCLASSIFIED_TRACK)
->get()->toArray(), ->get()->toArray(),
'show_songs' => ShowSong::select('title', 'id', 'slug', 'show_songs' => ShowSong::select(
DB::raw('(SELECT COUNT(tracks.id) FROM show_song_track INNER JOIN tracks ON tracks.id = show_song_track.track_id WHERE show_song_track.show_song_id = show_songs.id AND tracks.published_at IS NOT NULL) AS track_count'))->orderBy('title')->get()->toArray() 'title',
'id',
'slug',
DB::raw('(SELECT COUNT(tracks.id) FROM show_song_track INNER JOIN tracks ON tracks.id = show_song_track.track_id WHERE show_song_track.show_song_id = show_songs.id AND tracks.published_at IS NOT NULL) AS track_count')
)->orderBy('title')->get()->toArray()
], 200); ], 200);
} }
} }

View file

@ -23,7 +23,7 @@ namespace Poniverse\Ponyfm\Http\Controllers\Api\Web;
use Auth; use Auth;
use File; use File;
use Illuminate\Database\Eloquent\ModelNotFoundException; use Illuminate\Database\Eloquent\ModelNotFoundException;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse\Ponyfm\Commands\DeleteTrackCommand; use Poniverse\Ponyfm\Commands\DeleteTrackCommand;
use Poniverse\Ponyfm\Commands\EditTrackCommand; use Poniverse\Ponyfm\Commands\EditTrackCommand;
use Poniverse\Ponyfm\Commands\GenerateTrackFilesCommand; use Poniverse\Ponyfm\Commands\GenerateTrackFilesCommand;
@ -55,10 +55,8 @@ class TracksController extends ApiControllerBase
if ($track->status === Track::STATUS_PROCESSING) { if ($track->status === Track::STATUS_PROCESSING) {
return Response::json(['message' => 'Processing...'], 202); return Response::json(['message' => 'Processing...'], 202);
} elseif ($track->status === Track::STATUS_COMPLETE) { } elseif ($track->status === Track::STATUS_COMPLETE) {
return Response::json(['message' => 'Processing complete!'], 201); return Response::json(['message' => 'Processing complete!'], 201);
} else { } else {
// something went wrong // something went wrong
return Response::json(['error' => 'Processing failed!'], 500); return Response::json(['error' => 'Processing failed!'], 500);
@ -72,7 +70,7 @@ class TracksController extends ApiControllerBase
public function postEdit($id) public function postEdit($id)
{ {
return $this->execute(new EditTrackCommand($id, Input::all())); return $this->execute(new EditTrackCommand($id, Request::all()));
} }
public function postUploadNewVersion($trackId) public function postUploadNewVersion($trackId)
@ -97,10 +95,8 @@ class TracksController extends ApiControllerBase
if ($track->version_upload_status === Track::STATUS_PROCESSING) { if ($track->version_upload_status === Track::STATUS_PROCESSING) {
return Response::json(['message' => 'Processing...'], 202); return Response::json(['message' => 'Processing...'], 202);
} elseif ($track->version_upload_status === Track::STATUS_COMPLETE) { } elseif ($track->version_upload_status === Track::STATUS_COMPLETE) {
return Response::json(['message' => 'Processing complete!'], 201); return Response::json(['message' => 'Processing complete!'], 201);
} else { } else {
// something went wrong // something went wrong
return Response::json(['error' => 'Processing failed!'], 500); return Response::json(['error' => 'Processing failed!'], 500);
@ -114,7 +110,7 @@ class TracksController extends ApiControllerBase
$versions = []; $versions = [];
$trackFiles = $track->trackFilesForAllVersions()->where('is_master', 'true')->get(); $trackFiles = $track->trackFilesForAllVersions()->where('is_master', 'true')->get();
foreach($trackFiles as $trackFile) { foreach ($trackFiles as $trackFile) {
$versions[] = [ $versions[] = [
'version' => $trackFile->version, 'version' => $trackFile->version,
'url' => '/tracks/' . $track->id . '/version-change/' . $trackFile->version, 'url' => '/tracks/' . $track->id . '/version-change/' . $trackFile->version,
@ -151,7 +147,7 @@ class TracksController extends ApiControllerBase
return $this->notFound('Track not found!'); return $this->notFound('Track not found!');
} }
if (Input::get('log')) { if (Request::get('log')) {
ResourceLogItem::logItem('track', $id, ResourceLogItem::VIEW); ResourceLogItem::logItem('track', $id, ResourceLogItem::VIEW);
$track->view_count++; $track->view_count++;
} }
@ -209,8 +205,8 @@ class TracksController extends ApiControllerBase
$page = 1; $page = 1;
$perPage = 45; $perPage = 45;
if (Input::has('page')) { if (Request::has('page')) {
$page = Input::get('page'); $page = Request::get('page');
} }
if ($all) { if ($all) {
@ -295,8 +291,8 @@ class TracksController extends ApiControllerBase
*/ */
private function applyOrdering($query) private function applyOrdering($query)
{ {
if (Input::has('order')) { if (Request::has('order')) {
$order = \Input::get('order'); $order = \Request::get('order');
$parts = explode(',', $order); $parts = explode(',', $order);
$query->orderBy($parts[0], $parts[1]); $query->orderBy($parts[0], $parts[1]);
} }
@ -312,8 +308,8 @@ class TracksController extends ApiControllerBase
*/ */
private function applyFilters($query, $unknown = false) private function applyFilters($query, $unknown = false)
{ {
if (Input::has('is_vocal')) { if (Request::has('is_vocal')) {
$isVocal = \Input::get('is_vocal'); $isVocal = \Request::get('is_vocal');
if ($isVocal == 'true') { if ($isVocal == 'true') {
$query->whereIsVocal(true); $query->whereIsVocal(true);
} else { } else {
@ -321,24 +317,24 @@ class TracksController extends ApiControllerBase
} }
} }
if (Input::has('in_album')) { if (Request::has('in_album')) {
if (Input::get('in_album') == 'true') { if (Request::get('in_album') == 'true') {
$query->whereNotNull('album_id'); $query->whereNotNull('album_id');
} else { } else {
$query->whereNull('album_id'); $query->whereNull('album_id');
} }
} }
if (Input::has('genres')) { if (Request::has('genres')) {
$query->whereIn('genre_id', Input::get('genres')); $query->whereIn('genre_id', Request::get('genres'));
} }
if (Input::has('types') && !$unknown) { if (Request::has('types') && !$unknown) {
$query->whereIn('track_type_id', Input::get('types')); $query->whereIn('track_type_id', Request::get('types'));
} }
if ($unknown) { if ($unknown) {
$query->where(function($q) { $query->where(function ($q) {
$unknownGenre = Genre::where('name', 'Unknown')->first(); $unknownGenre = Genre::where('name', 'Unknown')->first();
$q->where('track_type_id', TrackType::UNCLASSIFIED_TRACK); $q->where('track_type_id', TrackType::UNCLASSIFIED_TRACK);
@ -351,14 +347,14 @@ class TracksController extends ApiControllerBase
$query->join('mlpma_tracks', 'tracks.id', '=', 'mlpma_tracks.track_id'); $query->join('mlpma_tracks', 'tracks.id', '=', 'mlpma_tracks.track_id');
} }
if (Input::has('songs')) { if (Request::has('songs')) {
// DISTINCT is needed here to avoid duplicate results // DISTINCT is needed here to avoid duplicate results
// when a track is associated with multiple show songs. // when a track is associated with multiple show songs.
$query->distinct(); $query->distinct();
$query->join('show_song_track', function ($join) { $query->join('show_song_track', function ($join) {
$join->on('tracks.id', '=', 'show_song_track.track_id'); $join->on('tracks.id', '=', 'show_song_track.track_id');
}); });
$query->whereIn('show_song_track.show_song_id', Input::get('songs')); $query->whereIn('show_song_track.show_song_id', Request::get('songs'));
} }
return $query; return $query;

View file

@ -32,11 +32,13 @@ class ArtistsController extends Controller
return View::make('artists.index'); return View::make('artists.index');
} }
public function getFavourites($slug) { public function getFavourites($slug)
{
return $this->getProfile($slug); return $this->getProfile($slug);
} }
public function getContent($slug) { public function getContent($slug)
{
return $this->getProfile($slug); return $this->getProfile($slug);
} }
@ -53,7 +55,7 @@ class ArtistsController extends Controller
public function getShortlink($id) public function getShortlink($id)
{ {
$user = User::find($id); $user = User::find($id);
if (!$user || $user->disabled_at !== NULL) { if (!$user || $user->disabled_at !== null) {
App::abort('404'); App::abort('404');
} }

View file

@ -24,7 +24,7 @@ use Poniverse\Ponyfm\Models\User;
use Auth; use Auth;
use Config; use Config;
use DB; use DB;
use Input; use Illuminate\Support\Facades\Request;
use Poniverse; use Poniverse;
use Redirect; use Redirect;
@ -60,57 +60,63 @@ class AuthController extends Controller
Config::get('poniverse.urls')['token'], Config::get('poniverse.urls')['token'],
'authorization_code', 'authorization_code',
[ [
'code' => Input::query('code'), 'code' => Request::query('code'),
'redirect_uri' => action('AuthController@getOAuth') 'redirect_uri' => action('AuthController@getOAuth')
]); ]
);
if ($code['code'] != 200) { if ($code['code'] != 200) {
if ($code['code'] == 400 && $code['result']['error_description'] == 'The authorization code has expired' && !isset($this->request['login_attempt'])) { if ($code['code'] == 400 && $code['result']['error_description'] == 'The authorization code has expired' && !isset($this->request['login_attempt'])) {
return Redirect::to($this->poniverse->getAuthenticationUrl('login_attempt')); return Redirect::to($this->poniverse->getAuthenticationUrl('login_attempt'));
} }
return Redirect::to('/')->with('message', return Redirect::to('/')->with(
'Unfortunately we are having problems attempting to log you in at the moment. Please try again at a later time.'); 'message',
'Unfortunately we are having problems attempting to log you in at the moment. Please try again at a later time.'
);
} }
$this->poniverse->setAccessToken($code['result']['access_token']); $this->poniverse->setAccessToken($code['result']['access_token']);
$poniverseUser = $this->poniverse->getUser(); $poniverseUser = $this->poniverse->getUser();
$token = DB::table('oauth2_tokens')->where('external_user_id', '=', $poniverseUser['id'])->where('service', '=', $token = DB::table('oauth2_tokens')->where('external_user_id', '=', $poniverseUser['id'])->where(
'poniverse')->first(); 'service',
'=',
'poniverse'
)->first();
$setData = [ $setData = [
'access_token' => $code['result']['access_token'], 'access_token' => $code['result']['access_token'],
'expires' => date('Y-m-d H:i:s', strtotime("+".$code['result']['expires_in']." Seconds", time())), 'expires' => date('Y-m-d H:i:s', strtotime("+".$code['result']['expires_in']." Seconds", time())),
'type' => $code['result']['token_type'], 'type' => $code['result']['token_type'],
]; ];
if (isset($code['result']['refresh_token']) && !empty($code['result']['refresh_token'])) { if (isset($code['result']['refresh_token']) && !empty($code['result']['refresh_token'])) {
$setData['refresh_token'] = $code['result']['refresh_token']; $setData['refresh_token'] = $code['result']['refresh_token'];
} }
if ($token) { if ($token) {
//User already exists, update access token and refresh token if provided. //User already exists, update access token and refresh token if provided.
DB::table('oauth2_tokens')->where('id', '=', $token->id)->update($setData); DB::table('oauth2_tokens')->where('id', '=', $token->id)->update($setData);
return $this->loginRedirect(User::find($token->user_id)); return $this->loginRedirect(User::find($token->user_id));
} }
// Check by login name to see if they already have an account // Check by login name to see if they already have an account
$user = User::findOrCreate($poniverseUser['username'], $poniverseUser['display_name'], $poniverseUser['email']); $user = User::findOrCreate($poniverseUser['username'], $poniverseUser['display_name'], $poniverseUser['email']);
if ($user->wasRecentlyCreated) { if ($user->wasRecentlyCreated) {
return $this->loginRedirect($user); return $this->loginRedirect($user);
} }
// We need to insert a new token row :O // We need to insert a new token row :O
$setData['user_id'] = $user->id; $setData['user_id'] = $user->id;
$setData['external_user_id'] = $poniverseUser['id']; $setData['external_user_id'] = $poniverseUser['id'];
$setData['service'] = 'poniverse'; $setData['service'] = 'poniverse';
DB::table('oauth2_tokens')->insert($setData); DB::table('oauth2_tokens')->insert($setData);
return $this->loginRedirect($user); return $this->loginRedirect($user);
} }
protected function loginRedirect($user, $rememberMe = true) protected function loginRedirect($user, $rememberMe = true)

View file

@ -21,11 +21,12 @@
namespace Poniverse\Ponyfm\Http\Controllers; namespace Poniverse\Ponyfm\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests; use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesResources;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController; use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests; use Illuminate\Foundation\Validation\ValidatesRequests;
abstract class Controller extends BaseController class Controller extends BaseController
{ {
use DispatchesJobs, ValidatesRequests, AuthorizesRequests; use DispatchesJobs, ValidatesRequests, AuthorizesRequests;
} }

View file

@ -153,12 +153,16 @@ class TracksController extends Controller
if (Config::get('app.sendfile')) { if (Config::get('app.sendfile')) {
$response->header('X-Sendfile', $filename); $response->header('X-Sendfile', $filename);
$response->header('Content-Disposition', $response->header(
'attachment; filename="'.$trackFile->getDownloadFilename().'"'); 'Content-Disposition',
'attachment; filename="'.$trackFile->getDownloadFilename().'"'
);
} else { } else {
$response->header('X-Accel-Redirect', $filename); $response->header('X-Accel-Redirect', $filename);
$response->header('Content-Disposition', $response->header(
'attachment; filename="'.$trackFile->getDownloadFilename().'"'); 'Content-Disposition',
'attachment; filename="'.$trackFile->getDownloadFilename().'"'
);
} }
$time = gmdate(filemtime($filename)); $time = gmdate(filemtime($filename));

View file

@ -31,12 +31,17 @@ class Kernel extends HttpKernel
*/ */
protected $middleware = [ protected $middleware = [
\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class, \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
\Poniverse\Ponyfm\Http\Middleware\EncryptCookies::class, ];
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class, protected $middlewareGroups = [
\Illuminate\View\Middleware\ShareErrorsFromSession::class, 'web' => [
\Poniverse\Ponyfm\Http\Middleware\VerifyCsrfToken::class, \Poniverse\Ponyfm\Http\Middleware\EncryptCookies::class,
\Poniverse\Ponyfm\Http\Middleware\DisabledAccountCheck::class, \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
\Poniverse\Ponyfm\Http\Middleware\VerifyCsrfToken::class,
\Poniverse\Ponyfm\Http\Middleware\DisabledAccountCheck::class,
]
]; ];
/** /**
@ -48,8 +53,10 @@ class Kernel extends HttpKernel
'auth' => \Poniverse\Ponyfm\Http\Middleware\Authenticate::class, 'auth' => \Poniverse\Ponyfm\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class, 'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'auth.oauth' => \Poniverse\Ponyfm\Http\Middleware\AuthenticateOAuth::class, 'auth.oauth' => \Poniverse\Ponyfm\Http\Middleware\AuthenticateOAuth::class,
'can' => \Poniverse\Ponyfm\Http\Middleware\Authorize::class, // 'can' => \Poniverse\Ponyfm\Http\Middleware\Authorize::class,
'json-exceptions' => \Poniverse\Ponyfm\Http\Middleware\JsonExceptions::class, 'json-exceptions' => \Poniverse\Ponyfm\Http\Middleware\JsonExceptions::class,
'can' => \Illuminate\Foundation\Http\Middleware\Authorize::class,
'guest' => \Poniverse\Ponyfm\Http\Middleware\RedirectIfAuthenticated::class, 'guest' => \Poniverse\Ponyfm\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
]; ];
} }

View file

@ -46,7 +46,8 @@ class AuthenticateOAuth
*/ */
private $session; private $session;
public function __construct(Poniverse $poniverse, Guard $auth, Store $session) { public function __construct(Poniverse $poniverse, Guard $auth, Store $session)
{
$this->poniverse = $poniverse; $this->poniverse = $poniverse;
$this->auth = $auth; $this->auth = $auth;
$this->session = $session; $this->session = $session;

View file

@ -37,7 +37,8 @@ class DisabledAccountCheck
* *
* @param Guard $auth * @param Guard $auth
*/ */
public function __construct(Guard $auth) { public function __construct(Guard $auth)
{
$this->auth = $auth; $this->auth = $auth;
} }

View file

@ -43,7 +43,6 @@ class JsonExceptions
{ {
try { try {
$response = $next($request); $response = $next($request);
} catch (HttpException $e) { } catch (HttpException $e) {
return \Response::json([ return \Response::json([
'message' => $e->getMessage() 'message' => $e->getMessage()

View file

@ -21,40 +21,24 @@
namespace Poniverse\Ponyfm\Http\Middleware; namespace Poniverse\Ponyfm\Http\Middleware;
use Closure; use Closure;
use Illuminate\Contracts\Auth\Guard; use Illuminate\Auth\AuthManager;
use Illuminate\Support\Facades\Auth;
class RedirectIfAuthenticated class RedirectIfAuthenticated
{ {
/**
* The Guard implementation.
*
* @var Guard
*/
protected $auth;
/**
* Create a new filter instance.
*
* @param Guard $auth
*/
public function __construct(Guard $auth)
{
$this->auth = $auth;
}
/** /**
* Handle an incoming request. * Handle an incoming request.
* *
* @param \Illuminate\Http\Request $request * @param \Illuminate\Http\Request $request
* @param \Closure $next * @param \Closure $next
* @param string|null $guard
* @return mixed * @return mixed
*/ */
public function handle($request, Closure $next) public function handle($request, Closure $next, $guard = null)
{ {
if ($this->auth->check()) { if (Auth::guard($guard)->check()) {
return redirect('/home'); return redirect('/home');
} }
return $next($request); return $next($request);
} }
} }

View file

@ -37,15 +37,15 @@ Route::get('/tracks/random', 'TracksController@getIndex');
Route::get('tracks/{id}-{slug}', 'TracksController@getTrack'); Route::get('tracks/{id}-{slug}', 'TracksController@getTrack');
Route::get('tracks/{id}-{slug}/edit', 'TracksController@getEdit'); Route::get('tracks/{id}-{slug}/edit', 'TracksController@getEdit');
Route::get('tracks/{id}-{slug}/stats', 'StatsController@getIndex'); Route::get('tracks/{id}-{slug}/stats', 'StatsController@getIndex');
Route::get('t{id}', 'TracksController@getShortlink' )->where('id', '\d+'); Route::get('t{id}', 'TracksController@getShortlink')->where('id', '\d+');
Route::get('t{id}/embed', 'TracksController@getEmbed' ); Route::get('t{id}/embed', 'TracksController@getEmbed');
Route::get('t{id}/stream.{extension}', 'TracksController@getStream' ); Route::get('t{id}/stream.{extension}', 'TracksController@getStream');
Route::get('t{id}/dl.{extension}', 'TracksController@getDownload' ); Route::get('t{id}/dl.{extension}', 'TracksController@getDownload');
Route::get('albums', 'AlbumsController@getIndex'); Route::get('albums', 'AlbumsController@getIndex');
Route::get('albums/{id}-{slug}', 'AlbumsController@getShow'); Route::get('albums/{id}-{slug}', 'AlbumsController@getShow');
Route::get('a{id}', 'AlbumsController@getShortlink')->where('id', '\d+'); Route::get('a{id}', 'AlbumsController@getShortlink')->where('id', '\d+');
Route::get('a{id}/dl.{extension}', 'AlbumsController@getDownload' ); Route::get('a{id}/dl.{extension}', 'AlbumsController@getDownload');
Route::get('artists', 'ArtistsController@getIndex'); Route::get('artists', 'ArtistsController@getIndex');
Route::get('playlists', 'PlaylistsController@getIndex'); Route::get('playlists', 'PlaylistsController@getIndex');
@ -55,9 +55,15 @@ Route::get('/login', 'AuthController@getLogin');
Route::post('/auth/logout', 'AuthController@postLogout'); Route::post('/auth/logout', 'AuthController@postLogout');
Route::get('/auth/oauth', 'AuthController@getOAuth'); Route::get('/auth/oauth', 'AuthController@getOAuth');
Route::get('/about', function() { return View::make('pages.about'); }); Route::get('/about', function () {
Route::get('/faq', function() { return View::make('pages.faq'); }); return View::make('pages.about');
Route::get('/mlpforums-advertising-program', function() { return View::make('pages.mlpforums-advertising-program'); }); });
Route::get('/faq', function () {
return View::make('pages.faq');
});
Route::get('/mlpforums-advertising-program', function () {
return View::make('pages.mlpforums-advertising-program');
});
Route::get('i{id}/{type}.{extension}', 'ImagesController@getImage')->where('id', '\d+'); Route::get('i{id}/{type}.{extension}', 'ImagesController@getImage')->where('id', '\d+');
@ -69,18 +75,18 @@ Route::get('notifications', 'AccountController@getNotifications');
Route::group(['prefix' => 'api/v1', 'middleware' => 'json-exceptions'], function() { Route::group(['prefix' => 'api/v1', 'middleware' => 'json-exceptions'], function () {
Route::get('/tracks/radio-details/{hash}', 'Api\V1\TracksController@getTrackRadioDetails'); Route::get('/tracks/radio-details/{hash}', 'Api\V1\TracksController@getTrackRadioDetails');
Route::post('/tracks/radio-details/{hash}', 'Api\V1\TracksController@getTrackRadioDetails'); Route::post('/tracks/radio-details/{hash}', 'Api\V1\TracksController@getTrackRadioDetails');
Route::group(['middleware' => 'auth.oauth:ponyfm:tracks:upload'], function() { Route::group(['middleware' => 'auth.oauth:ponyfm:tracks:upload'], function () {
Route::post('tracks', 'Api\V1\TracksController@postUploadTrack'); Route::post('tracks', 'Api\V1\TracksController@postUploadTrack');
Route::get('/tracks/{id}/upload-status', 'Api\V1\TracksController@getUploadStatus'); Route::get('/tracks/{id}/upload-status', 'Api\V1\TracksController@getUploadStatus');
}); });
}); });
Route::group(['prefix' => 'api/web'], function() { Route::group(['prefix' => 'api/web'], function () {
Route::get('/taxonomies/all', 'Api\Web\TaxonomiesController@getAll'); Route::get('/taxonomies/all', 'Api\Web\TaxonomiesController@getAll');
Route::get('/search', 'Api\Web\SearchController@getSearch'); Route::get('/search', 'Api\Web\SearchController@getSearch');
@ -108,7 +114,7 @@ Route::group(['prefix' => 'api/web'], function() {
Route::get('/dashboard', 'Api\Web\DashboardController@getIndex'); Route::get('/dashboard', 'Api\Web\DashboardController@getIndex');
Route::group(['middleware' => 'auth'], function() { Route::group(['middleware' => 'auth'], function () {
Route::post('/tracks/upload', 'Api\Web\TracksController@postUpload'); Route::post('/tracks/upload', 'Api\Web\TracksController@postUpload');
Route::get('/tracks/{id}/upload-status', 'Api\Web\TracksController@getUploadStatus'); Route::get('/tracks/{id}/upload-status', 'Api\Web\TracksController@getUploadStatus');
Route::post('/tracks/delete/{id}', 'Api\Web\TracksController@postDelete'); Route::post('/tracks/delete/{id}', 'Api\Web\TracksController@postDelete');
@ -170,7 +176,7 @@ Route::group(['prefix' => 'api/web'], function() {
Route::get('/favourites/playlists', 'Api\Web\FavouritesController@getPlaylists'); Route::get('/favourites/playlists', 'Api\Web\FavouritesController@getPlaylists');
}); });
Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'can:access-admin-area']], function() { Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'can:access-admin-area']], function () {
Route::get('/genres', 'Api\Web\GenresController@getIndex'); Route::get('/genres', 'Api\Web\GenresController@getIndex');
Route::post('/genres', 'Api\Web\GenresController@postCreate'); Route::post('/genres', 'Api\Web\GenresController@postCreate');
Route::put('/genres/{id}', 'Api\Web\GenresController@putRename')->where('id', '\d+'); Route::put('/genres/{id}', 'Api\Web\GenresController@putRename')->where('id', '\d+');
@ -189,7 +195,7 @@ Route::group(['prefix' => 'api/web'], function() {
}); });
Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'can:access-admin-area']], function() { Route::group(['prefix' => 'admin', 'middleware' => ['auth', 'can:access-admin-area']], function () {
Route::get('/genres', 'AdminController@getGenres'); Route::get('/genres', 'AdminController@getGenres');
Route::get('/tracks', 'AdminController@getTracks'); Route::get('/tracks', 'AdminController@getTracks');
Route::get('/tracks/unclassified', 'AdminController@getClassifierQueue'); Route::get('/tracks/unclassified', 'AdminController@getClassifierQueue');
@ -202,13 +208,13 @@ Route::get('u{id}', 'ArtistsController@getShortlink')->where('id', '\d+');
Route::get('users/{id}-{slug}', 'ArtistsController@getShortlink')->where('id', '\d+'); Route::get('users/{id}-{slug}', 'ArtistsController@getShortlink')->where('id', '\d+');
Route::group(['prefix' => '{slug}'], function() { Route::group(['prefix' => '{slug}'], function () {
Route::get('/', 'ArtistsController@getProfile'); Route::get('/', 'ArtistsController@getProfile');
Route::get('/content', 'ArtistsController@getContent'); Route::get('/content', 'ArtistsController@getContent');
Route::get('/favourites', 'ArtistsController@getFavourites'); Route::get('/favourites', 'ArtistsController@getFavourites');
Route::group(['prefix' => 'account', 'middleware' => 'auth'], function() { Route::group(['prefix' => 'account', 'middleware' => 'auth'], function () {
Route::get('/tracks', 'ContentController@getTracks'); Route::get('/tracks', 'ContentController@getTracks');
Route::get('/tracks/edit/{id}', 'ContentController@getTracks'); Route::get('/tracks/edit/{id}', 'ContentController@getTracks');
Route::get('/albums', 'ContentController@getAlbums'); Route::get('/albums', 'ContentController@getAlbums');
@ -224,7 +230,7 @@ Route::group(['prefix' => '{slug}'], function() {
Route::get('/', 'HomeController@getIndex'); Route::get('/', 'HomeController@getIndex');
Route::group(['domain' => 'api.pony.fm'], function() { Route::group(['domain' => 'api.pony.fm'], function () {
Route::get('tracks/latest', ['uses' => 'Api\Mobile\TracksController@latest']); Route::get('tracks/latest', ['uses' => 'Api\Mobile\TracksController@latest']);
Route::get('tracks/popular', [ 'uses' => 'Api\Mobile\TracksController@popular']); Route::get('tracks/popular', [ 'uses' => 'Api\Mobile\TracksController@popular']);
}); });

View file

@ -24,12 +24,11 @@ use Auth;
use DB; use DB;
use Poniverse\Ponyfm\Models\Genre; use Poniverse\Ponyfm\Models\Genre;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use SerializesModels; use SerializesModels;
class DeleteGenre extends Job implements SelfHandling, ShouldQueue class DeleteGenre extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;
@ -68,7 +67,7 @@ class DeleteGenre extends Job implements SelfHandling, ShouldQueue
// This is done instead of a single UPDATE query in order to // This is done instead of a single UPDATE query in order to
// generate revision logs for the change. // generate revision logs for the change.
$this->genreToDelete->tracks()->chunk(200, function($tracks) { $this->genreToDelete->tracks()->chunk(200, function ($tracks) {
foreach ($tracks as $track) { foreach ($tracks as $track) {
/** @var Track $track */ /** @var Track $track */

View file

@ -24,12 +24,11 @@ use Auth;
use DB; use DB;
use Poniverse\Ponyfm\Models\ShowSong; use Poniverse\Ponyfm\Models\ShowSong;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use SerializesModels; use SerializesModels;
class DeleteShowSong extends Job implements SelfHandling, ShouldQueue class DeleteShowSong extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;
@ -64,7 +63,7 @@ class DeleteShowSong extends Job implements SelfHandling, ShouldQueue
// This is done instead of a single UPDATE query in order to // This is done instead of a single UPDATE query in order to
// generate revision logs for the change. // generate revision logs for the change.
$this->songToDelete->tracks()->chunk(200, function($tracks) { $this->songToDelete->tracks()->chunk(200, function ($tracks) {
foreach ($tracks as $track) { foreach ($tracks as $track) {
/** @var Track $track */ /** @var Track $track */
$oldSongs = $track->showSongs; $oldSongs = $track->showSongs;

View file

@ -25,7 +25,6 @@ use Carbon\Carbon;
use Config; use Config;
use DB; use DB;
use File; use File;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels; use Illuminate\Queue\SerializesModels;
@ -36,7 +35,7 @@ use Poniverse\Ponyfm\Models\TrackFile;
use Symfony\Component\Process\Exception\ProcessFailedException; use Symfony\Component\Process\Exception\ProcessFailedException;
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue class EncodeTrackFile extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;
/** /**
@ -70,8 +69,7 @@ class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue
*/ */
public function __construct(TrackFile $trackFile, $isExpirable, $autoPublish = false, $isForUpload = false, $isReplacingTrack = false) public function __construct(TrackFile $trackFile, $isExpirable, $autoPublish = false, $isForUpload = false, $isReplacingTrack = false)
{ {
if ( if ((!$isForUpload && $trackFile->is_master) ||
(!$isForUpload && $trackFile->is_master) ||
($isForUpload && $trackFile->is_master && !$trackFile->getFormat()['is_lossless']) ($isForUpload && $trackFile->is_master && !$trackFile->getFormat()['is_lossless'])
) { ) {
throw new InvalidEncodeOptionsException("Master files cannot be encoded unless we're generating a lossless master file during the upload process."); throw new InvalidEncodeOptionsException("Master files cannot be encoded unless we're generating a lossless master file during the upload process.");
@ -97,7 +95,6 @@ class EncodeTrackFile extends Job implements SelfHandling, ShouldQueue
if ($this->trackFile->status === TrackFile::STATUS_PROCESSING) { if ($this->trackFile->status === TrackFile::STATUS_PROCESSING) {
Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is already being processed!'); Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is already being processed!');
return; return;
} elseif (!$this->trackFile->is_expired && File::exists($this->trackFile->getFile())) { } elseif (!$this->trackFile->is_expired && File::exists($this->trackFile->getFile())) {
Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is still valid! No need to re-encode it.'); Log::warning('Track file #'.$this->trackFile->id.' (track #'.$this->trackFile->track_id.') is still valid! No need to re-encode it.');
return; return;

View file

@ -44,7 +44,8 @@ abstract class Job
* method. It ensures that we don't lose the in-memory database during * method. It ensures that we don't lose the in-memory database during
* testing by disconnecting from it - which causes tests to fail. * testing by disconnecting from it - which causes tests to fail.
*/ */
protected function beforeHandle() { protected function beforeHandle()
{
if (App::environment() !== 'testing') { if (App::environment() !== 'testing') {
DB::reconnect(); DB::reconnect();
} }

View file

@ -23,14 +23,13 @@ namespace Poniverse\Ponyfm\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Poniverse\Ponyfm\Jobs\Job; use Poniverse\Ponyfm\Jobs\Job;
use Illuminate\Contracts\Bus\SelfHandling;
use Poniverse\Ponyfm\Library\Notifications\Drivers\AbstractDriver; use Poniverse\Ponyfm\Library\Notifications\Drivers\AbstractDriver;
use Poniverse\Ponyfm\Library\Notifications\Drivers\NativeDriver; use Poniverse\Ponyfm\Library\Notifications\Drivers\NativeDriver;
use Poniverse\Ponyfm\Library\Notifications\Drivers\PonyfmDriver; use Poniverse\Ponyfm\Library\Notifications\Drivers\PonyfmDriver;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use SerializesModels; use SerializesModels;
class SendNotifications extends Job implements SelfHandling, ShouldQueue class SendNotifications extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;

View file

@ -26,10 +26,9 @@ use Illuminate\Database\Eloquent\Model;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Poniverse\Ponyfm\Contracts\Searchable; use Poniverse\Ponyfm\Contracts\Searchable;
use Poniverse\Ponyfm\Jobs\Job; use Poniverse\Ponyfm\Jobs\Job;
use Illuminate\Contracts\Bus\SelfHandling;
use SerializesModels; use SerializesModels;
class UpdateSearchIndexForEntity extends Job implements SelfHandling, ShouldQueue class UpdateSearchIndexForEntity extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;

View file

@ -26,7 +26,6 @@ use DB;
use Log; use Log;
use Poniverse\Ponyfm\Models\Genre; use Poniverse\Ponyfm\Models\Genre;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use SerializesModels; use SerializesModels;
@ -39,7 +38,7 @@ use SerializesModels;
* *
* @package Poniverse\Ponyfm\Jobs * @package Poniverse\Ponyfm\Jobs
*/ */
class UpdateTagsForRenamedGenre extends Job implements SelfHandling, ShouldQueue class UpdateTagsForRenamedGenre extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;
@ -77,13 +76,12 @@ class UpdateTagsForRenamedGenre extends Job implements SelfHandling, ShouldQueue
Log::info("Tag updates for the \"{$this->genreThatWasRenamed->name}\" genre are currently in progress! Will try again in 30 seconds."); Log::info("Tag updates for the \"{$this->genreThatWasRenamed->name}\" genre are currently in progress! Will try again in 30 seconds.");
$this->release(30); $this->release(30);
return; return;
} else { } else {
Cache::forever($this->lockKey, true); Cache::forever($this->lockKey, true);
} }
$this->genreThatWasRenamed->tracks()->chunk(200, function($tracks) { $this->genreThatWasRenamed->tracks()->chunk(200, function ($tracks) {
foreach ($tracks as $track) { foreach ($tracks as $track) {
/** @var Track $track */ /** @var Track $track */
$track->updateTags(); $track->updateTags();

View file

@ -25,7 +25,6 @@ use Cache;
use Log; use Log;
use Poniverse\Ponyfm\Models\ShowSong; use Poniverse\Ponyfm\Models\ShowSong;
use Illuminate\Queue\InteractsWithQueue; use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Bus\SelfHandling;
use Illuminate\Contracts\Queue\ShouldQueue; use Illuminate\Contracts\Queue\ShouldQueue;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use SerializesModels; use SerializesModels;
@ -38,7 +37,7 @@ use SerializesModels;
* *
* @package Poniverse\Ponyfm\Jobs * @package Poniverse\Ponyfm\Jobs
*/ */
class UpdateTagsForRenamedShowSong extends Job implements SelfHandling, ShouldQueue class UpdateTagsForRenamedShowSong extends Job implements ShouldQueue
{ {
use InteractsWithQueue, SerializesModels; use InteractsWithQueue, SerializesModels;
@ -76,13 +75,12 @@ class UpdateTagsForRenamedShowSong extends Job implements SelfHandling, ShouldQu
Log::info("Tag updates for the \"{$this->songThatWasRenamed->title}\" song are currently in progress! Will try again in 30 seconds."); Log::info("Tag updates for the \"{$this->songThatWasRenamed->title}\" song are currently in progress! Will try again in 30 seconds.");
$this->release(30); $this->release(30);
return; return;
} else { } else {
Cache::forever($this->lockKey, true); Cache::forever($this->lockKey, true);
} }
$this->songThatWasRenamed->tracks()->chunk(200, function($tracks) { $this->songThatWasRenamed->tracks()->chunk(200, function ($tracks) {
foreach ($tracks as $track) { foreach ($tracks as $track) {
/** @var Track $track */ /** @var Track $track */
$track->updateTags(); $track->updateTags();

View file

@ -20,7 +20,8 @@
class Assets class Assets
{ {
public static function scriptIncludes(string $area) { public static function scriptIncludes(string $area)
{
$scriptTags = ''; $scriptTags = '';
if ('app' === $area) { if ('app' === $area) {

View file

@ -20,7 +20,7 @@
class AudioCache class AudioCache
{ {
private static $_movieCache = array(); private static $_movieCache = [];
public static function get(string $filename):FFmpegMovie public static function get(string $filename):FFmpegMovie
{ {

View file

@ -28,5 +28,4 @@ class File extends \Illuminate\Support\Facades\File
return $response; return $response;
} }
} }

View file

@ -47,7 +47,7 @@ class Helpers
return '0 MB'; return '0 MB';
} }
$units = array('B', 'KB', 'MB', 'GB', 'TB'); $units = ['B', 'KB', 'MB', 'GB', 'TB'];
$bytes = max($bytes, 0); $bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024)); $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
@ -82,7 +82,8 @@ class Helpers
* @param array[int] $rgb RGB values in an array * @param array[int] $rgb RGB values in an array
* @return string * @return string
*/ */
public static function rgb2hex($rgb) { public static function rgb2hex($rgb)
{
$hex = "#"; $hex = "#";
$hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT); $hex .= str_pad(dechex($rgb[0]), 2, "0", STR_PAD_LEFT);
$hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT); $hex .= str_pad(dechex($rgb[1]), 2, "0", STR_PAD_LEFT);

View file

@ -25,10 +25,12 @@ use Poniverse\Ponyfm\Contracts\NotificationHandler;
use Poniverse\Ponyfm\Library\Notifications\RecipientFinder; use Poniverse\Ponyfm\Library\Notifications\RecipientFinder;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
abstract class AbstractDriver implements NotificationHandler { abstract class AbstractDriver implements NotificationHandler
{
private $recipientFinder; private $recipientFinder;
public function __construct() { public function __construct()
{
$this->recipientFinder = new RecipientFinder(get_class($this)); $this->recipientFinder = new RecipientFinder(get_class($this));
} }
@ -41,7 +43,8 @@ abstract class AbstractDriver implements NotificationHandler {
* @param array $notificationData * @param array $notificationData
* @return User[] collection of {@link User} objects * @return User[] collection of {@link User} objects
*/ */
protected function getRecipients(string $notificationType, array $notificationData) { protected function getRecipients(string $notificationType, array $notificationData)
{
return call_user_func_array([$this->recipientFinder, $notificationType], $notificationData); return call_user_func_array([$this->recipientFinder, $notificationType], $notificationData);
} }
} }

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications\Drivers; namespace Poniverse\Ponyfm\Library\Notifications\Drivers;
use Config; use Config;
use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Contracts\Favouritable;
use Poniverse\Ponyfm\Models\Activity; use Poniverse\Ponyfm\Models\Activity;
@ -30,7 +29,8 @@ use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
use Minishlink\WebPush\WebPush; use Minishlink\WebPush\WebPush;
class NativeDriver extends AbstractDriver { class NativeDriver extends AbstractDriver
{
/** /**
* Method for sending notifications to devices * Method for sending notifications to devices
* *
@ -40,9 +40,9 @@ class NativeDriver extends AbstractDriver {
private function pushNotifications(Activity $activity, $recipients) private function pushNotifications(Activity $activity, $recipients)
{ {
if (Config::get('ponyfm.gcm_key') != 'default') { if (Config::get('ponyfm.gcm_key') != 'default') {
$apiKeys = array( $apiKeys = [
'GCM' => Config::get('ponyfm.gcm_key'), 'GCM' => Config::get('ponyfm.gcm_key'),
); ];
$webPush = new WebPush($apiKeys); $webPush = new WebPush($apiKeys);
@ -72,7 +72,8 @@ class NativeDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewTrack(Track $track) { public function publishedNewTrack(Track $track)
{
$activity = Activity::where('user_id', $track->user_id) $activity = Activity::where('user_id', $track->user_id)
->where('activity_type', Activity::TYPE_PUBLISHED_TRACK) ->where('activity_type', Activity::TYPE_PUBLISHED_TRACK)
->where('resource_id', $track->id) ->where('resource_id', $track->id)
@ -85,7 +86,8 @@ class NativeDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewPlaylist(Playlist $playlist) { public function publishedNewPlaylist(Playlist $playlist)
{
$activity = Activity::where('user_id', $playlist->user_id) $activity = Activity::where('user_id', $playlist->user_id)
->where('activity_type', Activity::TYPE_PUBLISHED_PLAYLIST) ->where('activity_type', Activity::TYPE_PUBLISHED_PLAYLIST)
->where('resource_id', $playlist->id) ->where('resource_id', $playlist->id)
@ -94,7 +96,8 @@ class NativeDriver extends AbstractDriver {
$this->pushNotifications($activity, $this->getRecipients(__FUNCTION__, func_get_args())); $this->pushNotifications($activity, $this->getRecipients(__FUNCTION__, func_get_args()));
} }
public function newFollower(User $userBeingFollowed, User $follower) { public function newFollower(User $userBeingFollowed, User $follower)
{
$activity = Activity::where('user_id', $follower->id) $activity = Activity::where('user_id', $follower->id)
->where('activity_type', Activity::TYPE_NEW_FOLLOWER) ->where('activity_type', Activity::TYPE_NEW_FOLLOWER)
->where('resource_id', $userBeingFollowed->id) ->where('resource_id', $userBeingFollowed->id)
@ -106,7 +109,8 @@ class NativeDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newComment(Comment $comment) { public function newComment(Comment $comment)
{
$activity = Activity::where('user_id', $comment->user_id) $activity = Activity::where('user_id', $comment->user_id)
->where('activity_type', Activity::TYPE_NEW_COMMENT) ->where('activity_type', Activity::TYPE_NEW_COMMENT)
->where('resource_id', $comment->id) ->where('resource_id', $comment->id)
@ -118,7 +122,8 @@ class NativeDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
$activity = Activity::where('user_id', $favouriter->id) $activity = Activity::where('user_id', $favouriter->id)
->where('activity_type', Activity::TYPE_CONTENT_FAVOURITED) ->where('activity_type', Activity::TYPE_CONTENT_FAVOURITED)
->where('resource_id', $entityBeingFavourited->id) ->where('resource_id', $entityBeingFavourited->id)

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications\Drivers; namespace Poniverse\Ponyfm\Library\Notifications\Drivers;
use ArrayAccess; use ArrayAccess;
use Carbon\Carbon; use Carbon\Carbon;
use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Contracts\Favouritable;
@ -31,14 +30,16 @@ use Poniverse\Ponyfm\Models\Playlist;
use Poniverse\Ponyfm\Models\Track; use Poniverse\Ponyfm\Models\Track;
use Poniverse\Ponyfm\Models\User; use Poniverse\Ponyfm\Models\User;
class PonyfmDriver extends AbstractDriver { class PonyfmDriver extends AbstractDriver
{
/** /**
* A helper method for bulk insertion of notification records. * A helper method for bulk insertion of notification records.
* *
* @param int $activityId * @param int $activityId
* @param User[] $recipients collection of {@link User} objects * @param User[] $recipients collection of {@link User} objects
*/ */
private function insertNotifications(int $activityId, $recipients) { private function insertNotifications(int $activityId, $recipients)
{
$notifications = []; $notifications = [];
foreach ($recipients as $recipient) { foreach ($recipients as $recipient) {
$notifications[] = [ $notifications[] = [
@ -52,7 +53,8 @@ class PonyfmDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewTrack(Track $track) { public function publishedNewTrack(Track $track)
{
$activity = Activity::create([ $activity = Activity::create([
'created_at' => Carbon::now(), 'created_at' => Carbon::now(),
'user_id' => $track->user_id, 'user_id' => $track->user_id,
@ -67,7 +69,8 @@ class PonyfmDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewPlaylist(Playlist $playlist) { public function publishedNewPlaylist(Playlist $playlist)
{
$activity = Activity::create([ $activity = Activity::create([
'created_at' => Carbon::now(), 'created_at' => Carbon::now(),
'user_id' => $playlist->user_id, 'user_id' => $playlist->user_id,
@ -79,7 +82,8 @@ class PonyfmDriver extends AbstractDriver {
$this->insertNotifications($activity->id, $this->getRecipients(__FUNCTION__, func_get_args())); $this->insertNotifications($activity->id, $this->getRecipients(__FUNCTION__, func_get_args()));
} }
public function newFollower(User $userBeingFollowed, User $follower) { public function newFollower(User $userBeingFollowed, User $follower)
{
$activity = Activity::create([ $activity = Activity::create([
'created_at' => Carbon::now(), 'created_at' => Carbon::now(),
'user_id' => $follower->id, 'user_id' => $follower->id,
@ -94,7 +98,8 @@ class PonyfmDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newComment(Comment $comment) { public function newComment(Comment $comment)
{
$activity = Activity::create([ $activity = Activity::create([
'created_at' => Carbon::now(), 'created_at' => Carbon::now(),
'user_id' => $comment->user_id, 'user_id' => $comment->user_id,
@ -109,7 +114,8 @@ class PonyfmDriver extends AbstractDriver {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
$activity = Activity::create([ $activity = Activity::create([
'created_at' => Carbon::now(), 'created_at' => Carbon::now(),
'user_id' => $favouriter->id, 'user_id' => $favouriter->id,

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications; namespace Poniverse\Ponyfm\Library\Notifications;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Contracts\Favouritable;
use Poniverse\Ponyfm\Contracts\NotificationHandler; use Poniverse\Ponyfm\Contracts\NotificationHandler;
@ -39,45 +38,52 @@ use Poniverse\Ponyfm\Models\User;
* All the heavy lifting happens asynchronously in the {@link SendNotifications} * All the heavy lifting happens asynchronously in the {@link SendNotifications}
* job and the notification drivers. * job and the notification drivers.
*/ */
class NotificationManager implements NotificationHandler { class NotificationManager implements NotificationHandler
{
use DispatchesJobs; use DispatchesJobs;
private function dispatchNotification(string $notificationType, array $notificationData) { private function dispatchNotification(string $notificationType, array $notificationData)
$this->dispatch( (new SendNotifications($notificationType, $notificationData))->onQueue('notifications') ); {
$this->dispatch((new SendNotifications($notificationType, $notificationData))->onQueue('notifications'));
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewTrack(Track $track) { public function publishedNewTrack(Track $track)
{
$this->dispatchNotification(__FUNCTION__, func_get_args()); $this->dispatchNotification(__FUNCTION__, func_get_args());
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewPlaylist(Playlist $playlist) { public function publishedNewPlaylist(Playlist $playlist)
{
$this->dispatchNotification(__FUNCTION__, func_get_args()); $this->dispatchNotification(__FUNCTION__, func_get_args());
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFollower(User $userBeingFollowed, User $follower) { public function newFollower(User $userBeingFollowed, User $follower)
{
$this->dispatchNotification(__FUNCTION__, func_get_args()); $this->dispatchNotification(__FUNCTION__, func_get_args());
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newComment(Comment $comment) { public function newComment(Comment $comment)
{
$this->dispatchNotification(__FUNCTION__, func_get_args()); $this->dispatchNotification(__FUNCTION__, func_get_args());
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
$this->dispatchNotification(__FUNCTION__, func_get_args()); $this->dispatchNotification(__FUNCTION__, func_get_args());
} }
} }

View file

@ -20,7 +20,6 @@
namespace Poniverse\Ponyfm\Library\Notifications; namespace Poniverse\Ponyfm\Library\Notifications;
use Illuminate\Foundation\Bus\DispatchesJobs; use Illuminate\Foundation\Bus\DispatchesJobs;
use Poniverse\Ponyfm\Contracts\Favouritable; use Poniverse\Ponyfm\Contracts\Favouritable;
use Poniverse\Ponyfm\Contracts\NotificationHandler; use Poniverse\Ponyfm\Contracts\NotificationHandler;
@ -36,28 +35,32 @@ use Poniverse\Ponyfm\Models\User;
/** /**
* Class RecipientFinder * Class RecipientFinder
* @package Poniverse\Ponyfm\Library\Notifications * @package Poniverse\Ponyfm\Library\Notifications
* *
* This class returns a list of users who are to receive a particular notification. * This class returns a list of users who are to receive a particular notification.
* It is instantiated on a per-driver basis. * It is instantiated on a per-driver basis.
*/ */
class RecipientFinder implements NotificationHandler { class RecipientFinder implements NotificationHandler
{
/** /**
* @var string class name of a notification driver * @var string class name of a notification driver
*/ */
private $notificationDriver; private $notificationDriver;
public function __construct(string $notificationDriver) { public function __construct(string $notificationDriver)
{
$this->notificationDriver = $notificationDriver; $this->notificationDriver = $notificationDriver;
} }
private function fail() { private function fail()
{
throw new \InvalidArgumentException("Unknown notification driver given: {$this->notificationDriver}"); throw new \InvalidArgumentException("Unknown notification driver given: {$this->notificationDriver}");
} }
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewTrack(Track $track) { public function publishedNewTrack(Track $track)
{
switch ($this->notificationDriver) { switch ($this->notificationDriver) {
case PonyfmDriver::class: case PonyfmDriver::class:
return $track->user->followers; return $track->user->followers;
@ -84,7 +87,8 @@ class RecipientFinder implements NotificationHandler {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function publishedNewPlaylist(Playlist $playlist) { public function publishedNewPlaylist(Playlist $playlist)
{
switch ($this->notificationDriver) { switch ($this->notificationDriver) {
case PonyfmDriver::class: case PonyfmDriver::class:
return $playlist->user->followers; return $playlist->user->followers;
@ -111,7 +115,8 @@ class RecipientFinder implements NotificationHandler {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFollower(User $userBeingFollowed, User $follower) { public function newFollower(User $userBeingFollowed, User $follower)
{
switch ($this->notificationDriver) { switch ($this->notificationDriver) {
case PonyfmDriver::class: case PonyfmDriver::class:
return [$userBeingFollowed]; return [$userBeingFollowed];
@ -125,7 +130,8 @@ class RecipientFinder implements NotificationHandler {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newComment(Comment $comment) { public function newComment(Comment $comment)
{
switch ($this->notificationDriver) { switch ($this->notificationDriver) {
case PonyfmDriver::class: case PonyfmDriver::class:
return return
@ -142,7 +148,8 @@ class RecipientFinder implements NotificationHandler {
/** /**
* @inheritdoc * @inheritdoc
*/ */
public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter) { public function newFavourite(Favouritable $entityBeingFavourited, User $favouriter)
{
switch ($this->notificationDriver) { switch ($this->notificationDriver) {
case PonyfmDriver::class: case PonyfmDriver::class:
return return

View file

@ -257,7 +257,7 @@ class PfmValidator extends Illuminate\Validation\Validator
/** OLD CODE /** OLD CODE
* public function validate_required_when($attribute, $value, $parameters) * public function validate_required_when($attribute, $value, $parameters)
* { * {
* if ( Input::get($parameters[0]) === $parameters[1] && static::required($attribute, $value) ){ * if ( Request::get($parameters[0]) === $parameters[1] && static::required($attribute, $value) ){
* return true; * return true;
* *
* } else { * } else {
@ -269,7 +269,7 @@ class PfmValidator extends Illuminate\Validation\Validator
// custom required_when validator // custom required_when validator
public function validateRequiredWhen($attribute, $value, $parameters) public function validateRequiredWhen($attribute, $value, $parameters)
{ {
if (Input::get($parameters[0]) == $parameters[1]) { if (Request::get($parameters[0]) == $parameters[1]) {
return $this->validate_required($attribute, $value); return $this->validate_required($attribute, $value);
} }

View file

@ -28,7 +28,8 @@ namespace Poniverse;
* @link https://tools.ietf.org/html/draft-richer-oauth-introspection-06 * @link https://tools.ietf.org/html/draft-richer-oauth-introspection-06
* @package Poniverse * @package Poniverse
*/ */
class AccessTokenInfo { class AccessTokenInfo
{
protected $token; protected $token;
protected $isActive; protected $isActive;
@ -42,21 +43,24 @@ class AccessTokenInfo {
protected $issuer; protected $issuer;
protected $tokenType; protected $tokenType;
public function __construct($accessToken) { public function __construct($accessToken)
{
$this->token = $accessToken; $this->token = $accessToken;
} }
/** /**
* @return mixed * @return mixed
*/ */
public function getToken() { public function getToken()
{
return $this->token; return $this->token;
} }
/** /**
* @return bool * @return bool
*/ */
public function getIsActive() { public function getIsActive()
{
return $this->isActive; return $this->isActive;
} }
@ -64,7 +68,8 @@ class AccessTokenInfo {
* @param bool $isActive * @param bool $isActive
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setIsActive($isActive) { public function setIsActive($isActive)
{
$this->isActive = $isActive; $this->isActive = $isActive;
return $this; return $this;
} }
@ -72,7 +77,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getExpiresAt() { public function getExpiresAt()
{
return $this->expiresAt; return $this->expiresAt;
} }
@ -80,7 +86,8 @@ class AccessTokenInfo {
* @param mixed $expiresAt * @param mixed $expiresAt
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setExpiresAt($expiresAt) { public function setExpiresAt($expiresAt)
{
$this->expiresAt = $expiresAt; $this->expiresAt = $expiresAt;
return $this; return $this;
} }
@ -88,7 +95,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getIssuedAt() { public function getIssuedAt()
{
return $this->issuedAt; return $this->issuedAt;
} }
@ -96,7 +104,8 @@ class AccessTokenInfo {
* @param mixed $issuedAt * @param mixed $issuedAt
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setIssuedAt($issuedAt) { public function setIssuedAt($issuedAt)
{
$this->issuedAt = $issuedAt; $this->issuedAt = $issuedAt;
return $this; return $this;
} }
@ -104,7 +113,8 @@ class AccessTokenInfo {
/** /**
* @return array * @return array
*/ */
public function getScopes() { public function getScopes()
{
return $this->scopes; return $this->scopes;
} }
@ -112,7 +122,8 @@ class AccessTokenInfo {
* @param array|string $scopes * @param array|string $scopes
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setScopes($scopes) { public function setScopes($scopes)
{
if (is_array($scopes)) { if (is_array($scopes)) {
$this->scopes = $scopes; $this->scopes = $scopes;
} else { } else {
@ -125,7 +136,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getClientId() { public function getClientId()
{
return $this->clientId; return $this->clientId;
} }
@ -133,7 +145,8 @@ class AccessTokenInfo {
* @param mixed $clientId * @param mixed $clientId
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setClientId($clientId) { public function setClientId($clientId)
{
$this->clientId = $clientId; $this->clientId = $clientId;
return $this; return $this;
} }
@ -141,7 +154,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getSub() { public function getSub()
{
return $this->sub; return $this->sub;
} }
@ -149,7 +163,8 @@ class AccessTokenInfo {
* @param mixed $sub * @param mixed $sub
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setSub($sub) { public function setSub($sub)
{
$this->sub = $sub; $this->sub = $sub;
return $this; return $this;
} }
@ -157,7 +172,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getUserId() { public function getUserId()
{
return $this->userId; return $this->userId;
} }
@ -165,7 +181,8 @@ class AccessTokenInfo {
* @param mixed $userId * @param mixed $userId
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setUserId($userId) { public function setUserId($userId)
{
$this->userId = $userId; $this->userId = $userId;
return $this; return $this;
} }
@ -173,7 +190,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getIntendedAudience() { public function getIntendedAudience()
{
return $this->intendedAudience; return $this->intendedAudience;
} }
@ -181,7 +199,8 @@ class AccessTokenInfo {
* @param mixed $intendedAudience * @param mixed $intendedAudience
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setIntendedAudience($intendedAudience) { public function setIntendedAudience($intendedAudience)
{
$this->intendedAudience = $intendedAudience; $this->intendedAudience = $intendedAudience;
return $this; return $this;
} }
@ -189,7 +208,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getIssuer() { public function getIssuer()
{
return $this->issuer; return $this->issuer;
} }
@ -197,7 +217,8 @@ class AccessTokenInfo {
* @param mixed $issuer * @param mixed $issuer
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setIssuer($issuer) { public function setIssuer($issuer)
{
$this->issuer = $issuer; $this->issuer = $issuer;
return $this; return $this;
} }
@ -205,7 +226,8 @@ class AccessTokenInfo {
/** /**
* @return mixed * @return mixed
*/ */
public function getTokenType() { public function getTokenType()
{
return $this->tokenType; return $this->tokenType;
} }
@ -213,7 +235,8 @@ class AccessTokenInfo {
* @param mixed $tokenType * @param mixed $tokenType
* @return AccessTokenInfo * @return AccessTokenInfo
*/ */
public function setTokenType($tokenType) { public function setTokenType($tokenType)
{
$this->tokenType = $tokenType; $this->tokenType = $tokenType;
return $this; return $this;
} }

View file

@ -28,7 +28,8 @@ use Poniverse\Ponyfm\Exceptions\InvalidAccessTokenException;
* this class is going to be a simple flat api class. * this class is going to be a simple flat api class.
*/ */
class Poniverse { class Poniverse
{
protected $clientId; protected $clientId;
protected $clientSecret; protected $clientSecret;
protected $accessToken; protected $accessToken;
@ -108,7 +109,7 @@ class Poniverse {
*/ */
public function getUser() public function getUser()
{ {
$data = \Httpful\Request::get($this->urls['api'] . "users?access_token=" . $this->accessToken ); $data = \Httpful\Request::get($this->urls['api'] . "users?access_token=" . $this->accessToken);
$result = $data->addHeader('Accept', 'application/json')->send(); $result = $data->addHeader('Accept', 'application/json')->send();

View file

@ -102,7 +102,7 @@ class SplClassLoader
*/ */
public function register() public function register()
{ {
spl_autoload_register(array($this, 'loadClass')); spl_autoload_register([$this, 'loadClass']);
} }
/** /**
@ -110,7 +110,7 @@ class SplClassLoader
*/ */
public function unregister() public function unregister()
{ {
spl_autoload_unregister(array($this, 'loadClass')); spl_autoload_unregister([$this, 'loadClass']);
} }
/** /**
@ -131,7 +131,7 @@ class SplClassLoader
} }
$fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension; $fileName .= str_replace('_', DIRECTORY_SEPARATOR, $className) . $this->_fileExtension;
require ($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName; require($this->_includePath !== null ? $this->_includePath . DIRECTORY_SEPARATOR : '') . $fileName;
} }
} }
} }

View file

@ -9,4 +9,4 @@ $response = \Httpful\Request::get($uri)
->expectsJson() ->expectsJson()
->sendIt(); ->sendIt();
echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n"; echo 'The Dead Weather has ' . count($response->body->result->album) . " albums.\n";

View file

@ -6,4 +6,4 @@ use \Httpful\Request;
$uri = 'https://github.com/api/v2/xml/user/show/nategood'; $uri = 'https://github.com/api/v2/xml/user/show/nategood';
$request = Request::get($uri)->send(); $request = Request::get($uri)->send();
echo "{$request->body->name} joined GitHub on " . date('M jS', strtotime($request->body->{'created-at'})) ."\n"; echo "{$request->body->name} joined GitHub on " . date('M jS', strtotime($request->body->{'created-at'})) ."\n";

View file

@ -5,7 +5,7 @@ require(__DIR__ . '/../bootstrap.php');
// a parser with different configuration options for a particular mime type // a parser with different configuration options for a particular mime type
// Example setting a namespace for the XMLHandler parser // Example setting a namespace for the XMLHandler parser
$conf = array('namespace' => 'http://example.com'); $conf = ['namespace' => 'http://example.com'];
\Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf)); \Httpful\Httpful::register(\Httpful\Mime::XML, new \Httpful\Handlers\XmlHandler($conf));
// We can also add the parsers with our own... // We can also add the parsers with our own...
@ -41,4 +41,4 @@ class SimpleCsvHandler extends \Httpful\Handlers\MimeHandlerAdapter
} }
} }
\Httpful\Httpful::register('text/csv', new SimpleCsvHandler()); \Httpful\Httpful::register('text/csv', new SimpleCsvHandler());

View file

@ -14,11 +14,11 @@ $response = Request::get($uri)
echo "The event {$response->body->event} will take place on {$response->body->event_start}\n"; echo "The event {$response->body->event} will take place on {$response->body->event_start}\n";
// Example overriding the default JSON handler with one that encodes the response as an array // Example overriding the default JSON handler with one that encodes the response as an array
\Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(array('decode_as_array' => true))); \Httpful\Httpful::register(\Httpful\Mime::JSON, new \Httpful\Handlers\JsonHandler(['decode_as_array' => true]));
$response = Request::get($uri) $response = Request::get($uri)
->expectsType('json') ->expectsType('json')
->sendIt(); ->sendIt();
// Print out the event details // Print out the event details
echo "The event {$response->body['event']} will take place on {$response->body['event_start']}\n"; echo "The event {$response->body['event']} will take place on {$response->body['event_start']}\n";

View file

@ -21,7 +21,7 @@ class Bootstrap
*/ */
public static function init() public static function init()
{ {
spl_autoload_register(array('\Httpful\Bootstrap', 'autoload')); spl_autoload_register(['\Httpful\Bootstrap', 'autoload']);
self::registerHandlers(); self::registerHandlers();
} }
@ -40,7 +40,7 @@ class Bootstrap
*/ */
public static function pharInit() public static function pharInit()
{ {
spl_autoload_register(array('\Httpful\Bootstrap', 'pharAutoload')); spl_autoload_register(['\Httpful\Bootstrap', 'pharAutoload']);
self::registerHandlers(); self::registerHandlers();
} }
@ -78,17 +78,18 @@ class Bootstrap
// @todo check a conf file to load from that instead of // @todo check a conf file to load from that instead of
// hardcoding into the library? // hardcoding into the library?
$handlers = array( $handlers = [
\Httpful\Mime::JSON => new \Httpful\Handlers\JsonHandler(), \Httpful\Mime::JSON => new \Httpful\Handlers\JsonHandler(),
\Httpful\Mime::XML => new \Httpful\Handlers\XmlHandler(), \Httpful\Mime::XML => new \Httpful\Handlers\XmlHandler(),
\Httpful\Mime::FORM => new \Httpful\Handlers\FormHandler(), \Httpful\Mime::FORM => new \Httpful\Handlers\FormHandler(),
\Httpful\Mime::CSV => new \Httpful\Handlers\CsvHandler(), \Httpful\Mime::CSV => new \Httpful\Handlers\CsvHandler(),
); ];
foreach ($handlers as $mime => $handler) { foreach ($handlers as $mime => $handler) {
// Don't overwrite if the handler has already been registered // Don't overwrite if the handler has already been registered
if (Httpful::hasParserRegistered($mime)) if (Httpful::hasParserRegistered($mime)) {
continue; continue;
}
Httpful::register($mime, $handler); Httpful::register($mime, $handler);
} }

View file

@ -1,7 +1,7 @@
<?php <?php
namespace Httpful\Exception; namespace Httpful\Exception;
class ConnectionErrorException extends \Exception class ConnectionErrorException extends \Exception
{ {
} }

View file

@ -14,17 +14,19 @@ class CsvHandler extends MimeHandlerAdapter
*/ */
public function parse($body) public function parse($body)
{ {
if (empty($body)) if (empty($body)) {
return null; return null;
}
$parsed = array(); $parsed = [];
$fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r'); $fp = fopen('data://text/plain;base64,' . base64_encode($body), 'r');
while (($r = fgetcsv($fp)) !== FALSE) { while (($r = fgetcsv($fp)) !== false) {
$parsed[] = $r; $parsed[] = $r;
} }
if (empty($parsed)) if (empty($parsed)) {
throw new \Exception("Unable to parse response as CSV"); throw new \Exception("Unable to parse response as CSV");
}
return $parsed; return $parsed;
} }
@ -37,7 +39,7 @@ class CsvHandler extends MimeHandlerAdapter
$fp = fopen('php://temp/maxmemory:'. (6*1024*1024), 'r+'); $fp = fopen('php://temp/maxmemory:'. (6*1024*1024), 'r+');
$i = 0; $i = 0;
foreach ($payload as $fields) { foreach ($payload as $fields) {
if($i++ == 0) { if ($i++ == 0) {
fputcsv($fp, array_keys($fields)); fputcsv($fp, array_keys($fields));
} }
fputcsv($fp, $fields); fputcsv($fp, $fields);

View file

@ -6,7 +6,7 @@
namespace Httpful\Handlers; namespace Httpful\Handlers;
class FormHandler extends MimeHandlerAdapter class FormHandler extends MimeHandlerAdapter
{ {
/** /**
* @param string $body * @param string $body
@ -14,7 +14,7 @@ class FormHandler extends MimeHandlerAdapter
*/ */
public function parse($body) public function parse($body)
{ {
$parsed = array(); $parsed = [];
parse_str($body, $parsed); parse_str($body, $parsed);
return $parsed; return $parsed;
} }
@ -27,4 +27,4 @@ class FormHandler extends MimeHandlerAdapter
{ {
return http_build_query($payload, null, '&'); return http_build_query($payload, null, '&');
} }
} }

View file

@ -21,11 +21,13 @@ class JsonHandler extends MimeHandlerAdapter
*/ */
public function parse($body) public function parse($body)
{ {
if (empty($body)) if (empty($body)) {
return null; return null;
}
$parsed = json_decode($body, $this->decode_as_array); $parsed = json_decode($body, $this->decode_as_array);
if (is_null($parsed)) if (is_null($parsed)) {
throw new \Exception("Unable to parse response as JSON"); throw new \Exception("Unable to parse response as JSON");
}
return $parsed; return $parsed;
} }
@ -37,4 +39,4 @@ class JsonHandler extends MimeHandlerAdapter
{ {
return json_encode($payload); return json_encode($payload);
} }
} }

View file

@ -10,7 +10,7 @@ namespace Httpful\Handlers;
class MimeHandlerAdapter class MimeHandlerAdapter
{ {
public function __construct(array $args = array()) public function __construct(array $args = [])
{ {
$this->init($args); $this->init($args);
} }
@ -40,4 +40,4 @@ class MimeHandlerAdapter
{ {
return (string) $payload; return (string) $payload;
} }
} }

View file

@ -12,4 +12,4 @@ class XHtmlHandler extends MimeHandlerAdapter
{ {
// @todo add html specific parsing // @todo add html specific parsing
// see DomDocument::load http://docs.php.net/manual/en/domdocument.loadhtml.php // see DomDocument::load http://docs.php.net/manual/en/domdocument.loadhtml.php
} }

View file

@ -23,7 +23,7 @@ class XmlHandler extends MimeHandlerAdapter
/** /**
* @param array $conf sets configuration options * @param array $conf sets configuration options
*/ */
public function __construct(array $conf = array()) public function __construct(array $conf = [])
{ {
$this->namespace = isset($conf['namespace']) ? $conf['namespace'] : ''; $this->namespace = isset($conf['namespace']) ? $conf['namespace'] : '';
$this->libxml_opts = isset($conf['libxml_opts']) ? $conf['libxml_opts'] : 0; $this->libxml_opts = isset($conf['libxml_opts']) ? $conf['libxml_opts'] : 0;
@ -36,11 +36,13 @@ class XmlHandler extends MimeHandlerAdapter
*/ */
public function parse($body) public function parse($body)
{ {
if (empty($body)) if (empty($body)) {
return null; return null;
}
$parsed = simplexml_load_string($body, null, $this->libxml_opts, $this->namespace); $parsed = simplexml_load_string($body, null, $this->libxml_opts, $this->namespace);
if ($parsed === false) if ($parsed === false) {
throw new \Exception("Unable to parse response as XML"); throw new \Exception("Unable to parse response as XML");
}
return $parsed; return $parsed;
} }
@ -84,7 +86,7 @@ class XmlHandler extends MimeHandlerAdapter
} else { } else {
$node->appendChild($dom->createTextNode($value)); $node->appendChild($dom->createTextNode($value));
} }
return array($node, $dom); return [$node, $dom];
} }
/** /**
* @author Zack Douglas <zack@zackerydouglas.info> * @author Zack Douglas <zack@zackerydouglas.info>
@ -100,7 +102,7 @@ class XmlHandler extends MimeHandlerAdapter
$parent->appendChild($el); $parent->appendChild($el);
$this->_future_serializeAsXml($v, $el, $dom); $this->_future_serializeAsXml($v, $el, $dom);
} }
return array($parent, $dom); return [$parent, $dom];
} }
/** /**
* @author Zack Douglas <zack@zackerydouglas.info> * @author Zack Douglas <zack@zackerydouglas.info>
@ -115,6 +117,6 @@ class XmlHandler extends MimeHandlerAdapter
$this->_future_serializeAsXml($pr->getValue($value), $el, $dom); $this->_future_serializeAsXml($pr->getValue($value), $el, $dom);
} }
} }
return array($parent, $dom); return [$parent, $dom];
} }
} }

View file

@ -21,7 +21,7 @@ class Http
*/ */
public static function safeMethods() public static function safeMethods()
{ {
return array(self::HEAD, self::GET, self::OPTIONS, self::TRACE); return [self::HEAD, self::GET, self::OPTIONS, self::TRACE];
} }
/** /**
@ -50,7 +50,7 @@ class Http
// Though it is possible to be idempotent, POST // Though it is possible to be idempotent, POST
// is not guarunteed to be, and more often than // is not guarunteed to be, and more often than
// not, it is not. // not, it is not.
return array(self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH); return [self::HEAD, self::GET, self::PUT, self::DELETE, self::OPTIONS, self::TRACE, self::PATCH];
} }
/** /**
@ -80,7 +80,6 @@ class Http
*/ */
public static function canHaveBody() public static function canHaveBody()
{ {
return array(self::POST, self::PUT, self::PATCH, self::OPTIONS); return [self::POST, self::PUT, self::PATCH, self::OPTIONS];
} }
}
}

View file

@ -2,10 +2,11 @@
namespace Httpful; namespace Httpful;
class Httpful { class Httpful
{
const VERSION = '0.2.4'; const VERSION = '0.2.4';
private static $mimeRegistrar = array(); private static $mimeRegistrar = [];
private static $default = null; private static $default = null;
/** /**
@ -43,4 +44,4 @@ class Httpful {
{ {
return isset(self::$mimeRegistrar[$mimeType]); return isset(self::$mimeRegistrar[$mimeType]);
} }
} }

View file

@ -22,7 +22,7 @@ class Mime
* Map short name for a mime type * Map short name for a mime type
* to a full proper mime type * to a full proper mime type
*/ */
public static $mimes = array( public static $mimes = [
'json' => self::JSON, 'json' => self::JSON,
'xml' => self::XML, 'xml' => self::XML,
'form' => self::FORM, 'form' => self::FORM,
@ -34,7 +34,7 @@ class Mime
'javascript'=> self::JS, 'javascript'=> self::JS,
'yaml' => self::YAML, 'yaml' => self::YAML,
'csv' => self::CSV, 'csv' => self::CSV,
); ];
/** /**
* Get the full Mime Type name from a "short name". * Get the full Mime Type name from a "short name".

View file

@ -30,12 +30,12 @@ class Request
public $uri, public $uri,
$method = Http::GET, $method = Http::GET,
$headers = array(), $headers = [],
$raw_headers = '', $raw_headers = '',
$strict_ssl = false, $strict_ssl = false,
$content_type, $content_type,
$expected_type, $expected_type,
$additional_curl_opts = array(), $additional_curl_opts = [],
$auto_parse = true, $auto_parse = true,
$serialize_payload_method = self::SERIALIZE_PAYLOAD_SMART, $serialize_payload_method = self::SERIALIZE_PAYLOAD_SMART,
$username, $username,
@ -46,7 +46,7 @@ class Request
$error_callback, $error_callback,
$follow_redirects = false, $follow_redirects = false,
$max_redirects = self::MAX_REDIRECTS_DEFAULT, $max_redirects = self::MAX_REDIRECTS_DEFAULT,
$payload_serializers = array(); $payload_serializers = [];
// Options // Options
// private $_options = array( // private $_options = array(
@ -70,7 +70,9 @@ class Request
*/ */
private function __construct($attrs = null) private function __construct($attrs = null)
{ {
if (!is_array($attrs)) return; if (!is_array($attrs)) {
return;
}
foreach ($attrs as $attr => $value) { foreach ($attrs as $attr => $value) {
$this->$attr = $value; $this->$attr = $value;
} }
@ -195,8 +197,9 @@ class Request
*/ */
public function send() public function send()
{ {
if (!$this->hasBeenInitialized()) if (!$this->hasBeenInitialized()) {
$this->_curlPrep(); $this->_curlPrep();
}
$result = curl_exec($this->_ch); $result = curl_exec($this->_ch);
@ -275,7 +278,8 @@ class Request
/** /**
* @return is this request setup for client side cert? * @return is this request setup for client side cert?
*/ */
public function hasClientSideCert() { public function hasClientSideCert()
{
return isset($this->client_cert) && isset($this->client_key); return isset($this->client_cert) && isset($this->client_key);
} }
@ -326,7 +330,9 @@ class Request
*/ */
public function mime($mime) public function mime($mime)
{ {
if (empty($mime)) return $this; if (empty($mime)) {
return $this;
}
$this->content_type = $this->expected_type = Mime::getFullMime($mime); $this->content_type = $this->expected_type = Mime::getFullMime($mime);
return $this; return $this;
} }
@ -349,7 +355,9 @@ class Request
*/ */
public function method($method) public function method($method)
{ {
if (empty($method)) return $this; if (empty($method)) {
return $this;
}
$this->method = $method; $this->method = $method;
return $this; return $this;
} }
@ -360,7 +368,9 @@ class Request
*/ */
public function expects($mime) public function expects($mime)
{ {
if (empty($mime)) return $this; if (empty($mime)) {
return $this;
}
$this->expected_type = Mime::getFullMime($mime); $this->expected_type = Mime::getFullMime($mime);
return $this; return $this;
} }
@ -376,7 +386,9 @@ class Request
*/ */
public function contentType($mime) public function contentType($mime)
{ {
if (empty($mime)) return $this; if (empty($mime)) {
return $this;
}
$this->content_type = Mime::getFullMime($mime); $this->content_type = Mime::getFullMime($mime);
return $this; return $this;
} }
@ -419,9 +431,10 @@ class Request
* @param string $auth_username Authentication username. Default null * @param string $auth_username Authentication username. Default null
* @param string $auth_password Authentication password. Default null * @param string $auth_password Authentication password. Default null
*/ */
public function useProxy($proxy_host, $proxy_port = 80, $auth_type = null, $auth_username = null, $auth_password = null){ public function useProxy($proxy_host, $proxy_port = 80, $auth_type = null, $auth_username = null, $auth_password = null)
{
$this->addOnCurlOption(CURLOPT_PROXY, "{$proxy_host}:{$proxy_port}"); $this->addOnCurlOption(CURLOPT_PROXY, "{$proxy_host}:{$proxy_port}");
if(in_array($auth_type, array(CURLAUTH_BASIC,CURLAUTH_NTLM)) ){ if (in_array($auth_type, [CURLAUTH_BASIC,CURLAUTH_NTLM])) {
$this->addOnCurlOption(CURLOPT_PROXYAUTH, $auth_type) $this->addOnCurlOption(CURLOPT_PROXYAUTH, $auth_type)
->addOnCurlOption(CURLOPT_PROXYUSERPWD, "{$auth_username}:{$auth_password}"); ->addOnCurlOption(CURLOPT_PROXYUSERPWD, "{$auth_username}:{$auth_password}");
} }
@ -431,7 +444,8 @@ class Request
/** /**
* @return is this request setup for using proxy? * @return is this request setup for using proxy?
*/ */
public function hasProxy(){ public function hasProxy()
{
return is_string($this->additional_curl_opts[CURLOPT_PROXY]); return is_string($this->additional_curl_opts[CURLOPT_PROXY]);
} }
@ -646,15 +660,17 @@ class Request
// This method also adds the custom header support as described in the // This method also adds the custom header support as described in the
// method comments // method comments
if (count($args) === 0) if (count($args) === 0) {
return; return;
}
// Strip the sugar. If it leads with "with", strip. // Strip the sugar. If it leads with "with", strip.
// This is okay because: No defined HTTP headers begin with with, // This is okay because: No defined HTTP headers begin with with,
// and if you are defining a custom header, the standard is to prefix it // and if you are defining a custom header, the standard is to prefix it
// with an "X-", so that should take care of any collisions. // with an "X-", so that should take care of any collisions.
if (substr($method, 0, 4) === 'with') if (substr($method, 0, 4) === 'with') {
$method = substr($method, 4); $method = substr($method, 4);
}
// Precede upper case letters with dashes, uppercase the first letter of method // Precede upper case letters with dashes, uppercase the first letter of method
$header = ucwords(implode('-', preg_split('/([A-Z][^A-Z]*)/', $method, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY))); $header = ucwords(implode('-', preg_split('/([A-Z][^A-Z]*)/', $method, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY)));
@ -681,7 +697,7 @@ class Request
// recusion. Do not use this syntax elsewhere. // recusion. Do not use this syntax elsewhere.
// It goes against the whole readability // It goes against the whole readability
// and transparency idea. // and transparency idea.
self::$_template = new Request(array('method' => Http::GET)); self::$_template = new Request(['method' => Http::GET]);
// This is more like it... // This is more like it...
self::$_template self::$_template
@ -695,11 +711,13 @@ class Request
*/ */
private function _setDefaults() private function _setDefaults()
{ {
if (!isset(self::$_template)) if (!isset(self::$_template)) {
self::_initializeDefaults(); self::_initializeDefaults();
foreach (self::$_template as $k=>$v) { }
if ($k[0] != '_') foreach (self::$_template as $k => $v) {
if ($k[0] != '_') {
$this->$k = $v; $this->$k = $v;
}
} }
return $this; return $this;
} }
@ -725,8 +743,9 @@ class Request
Bootstrap::init(); Bootstrap::init();
// Setup the default template if need be // Setup the default template if need be
if (!isset(self::$_template)) if (!isset(self::$_template)) {
self::_initializeDefaults(); self::_initializeDefaults();
}
$request = new Request(); $request = new Request();
return $request return $request
@ -745,8 +764,9 @@ class Request
public function _curlPrep() public function _curlPrep()
{ {
// Check for required stuff // Check for required stuff
if (!isset($this->uri)) if (!isset($this->uri)) {
throw new \Exception('Attempting to send a request before defining a URI endpoint.'); throw new \Exception('Attempting to send a request before defining a URI endpoint.');
}
$ch = curl_init($this->uri); $ch = curl_init($this->uri);
@ -757,18 +777,19 @@ class Request
} }
if ($this->hasClientSideCert()) { if ($this->hasClientSideCert()) {
if (!file_exists($this->client_key)) {
if (!file_exists($this->client_key))
throw new \Exception('Could not read Client Key'); throw new \Exception('Could not read Client Key');
}
if (!file_exists($this->client_cert)) if (!file_exists($this->client_cert)) {
throw new \Exception('Could not read Client Certificate'); throw new \Exception('Could not read Client Certificate');
}
curl_setopt($ch, CURLOPT_SSLCERTTYPE, $this->client_encoding); curl_setopt($ch, CURLOPT_SSLCERTTYPE, $this->client_encoding);
curl_setopt($ch, CURLOPT_SSLKEYTYPE, $this->client_encoding); curl_setopt($ch, CURLOPT_SSLKEYTYPE, $this->client_encoding);
curl_setopt($ch, CURLOPT_SSLCERT, $this->client_cert); curl_setopt($ch, CURLOPT_SSLCERT, $this->client_cert);
curl_setopt($ch, CURLOPT_SSLKEY, $this->client_key); curl_setopt($ch, CURLOPT_SSLKEY, $this->client_key);
curl_setopt($ch, CURLOPT_SSLKEYPASSWD, $this->client_passphrase); curl_setopt($ch, CURLOPT_SSLKEYPASSWD, $this->client_passphrase);
// curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->client_cert_passphrase); // curl_setopt($ch, CURLOPT_SSLCERTPASSWD, $this->client_cert_passphrase);
} }
@ -792,7 +813,7 @@ class Request
$this->headers['Content-Length'] = strlen($this->serialized_payload); $this->headers['Content-Length'] = strlen($this->serialized_payload);
} }
$headers = array(); $headers = [];
// https://github.com/nategood/httpful/issues/37 // https://github.com/nategood/httpful/issues/37
// Except header removes any HTTP 1.1 Continue from response headers // Except header removes any HTTP 1.1 Continue from response headers
$headers[] = 'Expect:'; $headers[] = 'Expect:';
@ -851,7 +872,8 @@ class Request
return $this; return $this;
} }
public function buildUserAgent() { public function buildUserAgent()
{
$user_agent = 'User-Agent: Httpful/' . Httpful::VERSION . ' (cURL/'; $user_agent = 'User-Agent: Httpful/' . Httpful::VERSION . ' (cURL/';
$curl = \curl_version(); $curl = \curl_version();
@ -864,8 +886,11 @@ class Request
$user_agent .= ' PHP/'. PHP_VERSION . ' (' . PHP_OS . ')'; $user_agent .= ' PHP/'. PHP_VERSION . ' (' . PHP_OS . ')';
if (isset($_SERVER['SERVER_SOFTWARE'])) { if (isset($_SERVER['SERVER_SOFTWARE'])) {
$user_agent .= ' ' . \preg_replace('~PHP/[\d\.]+~U', '', $user_agent .= ' ' . \preg_replace(
$_SERVER['SERVER_SOFTWARE']); '~PHP/[\d\.]+~U',
'',
$_SERVER['SERVER_SOFTWARE']
);
} else { } else {
if (isset($_SERVER['TERM_PROGRAM'])) { if (isset($_SERVER['TERM_PROGRAM'])) {
$user_agent .= " {$_SERVER['TERM_PROGRAM']}"; $user_agent .= " {$_SERVER['TERM_PROGRAM']}";
@ -915,12 +940,14 @@ class Request
*/ */
private function _serializePayload($payload) private function _serializePayload($payload)
{ {
if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER) if (empty($payload) || $this->serialize_payload_method === self::SERIALIZE_PAYLOAD_NEVER) {
return $payload; return $payload;
}
// When we are in "smart" mode, don't serialize strings/scalars, assume they are already serialized // When we are in "smart" mode, don't serialize strings/scalars, assume they are already serialized
if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload)) if ($this->serialize_payload_method === self::SERIALIZE_PAYLOAD_SMART && is_scalar($payload)) {
return $payload; return $payload;
}
// Use a custom serializer if one is registered for this mime type // Use a custom serializer if one is registered for this mime type
if (isset($this->payload_serializers['*']) || isset($this->payload_serializers[$this->content_type])) { if (isset($this->payload_serializers['*']) || isset($this->payload_serializers[$this->content_type])) {

Some files were not shown because too many files have changed in this diff Show more