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

Migrate to dio5.0 #66

Merged
merged 24 commits into from
Apr 18, 2023
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 base/.pubignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
pubspec.lock
8 changes: 8 additions & 0 deletions base/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,11 @@
## 0.5.0

* upgrade dio to 5.0.0

## 0.4.1

- fix package file name

## 0.4.0

- 新增 putBytes 接口用于上传 Uint8List 类型的资源
Expand Down
84 changes: 6 additions & 78 deletions base/analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
# copy from https://github.com/dart-lang/http/blob/master/analysis_options.yaml

include: package:pedantic/analysis_options.yaml
include: package:lints/recommended.yaml

analyzer:
# enable-experiment:
Expand All @@ -12,78 +10,8 @@ analyzer:

linter:
rules:
- annotate_overrides
- avoid_bool_literals_in_conditional_expressions
- avoid_classes_with_only_static_members
- avoid_empty_else
- avoid_function_literals_in_foreach_calls
- avoid_init_to_null
- avoid_null_checks_in_equality_operators
- avoid_relative_lib_imports
- avoid_renaming_method_parameters
- avoid_return_types_on_setters
- avoid_returning_null_for_void
- avoid_returning_this
- avoid_shadowing_type_parameters
- avoid_single_cascade_in_expression_statements
- avoid_types_as_parameter_names
- avoid_unused_constructor_parameters
- await_only_futures
- camel_case_types
- cascade_invocations
# comment_references
- control_flow_in_finally
- curly_braces_in_flow_control_structures
- directives_ordering
- empty_catches
- empty_constructor_bodies
- empty_statements
- file_names
- hash_and_equals
- iterable_contains_unrelated_type
- library_names
- library_prefixes
- list_remove_unrelated_type
- no_adjacent_strings_in_list
- no_duplicate_case_values
- non_constant_identifier_names
- null_closures
- omit_local_variable_types
- only_throw_errors
- overridden_fields
- package_names
- package_prefixed_library_names
- prefer_adjacent_string_concatenation
- prefer_conditional_assignment
- prefer_contains
- prefer_equal_for_default_values
- prefer_final_fields
- prefer_collection_literals
- prefer_generic_function_type_aliases
- prefer_initializing_formals
- prefer_is_empty
- prefer_is_not_empty
- prefer_null_aware_operators
- prefer_single_quotes
- prefer_typing_uninitialized_variables
- recursive_getters
- slash_for_doc_comments
- test_types_in_equals
- throw_in_finally
- type_init_formals
- unawaited_futures
- unnecessary_brace_in_string_interps
- unnecessary_const
- unnecessary_getters_setters
- unnecessary_lambdas
- unnecessary_new
- unnecessary_null_aware_assignments
- unnecessary_null_in_if_null_operators
- unnecessary_overrides
- unnecessary_parenthesis
- unnecessary_statements
- unnecessary_this
- unrelated_type_equality_checks
- use_rethrow_when_possible
- valid_regexps
- void_checks
constant_identifier_names: false
prefer_final_locals: true
prefer_single_quotes: true
always_declare_return_types: true
require_trailing_commas: true
32 changes: 17 additions & 15 deletions base/lib/src/auth/auth.dart
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,9 @@ class Auth {
String generateUploadToken({
required PutPolicy putPolicy,
}) {
var data = jsonEncode(putPolicy);
var encodedPutPolicy = base64Url.encode(utf8.encode(data));
var baseToken = generateAccessToken(bytes: utf8.encode(encodedPutPolicy));
final data = jsonEncode(putPolicy);
final encodedPutPolicy = base64Url.encode(utf8.encode(data));
final baseToken = generateAccessToken(bytes: utf8.encode(encodedPutPolicy));
return '$baseToken:$encodedPutPolicy';
}

Expand All @@ -58,18 +58,18 @@ class Auth {
required int deadline,
required String bucketDomain,
}) {
var downloadURL = '$bucketDomain/$key?e=$deadline';
final downloadURL = '$bucketDomain/$key?e=$deadline';
return generateAccessToken(bytes: utf8.encode(downloadURL));
}

/// 根据数据签名,生成 Token(用于接口的访问鉴权)。
///
/// 访问七牛的接口需要对请求进行签名, 该方法提供 Token 签发服务
String generateAccessToken({required List<int> bytes}) {
var hmacEncoder = Hmac(sha1, utf8.encode(secretKey));
final hmacEncoder = Hmac(sha1, utf8.encode(secretKey));

var sign = hmacEncoder.convert(bytes);
var encodedSign = base64Url.encode(sign.bytes);
final sign = hmacEncoder.convert(bytes);
final encodedSign = base64Url.encode(sign.bytes);
return '$accessKey:$encodedSign';
}

