Jake Vanderwerf
5 days ago 266aa37c48222993bf7bdad6834e31bd08736f5e
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
<?php
namespace JVBase\integrations;
 
use Exception;
use WP_Error;
 
if (!defined('ABSPATH')) {
    exit;
}
 
class BlueSky extends Integrations
{
    protected string $api_base = 'https://bsky.social/xrpc/';
    protected int $max_description_length = 300;
    protected ?string $access_token = null;
    protected ?string $did = null;
 
    public function __construct(?int $user_id = null) {
        $this->service_name = 'bluesky';
        $this->title = 'BlueSky';
        $this->icon = 'fediverse-logo';
        $this->canSync = [
            'initial'   => true,
            'schedule'  => true,
        ];
 
        $this->fields = [
            'handle'    => [
                'type'  => 'text',
                'placeholder'=> 'your-handle.bsky.social',
                'required'  => true,
                'label' => 'Handle',
            ],
            'password'  => [
                'type'  => 'text',
                'subtype'=>'password',
                'label' => 'Application Password',
                'required'  => true,
                'hint'  => '<strong>Security:</strong> Generate an App Password in your BlueSky settings for better security.'
            ]
        ];
        parent::__construct($user_id);
    }
    protected function initialize(): void
    {
    }
 
 
    /**
     * Setup BlueSky client with credentials
     */
    protected function setupClient(?int $user_id = null): bool
    {
        $creds = $this->credentials;
 
        if (empty($creds['identifier']) || empty($creds['password'])) {
            return false;
        }
 
        try {
            $session = $this->createSession($creds['identifier'], $creds['password']);
 
            if ($session) {
                $this->access_token = $session['accessJwt'];
                $this->did = $session['did'];
                return true;
            }
        } catch (Exception $e) {
            $this->handleError($e);
        }
 
        return false;
    }
 
