Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Logger #40

Merged
merged 17 commits into from
Mar 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@ githubrepo=github_repo
youtube=youtube_token
openweather=openweather_token
conversatorkey=chatgpt_token
isproduction=0_or_1
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ doc/api/

.env
.idea
logs.txt

assets/swearwords/swearwords.*.json
!assets/swearwords/swearwords.sample.json
Expand Down
33 changes: 20 additions & 13 deletions bin/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@ import 'dart:async';
import 'package:dotenv/dotenv.dart';
import 'package:postgres/postgres.dart';
import 'package:weather/weather.dart';
import 'package:weather/src/injector/injection.dart';
import 'package:weather/src/globals/chat_platform.dart';
import 'package:weather/src/utils/migrations_manager.dart';
import 'package:weather/src/utils/logger.dart';

// TODO: move to database.dart
Future<Pool> getDatabaseConnection(DotEnv env) async {
final username = env['dbuser']!;
final password = env['dbpassword']!;
Expand All @@ -20,28 +23,34 @@ Future<void> runMigrations(Pool dbConnection) async {
await migrationsManager.runMigrations();
}

ChatPlatform getPlatform(String envPlatform) {
ChatPlatform getPlatform(String? envPlatform) {
if (envPlatform == 'telegram') return ChatPlatform.telegram;
if (envPlatform == 'discord') return ChatPlatform.discord;

throw Exception('Invalid platform $envPlatform');
}

bool getIsProductionMode(String? envIsProduction) {
return int.parse(envIsProduction ?? '0') == 1;
}

void main(List<String> args) async {
var env = DotEnv(includePlatformEnvironment: true)..load();
final dbConnection = await getDatabaseConnection(env);
// TODO: move to core config module
final token = env['bottoken']!;
final adminId = env['adminid']!;
final repoUrl = env['githubrepo']!;
final youtubeKey = env['youtube']!;
final openweatherKey = env['openweather']!;
final conversatorKey = env['conversatorkey']!;
final platformName = getPlatform(env['platform']);
final isProduction = getIsProductionMode(env['isproduction']);

setupInjection(isProduction);
await runMigrations(dbConnection);

runZonedGuarded(() {
final token = env['bottoken']!;
final adminId = env['adminid']!;
final repoUrl = env['githubrepo']!;
final youtubeKey = env['youtube']!;
final openweatherKey = env['openweather']!;
final conversatorKey = env['conversatorkey']!;
final platformName = getPlatform(env['platform']!);

Bot(
platformName: platformName,
botToken: token,
Expand All @@ -53,10 +62,8 @@ void main(List<String> args) async {
dbConnection: dbConnection,
).startBot();
}, (error, stack) {
var now = DateTime.now();
var logger = getIt<Logger>();

print('[$now]: Error caught');
print(error);
print(stack);
logger.e('Uncaught error', error);
});
}
35 changes: 13 additions & 22 deletions lib/src/core/access.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import 'package:weather/src/globals/message_event.dart';
import 'package:weather/src/globals/access_level.dart';
import 'event_bus.dart';
import 'package:weather/src/injector/injection.dart';
import 'package:weather/src/utils/logger.dart';
import 'events/access_events.dart';
import 'database.dart';
import 'event_bus.dart';

typedef OnSuccessCallback = void Function(MessageEvent event);
typedef OnFailureCallback = Future Function(MessageEvent event);
Expand All @@ -11,8 +13,9 @@ class Access {
final Database db;
final EventBus eventBus;
final String adminId;
final Logger _logger;

Access({required this.db, required this.eventBus, required this.adminId});
Access({required this.db, required this.eventBus, required this.adminId}) : _logger = getIt<Logger>();

void execute(
{required MessageEvent event,
Expand All @@ -23,31 +26,19 @@ class Access {
var user = await db.user.getSingleUserForChat(event.chatId, event.userId);

if (user == null || user.banned) {
onFailure(event);

return;
}

if (user.id == adminId) {
eventBus.fire(AccessEvent(chatId: event.chatId, user: user, command: command));
onSuccess(event);

return;
return onFailure(event);
}

if (accessLevel == AccessLevel.admin) {
onFailure(event);
var canExecuteAsAdmin = user.id == adminId;
var canExecuteAsModerator = accessLevel == AccessLevel.moderator && user.moderator;

return;
}

if (accessLevel == AccessLevel.moderator && !user.moderator) {
onFailure(event);
if (canExecuteAsAdmin || canExecuteAsModerator) {
_logger.i('Executing /$command with event: $event');
eventBus.fire(AccessEvent(chatId: event.chatId, user: user, command: command));

return;
return onSuccess(event);
}

eventBus.fire(AccessEvent(chatId: event.chatId, user: user, command: command));
onSuccess(event);
return onFailure(event);
}
}
9 changes: 6 additions & 3 deletions lib/src/core/conversator.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ import 'dart:convert';
import 'package:cron/cron.dart';
import 'package:http/http.dart' as http;
import 'package:weather/src/globals/module_exception.dart';
import 'package:weather/src/injector/injection.dart';
import 'package:weather/src/utils/logger.dart';
import 'database.dart';

const String _converstorApiURL = 'https://api.openai.com/v1/chat/completions';
Expand Down Expand Up @@ -39,11 +41,12 @@ class ConversatorUser {

class Conversator {
final Database db;
final Logger _logger;
final String conversatorApiKey;
final String adminId;
final String _apiBaseUrl = _converstorApiURL;

Conversator({required this.db, required this.conversatorApiKey, required this.adminId});
Conversator({required this.db, required this.conversatorApiKey, required this.adminId}) : _logger = getIt<Logger>();

void initialize() {
_startResetDailyInvocationsUsageJob();
Expand Down Expand Up @@ -130,9 +133,9 @@ class Conversator {
var result = await db.conversatorUser.resetDailyInvocations();

if (result == 0) {
print('Something went wrong with resetting conversator daily invocations usage');
_logger.w('Something went wrong with resetting conversator daily invocations usage');
} else {
print('Reset conversator daily invocation usage for $result rows');
_logger.i('Reset conversator daily invocation usage for $result rows');
}
});
}
Expand Down
4 changes: 3 additions & 1 deletion lib/src/core/dadjokes.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import 'dart:convert';
import 'package:http/http.dart' as http;

const _dadjokesApiBase = 'https://icanhazdadjoke.com/';

class DadJokesJoke {
final String joke;

Expand All @@ -10,7 +12,7 @@ class DadJokesJoke {
}

class DadJokes {
final String _apiBaseUrl = 'https://icanhazdadjoke.com/';
final String _apiBaseUrl = _dadjokesApiBase;

Future<DadJokesJoke> getJoke() async {
var response = await http.get(Uri.parse(_apiBaseUrl), headers: {'Accept': 'application/json'});
Expand Down
4 changes: 3 additions & 1 deletion lib/src/core/general.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import 'dart:convert';
import 'package:http/http.dart' as http;
import 'chat.dart';

const _githubApiBase = 'https://api.github.com';

class General {
final Chat chat;
final String repositoryUrl;
final String _baseGithubApiUrl = 'https://api.github.com';
final String _baseGithubApiUrl = _githubApiBase;

General({required this.chat, required this.repositoryUrl});

Expand Down
12 changes: 7 additions & 5 deletions lib/src/core/repositories/repository.dart
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import 'dart:io';
import 'package:meta/meta.dart';
import 'package:postgres/postgres.dart';
import 'package:weather/src/injector/injection.dart';
import 'package:weather/src/utils/logger.dart';

const String _pathToQueries = 'assets/db/queries';

class Repository {
final String repositoryName;
final Pool dbConnection;
final Logger _logger;
final String _queriesDirectory = _pathToQueries;

@protected
final Map<String, String> queriesMap = {};

Repository({required this.repositoryName, required this.dbConnection});
Repository({required this.repositoryName, required this.dbConnection}) : _logger = getIt<Logger>();

initRepository() async {
var queriesLocation = Directory('$_queriesDirectory/$repositoryName');
Expand All @@ -30,7 +33,7 @@ class Repository {
@protected
Future<Result?> executeQuery(String? query, [Map<String, dynamic>? parameters]) async {
if (query == null) {
print('Wrong query $query');
_logger.e('Wrong query: $query');

return null;
}
Expand All @@ -41,7 +44,7 @@ class Repository {
@protected
Future<int> executeTransaction(String? query, [Map<String, dynamic>? parameters]) async {
if (query == null) {
print('Wrong query $query');
_logger.e('Wrong query: $query');

return 0;
}
Expand All @@ -51,8 +54,7 @@ class Repository {

return queryResult.affectedRows;
}).catchError((error) {
print('DB transaction error');
print(error);
_logger.e('DB transaction error: $error');

return 0;
});
Expand Down
6 changes: 0 additions & 6 deletions lib/src/core/repositories/reputation_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,6 @@ class ReputationRepository extends Repository {
return null;
}

if (data.length != 1) {
print('One piece of reputation data data was expected, got ${data.length} instead');

return null;
}

var reputationData = data[0].toColumnMap();

return SingleReputationData(
Expand Down
6 changes: 0 additions & 6 deletions lib/src/core/repositories/weather_repository.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,6 @@ class WeatherRepository extends Repository {
return [];
}

if (data.length != 1) {
print('One piece of cities data was expected, got ${data.length} instead');

return null;
}

var citiesData = data[0].toColumnMap();

return citiesData['cities']?.split(',');
Expand Down
9 changes: 6 additions & 3 deletions lib/src/core/reputation.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import 'dart:async';
import 'package:cron/cron.dart';
import 'package:weather/src/globals/module_exception.dart';
import 'package:weather/src/injector/injection.dart';
import 'package:weather/src/utils/logger.dart';
import 'events/accordion_poll_events.dart';
import 'database.dart';
import 'event_bus.dart';
Expand Down Expand Up @@ -32,8 +34,9 @@ class ChatReputationData {
class Reputation {
final Database db;
final EventBus eventBus;
final Logger _logger;

Reputation({required this.db, required this.eventBus});
Reputation({required this.db, required this.eventBus}) : _logger = getIt<Logger>();

void initialize() {
_startResetVotesJob();
Expand Down Expand Up @@ -137,9 +140,9 @@ class Reputation {
var result = await db.reputation.resetChangeOptions(numberOfVoteOptions);

if (result == 0) {
print('Something went wrong with resetting reputation change options');
_logger.w('Something went wrong with resetting reputation change options');
} else {
print('Reset reputation change options for $result rows');
_logger.i('Reset reputation change options for $result rows');
}
});
}
Expand Down
33 changes: 9 additions & 24 deletions lib/src/core/weather.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import 'package:http/http.dart' as http;
import 'package:cron/cron.dart';
import 'database.dart';

const _weatherApiBase = 'https://api.openweathermap.org/data/2.5';

class OpenWeatherData {
final String city;
final num temp;
Expand All @@ -28,7 +30,7 @@ class ChatNotificationHour {
class Weather {
final Database db;
final String openweatherKey;
final String _apiBaseUrl = 'https://api.openweathermap.org/data/2.5';
final String _apiBaseUrl = _weatherApiBase;

late StreamController<ChatWeatherData> _weatherStreamController;
List<ScheduledTask> _weatherCronTasks = [];
Expand Down Expand Up @@ -83,15 +85,7 @@ class Weather {
}

Future<num?> getWeatherForCity(String city) async {
try {
var weatherData = await _getCurrentWeather(city);

return weatherData.temp;
} catch (err) {
print(err);

return null;
}
return _getCurrentWeather(city).then((weatherData) => weatherData.temp);
}

Future<bool> setNotificationHour(String chatId, int notificationHour) async {
Expand All @@ -107,21 +101,12 @@ class Weather {
}

Future<List<OpenWeatherData>> getWeatherForCities(List<String> cities) async {
List<OpenWeatherData> result = [];

await Future.forEach(cities, (city) async {
try {
var weather = await _getCurrentWeather(city);

result.add(OpenWeatherData(weather.city, weather.temp));

await Future.delayed(Duration(milliseconds: 500));
} catch (err) {
print("Can't get weather for city $city");
}
});
return Future.wait(cities.map((city) async {
var weather = await _getCurrentWeather(city);
await Future.delayed(Duration(milliseconds: 500));

return result;
return OpenWeatherData(weather.city, weather.temp);
}));
}

Future<OpenWeatherData> _getCurrentWeather(String city) async {
Expand Down
Loading