mastodon_vk_reposter/bin/server.dart

71 lines
2.4 KiB
Dart
Raw Normal View History

2022-04-21 05:59:37 +00:00
import 'dart:convert';
import 'dart:io';
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/shelf_router.dart';
// Load confirmation token from env
final confirmationToken = Platform.environment['CONFIRMATION_TOKEN'];
// Load secret key from env
final secretKey = Platform.environment['SECRET_KEY'];
// Configure routes.
final _router = Router()
..get('/', _rootHandler)
..post('/vk', _vkHandler);
Response _rootHandler(Request req) {
return Response.ok('Hello, World!\n');
}
Future<Response> _vkHandler(Request req) async {
// POST request should contain a JSON body.
// JSON must contain a 'type' field.
// The value of the 'type' field must be one of the following:
// 'confirmation'
// 'wall_post_new'
// If we recieve a 'confirmation' request, we should respond with a confirmationToken.
// If we recieve a 'wall_post_new' request, we should validate if 'secret' field equals
// secretKey and respond with an 'ok' string, printing request in the console.
final requestBody = await req.readAsString();
final requestJson = json.decode(requestBody);
final requestType = requestJson['type'];
if (requestType == 'confirmation') {
return Response.ok(confirmationToken);
} else if (requestType == 'wall_post_new') {
if (requestJson['secret'] == secretKey) {
print(requestBody);
return Response.ok('ok');
} else {
return Response.ok('invalid secret');
}
} else {
return Response.ok('invalid request type');
}
}
// Future<void> _postOnMastodon(reqJson) async {
// // Called to repost the post on Mastodon on vk.
// // reqJson contains the 'object' field of the VK post.
// // This object has the 'text' field with the post text.
// // Also it contains the 'attachments' field with the attachments.
// // The attachments field is an array of objects.
// }
void main(List<String> args) async {
// Use any available host or container IP (usually `0.0.0.0`).
final ip = InternetAddress.anyIPv4;
// Configure a pipeline that logs requests.
final _handler = Pipeline().addMiddleware(logRequests()).addHandler(_router);
// For running in containers, we respect the PORT environment variable.
final port = int.parse(Platform.environment['PORT'] ?? '8080');
final server = await serve(_handler, ip, port);
print('Server listening on port ${server.port}');
}