Expand All @@ -79,13 +79,13 @@ class Auth {
static TokenInfo parseToken(String token) {
assert(token != '');

var segments = token.split(':');
final segments = token.split(':');
if (segments.length < 2) {
throw ArgumentError('invalid token');
}

PutPolicy? putPolicy;
var accessKey = segments.first;
final accessKey = segments.first;

/// 具体的 token 信息可以参考这里。
/// [内部文档](https://github.com/qbox/product/blob/master/kodo/auths/UpToken.md#admin-uptoken-authorization)
Expand All @@ -94,13 +94,15 @@ class Auth {
throw ArgumentError('invalid token');
}

putPolicy = PutPolicy.fromJson(jsonDecode(
String.fromCharCodes(
base64Url.decode(
segments.last,
putPolicy = PutPolicy.fromJson(
jsonDecode(
String.fromCharCodes(
base64Url.decode(
segments.last,
),
),
),
) as Map<String, dynamic>);
) as Map<String, dynamic>,
);
}

return TokenInfo(accessKey, putPolicy);
Expand Down
7 changes: 2 additions & 5 deletions base/lib/src/storage/config/config.dart
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
import 'package:dio/dio.dart';

import 'package:qiniu_sdk_base/src/storage/error/error.dart';

import 'http_adaptor/native_adaptor.dart'
if (dart.library.html) 'http_adaptor/browser_adaptor.dart';
import '../../storage/error/error.dart';

part 'cache.dart';
part 'host.dart';
Expand All @@ -26,5 +23,5 @@ class Config {
this.retryLimit = 3,
}) : hostProvider = hostProvider ?? DefaultHostProvider(),
cacheProvider = cacheProvider ?? DefaultCacheProvider(),
httpClientAdapter = httpClientAdapter ?? createHttpAdaptor();
httpClientAdapter = httpClientAdapter ?? HttpClientAdapter();
}
16 changes: 8 additions & 8 deletions base/lib/src/storage/config/host.dart
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,9 @@ class DefaultHostProvider extends HostProvider {
// 解冻需要被解冻的 host
_frozenUpDomains.removeWhere((domain) => !domain.isFrozen());

var _upDomains = <_Domain>[];
final upDomains = <_Domain>[];
if ('$accessKey:$bucket' == _cacheKey && _stashedUpDomains.isNotEmpty) {
_upDomains.addAll(_stashedUpDomains);
upDomains.addAll(_stashedUpDomains);
} else {
final url =
'$protocol://api.qiniu.com/v4/query?ak=$accessKey&bucket=$bucket';
Expand All @@ -47,21 +47,21 @@ class DefaultHostProvider extends HostProvider {
for (var host in hosts) {
final domainList = host.up['domains'].cast<String>() as List<String>;
final domains = domainList.map((domain) => _Domain(domain));
_upDomains.addAll(domains);
upDomains.addAll(domains);
}

_cacheKey = '$accessKey:$bucket';
_stashedUpDomains.addAll(_upDomains);
_stashedUpDomains.addAll(upDomains);
}

// 每次都从头遍历一遍,最合适的 host 总是会排在最前面
for (var index = 0; index < _upDomains.length; index++) {
final availableDomain = _upDomains.elementAt(index);
for (var index = 0; index < upDomains.length; index++) {
final availableDomain = upDomains.elementAt(index);
// 检查看起来可用的 host 是否之前被冻结过
final frozen = isFrozen(protocol + '://' + availableDomain.value);
final frozen = isFrozen('$protocol://${availableDomain.value}');

if (!frozen) {
return protocol + '://' + availableDomain.value;
return '$protocol://${availableDomain.value}';
}
}
// 全部被冻结,几乎不存在的情况
Expand Down
4 changes: 0 additions & 4 deletions base/lib/src/storage/config/http_adaptor/browser_adaptor.dart

This file was deleted.

4 changes: 0 additions & 4 deletions base/lib/src/storage/config/http_adaptor/native_adaptor.dart

This file was deleted.

16 changes: 9 additions & 7 deletions base/lib/src/storage/error/error.dart
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import 'package:dio/dio.dart';
import 'package:qiniu_sdk_base/src/error/error.dart';

import '../../error/error.dart';

enum StorageErrorType {
/// 连接超时
Expand Down Expand Up @@ -41,9 +42,10 @@ class StorageError extends QiniuError {

factory StorageError.fromError(Error error) {
return StorageError(
type: StorageErrorType.UNKNOWN,
rawError: error,
message: error.toString());
type: StorageErrorType.UNKNOWN,
rawError: error,
message: error.toString(),
);
}

factory StorageError.fromDioError(DioError error) {
Expand All @@ -65,17 +67,17 @@ class StorageError extends QiniuError {

StorageErrorType _mapDioErrorType(DioErrorType type) {
switch (type) {
case DioErrorType.connectTimeout:
case DioErrorType.connectionTimeout:
return StorageErrorType.CONNECT_TIMEOUT;
case DioErrorType.sendTimeout:
return StorageErrorType.SEND_TIMEOUT;
case DioErrorType.receiveTimeout:
return StorageErrorType.RECEIVE_TIMEOUT;
case DioErrorType.response:
case DioErrorType.badResponse:
return StorageErrorType.RESPONSE;
case DioErrorType.cancel:
return StorageErrorType.CANCEL;
case DioErrorType.other:
case DioErrorType.unknown:
default:
return StorageErrorType.UNKNOWN;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,9 @@ class CompletePartsTask extends RequestTask<PutResponse> {
final response = await client.post<Map<String, dynamic>>(
paramUrl,
data: data,
options: Options(headers: headers),
options: Options(
headers: headers,
),
);

return PutResponse.fromJson(response.data!);
Expand Down
7 changes: 5 additions & 2 deletions base/lib/src/storage/methods/put/by_part/init_parts_task.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,8 @@ class InitPartsTask extends RequestTask<InitParts> with CacheMixin<InitParts> {
final initPartsCache = await getCache();
if (initPartsCache != null) {
return InitParts.fromJson(
json.decode(initPartsCache) as Map<String, dynamic>);
json.decode(initPartsCache) as Map<String, dynamic>,
);
}

final bucket = _tokenInfo.putPolicy.getBucket();
Expand All @@ -82,7 +83,9 @@ class InitPartsTask extends RequestTask<InitParts> with CacheMixin<InitParts> {

/// 这里 data 不传,dio 不会触发 cancel 事件
data: <String, dynamic>{},
options: Options(headers: headers),
options: Options(
headers: headers,
),
);

return InitParts.fromJson(response.data!);
Expand Down
30 changes: 0 additions & 30 deletions base/lib/src/storage/methods/put/by_part/put_by_part_options.dart

This file was deleted.

Loading