    /**
     * Create BlueSky session
     */
    private function createSession(string $identifier, string $password): ?array
    {
        $response = wp_remote_post($this->api_base . 'com.atproto.server.createSession', [
            'headers' => [
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode([
                'identifier' => $identifier,
                'password' => $password
            ]),
            'timeout' => 30
        ]);
 
        if (is_wp_error($response)) {
            throw new Exception('Failed to connect to BlueSky: ' . $response->get_error_message());
        }
 
        $body = json_decode(wp_remote_retrieve_body($response), true);
        $status_code = wp_remote_retrieve_response_code($response);
 
        if ($status_code !== 200) {
            throw new Exception('BlueSky authentication failed: ' . ($body['message'] ?? 'Unknown error'));
        }
 
        return $body;
    }
 
    /**
     * Publish a post to BlueSky
     */
    public function publishPost(array $content, ?int $user_id = null): array
    {
        try {
            // Validate content
            $errors = $this->validateContent($content);
            if (!empty($errors)) {
                return [
                    'success' => false,
                    'error' => implode(', ', $errors)
                ];
            }
 
            // Setup client for this request
            if (!$this->setupClient($user_id)) {
                return [
                    'success' => false,
                    'error' => 'Failed to authenticate with BlueSky'
                ];
            }
 
            // Check rate limiting
            if (!$this->checkRateLimit()) {
                return [
                    'success' => false,
                    'error' => 'Rate limit exceeded'
                ];
            }
 
            // Prepare post data
            $post_data = [
                'repo' => $this->did,
                'collection' => 'app.bsky.feed.post',
                'record' => [
                    'text' => $this->prepareDescription($content['description'] ?? ''),
                    'createdAt' => date('c'),
                    '$type' => 'app.bsky.feed.post'
                ]
            ];
 
            // Add link if post URL provided
            if (!empty($content['post_url'])) {
                $post_data['record']['text'] .= "\n\n" . $content['post_url'];
            }
 
            // Upload and attach image if provided
            if (!empty($content['image_path']) && file_exists($content['image_path'])) {
                $image_result = $this->uploadImage($content['image_path']);
 
                if ($image_result['success']) {
                    $post_data['record']['embed'] = [
                        '$type' => 'app.bsky.embed.images',
                        'images' => [
                            [
                                'alt' => $content['title'] ?? 'Image',
                                'image' => $image_result['blob']
                            ]
                        ]
                    ];
                }
            }
 
            // Post to BlueSky
            $response = $this->makeApiRequest('com.atproto.repo.createRecord', $post_data);
 
            if ($response['success']) {
                $this->log("Successfully posted to BlueSky", 'info');
 
                return [
                    'success' => true,
                    'platform_id' => $response['data']['uri'] ?? null,
                    'post_url' => $this->getPostUrl($response['data']['uri'] ?? ''),
                    'data' => $response['data']
                ];
            }
 
            return [
                'success' => false,
                'error' => $response['error'] ?? 'Unknown error'
            ];
 
        } catch (Exception $e) {
            $this->handleError($e);
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
 
    /**
     * Validate content before posting
     */
    protected function validateContent(array $content): array
    {
        $errors = [];
 
        // Check description length
        if (isset($content['description']) && strlen($content['description']) > $this->max_description_length) {
            $errors[] = "Description exceeds {$this->max_description_length} characters";
        }
 
        // Check image if provided
        if (isset($content['image_path']) && $content['image_path']) {
            if (!file_exists($content['image_path'])) {
                $errors[] = "Image file does not exist";
            } else {
                $mime_type = mime_content_type($content['image_path']);
                $supported_types = ['image/jpeg', 'image/png', 'image/gif'];
 
                if (!in_array($mime_type, $supported_types)) {
                    $errors[] = "Unsupported image type: {$mime_type}";
                }
 
                $file_size = filesize($content['image_path']);
                $max_size = 5242880; // 5MB
                if ($file_size > $max_size) {
                    $errors[] = "Image too large: " . round($file_size / 1048576, 2) . "MB (max: 5MB)";
                }
            }
        }
 
        return $errors;
    }
 
    /**
     * Prepare description with length limits
     */
    protected function prepareDescription(string $description): string
    {
        if (strlen($description) <= $this->max_description_length) {
            return $description;
        }
 
        // Truncate intelligently at word boundaries
        $truncated = substr($description, 0, $this->max_description_length - 3);
        $last_space = strrpos($truncated, ' ');
 
        if ($last_space !== false) {
            $truncated = substr($truncated, 0, $last_space);
        }
 
        return $truncated . '...';
    }
 
    /**
     * Upload image to BlueSky
     */
    protected function uploadImage(string $image_path): array
    {
        try {
            $mime_type = mime_content_type($image_path);
            $image_data = file_get_contents($image_path);
 
            $response = wp_remote_post($this->api_base . 'com.atproto.repo.uploadBlob', [
                'headers' => [
                    'Authorization' => 'Bearer ' . $this->access_token,
                    'Content-Type' => $mime_type,
                ],
                'body' => $image_data,
                'timeout' => 60
            ]);
 
            if (is_wp_error($response)) {
                throw new Exception('Failed to upload image: ' . $response->get_error_message());
            }
 
            $body = json_decode(wp_remote_retrieve_body($response), true);
            $status_code = wp_remote_retrieve_response_code($response);
 
            if ($status_code === 200 && isset($body['blob'])) {
                return [
                    'success' => true,
                    'blob' => $body['blob']
                ];
            }
 
            return [
                'success' => false,
                'error' => $body['message'] ?? 'Image upload failed'
            ];
 
        } catch (Exception $e) {
            return [
                'success' => false,
                'error' => $e->getMessage()
            ];
        }
    }
 
    /**
     * Make API request to BlueSky
     */
    private function makeApiRequest(string $endpoint, array $data): array
    {
        $response = wp_remote_post($this->api_base . $endpoint, [
            'headers' => [
                'Authorization' => 'Bearer ' . $this->access_token,
                'Content-Type' => 'application/json',
            ],
            'body' => json_encode($data),
            'timeout' => 30
        ]);
 
        if (is_wp_error($response)) {
            return [
                'success' => false,
                'error' => $response->get_error_message()
            ];
        }
 
        $body = json_decode(wp_remote_retrieve_body($response), true);
        $status_code = wp_remote_retrieve_response_code($response);
 
        if ($status_code === 200) {
            return [
                'success' => true,
                'data' => $body
            ];
        }
 
        return [
            'success' => false,
            'error' => $body['message'] ?? "HTTP {$status_code} error"
        ];
    }
 
    /**
     * Get post URL from BlueSky URI
     */
    private function getPostUrl(string $uri): string
    {
        if (preg_match('/at:\/\/([^\/]+)\/app\.bsky\.feed\.post\/(.+)/', $uri, $matches)) {
            $did = $matches[1];
            $rkey = $matches[2];
            return "https://bsky.app/profile/{$did}/post/{$rkey}";
        }
 
        return '';
    }
 
    /**
     * Disconnect user from this platform
     */
    public function disconnectUser(int $user_id): bool
    {
        $key = "user_{$user_id}_{$this->service_name}";
        $credentials_manager = CredentialsManager::getInstance();
        return $credentials_manager->deleteCredentials($key);
    }
 
    /**
     * Get display name for this platform
     */
    public function getDisplayName(): string
    {
        return 'BlueSky';
    }
 
    /**
     * Get icon name for this platform
     */
    public function getIconName(): string
    {
        return 'fediverse'; // Using existing fediverse icon
    }
 
    /**
     * Get supported post types
     */
    public function getSupportedPostTypes(): array
    {
        return ['text', 'image', 'link'];
    }
 
 
    public function getServiceDescription(): string
    {
        return "Cross-post content to the BlueSky social network.";
    }
 
    protected function getRequestHeaders(): array
    {
        // TODO: Implement getRequestHeaders() method.
        return [];
    }
 
    protected function getApiUrl(string $endpoint, ?string $baseUrl = null): string
    {
        return 'https://bsky.social/xrpc/';
    }
 
    protected function processIntegrationAction(string $action, array $data):\WP_Error|array
    {
        return [];
    }
}