Add Mastodon

This commit is contained in:
Clément 2021-03-03 21:07:23 +01:00
parent de4c345913
commit 4b79173585
4 changed files with 97 additions and 1 deletions

3
.gitignore vendored
View File

@ -1,3 +1,4 @@
/config.php
/twitter-config.php
/mastodon-config.php
/.idea
/vendor/

47
Mastodon/Mastodon.php Normal file
View File

@ -0,0 +1,47 @@
<?php
class MastodonAPI
{
private $token;
private $instance_url;
public function __construct($token, $instance_url)
{
$this->token = $token;
$this->instance_url = $instance_url;
}
public function postStatus($status)
{
return $this->callAPI('/api/v1/statuses', 'POST', $status);
}
public function uploadMedia($media)
{
return $this->callAPI('/api/v1/media', 'POST', $media);
}
public function callAPI($endpoint, $method, $data)
{
$headers = [
'Authorization: Bearer '.$this->token,
'Content-Type: multipart/form-data',
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $this->instance_url.$endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$reply = curl_exec($ch);
if (!$reply) {
return json_encode(['ok'=>false, 'curl_error_code' => curl_errno($ch_status), 'curl_error' => curl_error(ch_status)]);
}
curl_close($ch);
return json_decode($reply);
}
}

View File

@ -0,0 +1,8 @@
<?php
return [
'domain' => '',
'app_id' => '',
'secret' => '',
'access_token' => '',
];

40
mastodon.php Normal file
View File

@ -0,0 +1,40 @@
<?php
use Shikiryu\WebGobbler\Assembler\Superpose;
use Shikiryu\WebGobbler\Config;
use Shikiryu\WebGobbler\Pool;
include 'vendor/autoload.php';
include 'Mastodon/Mastodon.php';
$mastodon_config = require 'mastodon-config.php';
try {
// generate picture
$config = new Config('./config.json');
$pool = new Pool($config);
$upload_image_name = uniqid('superpose_', true);
$image = new Superpose($pool, $config);
$image_path = sprintf('./render/%s.jpg', $upload_image_name);
$image->saveTo($image_path);
// send picture to mastodon
$app = new MastodonAPI($mastodon_config['access_token'], $mastodon_config['domain']);
$curl_file = curl_file_create(realpath($image_path));
$body = ['file' => $curl_file];
$response = $app->uploadMedia($body);
$file_id = $response->id;
$statusText = 'Nouveau collage';
$status_data = [
'status' => $statusText,
'visibility' => 'public',
'language' => 'fr',
'media_ids[]' => $file_id,
];
$app->postStatus($status_data);
} catch (Exception $exception) {
echo $exception->getMessage();
}