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