Skip to content

Commit

Permalink
Remove over-engineered service
Browse files Browse the repository at this point in the history
  • Loading branch information
phanan committed Sep 4, 2018
1 parent 4b8153e commit 096eb7e
Show file tree
Hide file tree
Showing 19 changed files with 217 additions and 317 deletions.
4 changes: 2 additions & 2 deletions app/Events/SongLikeToggled.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,9 @@ class SongLikeToggled extends Event
public $interaction;
public $user;

public function __construct(Interaction $interaction, User $user)
public function __construct(Interaction $interaction, User $user = null)
{
$this->interaction = $interaction;
$this->user = $user;
$this->user = $user ?: auth()->user();
}
}
15 changes: 6 additions & 9 deletions app/Http/Controllers/API/LastfmController.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,8 @@ class LastfmController extends Controller
private $lastfmService;
private $jwtAuth;

public function __construct(
Guard $auth,
LastfmService $lastfmService,
JWTAuth $jwtAuth
) {
public function __construct(Guard $auth, LastfmService $lastfmService, JWTAuth $jwtAuth)
{
$this->auth = $auth;
$this->lastfmService = $lastfmService;
$this->jwtAuth = $jwtAuth;
Expand Down Expand Up @@ -57,11 +54,11 @@ public function connect()
*/
public function callback(LastfmCallbackRequest $request)
{
$sessionKey = $this->lastfmService->fetchSessionKeyUsingToken($request->token);
$sessionKey = $this->lastfmService->getSessionKey($request->token);

abort_unless($sessionKey, 500, 'Invalid token key.');

$this->lastfmService->setUserSessionKey($this->auth->user(), $sessionKey);
$this->auth->user()->savePreference('lastfm_session_key', $sessionKey);

return view('api.lastfm.callback');
}
Expand All @@ -75,7 +72,7 @@ public function callback(LastfmCallbackRequest $request)
*/
public function setSessionKey(LastfmSetSessionKeyRequest $request)
{
$this->lastfmService->setUserSessionKey($this->auth->user(), $request->key);
$this->auth->user()->savePreference('lastfm_session_key', trim($request->key));

return response()->json();
}
Expand All @@ -87,7 +84,7 @@ public function setSessionKey(LastfmSetSessionKeyRequest $request)
*/
public function disconnect()
{
$this->lastfmService->deleteUserSessionKey($this->auth->user());
$this->auth->user()->deletePreference('lastfm_session_key');

return response()->json();
}
Expand Down
4 changes: 2 additions & 2 deletions app/Http/Controllers/API/ScrobbleController.php
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,13 @@ public function __construct(LastfmService $lastfmService)
*/
public function store(Request $request, Song $song, string $timestamp)
{
if (!$song->artist->is_unknown && $this->lastfmService->isUserConnected($request->user())) {
if (!$song->artist->is_unknown && $request->user()->connectedToLastfm()) {
$this->lastfmService->scrobble(
$song->artist->name,
$song->title,
(int) $timestamp,
$song->album->name === Album::UNKNOWN_NAME ? '' : $song->album->name,
$this->lastfmService->getUserSessionKey($request->user())
$request->user()->lastfm_session_key
);
}

Expand Down
16 changes: 6 additions & 10 deletions app/Listeners/LoveTrackOnLastfm.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,18 @@ public function __construct(LastfmService $lastfm)

public function handle(SongLikeToggled $event): void
{
if (!$this->shouldHandle($event)) {
if (!$this->lastfm->enabled() ||
!($sessionKey = $event->user->lastfm_session_key) ||
$event->interaction->song->album->artist->is_unknown
) {
return;
}

$this->lastfm->toggleLoveTrack(
$event->interaction->song->title,
$event->interaction->song->artist->name,
$this->lastfm->getUserSessionKey($event->user),
$event->interaction->song->album->artist->name,
$sessionKey,
$event->interaction->liked
);
}

private function shouldHandle(SongLikeToggled $event): bool
{
return $this->lastfm->enabled()
&& $this->lastfm->isUserConnected($event->user)
&& !$event->interaction->song->artist->is_unknown;
}
}
14 changes: 5 additions & 9 deletions app/Listeners/UpdateLastfmNowPlaying.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@ public function __construct(LastfmService $lastfm)

public function handle(SongStartedPlaying $event): void
{
if (!$this->shouldHandle($event)) {
if (!$this->lastfm->enabled() ||
!($sessionKey = $event->user->lastfm_session_key) ||
$event->song->artist->is_unknown
) {
return;
}

Expand All @@ -26,14 +29,7 @@ public function handle(SongStartedPlaying $event): void
$event->song->title,
$event->song->album->name === Album::UNKNOWN_NAME ? '' : $event->song->album->name,
$event->song->length,
$this->lastfm->getUserSessionKey($event->user)
$sessionKey
);
}

private function shouldHandle(SongStartedPlaying $event): bool
{
return $this->lastfm->enabled()
&& $this->lastfm->isUserConnected($event->user)
&& !$event->song->artist->is_unknown;
}
}
64 changes: 62 additions & 2 deletions app/Models/User.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

namespace App\Models;

use App\Services\LastfmService;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
Expand All @@ -11,6 +10,7 @@
* @property array $preferences
* @property int $id
* @property bool $is_admin
* @property string $lastfm_session_key
*/
class User extends Authenticatable
{
Expand All @@ -21,7 +21,7 @@ class User extends Authenticatable
*
* @var array
*/
private const HIDDEN_PREFERENCES = [LastfmService::SESSION_KEY_PREFERENCE_KEY];
private const HIDDEN_PREFERENCES = ['lastfm_session_key'];

protected $guarded = ['id'];
protected $casts = [
Expand All @@ -40,6 +40,66 @@ public function interactions(): HasMany
return $this->hasMany(Interaction::class);
}

/**
* @return mixed|null
*/
public function getPreference(string $key)
{
// We can't use $this->preferences directly, since the data has been tampered
// by getPreferencesAttribute().
return array_get((array) unserialize($this->attributes['preferences']), $key);
}

/**
* @param mixed $val
*/
public function savePreference(string $key, $val): void
{
$preferences = $this->preferences;
$preferences[$key] = $val;
$this->preferences = $preferences;

$this->save();
}

/**
* An alias to savePreference().
*
* @param mixed $val
*
* @see self::savePreference
*/
public function setPreference(string $key, $val): void
{
$this->savePreference($key, $val);
}

public function deletePreference(string $key): void
{
$preferences = $this->preferences;
array_forget($preferences, $key);

$this->update(compact('preferences'));
}

/**
* Determine if the user is connected to Last.fm.
*/
public function connectedToLastfm(): bool
{
return (bool) $this->lastfm_session_key;
}

/**
* Get the user's Last.fm session key.
*
* @return string|null The key if found, or null if user isn't connected to Last.fm
*/
public function getLastfmSessionKeyAttribute(): ?string
{
return $this->getPreference('lastfm_session_key');
}

/**
* User preferences are stored as a serialized associative array.
*
Expand Down
2 changes: 2 additions & 0 deletions app/Services/ApiClient.php
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,8 @@ public function request(string $method, string $uri, bool $appendKey = true, arr
} catch (ClientException $e) {
$this->logger->error($e);
}

return null;
}

/**
Expand Down
12 changes: 6 additions & 6 deletions app/Services/InteractionService.php
Original file line number Diff line number Diff line change
Expand Up @@ -45,11 +45,11 @@ public function toggleLike(string $songId, User $user): Interaction
return tap($this->interaction->firstOrCreate([
'song_id' => $songId,
'user_id' => $user->id,
]), static function (Interaction $interaction) use ($user): void {
]), static function (Interaction $interaction): void {
$interaction->liked = !$interaction->liked;
$interaction->save();

event(new SongLikeToggled($interaction, $user));
event(new SongLikeToggled($interaction));
});
}

Expand All @@ -66,15 +66,15 @@ public function batchLike(array $songIds, User $user): array
return tap($this->interaction->firstOrCreate([
'song_id' => $songId,
'user_id' => $user->id,
]), static function (Interaction $interaction) use ($user): void {
]), static function (Interaction $interaction): void {
if (!$interaction->exists) {
$interaction->play_count = 0;
}

$interaction->liked = true;
$interaction->save();

event(new SongLikeToggled($interaction, $user));
event(new SongLikeToggled($interaction));
});
})->all();
}
Expand All @@ -90,11 +90,11 @@ public function batchUnlike(array $songIds, User $user): void
->whereIn('song_id', $songIds)
->where('user_id', $user->id)
->get()
->each(static function (Interaction $interaction) use ($user): void {
->each(static function (Interaction $interaction): void {
$interaction->liked = false;
$interaction->save();

event(new SongLikeToggled($interaction, $user));
event(new SongLikeToggled($interaction));
}
);
}
Expand Down
40 changes: 1 addition & 39 deletions app/Services/LastfmService.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,10 @@

namespace App\Services;

use App\Models\User;
use Exception;
use GuzzleHttp\Client;
use Illuminate\Contracts\Cache\Repository as Cache;
use Illuminate\Log\Logger;

class LastfmService extends ApiClient implements ApiConsumerInterface
{
public const SESSION_KEY_PREFERENCE_KEY = 'lastfm_session_key';

/**
* Specify the response format, since Last.fm only returns XML.
*
Expand All @@ -26,18 +20,6 @@ class LastfmService extends ApiClient implements ApiConsumerInterface
*/
protected $keyParam = 'api_key';

private $userPreferenceService;

public function __construct(
Client $client,
Cache $cache,
Logger $logger,
UserPreferenceService $userPreferenceService
) {
parent::__construct($client, $cache, $logger);
$this->userPreferenceService = $userPreferenceService;
}

/**
* Determine if our application is using Last.fm.
*/
Expand Down Expand Up @@ -185,7 +167,7 @@ private function buildAlbumInformation(array $albumData): array
*
* @link http://www.last.fm/api/webauth#4
*/
public function fetchSessionKeyUsingToken(string $token): ?string
public function getSessionKey(string $token): ?string
{
$query = $this->buildAuthCallParams([
'method' => 'auth.getSession',
Expand Down Expand Up @@ -327,26 +309,6 @@ protected function formatText($value): string
return trim(str_replace('Read more on Last.fm', '', nl2br(strip_tags(html_entity_decode($value)))));
}

public function getUserSessionKey(User $user): ?string
{
return $this->userPreferenceService->get($user, self::SESSION_KEY_PREFERENCE_KEY);
}

public function setUserSessionKey(User $user, string $sessionKey): void
{
$this->userPreferenceService->set($user, self::SESSION_KEY_PREFERENCE_KEY, $sessionKey);
}

public function deleteUserSessionKey(User $user): void
{
$this->userPreferenceService->delete($user, self::SESSION_KEY_PREFERENCE_KEY);
}

public function isUserConnected(User $user): bool
{
return (bool) $this->getUserSessionKey($user);
}

public function getKey(): ?string
{
return config('koel.lastfm.key');
Expand Down
36 changes: 0 additions & 36 deletions app/Services/UserPreferenceService.php

This file was deleted.

Loading

0 comments on commit 096eb7e

Please sign in to comment.