friendship ended with social-app. php is my new best friend
1<?php
2error_reporting(E_ALL);
3ini_set('display_errors', 'On');
4ini_set('log_errors_max_len', '0');
5
6require_once('vendor/autoload.php');
7require_once('config.php');
8require_once('lib/bskyToucher.php');
9require_once('lib/bskyProvider.php');
10
11use flight\Engine;
12use League\CommonMark\CommonMarkConverter;
13use React\Promise\Deferred;
14use React\EventLoop\Loop;
15use React\Promise\Promise;
16use GuzzleHttp\Client;
17use Tracy\Debugger;
18use Tracy\OutputDebugger;
19use Matrix\Async;
20use GuzzleHttp\Psr7\HttpFactory;
21use chillerlan\OAuth\OAuthOptions;
22use DateTimeImmutable;
23use Lcobucci\JWT\Token\Builder;
24use Lcobucci\JWT\Encoding\ChainedFormatter;
25use Lcobucci\JWT\Encoding\JoseEncoder;
26use Lcobucci\JWT\Signer\Key\InMemory;
27use Lcobucci\JWT\Signer\Ecdsa\Sha256;
28use Smallnest\Bsky\BskyProvider;
29
30$bskyToucher = new BskyToucher();
31
32$favoriteFeeds = array_map(function ($feed) use ($bskyToucher) {
33 return $bskyToucher->getFeedInfo($feed);
34}, FAVORITE_FEEDS);
35
36function getPostOgImage(object $post): ?string {
37 if (!property_exists($post, 'embedType') || !$post->embedType) return null;
38
39 if ($post->embedType === 'app.bsky.embed.images') {
40 return $post->embeds[0]->imgUrl;
41 } else if ($post->embedType === 'app.bsky.embed.external' || $post->embedType === 'app.bsky.embed.video') {
42 return $post->embeds[0]->thumb;
43 } else if ($post->embedType === 'app.bsky.embed.record') {
44 return getPostOgImage($post->embeds[0]->post);
45 }
46 return null;
47}
48
49/*Debugger::enable();
50// This where errors and exceptions will be logged. Make sure this directory exists and is writable.
51Debugger::$logDirectory = __DIR__ . '/../log/';
52//Debugger::$strictMode = true; // display all errors
53// Debugger::$strictMode = E_ALL & ~E_DEPRECATED & ~E_USER_DEPRECATED; // all errors except deprecated notices
54if (Debugger::$showBar) {
55 // This is specific to the Tracy Extension for Flight if you've included that
56 // otherwise comment this out.
57 //new TracyExtensionLoader($app);
58}*/
59
60Flight::set('frontpageFeed', FRONTPAGE_FEED);
61Flight::set('slingshotInstance', SLINGSHOT_INSTANCE);
62Flight::set('constellationInstance', CONSTELLATION_INSTANCE);
63Flight::set('plcDirectory', PLC_DIRECTORY);
64Flight::set('defaultPds', DEFAULT_PDS);
65Flight::set('publicApi', PUBLIC_API);
66Flight::set('frontpageFeed', FRONTPAGE_FEED);
67Flight::set('defaultRelay', DEFAULT_RELAY);
68Flight::set('userAuth', null);
69Flight::set('flight.log_errors', false);
70Flight::set('flight.handle_errors', false);
71Flight::set('flight.content_length', false);
72
73Flight::set('standardParams', [
74 'siteTitle' => SITE_TITLE,
75 'themes' => THEMES,
76 'fonts' => FONTS,
77 'setTheme' => array_key_exists('sbs_theme', $_COOKIE) ? $_COOKIE['sbs_theme'] : DEFAULT_THEME,
78 'setFont' => array_key_exists('sbs_font', $_COOKIE) ? $_COOKIE['sbs_font'] : DEFAULT_FONT,
79 'userAuth' => Flight::get('userAuth'),
80 'favFeeds' => $favoriteFeeds,
81 'pages' => PAGES,
82 'links' => LINKS,
83 'ogdomain' => 'https://'.SITE_DOMAIN
84]);
85
86Flight::route('/', function () {
87 $bskyToucher = new BskyToucher();
88 $posts = $bskyToucher->getFeed(Flight::get('frontpageFeed'));
89 $feedInfo = $bskyToucher->getFeedInfo(Flight::get('frontpageFeed'));
90 $latte = new Latte\Engine;
91 $latte->render('./templates/home.latte', array_merge(Flight::get('standardParams'), [
92 'mainClass' => 'home feed',
93 'feedInfo' => $feedInfo,
94 'posts' => array_map(function ($p) { return $p->post; }, $posts->feed),
95 'cursor' => $posts->cursor,
96 'feedAtUri' => FRONTPAGE_FEED,
97 'ogtitle' => SITE_TITLE,
98 'ogdesc' => SITE_DESC,
99 'ogimage' => '',
100 'ogurl' => 'https://'.SITE_DOMAIN.'/'
101 ]));
102});
103
104Flight::route('/u/@handle:[a-z0-9\.]+/@rkey:[a-z0-9]+', function (string $handle, string $rkey): void {
105 $bskyToucher = new BskyToucher();
106 $did = $bskyToucher->resolveHandle($handle);
107 $userInfo = $bskyToucher->getUserInfo($handle);
108 $atUri = 'at://'.$did.'/app.bsky.feed.post/'.$rkey;
109 $latte = new Latte\Engine;
110 $latte->render('./templates/single.latte', array_merge(Flight::get('standardParams'), [
111 'mainClass' => 'post',
112 'post' => $atUri,
113 'displayName' => $userInfo->displayName,
114 'handle' => $handle,
115 'ogtitle' => SITE_TITLE." | ".$userInfo->displayName." (@".$handle.")",
116 'ogdesc' => '', //$post->content,
117 'ogimage' => '', //getPostOgImage($post),
118 'ogurl' => 'https://'.SITE_DOMAIN.'/u/'.$handle.'/'.$rkey
119 ]));
120});
121
122Flight::route('/u/@handle:[a-z0-9\.]+(/@tab:[a-z]+)', function (string $handle, ?string $tab): void {
123 $bskyToucher = new BskyToucher();
124 $user = $bskyToucher->getUserInfo($handle, 'handle');
125 $posts = $bskyToucher->getUserPosts($user->did);
126 $latte = new Latte\Engine;
127 $latte->render('./templates/profile.latte', array_merge(Flight::get('standardParams'), [
128 'mainClass' => 'profile',
129 'handle' => $handle,
130 'posts' => array_map(function ($p) { return $p->uri; }, $posts->records),
131 'cursor' => $posts->cursor,
132 'user' => $user,
133 'ogtitle' => SITE_TITLE." | ".$user->displayName." (@".$user->handle.")",
134 'ogdesc' => $user->description,
135 'ogimage' => $user->avatar,
136 'ogurl' => 'https://'.SITE_DOMAIN.'/u/'.$user->handle.'/'
137 ]));
138});
139
140Flight::route('/f/@did:did:plc:[0-9a-z]+/@name:[a-z0-9\-\_]+', function (string $did, string $name): void {
141 $bskyToucher = new BskyToucher();
142 $feedUrl = "at://".$did."/app.bsky.feed.generator/".$name;
143 $feedInfo = $bskyToucher->getFeedInfo($feedUrl);
144 $creatorInfo = $bskyToucher->getUserInfo($feedInfo->creatorDid, 'did');
145 $posts = $bskyToucher->getFeed($feedUrl);
146 $latte = new Latte\Engine;
147 $latte->render('./templates/feed.latte', array_merge(Flight::get('standardParams'), [
148 'mainClass' => 'feed',
149 'posts' => array_map(function ($p) { return $p->post; }, $posts->feed),
150 'cursor' => '',
151 'feedName' => $feedInfo->title,
152 'feedAvatar' => $feedInfo->avatar,
153 'feedDescription' => $feedInfo->description,
154 'feedAtUri' => $feedUrl,
155 'feedAuthorName' => $creatorInfo->displayName,
156 'feedAuthorHandle' => $creatorInfo->handle,
157 'feedAuthorDid' => $creatorInfo->did,
158 'feedAuthorPds' => $creatorInfo->pds,
159 'ogtitle' => SITE_TITLE." | ".$feedInfo->title,
160 'ogdesc' => $feedInfo->description,
161 'ogimage' => $feedInfo->avatar,
162 'ogurl' => 'https://'.SITE_DOMAIN.'/f/'.$did.'/'.$name
163 ]));
164});
165
166Flight::route('/s', function (): void {
167 $latte = new Latte\Engine;
168 $latte->render('./templates/search.latte', array_merge(Flight::get('standardParams'), [
169 'mainClass' => 'search',
170 'params' => $_GET,
171 'ogtitle' => SITE_TITLE." | search".(array_key_exists('s', $_GET) ? ': '.$_GET['s'] : ''),
172 'ogdesc' => SITE_DESC,
173 'ogimage' => '',
174 'ogurl' => 'https://'.SITE_DOMAIN.'/u/'.$handle.'/'.$rkey
175 ]));
176});
177
178Flight::route('/login', function(): void {
179 if (!array_key_exists('username', $_GET)) {
180 $latte = new Latte\Engine;
181 $latte->render('./templates/login.latte', array_merge(Flight::get('standardParams'), [
182 'mainClass' => 'form',
183 'ogtitle' => SITE_TITLE." | login",
184 'ogdesc' => SITE_DESC,
185 'ogimage' => '',
186 'ogurl' => 'https://'.SITE_DOMAIN.'/login'
187 ]));
188 die(1);
189 }
190 $username = $_GET['username'];
191 $bskyToucher = new BskyToucher();
192 $userInfo = $bskyToucher->getUserInfo($username);
193 if (!$userInfo) die(1);
194 $pds = $userInfo->pds;
195 $options = new OAuthOptions([
196 'key' => 'https://'.SITE_DOMAIN.CLIENT_ID,
197 'secret' => CLIENT_SECRET,
198 'callbackURL' => 'http://127.0.0.1/login',
199 'sessionStart' => true,
200 ]);
201 $connector = new React\Socket\Connector([
202 'dns' => '1.1.1.1'
203 ]);
204 $http = new React\Http\Browser($connector);
205 $httpFactory = new HttpFactory();
206 $token_builder = Builder::new(new JoseEncoder(), ChainedFormatter::default());
207 $algorithm = new Sha256();
208 $signing_key = InMemory::file(CERT_PATH);
209 $now = new DateTimeImmutable();
210 $token = $token_builder
211 ->withHeader('alg', 'ES256')
212 ->withHeader('typ', 'JWT')
213 ->withHeader('kid', 'ocwgKj_O7H9at1sL6yWf9ZZ82NOM7D0xlN8HGIyWH6M')
214 ->issuedBy('https://'.SITE_DOMAIN.CLIENT_ID)
215 ->identifiedBy(uniqid())
216 ->relatedTo('https://'.SITE_DOMAIN.CLIENT_ID)
217 ->permittedFor($pds)
218 ->issuedAt($now->modify('-5 seconds'))
219 ->getToken($algorithm, $signing_key);
220 $client = new GuzzleHttp\Client([
221 'verify' => true,
222 'headers' => [
223 'User-Agent' => USER_AGENT_STR,
224 'Authorization' => 'Bearer: '.$token->toString()
225 ]
226 ]);
227 $provider = new BskyProvider($options, $client, $httpFactory, $httpFactory, $httpFactory);
228 $provider->setPds($pds);
229 $name = $provider->getName();
230
231 if (isset($_GET['login']) && $_GET['login'] === $name) {
232 $auth_url = $provider->getAuthorizationUrl([
233 'client_assertion_type' => 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',
234 'client_assertion' => $token->toString()
235 ]);
236 header('Location: '.$auth_url);
237 die(1);
238 } else if (isset($_GET['code'], $_GET['state'])) {
239 $token = $provider->getAccessToken($_GET['code'], $_GET['state']);
240
241 // save the token in a permanent storage
242 // [...]
243
244 // access granted, redirect
245 header('Location: ?granted='.$name);
246 die(1);
247 } else if (isset($_GET['granted']) && $_GET['granted'] === $name) {
248 die(1);
249 } else if (isset($_GET['error'])) {
250 die(1);
251 }
252 $latte = new Latte\Engine;
253 $latte->render('./templates/login.latte', array_merge(Flight::get('standardParams'), [
254 'mainClass' => 'form',
255 'ogtitle' => SITE_TITLE." | login",
256 'ogdesc' => SITE_DESC,
257 'ogimage' => '',
258 'ogurl' => 'https://'.SITE_DOMAIN.'/login'
259 ]));
260});
261
262// https://shimaenaga.veryroundbird.house/oauth/authorize?client_id=https%3A%2F%2Ftangled.org%2Foauth%2Fclient-metadata.json&request_uri=urn%3Aietf%3Aparams%3Aoauth%3Arequest_uri%3Areq-2399ff42af66498132ebf8de809254b7
263
264Flight::route('/createaccount', function(): void {
265 $latte = new Latte\Engine;
266 $latte->render('./templates/create.latte', array_merge(Flight::get('standardParams'), [
267 'mainClass' => 'form',
268 'ogtitle' => SITE_TITLE." | create account",
269 'ogdesc' => SITE_DESC,
270 'ogimage' => '',
271 'ogurl' => SITE_DOMAIN.'/createaccount'
272 ]));
273});
274
275Flight::route('/api/post/@did/@rkey', function (string $did, string $rkey): void {
276 $bskyToucher = new BskyToucher();
277 $ret = $bskyToucher->getPost($did, $rkey, true);
278 if ($ret) {
279 $latte = new Latte\Engine;
280 $latte->render('./templates/_partials/post.latte', array_merge(Flight::get('standardParams'), [
281 'post' => $ret
282 ]));
283 die(1);
284 }
285 Flight::json(['error' => 'malformed response or bad vibes']);
286});
287
288Flight::route('/api/likes/@did/@rkey', function (string $did, string $rkey): void {
289 $bskyToucher = new BskyToucher();
290 $ret = $bskyToucher->getLikes('at://'.$did.'/app.bsky.feed.post/'.$rkey);
291 if ($ret) {
292 $latte = new Latte\Engine;
293 $output = $latte->renderToString('./templates/_partials/interaction_list.latte', array_merge(Flight::get('standardParams'), [
294 'interactions' => $ret->records
295 ]));
296 $ret->rendered = $output;
297 Flight::json($ret);
298 }
299});
300
301Flight::route('/api/reposts/@did/@rkey', function (string $did, string $rkey): void {
302 $bskyToucher = new BskyToucher();
303 $ret = $bskyToucher->getReposts('at://'.$did.'/app.bsky.feed.post/'.$rkey);
304 if ($ret) {
305 $latte = new Latte\Engine;
306 $output = $latte->renderToString('./templates/_partials/interaction_list.latte', array_merge(Flight::get('standardParams'), [
307 'interactions' => $ret->records
308 ]));
309 $ret->rendered = $output;
310 Flight::json($ret);
311 }
312});
313
314Flight::route('/api/replies/@did/@rkey', function (string $did, string $rkey): void {
315 $bskyToucher = new BskyToucher();
316 $ret = $bskyToucher->getReplies('at://'.$did.'/app.bsky.feed.post/'.$rkey);
317 if ($ret) {
318 $latte = new Latte\Engine;
319 $output = $latte->renderToString('./templates/_partials/feedPosts.latte', array_merge(Flight::get('standardParams'), [
320 'total' => $ret->total,
321 'cursor' => $ret->cursor,
322 'posts' => array_map(function($p) { return $p->uri; }, $ret->records)
323 ]));
324 $ret->rendered = $output;
325 Flight::json($ret);
326 }
327});
328
329Flight::route('/api/quotes/@did/@rkey', function (string $did, string $rkey): void {
330 $bskyToucher = new BskyToucher();
331 $ret = $bskyToucher->getLikes('at://'.$did.'/app.bsky.feed.post/'.$rkey);
332 if ($ret) {
333 $latte = new Latte\Engine;
334 $output = $latte->renderToString('./templates/_partials/interaction_list.latte', array_merge(Flight::get('standardParams'), [
335 'interactions' => $ret->records
336 ]));
337 $ret->rendered = $output;
338 Flight::json($ret);
339 }
340});
341
342Flight::route('/api/user/@handle', function (string $handle): void {
343 $bskyToucher = new BskyToucher();
344 $ret = $bskyToucher->getUserInfo($handle);
345 if ($ret) {
346 Flight::json($ret);
347 die(1);
348 }
349 Flight::json(['error' => 'malformed response or bad vibes']);
350});
351
352Flight::route('/api/feed/@did/@rkey', function (string $did, string $rkey): void {
353 $bskyToucher = new BskyToucher();
354});
355
356Flight::route('/@page', function (string $page): void {
357 $latte = new Latte\Engine;
358 $converter = new CommonMarkConverter();
359 $md = $converter->convert(file_get_contents('./pages/'.$page.'.md'));
360 $latte->render('./templates/page.latte', array_merge(Flight::get('standardParams'), [
361 'mainClass' => 'page',
362 'content' => $md,
363 'ogtitle' => SITE_TITLE." | ".$page,
364 'ogdesc' => SITE_DESC,
365 'ogimage' => '',
366 'ogurl' => SITE_DOMAIN.'/'.$page
367 ]));
368});
369
370Flight::start();
371
372?>