Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
wheremyfiji committed Apr 17, 2023
1 parent 7e921d6 commit 896180e
Show file tree
Hide file tree
Showing 9 changed files with 15 additions and 128 deletions.
14 changes: 0 additions & 14 deletions lib/src/constants/config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,10 @@ class AppConfig {
static const int databaseVersion = 1;
static const String databaseVersionKey = "isarVersionKey";

/// keys
static const Duration maxCacheAge = Duration(minutes: 5); //30

static const String dioCacheForceRefreshKey = 'dio_cache_force_refresh_key';
static const String dioNeedToCacheKey = 'dio_need_to_cache_key';
// Theme key to store and retrieve user preferred theme
static const String themeModeKey = "theme";
// Appcolor key to store and retrieve user preferred appcolor
static const String appColorKey = "appColor";

/// API url
static const String baseUrl = 'https://shikimori.me/api/';
static const String staticUrl = 'https://shikimori.me';
//final kStaticUrl = Uri.parse('https://shikimori.one');

// static const String trendingUrl = "trending";
// static const String popularUrl = "popular";
// static const String searchUrl = "advanced-search";
// static const String infoUrl = "info";
// static const String watchUrl = "watch";
}
4 changes: 0 additions & 4 deletions lib/src/constants/hive_keys.dart
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,3 @@ const String dynamicThemeKey = 'key_dynamic_color';
const String oledModeKey = 'key_oled_mode';

const String playerDiscordRpc = 'key_player_discord_rpc';

