-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMastodonPoster.php
80 lines (63 loc) · 2.57 KB
/
MastodonPoster.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
<?php
namespace ulrischa;
class MastodonPoster {
private $accessToken;
private $apiBaseUrl = 'https://mastodon.social';
public function __construct($accessToken) {
$this->accessToken = $accessToken;
}
private function sendHttp($url, $custom_headers = [], $post_data = null) {
$headers = [
'Authorization: Bearer ' . $this->accessToken,
'Content-Type: application/json'
];
$headers = array_merge($headers, $custom_headers);
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
if ($post_data !== null) {
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($post_data));
}
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
die('Error: ' . $error);
}
return json_decode($response, true);
}
private function uploadMedia($filePath, $description) {
$url = $this->apiBaseUrl . '/api/v1/media';
$file = new \CURLFile($filePath);
$postData = ['file' => $file, 'description' => $description];
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer ' . $this->accessToken,
'Content-Type: multipart/form-data'
]);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
$response = curl_exec($ch);
$error = curl_error($ch);
curl_close($ch);
if ($error) {
die('Error: ' . $error);
}
return json_decode($response, true);
}
public function postStatus($statusText, $filePaths=null, $descriptions=null) {
if (!empty($filePaths) && !empty($descriptions)) {
$mediaIds = [];
foreach ($filePaths as $index => $filePath) {
$description = $descriptions[$index] ?? '';
$uploadResponse = $this->uploadMedia($filePath, $description);
$mediaIds[] = $uploadResponse['id'] ?? null;
}
return $this->sendHttp($this->apiBaseUrl . '/api/v1/statuses', [], ['status' => $statusText, 'media_ids' => $mediaIds]);
}
else return $this->sendHttp($this->apiBaseUrl . '/api/v1/statuses', [], ['status' => $statusText]);
}
}
?>