Skip to content

Commit

Permalink
0.0.2
Browse files Browse the repository at this point in the history
  • Loading branch information
nodeloc committed Jan 21, 2024
1 parent 36cc6c0 commit 4822a36
Show file tree
Hide file tree
Showing 11 changed files with 76 additions and 68 deletions.
14 changes: 7 additions & 7 deletions extend.php
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
<?php

namespace Nodeloc\Telegram;
use Flarum\Api\Serializer\UserSerializer;
use Nodeloc\Telegram\Controllers\TelegramAuthController;
use Nodeloc\Telegram\Controllers\TelegramBotController;
use Flarum\Extend;

use Illuminate\Contracts\Events\Dispatcher;
use Illuminate\Contracts\View\Factory;
use Flarum\Notification\Event\Sending;
use Flarum\Api\Event\Serializing;
use Nodeloc\Telegram\Listeners\AddUserAttributes;

return [
(new Extend\Frontend('forum'))
->js(__DIR__.'/js/dist/forum.js')
->css(__DIR__.'/resources/less/forum.less'),
(new Extend\Locales(__DIR__ . '/resources/locale')),
(new Extend\Event)
->listen(Serializing::class, Listeners\AddUserAttributes::class)
->subscribe(Listeners\SendTelegramNotifications::class)
->subscribe(Listeners\EnableTelegramNotifications::class)
->subscribe(Listeners\InjectSettings::class),
(new Extend\ApiSerializer(UserSerializer::class))->attributes(AddUserAttributes::class),
(new Extend\Settings)
->serializeToForum('nodeloc-telegram.botUsername', 'nodeloc-telegram.botUsername', 'boolval')
->serializeToForum('nodeloc-telegram.botToken', 'nodeloc-telegram.botToken', 'boolval')
->serializeToForum('nodeloc-telegram.enableNotifications', 'nodeloc-telegram.enableNotifications', 'boolval'),
(new Extend\Frontend('admin'))
->js(__DIR__.'/js/dist/admin.js'),

(new Extend\Routes('forum'))
->get('/auth/telegram', 'auth.telegram', TelegramAuthController::class),
];
Expand Down
2 changes: 1 addition & 1 deletion js/dist/forum.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion js/dist/forum.js.map

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions js/src/forum/addLoginButton.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
import {extend} from 'flarum/extend';
import LogInButtons from 'flarum/components/LogInButtons';
import app from 'flarum/app';