const String userNameKey = 'user_name_key';
const String userIntroKey = 'user_intro_key';
const String userImageKey = 'user_image_key';
7 changes: 0 additions & 7 deletions lib/src/presentation/widgets/app_theme_builder.dart
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,5 @@ class AppThemeBuilder extends ConsumerWidget {
);
},
);
// final appTheme = ref.watch(appThemeDataProvider);
// return DynamicColorBuilder(
// builder: (light, dark) => builder(
// context,
// appTheme.fillWith(light: light, dark: dark, useMonet: true),
// ),
// );
}
}
3 changes: 0 additions & 3 deletions lib/src/services/anime_database/anime_database_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ class LocalAnimeDatabaseImpl implements LocalAnimeDatabaseRepo {
LocalAnimeDatabaseImpl(this.isardb);

static Future<LocalAnimeDatabaseImpl> initialization() async {
//final appDocDir = await path_prov.getApplicationDocumentsDirectory();
final appDocDir = await path_prov.getApplicationSupportDirectory();
return LocalAnimeDatabaseImpl(
await Isar.open(
Expand All @@ -33,8 +32,6 @@ class LocalAnimeDatabaseImpl implements LocalAnimeDatabaseRepo {

@override
Stream<List<AnimeDatabase>> getLocalAnimes() {
// Query<AnimeDatabase> animeList =
// isardb.animeDatabases.where(sort: Sort.asc).build();
Query<AnimeDatabase> animeList =
isardb.animeDatabases.where().sortByLastUpdateDesc().build();
return animeList.watch(fireImmediately: true);
Expand Down
30 changes: 0 additions & 30 deletions lib/src/services/http/dio_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,6 @@ class DioHttpService implements HttpService {
// },
// ));
// }
//dio.interceptors.add(DioNetworkLogger());
dio.interceptors.add(RetryInterceptor(
dio: dio,
logPrint: log,
Expand All @@ -60,7 +59,6 @@ class DioHttpService implements HttpService {
],
));

//dio.interceptors.add(CustomInterceptors());
dio.interceptors.add(CacheInterceptor(storageService));
dio.interceptors.add(RefreshTokenInterceptor(dio));
dio.interceptors.add(RequestInterceptors(dio));
Expand All @@ -84,15 +82,10 @@ class DioHttpService implements HttpService {
//dio.addSentry();
}

/// Storage service used for caching http responses
final CacheStorageRepo storageService;

/// The Dio Http client
late final Dio dio;

/// The Dio base options
BaseOptions get baseOptions => BaseOptions(
//receiveDataWhenStatusError: true,
baseUrl: baseUrl,
headers: headers,
connectTimeout: const Duration(seconds: 12),
Expand All @@ -104,19 +97,13 @@ class DioHttpService implements HttpService {
@override
String get baseUrl => AppConfig.baseUrl;

// Default headers
@override
Map<String, String> headers = {
//'User-Agent': 'Shikimori Flutter App',
//'User-Agent': 'Shikimori Flutter Windows App',
'User-Agent': TargetP.instance.userAgent,
//'accept': 'application/json',
//'content-type': 'application/json'
};

/// GET method
@override
// Future<Map<String, dynamic>> get(String endpoint,
Future<dynamic> get(String endpoint,
{Map<String, dynamic>? queryParameters,
Options? options,
Expand All @@ -130,11 +117,6 @@ class DioHttpService implements HttpService {
endpoint,
queryParameters: queryParameters,
options: options,
// options: Options(
// headers: {
// 'Authorization': 'Bearer $token',
// },
// ),
cancelToken: cancelToken,
);
return response.data;
Expand Down Expand Up @@ -217,18 +199,6 @@ class DioHttpService implements HttpService {
.delete(endpoint, options: options)
.then((value) => value.statusCode?.clamp(200, 299) == value.statusCode)
.onError((_, __) => false);
// try {
// var response = await dio.delete(
// endpoint,
// data: data,
// queryParameters: queryParameters,
// options: options,
// cancelToken: cancelToken,
// );
// return response.data;
// } catch (e) {
// rethrow;
// }
}
}

Expand Down
24 changes: 12 additions & 12 deletions lib/src/services/http/interceptors/cache_interceptor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -60,20 +60,20 @@ class CacheInterceptor implements Interceptor {
);

if (options.extra[AppConfig.dioNeedToCacheKey] == false) {
log('(onRequest) Does not need caching', name: 'CacheInterceptor');
//log('(onRequest) Does not need caching', name: 'CacheInterceptor');
if (cacheStorageService.has(storageKey)) {
log('(onRequest) Delete responce from caching',
name: 'CacheInterceptor');
// log('(onRequest) Delete responce from caching',
// name: 'CacheInterceptor');
cacheStorageService.remove(storageKey);
}
return handler.next(options);
}

if (options.extra[AppConfig.dioCacheForceRefreshKey] == true) {
log('(onRequest) Cache Force Refresh', name: 'CacheInterceptor');
//log('(onRequest) Cache Force Refresh', name: 'CacheInterceptor');
if (cacheStorageService.has(storageKey)) {
log('(onRequest) Delete responce from caching',
name: 'CacheInterceptor');
// log('(onRequest) Delete responce from caching',
// name: 'CacheInterceptor');
cacheStorageService.remove(storageKey);
}
return handler.next(options);
Expand All @@ -82,7 +82,7 @@ class CacheInterceptor implements Interceptor {
if (cacheStorageService.has(storageKey)) {
final cachedResponse = _getCachedResponse(storageKey);
if (cachedResponse != null) {
log('(onRequest) Get response from cache', name: 'CacheInterceptor');
//log('(onRequest) Get response from cache', name: 'CacheInterceptor');
final response = cachedResponse.buildResponse(options);
return handler.resolve(response);
}
Expand Down Expand Up @@ -118,7 +118,7 @@ class CacheInterceptor implements Interceptor {
ResponseInterceptorHandler handler,
) {
if (response.requestOptions.extra[AppConfig.dioNeedToCacheKey] == false) {
log('(onResponse) Does not need caching', name: 'CacheInterceptor');
//log('(onResponse) Does not need caching', name: 'CacheInterceptor');
return handler.next(response);
}

Expand All @@ -131,7 +131,7 @@ class CacheInterceptor implements Interceptor {

if (response.requestOptions.extra[AppConfig.dioCacheForceRefreshKey] ==
true) {
log('(onResponse) Cache Force Refresh', name: 'CacheInterceptor');
//log('(onResponse) Cache Force Refresh', name: 'CacheInterceptor');
return handler.next(response);
}

Expand All @@ -144,7 +144,7 @@ class CacheInterceptor implements Interceptor {
age: DateTime.now(),
statusCode: response.statusCode!,
);
log('Save response to cache', name: 'CacheInterceptor');
//log('Save response to cache', name: 'CacheInterceptor');
cacheStorageService.set(storageKey, cachedResponse.toJson());
}
return handler.next(response);
Expand All @@ -159,12 +159,12 @@ class CacheInterceptor implements Interceptor {
if (cachedResponse.isValid) {
return cachedResponse;
} else {
log('Cache is outdated, deleting it...', name: 'CacheInterceptor');
//log('Cache is outdated, deleting it...', name: 'CacheInterceptor');
cacheStorageService.remove(storageKey);
return null;
}
} catch (e) {
log('Error retrieving response from cache', name: 'CacheInterceptor');
//log('Error retrieving response from cache', name: 'CacheInterceptor');
log('e: $e');
return null;
}
Expand Down
28 changes: 2 additions & 26 deletions lib/src/services/http/interceptors/refresh_token_interceptor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ class RefreshTokenInterceptor extends Interceptor {
return handler.next(err);
}
if (err.response!.statusCode == 401) {
log('RefreshTokenInterceptor:: statusCode == 401');
//log('RefreshTokenInterceptor:: statusCode == 401');
var res = await refreshToken();
if (res != null) {
await _retry(err.requestOptions, res);
Expand All @@ -29,49 +29,25 @@ class RefreshTokenInterceptor extends Interceptor {
GoRouter.of(ctx!).go('/login');
}
}
//super.onError(err, handler);
return handler.next(err);
}

/// Api to get new token from refresh token
///
Future<String?> refreshToken() async {
log('RefreshTokenInterceptor:: refreshToken');
//log('RefreshTokenInterceptor:: refreshToken');

///call your refesh token api here
final token = await OAuthService.instance.refreshToken();

return token;

// if (await OAuthService.instance.refreshToken()) {
// return true;
// }
// return null;
}

/// For retrying request with new token
///
Future<Response<dynamic>> _retry(
RequestOptions requestOptions, String newToken) async {
log('RefreshTokenInterceptor:: _retry');
// final options = Options(
// method: requestOptions.method,
// headers: requestOptions.headers,
// );

// final options = requestOptions.copyWith(
// headers: {
// 'User-Agent': 'Shikimori Flutter App',
// 'Authorization': 'Bearer $newToken',
// },
// );

final options = Options(
method: requestOptions.method,
responseType: requestOptions.responseType,
headers: {
//'User-Agent': 'Shikimori Flutter App',
//'User-Agent': 'Shikimori Flutter Windows App',
'User-Agent': TargetP.instance.userAgent,
'Authorization': 'Bearer $newToken',
},
Expand Down
24 changes: 1 addition & 23 deletions lib/src/services/http/interceptors/request_interceptor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -12,34 +12,15 @@ class RequestInterceptors extends Interceptor {
void onRequest(
RequestOptions options, RequestInterceptorHandler handler) async {
ConnectivityResult connectivity = await Connectivity().checkConnectivity();
if (connectivity == ConnectivityResult.none
//&&
// options.extra[AppConfig.dioNeedToCacheKey] == false
) {
if (connectivity == ConnectivityResult.none) {
handler.reject(
NoInternetConnectionException(options),
// DioError(
// requestOptions: options,
// message: 'No internet connection detected',
// type: DioErrorType.connectionError),
);
return;
//throw NoInternetConnectionException(options);
}
super.onRequest(options, handler);
//return handler.next(options);
}

// @override
// void onResponse(
// Response<dynamic> response,
// ResponseInterceptorHandler handler,
// ) {
// final code = response.statusCode;
// log('::onResponse -> code: $code');
// return handler.next(response);
// }

@override
void onError(DioError err, ErrorInterceptorHandler handler) {
switch (err.type) {
Expand Down Expand Up @@ -85,7 +66,6 @@ class BadResponceErrorException extends DioError {

@override
String toString() {
// return 'Host or unknown error';
return 'Код ошибки 422 (Bad Responce)';
}
}
Expand All @@ -95,7 +75,6 @@ class UnknownErrorException extends DioError {

@override
String toString() {
// return 'Host or unknown error';
return 'Скорее всего Shikimori недоступен, попробуй позже';
}
}
Expand Down Expand Up @@ -141,7 +120,6 @@ class NotFoundException extends DioError {

@override
String toString() {
// return 'The requested information could not be found bebra';
return 'Ошибка 404. Ничего не найдено';
}
}
Expand Down
9 changes: 0 additions & 9 deletions lib/src/services/oauth/oauth_service.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,7 @@ import '../secure_storage/secure_storage_service.dart';
class OAuthService {
static OAuthService instance = OAuthService();

// String userAgent = TargetP.instance.isDesktop
// ? 'Shikimori Flutter Windows App'
// : 'Shikimori Flutter App';

Map<String, String> headers = {
//'User-Agent': 'Shikimori Flutter App',
'User-Agent': TargetP.instance.isDesktop
? 'Shikimori Flutter Windows App'
: 'Shikimori Flutter App',
Expand Down Expand Up @@ -72,8 +67,6 @@ class OAuthService {
'/oauth/token',
{
'grant_type': 'refresh_token',
// 'client_id': kShikiClientId,
// 'client_secret': kShikiClientSecret,
'client_id': TargetP.instance.isDesktop
? kShikiClientIdDesktop
: kShikiClientId,
Expand Down Expand Up @@ -116,8 +109,6 @@ class OAuthService {
final Uri userUrl = Uri.https('shikimori.me', 'api/users/whoami');

final Map<String, String> headers = {
//'User-Agent': 'Shikimori Flutter App',
//'User-Agent': 'Shikimori Flutter Windows App',
'User-Agent': TargetP.instance.isDesktop
? 'Shikimori Flutter Windows App'
: 'Shikimori Flutter App',
Expand Down

0 comments on commit 896180e

Please sign in to comment.