67 lines
1.9 KiB
PHP
67 lines
1.9 KiB
PHP
<?php
|
||
/*
|
||
Plugin Name: Spotify Recent OAuth
|
||
Description: Visar senast spelade låt från Spotify (som block).
|
||
Version: 1.0.0
|
||
Author: Christian Ohlsson
|
||
*/
|
||
|
||
if (!defined('ABSPATH')) exit;
|
||
|
||
// Ladda admin
|
||
require_once plugin_dir_path(__FILE__) . 'admin/settings.php';
|
||
require_once plugin_dir_path(__FILE__) . 'admin/oauth-handler.php';
|
||
|
||
function sro_register_block() {
|
||
|
||
wp_register_script(
|
||
'sro-block-js',
|
||
plugins_url('blocks/block.js', __FILE__),
|
||
array('wp-blocks', 'wp-element', 'wp-block-editor'),
|
||
filemtime(plugin_dir_path(__FILE__) . 'blocks/block.js')
|
||
);
|
||
|
||
wp_register_style(
|
||
'sro-style',
|
||
plugins_url('blocks/style.css', __FILE__),
|
||
array(),
|
||
filemtime(plugin_dir_path(__FILE__) . 'blocks/style.css')
|
||
);
|
||
|
||
register_block_type(__DIR__ . '/blocks');
|
||
}
|
||
add_action('init', 'sro_register_block');
|
||
|
||
function sro_fetch_recent_track() {
|
||
$access = get_option('sro_access_token');
|
||
if(!$access) return false;
|
||
|
||
$res = wp_remote_get(
|
||
"https://api.spotify.com/v1/me/player/recently-played?limit=1",
|
||
array('headers' => array('Authorization' => "Bearer $access"))
|
||
);
|
||
|
||
if(is_wp_error($res)) return false;
|
||
$data = json_decode(wp_remote_retrieve_body($res), true);
|
||
return $data['items'][0] ?? false;
|
||
}
|
||
|
||
function sro_render_block() {
|
||
|
||
$item = sro_fetch_recent_track();
|
||
if(!$item) return "<p>Ingen nyligen spelad låt hittad.</p>";
|
||
|
||
$img = esc_url($item['track']['album']['images'][0]['url']);
|
||
$track = esc_html($item['track']['name']);
|
||
$artist = esc_html($item['track']['artists'][0]['name']);
|
||
|
||
ob_start(); ?>
|
||
<div class="sro-container">
|
||
<img src="<?php echo $img; ?>" class="sro-album" alt="">
|
||
<div class="sro-info">
|
||
<div class="sro-track"><?php echo "$artist – $track"; ?></div>
|
||
</div>
|
||
</div>
|
||
<?php
|
||
return ob_get_clean();
|
||
}
|