export default function () {
extend(LogInButtons.prototype, 'items', function (items) {
const currentDomain = window.location.origin;
User.prototype.canReceiveTelegramNotifications = app.session.user.attribute("canReceiveTelegramNotifications");
User.prototype.nodelocTelegramError = app.session.user.attribute("nodelocTelegramError");
const authUrl = app.forum.attribute('baseUrl') + '/auth/telegram';
// Replace the Telegram widget script
items.add('nodeloc-telegram',
m('script', { async: true, src: 'https://telegram.org/js/telegram-widget.js?22',
'data-telegram-login': 'nodeloc_bot',
'data-size': 'large',
'data-radius': '10',
'data-auth-url': currentDomain + '/auth/telegram',
'data-auth-url': authUrl,
'data-request-access': 'write' })
);
});
Expand Down
5 changes: 1 addition & 4 deletions js/src/forum/addNotificationMethod.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,10 @@ export default function () {
if (!app.forum.attribute('nodeloc-telegram.enableNotifications')) {
return;
}

let user = app.session.user;
if (!user || !user.canReceiveTelegramNotifications()) {
return;
}

// Add telegram notifications method column
items.add('telegram', {
name: 'telegram',
Expand All @@ -26,6 +24,7 @@ export default function () {
if (!app.forum.attribute('nodeloc-telegram.enableNotifications')) {
return;
}

let user = app.session.user;
if (user && !user.canReceiveTelegramNotifications()) {
// add button to link current account with telegram
Expand All @@ -47,12 +46,10 @@ export default function () {
if (!app.forum.attribute('nodeloc-telegram.enableNotifications')) {
return;
}

let user = app.session.user;
if (!user || !user.nodelocTelegramError()) {
return;
}

const botUsername = app.forum.attribute('nodeloc-telegram.botUsername');

items.add('nodelocTelegramError', {
Expand Down
38 changes: 17 additions & 21 deletions src/Controllers/TelegramAuthController.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,9 @@
use Flarum\Settings\SettingsRepositoryInterface;
use Psr\Http\Message\ServerRequestInterface as Request;
use Exception;
use Flarum\Http\Response as FlarumResponse;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\Http\Message\ResponseInterface;
use GuzzleHttp\Client;
use Laminas\Diactoros\Response\HtmlResponse;
use Flarum\User\LoginProvider;

class TelegramAuthController implements RequestHandlerInterface
Expand All @@ -32,53 +31,50 @@ public function __construct(ResponseFactory $authResponse, SettingsRepositoryInt
if (!$token) {
throw new Exception('No bot token configured for Telegram');
}

$this->client = new Client([
'base_uri' => 'https://api.telegram.org/bot' . $token . '/',
]);
}

public function handle(Request $request): ResponseInterface
{
$provider = 'telegram';
$auth = $request->getQueryParams();

try {
$auth = checkTelegramAuthorization($_GET);

$auth = $this->checkTelegramAuthorization($_GET);
$user = $request->getAttribute('actor');

if ($user && $user->id) {
$identifier = array_get($auth, 'id');
// var_dump($this->checkTelegramId($identifier));exit(1);
$identifier = $auth['id'] ?? null;

if ($this->checkTelegramId($provider, $identifier)) {
$content = '<div style="text-align:center;font-family:Arial;">You can\'t link this telegram account to this user.</div>';
return new HtmlResponse($content);
}

$user->loginProviders()->create(compact('provider', 'identifier'));
$content = '<script>window.close();window.opener.document.location.reload(true);</script>';
$content = '<script>window.opener.document.location.reload(true);</script>';

return new HtmlResponse($content);
}

$suggestions = [];
if (array_get($auth, 'username')) $suggestions['username'] = array_get($auth, 'username');
if (array_get($auth, 'photo_url')) $suggestions['avatarUrl'] = array_get($auth, 'photo_url');
if ($auth['username']) $suggestions['username'] = $auth['username'];
if ($auth['photo_url']) $suggestions['avatar_url'] = $auth['photo_url'];


return $this->authResponse->make(
$provider, array_get($auth, 'id'),
function (Registration $registration) use ($suggestions) {
if ($suggestions['username']) {
$registration->suggestUsername($suggestions['username']);
}
$provider, $auth['id'], function (Registration $registration) use ($suggestions) {
// 设置 Telegram 提供的信息
$registration->provide('username', $suggestions['username']);
$registration->provide('avatar_url', $suggestions['avatar_url']);
$registration->setPayload($suggestions);
}
}
);
} catch (Exception $e) {
die ($e->getMessage());
// 在异常情况下返回错误响应
return new HtmlResponse('Error: ' . $e->getMessage(), 500);
}
}


protected function checkTelegramId($provider, $identifier)
{
$provider = LoginProvider::where(compact('provider', 'identifier'))->first();
Expand Down
24 changes: 12 additions & 12 deletions src/Listeners/AddUserAttributes.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,34 +2,34 @@

namespace Nodeloc\Telegram\Listeners;

use Flarum\Api\Serializer\CurrentUserSerializer;
use Flarum\Api\Event\Serializing;
use Flarum\Api\Serializer\UserSerializer;
use Flarum\Settings\SettingsRepositoryInterface;
use Flarum\User\LoginProvider;
use Flarum\User\User;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Events\Dispatcher;

class AddUserAttributes
{
protected $settings;
protected $events;

public function __construct(SettingsRepositoryInterface $settings)
public function __construct(SettingsRepositoryInterface $settings, Dispatcher $events)
{
$this->settings = $settings;
$this->events = $events;
}
public function handle($event)

public function __invoke(UserSerializer $serializer, User $user)
{
if ($event->isSerializer(CurrentUserSerializer::class)) {
// $event->attributes['canReceiveTelegramNotifications'] = !is_null($event->model->attributes->flagrow_telegram_id);
$event->attributes['canReceiveTelegramNotifications'] = !is_null($this->getTelegramId($event->model));
$event->attributes['nodelocTelegramError'] = $event->model->flagrow_telegram_error;
}
$attributes['canReceiveTelegramNotifications'] = !is_null($this->getTelegramId($user));
$attributes['nodelocTelegramError'] = $user->flagrow_telegram_error;
return $attributes;
}

/**
* @param User $actor
* @return int
*/
protected function getTelegramId($actor)
protected function getTelegramId(User $actor)
{
$query = LoginProvider::where('user_id', '=', $actor->id);

Expand Down
2 changes: 1 addition & 1 deletion src/Listeners/EnableTelegramNotifications.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public function __construct(SettingsRepositoryInterface $settings)
$this->settings = $settings;
}

public function subscribe($events)
public function subscribe(Dispatcher $events)
{
$events->listen(ConfigureNotificationTypes::class, [$this, 'configure']);
}
Expand Down
1 change: 0 additions & 1 deletion src/Listeners/InjectSettings.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
use Flarum\Api\Serializer\ForumSerializer;
use Flarum\Api\Event\Serializing;
use Flarum\Settings\SettingsRepositoryInterface;
use Illuminate\Contracts\Events\Dispatcher;

class InjectSettings
{
Expand Down
43 changes: 27 additions & 16 deletions src/Listeners/SendTelegramNotifications.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

namespace Nodeloc\Telegram\Listeners;

use Flarum\Notification\Driver\NotificationDriverInterface;
use Illuminate\Contracts\Queue\Queue;
use Nodeloc\Telegram\Notifications\TelegramMailer;
use Flarum\Notification\Blueprint\BlueprintInterface;
use Flarum\User\User;
Expand All @@ -10,35 +12,38 @@
use Flarum\User\LoginProvider;
use Flarum\Settings\SettingsRepositoryInterface;

class SendTelegramNotifications
class SendTelegramNotifications implements NotificationDriverInterface
{
protected $settings;
/**
* @var Queue
*/
protected $queue;

public function __construct(SettingsRepositoryInterface $settings)
public function __construct(Queue $queue)
{
$this->settings = $settings;
$this->queue = $queue;
}

public function subscribe($events)
{
$events->listen(Sending::class, [$this, 'send']);
}

public function send($event)
/**
* {@inheritDoc}
* @throws \Exception
*/
public function send(BlueprintInterface $blueprint, array $users): void
{
/**
* @var $mailer TelegramMailer
*/
$mailer = app(TelegramMailer::class);
// var_dump(json_encode($event));
foreach ($event->users as $user) {
$telegram_id = $this->shouldSendTelegramToUser($event->blueprint, $user);
if ($telegram_id) {
$mailer->send($event->blueprint, $user, $telegram_id);
}
// The `send` method is responsible for determining any notifications need to be sent.
// If not (for example, if there are no users to send to), there's no point in scheduling a job.
// We HIGHLY recommend that notifications are sent via a queue job for performance reasons.
if (count($users)) {
$this->queue->push(new TelegramMailer($blueprint, $users));
}
// exit(1);
}


protected function shouldSendTelegramToUser($blueprint, $user)
{
if (!$user->getPreference(User::getNotificationPreferenceKey($blueprint::getType(), 'telegram'))) {
Expand All @@ -54,4 +59,10 @@ protected function getTelegramId($actor)
// var_dump(json_encode($actor->username));
return $provider->identifier;
}

public function registerType(string $blueprintClass, array $driversEnabledByDefault): void
{
var_dump($driversEnabledByDefault);
app('flarum.notification.types')->addType($blueprintClass, $driversEnabledByDefault);
}
}
6 changes: 4 additions & 2 deletions src/Notifications/TelegramMailer.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use Illuminate\Contracts\View\Factory;

use Flarum\Notification\Driver\NotificationDriverInterface;
class TelegramMailer
{
protected $client;
Expand All @@ -31,8 +31,9 @@ public function __construct(SettingsRepositoryInterface $settings, Factory $view
$this->views = $views;
}

public function send(BlueprintInterface $blueprint, User $user, $telegram_id)
public function send(BlueprintInterface $blueprint, array $user): void
{
$telegram_id ="";
if ($blueprint instanceof MailableInterface) {
$view = $this->pickBestView($blueprint->getEmailView());

Expand Down Expand Up @@ -112,4 +113,5 @@ protected function pickBestView($view)

throw new Exception('No view found for that mailable');
}

}

0 comments on commit 4822a36

Please sign in to comment.