#!/usr/bin/env perl

# Simple script to post YouTube links to Mastodon

use strict;
use warnings;

use Mastodon::Client;
use YouTube::Util qw( extract_youtube_video_id );
use JSON::PP qw( decode_json );
use HTTP::Tiny;
use URL::Encode qw( url_encode );

open my $log, '>>', '/tmp/yt-scrobble.log';

my $url = shift or die;

print $log "$url\n";

my $client = 'Mastodon::Client'->new(
  instance        => 'my.mastodon.instance.example',
  name            => 'username',
  client_id       => 'CLIENT_ID',
  client_secret   => 'CLIENT_SECRET',
  access_token    => 'ACCESS_TOKEN',
  coerce_entities => 1,
);

my $id = extract_youtube_video_id( $url );
my $oembed_url = sprintf(
	'https://www.youtube.com/oembed?format=json&url=%s',
	url_encode( $url ),
);
my $info = decode_json( HTTP::Tiny->new->get( $oembed_url )->{content} );

$client->post_status( sprintf(
	"https://youtu.be/%s\n%s\n%s\n",
	$id,
	$info->{title},
	$info->{author_name},
) );