Permalink
Browse files

Sharing music collection

  • Loading branch information...
Thoulah committed Jun 19, 2018
1 parent 9586fb7 commit f7afec224e67ef24b875a81496ea310564e0fa4f
View

Some generated files are not rendered by default. Learn more.

Oops, something went wrong.
@@ -81,6 +81,12 @@ svg.fa {
}
}
&music-collection {
.card {
min-width: 9rem;
}
}
&lyrics-lyrics {
.row {
@include dividing-line(10px, $lighterBlue);
@@ -2,6 +2,7 @@
namespace app\commands;
use Yii;
use app\models\Webrequest;
use app\models\music\Collection;
use app\models\feed\Feed;
use app\models\user\{Profile, RecentTracks, WeeklyArtist};
use Da\User\Model\User;
@@ -15,6 +16,34 @@ class FeedController extends Controller {
public $defaultAction = 'webfeed';
public $limit = 25;
/**
* Retrieves and stores Discogs collection
*/
public function actionDiscogsCollection(): int {
$discogs = new Collection();
foreach (User::find()->where(['blocked_at' => null])->all() as $user) :
$profile = Profile::findOne(['user_id' => $user->id]);
if (isset($profile->discogs)) :
$response = Webrequest::getDiscogsApi("/users/{$profile->discogs}/collection/folders/0/releases");
if (!$response->isOK) :
continue;
endif;
Collection::deleteAll(['user_id' => $profile->user_id]);
$discogs->saveCollection($profile->user_id, $response->data['releases']);
for ($x = 2; $x < (int) ArrayHelper::getValue($response->data, 'pagination.pages'); $x++) :
$response = Webrequest::getDiscogsApi("/users/{$profile->discogs}/collection/folders/0/releases?".http_build_query(['page' => $x]));
if (!$response->isOK) :
continue;
endif;
$discogs->saveCollection($profile->user_id, $response->data['releases']);
endfor;
endif;
endforeach;
return self::EXIT_CODE_NORMAL;
}
/**
* Retrieves and stores Recent Tracks from Last.fm.
*/
@@ -47,7 +76,7 @@ public function actionLastfmWeeklyArtist(): int {
if (isset($profile->lastfm)) :
$response = Webrequest::getLastfmApi('user.getweeklyartistchart', $profile->lastfm, $this->limit);
if (!$response->isOK) :
return self::EXIT_CODE_ERROR;
continue;
endif;
WeeklyArtist::deleteAll(['userid' => $profile->user_id]);
View
@@ -113,6 +113,7 @@
'lyrics/<artist:.*?>/<year:\d{4}>/<album:.*?>-<size:.{2,5}>.jpg' => 'lyrics/albumcover',
'lyrics/<artist:.*?>/<year:\d{4}>/<album:.*?>' => 'lyrics/index',
'lyrics/<artist:.*?>' => 'lyrics/index',
'music/collection-cover/<id:.*>.jpg' => 'music/collection-cover',
'articles/<id:\d+>/<title:.*?>.pdf' => 'articles/pdf',
$params['shortDomain'].'art<id:\d+>' => 'permalink/articles',
'articles/<id:\d+>/<title:.*?>' => 'articles/index',
@@ -0,0 +1,17 @@
<?php
namespace app\controllers;
use Yii;
use app\models\music\Collection;
class MusicController extends \yii\web\Controller {
public function actionCollection() {
return $this->render('collection', [
'model' => new Collection(),
]);
}
public function actionCollectionCover(int $id) {
$album = Collection::find()->where(['id' => $id])->one();
return Yii::$app->response->sendContentAsFile($album->image, "{$id}.jpg", ['mimeType' => 'image/jpeg', 'inline' => true]);
}
}
@@ -2,26 +2,33 @@
namespace app\controllers;
use Yii;
use app\commands\FeedController;
use yii\models\webhook\Github;
use yii\web\{Response, NotFoundHttpException, UnauthorizedHttpException};
class WebhookController extends \yii\web\Controller {
public $enableCsrfValidation = false;
public function actionGitPush() {
public function actionGithub() {
Yii::$app->response->format = Response::FORMAT_JSON;
list($algo, $hash) = explode('=', Yii::$app->request->headers->get('X-Hub-Signature', 'sha512=1'), 2);
if (!hash_equals($hash, hash_hmac($algo, file_get_contents('php://input'), Yii::$app->params['secrets']['github']['hook']))) :
throw new UnauthorizedHttpException('Access denied!');
elseif (Yii::$app->request->headers->get('X-GitHub-Event') === 'ping') :
return ['status' => 'success', 'message' => 'Pong!'];
elseif (Yii::$app->request->headers->get('X-GitHub-Event') !== 'push') :
throw new NotFoundHttpException('Action not found.');
endif;
$github = new Github();
switch (Yii::$app->request->headers->get('X-GitHub-Event')) :
case 'ping':
return ['status' => 'success', 'message' => 'Pong!'];
case 'push':
return $github->push(Yii::$app->request->post('payload'));
default:
throw new NotFoundHttpException('Action not found.');
endswitch;
$payload = json_decode(Yii::$app->request->post('payload'));
$controller = new FeedController(Yii::$app->controller->id, Yii::$app);
$controller->limit = 5;
$controller->actionWebfeed('atom', 'Mr42Commits', "https://github.com/{$payload->repository->full_name}/commits/{$payload->repository->default_branch}.atom");
$controller->actionWebfeed('atom', 'Mr42Commits', "https://github.com/{$payload->repository->full_name}/commits/{$payload->repository->default_branch}.atom", 'content');
return ['status' => 'success', 'message' => 'Successfully updated.'];
}
View
@@ -31,7 +31,12 @@
['label' => Yii::t('mr42', 'QR Code Generator'), 'url' => ['/tools/qr']],
],
],
['label' => Yii::$app->icon->show('music', ['class' => 'mr-1']).Yii::t('mr42', 'Lyrics'), 'url' => ['/lyrics/index'], 'visible' => true],
['label' => Yii::$app->icon->show('music', ['class' => 'mr-1']).Yii::t('mr42', 'Music'), 'url' => null,
'items' => [
['label' => Yii::t('mr42', 'Lyrics'), 'url' => ['/lyrics/index'], 'visible' => true],
['label' => Yii::t('mr42', 'Collection'), 'url' => ['/music/collection']],
],
],
$isGuest
? ['label' => Yii::$app->icon->show('sign-in-alt', ['class' => 'mr-1']).Yii::t('usuario', 'Login'), 'url' => ['/user/security/login'], 'visible' => true]
: ['label' => Yii::$app->icon->show('user-circle', ['class' => 'mr-1']).Yii::$app->user->identity->username.$unreadBadge, 'url' => null,
@@ -47,6 +47,7 @@
'Changelog' => 'Änderungsprotokoll',
'Click on the image to retrieve a new verification code.' => 'Klicken Sie auf das Bild, um einen neuen Prüfcode abzurufen.',
'Code' => 'Code',
'Collection' => 'Sammlung',
'Comment' => 'Kommentar',
'Comments' => 'Kommentare',
'Completely Automated Public Turing test to tell Computers and Humans Apart' => 'Vollautomatischer öffentlicher Turing-Test zur Unterscheidung von Computern und Menschen',
@@ -118,6 +119,7 @@
'Message' => 'Nachricht',
'Microsoft® Office 365® End Date' => 'Microsoft® Office 365® Enddatum',
'Microsoft® Office 365® End Date Calculator' => 'Microsoft® Office 365® Enddatumsrechner',
'Music' => 'Musik',
'Name' => 'Name',
'Next Article' => 'Nächster Artikel',
'Nickname' => 'Spitzname',
@@ -47,6 +47,7 @@
'Changelog' => 'Изменения',
'Click on the image to retrieve a new verification code.' => 'Нажмите на изображение, чтобы получить новый код подтверждения.',
'Code' => 'Код',
'Collection' => 'Коллекция',
'Comment' => 'Комментарий',
'Comments' => 'Комментарии',
'Completely Automated Public Turing test to tell Computers and Humans Apart' => 'Полностью автоматизированный публичный тест Тьюринга для различения компьютеров и людей',
@@ -118,6 +119,7 @@
'Message' => 'Сообщение',
'Microsoft® Office 365® End Date' => 'Дата окончания выпуска Microsoft® Office 365®',
'Microsoft® Office 365® End Date Calculator' => 'Калькулятор даты выпуска Microsoft® Office 365®',
'Music' => 'Музыка',
'Name' => 'Имя',
'Next Article' => 'Следующая статья',
'Nickname' => 'Кличка',
View
@@ -0,0 +1,19 @@
<?php
namespace app\models;
class Image {
public static function resize(string $image, int $size): string {
$process = proc_open("convert -resize {$size} -strip -quality 85% -interlace Plane - jpg:-", [['pipe', 'r'], ['pipe', 'w']], $pipes);
if (is_resource($process)) :
fwrite($pipes[0], $image);
fclose($pipes[0]);
$image = stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($process);
endif;
return $image;
}
}
@@ -5,6 +5,13 @@
use yii\httpclient\{Client, Response};
class Webrequest {
public static function getDiscogsApi(string $content): Response {
return self::getUrl('https://api.discogs.com/', $content, [
'key' => Yii::$app->params['secrets']['discogs']['Key'],
'secret' => Yii::$app->params['secrets']['discogs']['Secret'],
]);
}
public static function getLastfmApi(string $method, string $user, int $limit): Response {
return self::getUrl('https://ws.audioscrobbler.com/2.0/', '', [
'api_key' => Yii::$app->params['secrets']['last.fm']['API'],
@@ -25,7 +32,7 @@ public static function getYoutubeApi(string $id, string $content): Response {
public static function getUrl(string $base, string $url, array $data = []): Response {
$client = new Client(['baseUrl' => $base]);
return $client->createRequest()
->addHeaders(['user-agent' => Yii::$app->name.' (+'.Url::to(['site/index'], true).')'])
->addHeaders(['user-agent' => Yii::$app->name.' (+'.Yii::$app->params['shortDomain'].')'])
->setData($data)
->setUrl($url)
->send();
@@ -1,7 +1,7 @@
<?php
namespace app\models\lyrics;
use Yii;
use app\models\{Pdf, Video};
use app\models\{Image, Pdf, Video};
use yii\behaviors\TimestampBehavior;
use yii\bootstrap4\Html;
use yii\db\Expression;
@@ -96,16 +96,7 @@ public static function getCover(int $size, $album): array {
endif;
if ($size !== 'cover') :
$process = proc_open("convert -resize {$size} -strip -quality 85% -interlace Plane - jpg:-", [['pipe', 'r'], ['pipe', 'w']], $pipes);
if (is_resource($process)) :
fwrite($pipes[0], $album->image);
fclose($pipes[0]);
$album->image = stream_get_contents($pipes[1]);
fclose($pipes[1]);
proc_close($process);
endif;
$album->image = Image::resize($album->image, $size);
endif;
return [$fileName, $album->image];
@@ -0,0 +1,28 @@
<?php
namespace app\models\music;
use app\models\{Image, Webrequest};
use yii\console\Controller;
use yii\helpers\ArrayHelper;
class Collection extends \yii\db\ActiveRecord {
public static function tableName(): string {
return '{{%discogs_collection}}';
}
public function saveCollection(int $user, array $data) {
foreach ($data as $item) :
$addItem = new Collection();
$addItem->id = (int) ArrayHelper::getValue($item, 'basic_information.id');
$addItem->user_id = $user;
$addItem->artist = ArrayHelper::getValue($item, 'basic_information.artists.0.name');
$addItem->year = (int)ArrayHelper::getValue($item, 'basic_information.year');
$addItem->title = ArrayHelper::getValue($item, 'basic_information.title');
$addItem->image = null;
if ($image = ArrayHelper::getValue($item, 'basic_information.cover_image')) :
$img = Webrequest::getUrl($image, '');
$addItem->image = Image::resize($img->content, 250);
endif;
$addItem->save();
endforeach;
}
}
@@ -0,0 +1,13 @@
<?php
namespace app\models\webhook;
use app\commands\FeedController;
class Github extends \yii\base\Model {
public function push(string $payload): array {
$controller = new FeedController(Yii::$app->controller->id, Yii::$app);
$controller->limit = 5;
$controller->actionWebfeed('atom', 'Mr42Commits', "https://github.com/{$payload->repository->full_name}/commits/{$payload->repository->default_branch}.atom", 'content');
return ['status' => 'success', 'message' => 'Successfully updated.'];
}
}
@@ -2,6 +2,7 @@
use yii\bootstrap4\Html;
$this->title = Yii::t('mr42', 'Lyrics');
$this->params['breadcrumbs'][] = Yii::t('mr42', 'Music');
$this->params['breadcrumbs'][] = $this->title;
echo Html::tag('h1', $this->title);
@@ -3,6 +3,7 @@
use yii\bootstrap4\Html;
$this->title = implode(' - ', [$data[0]->artist->name, 'Lyrics']);
$this->params['breadcrumbs'][] = Yii::t('mr42', 'Music');
$this->params['breadcrumbs'][] = ['label' => Yii::t('mr42', 'Lyrics'), 'url' => ['index']];
$this->params['breadcrumbs'][] = $data[0]->artist->name;
@@ -2,6 +2,7 @@
use yii\bootstrap4\Html;
$this->title = implode(' - ', [$data[0]->artist->name, $data[0]->album->name, 'Lyrics']);
$this->params['breadcrumbs'][] = Yii::t('mr42', 'Music');
$this->params['breadcrumbs'][] = ['label' => Yii::t('mr42', 'Lyrics'), 'url' => ['index']];
$this->params['breadcrumbs'][] = ['label' => $data[0]->artist->name, 'url' => ['index', 'artist' => $data[0]->artist->url]];
$this->params['breadcrumbs'][] = $data[0]->album->name;
@@ -0,0 +1,22 @@
<?php
use yii\helpers\{Html, Url};
$this->title = Yii::t('mr42', 'Collection');
$this->params['breadcrumbs'][] = Yii::t('mr42', 'Music');
$this->params['breadcrumbs'][] = $this->title;
echo Html::tag('h1', $this->title);
echo Html::beginTag('div', ['class' => 'site-music-collection']);
echo Html::beginTag('div', ['class' => 'card-deck']);
foreach ($model->find()->orderBy('artist, year')->all() as $album) :
echo Html::beginTag('div', ['class' => 'card mb-3']);
echo Html::a(
Html::img(['music/collection-cover', 'id' => $album->id], ['alt' => "{$album->artist} - {$album->year} - {$album->title}", 'class' => 'card-img-top rounded'])
, "https://www.discogs.com/release/{$album->id}");
echo Html::tag('div', Html::tag('small', $album->title, ['class' => 'card-text mt-auto font-weight-bold']), ['class' => 'card-body d-flex text-left']);
echo Html::tag('div', Html::tag('small', $album->artist), ['class' => 'card-footer text-left']);
echo Html::endTag('div');
endforeach;
echo Html::endTag('div');
echo Html::endTag('div');

0 comments on commit f7afec2

Please sign in to comment.