change api framework to angel3. #5
Merged
debuggerx
merged 14 commits from dev into master 4 years ago
@ -0,0 +1,10 @@
|
|||||||
|
.dart_tool
|
||||||
|
.idea
|
||||||
|
.pub
|
||||||
|
.vscode
|
||||||
|
logs/
|
||||||
|
test/
|
||||||
|
build/
|
||||||
|
.analysis-options
|
||||||
|
.packages
|
||||||
|
*.g.dart
|
||||||
@ -1,28 +1,97 @@
|
|||||||
# Created by .ignore support plugin (hsz.mobi)
|
# Created by .ignore support plugin (hsz.mobi)
|
||||||
### Dart template
|
### Dart template
|
||||||
# See https://www.dartlang.org/guides/libraries/private-files
|
# See https://www.dartlang.org/tools/private-files.html
|
||||||
|
|
||||||
|
# source_gen
|
||||||
|
.dart_tool
|
||||||
|
|
||||||
# Files and directories created by pub
|
# Files and directories created by pub
|
||||||
.dart_tool/
|
.buildlog
|
||||||
.packages
|
.packages
|
||||||
|
.project
|
||||||
|
.pub/
|
||||||
|
.scripts-bin/
|
||||||
build/
|
build/
|
||||||
# If you're building an application, you may want to check-in your pubspec.lock
|
**/packages/
|
||||||
pubspec.lock
|
|
||||||
|
|
||||||
# Directory created by dartdoc
|
|
||||||
# If you don't generate documentation locally you can remove this line.
|
|
||||||
doc/api/
|
|
||||||
|
|
||||||
# Avoid committing generated Javascript files:
|
# Files created by dart2js
|
||||||
|
# (Most Dart developers will use pub build to compile Dart, use/modify these
|
||||||
|
# rules if you intend to use dart2js directly
|
||||||
|
# Convention is to use extension '.dart.js' for Dart compiled to Javascript to
|
||||||
|
# differentiate from explicit Javascript files)
|
||||||
*.dart.js
|
*.dart.js
|
||||||
*.info.json # Produced by the --dump-info flag.
|
*.part.js
|
||||||
*.js # When generated by dart2js. Don't specify *.js if your
|
|
||||||
# project includes source files written in JavaScript.
|
|
||||||
*.js_
|
|
||||||
*.js.deps
|
*.js.deps
|
||||||
*.js.map
|
*.js.map
|
||||||
|
*.info.json
|
||||||
|
|
||||||
|
# Directory created by dartdoc
|
||||||
|
doc/api/
|
||||||
|
|
||||||
|
# Don't commit pubspec lock file
|
||||||
|
# (Library packages only! Remove pattern if developing an application package)
|
||||||
|
pubspec.lock
|
||||||
|
### JetBrains template
|
||||||
|
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
|
||||||
|
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||||
|
|
||||||
|
# User-specific stuff:
|
||||||
|
.idea/workspace.xml
|
||||||
|
.idea/tasks.xml
|
||||||
|
.idea/dictionaries
|
||||||
|
.idea/vcs.xml
|
||||||
|
.idea/jsLibraryMappings.xml
|
||||||
|
|
||||||
|
# Sensitive or high-churn files:
|
||||||
|
.idea/dataSources.ids
|
||||||
|
.idea/dataSources.xml
|
||||||
|
.idea/dataSources.local.xml
|
||||||
|
.idea/sqlDataSources.xml
|
||||||
|
.idea/dynamic.xml
|
||||||
|
.idea/uiDesigner.xml
|
||||||
|
|
||||||
|
# Gradle:
|
||||||
|
.idea/gradle.xml
|
||||||
|
.idea/libraries
|
||||||
|
|
||||||
|
# Mongo Explorer plugin:
|
||||||
|
.idea/mongoSettings.xml
|
||||||
|
|
||||||
|
## File-based project format:
|
||||||
|
*.iws
|
||||||
|
|
||||||
|
## Plugin-specific files:
|
||||||
|
|
||||||
|
# IntelliJ
|
||||||
|
/out/
|
||||||
|
|
||||||
|
# mpeltonen/sbt-idea plugin
|
||||||
|
.idea_modules/
|
||||||
|
|
||||||
|
# JIRA plugin
|
||||||
|
atlassian-ide-plugin.xml
|
||||||
|
|
||||||
|
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||||
|
com_crashlytics_export_strings.xml
|
||||||
|
crashlytics.properties
|
||||||
|
crashlytics-build.properties
|
||||||
|
fabric.properties
|
||||||
|
|
||||||
|
### VSCode template
|
||||||
|
.vscode/
|
||||||
|
!.vscode/settings.json
|
||||||
|
!.vscode/tasks.json
|
||||||
|
!.vscode/launch.json
|
||||||
|
!.vscode/extensions.json
|
||||||
|
|
||||||
|
logs/
|
||||||
|
*.pem
|
||||||
|
.DS_Store
|
||||||
|
server_log.txt
|
||||||
|
|
||||||
|
.metals/
|
||||||
|
|
||||||
.flutter-plugins
|
/config/production.yaml
|
||||||
.flutter-plugins-dependencies
|
/config/development.yaml
|
||||||
|
|
||||||
config.yaml
|
*.g.dart
|
||||||
|
|||||||
@ -0,0 +1,15 @@
|
|||||||
|
## v2.0.1
|
||||||
|
* Fixed issue when adding multiple commands without waiting for them to complete first.
|
||||||
|
|
||||||
|
## v2.0.0
|
||||||
|
* Migrated to null-safety, dropping dependency on `package:dartis`.
|
||||||
|
|
||||||
|
## v1.0.2
|
||||||
|
* Upgrade `package:dartis`.
|
||||||
|
|
||||||
|
## v1.0.1
|
||||||
|
* Avoid unnecessary purging when calling `set` with a `create` function that
|
||||||
|
returns `null`.
|
||||||
|
|
||||||
|
## v1.0.0
|
||||||
|
* Initial release.
|
||||||
@ -0,0 +1,202 @@
|
|||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
@ -0,0 +1,39 @@
|
|||||||
|
Neat Cache
|
||||||
|
==========
|
||||||
|
|
||||||
|
Abstractions around in-memory caches stores such as redis, with timeouts and
|
||||||
|
automatic reconnects.
|
||||||
|
|
||||||
|
**Disclaimer:** This is not an officially supported Google product.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```dart
|
||||||
|
import 'dart:async' show Future;
|
||||||
|
import 'dart:convert' show utf8;
|
||||||
|
import 'package:neat_cache/neat_cache.dart';
|
||||||
|
|
||||||
|
Future<void> main() async {
|
||||||
|
final cacheProvider = Cache.redisCacheProvider('redis://localhost:6379');
|
||||||
|
final cache = Cache(cacheProvider);
|
||||||
|
|
||||||
|
/// Create a sub-cache using a prefix, and apply a codec to store utf8
|
||||||
|
final userCache = cache.withPrefix('users').withCodec(utf8);
|
||||||
|
|
||||||
|
/// Get data form cache
|
||||||
|
String userinfo = await userCache['peter-pan'].get();
|
||||||
|
print(userinfo);
|
||||||
|
|
||||||
|
/// Put data into cache
|
||||||
|
await userCache['winnie'].set('Like honey');
|
||||||
|
|
||||||
|
await cacheProvider.close();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Development
|
||||||
|
To test the redis `CacheProvider` a redis instance must be running on
|
||||||
|
`localhost:6379`, this can be setup with:
|
||||||
|
|
||||||
|
* `docker run --rm -p 127.0.0.1:6379:6379 redis`
|
||||||
@ -0,0 +1 @@
|
|||||||
|
include: package:pedantic/analysis_options.yaml
|
||||||
@ -0,0 +1,77 @@
|
|||||||
|
// Copyright 2019 Google LLC
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'neat_cache.dart' show Cache;
|
||||||
|
|
||||||
|
/// Low-level interface for a cache.
|
||||||
|
///
|
||||||
|
/// This can be an in-memory cache, something that writes to disk or to an
|
||||||
|
/// cache service such as memcached or redis.
|
||||||
|
///
|
||||||
|
/// The [Cache] provided by `package:neat_cache`, is intended to wrap
|
||||||
|
/// a [CacheProvider] and provide a more convinient high-level interface.
|
||||||
|
///
|
||||||
|
/// Implementers of [CacheProvider] can implement something that stores a value
|
||||||
|
/// of any type `T`, but usually implementers should aim to implement
|
||||||
|
/// `CacheProvider<List<int>>` which stores binary data.
|
||||||
|
///
|
||||||
|
/// Implementations of the [CacheProvider] interface using a remote backing
|
||||||
|
/// store should throw [IntermittentCacheException] when an intermittent network
|
||||||
|
/// issue occurs. The [CacheProvider] should obviously attempt to reconnect to
|
||||||
|
/// the remote backing store, but it should not retry operations.
|
||||||
|
///
|
||||||
|
/// Operations will be retried by [Cache], if necessary. Many use-cases of
|
||||||
|
/// caching are resilient to intermittent failures.
|
||||||
|
abstract class CacheProvider<T> {
|
||||||
|
/// Fetch data stored under [key].
|
||||||
|
///
|
||||||
|
/// If nothing is cached for [key], this **must** return `null`.
|
||||||
|
Future<T?> get(String key);
|
||||||
|
|
||||||
|
/// Set [value] stored at [key] with optional [ttl].
|
||||||
|
///
|
||||||
|
/// If a value is already stored at [key], that value should be overwritten
|
||||||
|
/// with the new [value] given here.
|
||||||
|
///
|
||||||
|
/// When given [ttl] is advisory, however, implementers should avoid returning
|
||||||
|
/// entries that are far past their [ttl].
|
||||||
|
Future<void> set(String key, T value, [Duration? ttl]);
|
||||||
|
|
||||||
|
/// Clear value stored at [key].
|
||||||
|
///
|
||||||
|
/// After this has returned future calls to [get] for the given [key] should
|
||||||
|
/// not return any value, unless a new value have been set.
|
||||||
|
Future<void> purge(String key);
|
||||||
|
|
||||||
|
/// Close all connections, causing all future operations to throw.
|
||||||
|
///
|
||||||
|
/// This method frees resources used by this [CacheProvider], if backed by
|
||||||
|
/// a remote service like redis, this should close the connection.
|
||||||
|
///
|
||||||
|
/// Calling [close] multiple times does not throw. But after this has returned
|
||||||
|
/// all future operations should throw [StateError].
|
||||||
|
Future<void> close();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Exception thrown when there is an intermittent exception.
|
||||||
|
///
|
||||||
|
/// This is typically thrown if there is an intermittent connection error.
|
||||||
|
class IntermittentCacheException implements Exception {
|
||||||
|
final String _message;
|
||||||
|
IntermittentCacheException(this._message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => _message;
|
||||||
|
}
|
||||||
@ -0,0 +1,228 @@
|
|||||||
|
// Copyright 2019 Google LLC
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:convert/convert.dart' show IdentityCodec;
|
||||||
|
import 'package:logging/logging.dart';
|
||||||
|
import 'package:retry/retry.dart';
|
||||||
|
|
||||||
|
import 'cache_provider.dart';
|
||||||
|
import 'src/providers/inmemory.dart';
|
||||||
|
import 'src/providers/redis.dart';
|
||||||
|
|
||||||
|
final _logger = Logger('neat_cache');
|
||||||
|
|
||||||
|
/// Cache for objects of type [T], wrapping a [CacheProvider] to provide a
|
||||||
|
/// high-level interface.
|
||||||
|
///
|
||||||
|
/// Cache entries are accessed using the indexing operator `[]`, this returns a
|
||||||
|
/// [Entry<T>] wrapper that can be used to get/set data cached at given key.
|
||||||
|
///
|
||||||
|
/// **Example**
|
||||||
|
/// ```dart
|
||||||
|
/// final Cache<List<int>> cache = Cache.inMemoryCache(4096);
|
||||||
|
///
|
||||||
|
/// // Write data to cache
|
||||||
|
/// await cache['cached-zeros'].set([0, 0, 0, 0]);
|
||||||
|
///
|
||||||
|
/// // Read data from cache
|
||||||
|
/// var r = await cache['cached-zeros'].get();
|
||||||
|
/// expect(r, equals([0, 0, 0, 0]));
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// A [Cache] can be _fused_ with a [Codec] using [withCodec] to get a cache
|
||||||
|
/// that stores a different kind of objects. It is also possible to create
|
||||||
|
/// a chuild cache using [withPrefix], such that all entries in the child
|
||||||
|
/// cache have a given prefix.
|
||||||
|
abstract class Cache<T> {
|
||||||
|
/// Get [Entry] wrapping data cached at [key].
|
||||||
|
Entry<T> operator [](String key);
|
||||||
|
|
||||||
|
/// Get a [Cache] wrapping of this cache with given [prefix].
|
||||||
|
Cache<T> withPrefix(String prefix);
|
||||||
|
|
||||||
|
/// Get a [Cache] wrapping of this cache by encoding objects of type [S] as
|
||||||
|
/// [T] using the given [codec].
|
||||||
|
Cache<S> withCodec<S>(Codec<S, T> codec);
|
||||||
|
|
||||||
|
/// Get a [Cache] wrapping of this cache with given [ttl] as default for all
|
||||||
|
/// entries being set using [Entry.set].
|
||||||
|
///
|
||||||
|
/// This only specifies a different default [ttl], to be used when [Entry.set]
|
||||||
|
/// is called without a [ttl] parameter.
|
||||||
|
Cache<T> withTTL(Duration ttl);
|
||||||
|
|
||||||
|
/// Create a [Cache] wrapping a [CacheProvider].
|
||||||
|
factory Cache(CacheProvider<T> provider) {
|
||||||
|
return _Cache<T, T>(provider, '', IdentityCodec());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create an in-memory [CacheProvider] holding a maximum of [maxSize] cache
|
||||||
|
/// entries.
|
||||||
|
static CacheProvider<List<int>> inMemoryCacheProvider(int maxSize) {
|
||||||
|
return InMemoryCacheProvider(maxSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Create a redis [CacheProvider] by connecting using a [connectionString] on
|
||||||
|
/// the form `redis://<host>:<port>`.
|
||||||
|
static CacheProvider<List<int>> redisCacheProvider(Uri connectionString, {Duration commandTimeLimit = const Duration(milliseconds: 200)}) {
|
||||||
|
return RedisCacheProvider(connectionString, commandTimeLimit: commandTimeLimit);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pointer to a location in the cache.
|
||||||
|
///
|
||||||
|
/// This simply wraps a cache key, such that you don't need to supply a cache
|
||||||
|
/// key for [get], [set] and [purge] operations.
|
||||||
|
abstract class Entry<T> {
|
||||||
|
/// Get value stored in this cache entry.
|
||||||
|
///
|
||||||
|
/// If used without [create], this function simply gets the value or `null` if
|
||||||
|
/// no value is stored.
|
||||||
|
///
|
||||||
|
/// If used with [create], this function becomes an upsert, returning the
|
||||||
|
/// value stored if any, otherwise creating a new value and storing it with
|
||||||
|
/// optional [ttl]. If multiple callers are using the same cache this is an
|
||||||
|
/// inherently racy operation, that is multiple instances of the value may
|
||||||
|
/// be created.
|
||||||
|
///
|
||||||
|
/// The [get] method is a best-effort method. In case of intermittent failures
|
||||||
|
/// from the underlying [CacheProvider] the [get] method will ignore failures
|
||||||
|
/// and return `null` (or result from [create] if specified).
|
||||||
|
Future<T?> get([Future<T?> Function() create, Duration ttl]);
|
||||||
|
|
||||||
|
/// Set the value stored in this cache entry.
|
||||||
|
///
|
||||||
|
/// If given [ttl] specifies the time-to-live. Notice that this is advisatory,
|
||||||
|
/// the underlying [CacheProvider] may choose to evit cache entries at any
|
||||||
|
/// time. However, it can be assumed that entries will not live far past
|
||||||
|
/// their [ttl].
|
||||||
|
///
|
||||||
|
/// The [set] method is a best-effort method. In case of intermittent failures
|
||||||
|
/// from the underlying [CacheProvider] the [set] method will ignore failures.
|
||||||
|
///
|
||||||
|
/// To ensure that cache entries are purged, use the [purge] method with
|
||||||
|
/// `retries` not set to zero.
|
||||||
|
Future<T?> set(T? value, [Duration ttl]);
|
||||||
|
|
||||||
|
/// Clear the value stored in this cache entry.
|
||||||
|
///
|
||||||
|
/// If [retries] is `0` (default), this is a best-effort method, which will
|
||||||
|
/// ignore intermittent failures. If [retries] is non-zero the operation will
|
||||||
|
/// be retried with exponential back-off, and [IntermittentCacheException]
|
||||||
|
/// will be thrown if all retries fails.
|
||||||
|
Future purge({int retries = 0});
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Cache<T, V> implements Cache<T> {
|
||||||
|
final CacheProvider<V> _provider;
|
||||||
|
final String _prefix;
|
||||||
|
final Codec<T, V> _codec;
|
||||||
|
final Duration? _ttl;
|
||||||
|
|
||||||
|
_Cache(this._provider, this._prefix, this._codec, [this._ttl]);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Entry<T> operator [](String key) => _Entry(this, _prefix + key);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Cache<T> withPrefix(String prefix) =>
|
||||||
|
_Cache(_provider, _prefix + prefix, _codec, _ttl);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Cache<S> withCodec<S>(Codec<S, T> codec) =>
|
||||||
|
_Cache(_provider, _prefix, codec.fuse(_codec), _ttl);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Cache<T> withTTL(Duration ttl) => _Cache(_provider, _prefix, _codec, ttl);
|
||||||
|
}
|
||||||
|
|
||||||
|
class _Entry<T, V> implements Entry<T> {
|
||||||
|
final _Cache<T, V> _owner;
|
||||||
|
final String _key;
|
||||||
|
_Entry(this._owner, this._key);
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<T?> get([Future<T?> Function()? create, Duration? ttl]) async {
|
||||||
|
V? value;
|
||||||
|
try {
|
||||||
|
_logger.finest(() => 'reading cache entry for "$_key"');
|
||||||
|
value = await _owner._provider.get(_key);
|
||||||
|
} on IntermittentCacheException {
|
||||||
|
_logger.fine(
|
||||||
|
// embedding [intermittent-cache-failure] to allow for easy log metrics
|
||||||
|
'[intermittent-cache-failure], failed to get cache entry for "$_key"',
|
||||||
|
);
|
||||||
|
value = null;
|
||||||
|
}
|
||||||
|
if (value == null) {
|
||||||
|
if (create == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
final created = await create();
|
||||||
|
if (created != null) {
|
||||||
|
// Calling `set(null)` is equivalent to `purge()`, we can skip that here
|
||||||
|
await set(created, ttl);
|
||||||
|
}
|
||||||
|
return created;
|
||||||
|
}
|
||||||
|
return _owner._codec.decode(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<T?> set(T? value, [Duration? ttl]) async {
|
||||||
|
if (value == null) {
|
||||||
|
await purge();
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
ttl ??= _owner._ttl;
|
||||||
|
final raw = _owner._codec.encode(value);
|
||||||
|
try {
|
||||||
|
await _owner._provider.set(_key, raw, ttl);
|
||||||
|
} on IntermittentCacheException {
|
||||||
|
_logger.fine(
|
||||||
|
// embedding [intermittent-cache-failure] to allow for easy log metrics
|
||||||
|
'[intermittent-cache-failure], failed to set cache entry for "$_key"',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> purge({int retries = 0}) async {
|
||||||
|
// Common path is that we have no retries
|
||||||
|
if (retries == 0) {
|
||||||
|
try {
|
||||||
|
await _owner._provider.purge(_key);
|
||||||
|
} on IntermittentCacheException {
|
||||||
|
_logger.fine(
|
||||||
|
// embedding [intermittent-cache-failure] to allow for easy log metrics
|
||||||
|
'[intermittent-cache-failure], failed to purge cache entry for "$_key"',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Test that we have a positive number of retries.
|
||||||
|
if (retries < 0) {
|
||||||
|
ArgumentError.value(retries, 'retries', 'retries < 0 is not allowed');
|
||||||
|
}
|
||||||
|
return await retry(
|
||||||
|
() => _owner._provider.purge(_key),
|
||||||
|
retryIf: (e) => e is IntermittentCacheException,
|
||||||
|
maxAttempts: 1 + retries,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,110 @@
|
|||||||
|
// Copyright 2019 Google LLC
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import '../../cache_provider.dart';
|
||||||
|
|
||||||
|
class _InMemoryEntry<T> {
|
||||||
|
final T value;
|
||||||
|
final DateTime? _expires;
|
||||||
|
_InMemoryEntry(this.value, [this._expires]);
|
||||||
|
bool get isExpired => _expires != null && _expires!.isBefore(DateTime.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Simple two-generational LRU cache inspired by:
|
||||||
|
/// https://github.com/sindresorhus/quick-lru
|
||||||
|
class InMemoryCacheProvider<T> extends CacheProvider<T> {
|
||||||
|
/// New generation of cache entries.
|
||||||
|
Map<String, _InMemoryEntry<T>> _new = <String, _InMemoryEntry<T>>{};
|
||||||
|
|
||||||
|
/// Old generation of cache entries.
|
||||||
|
Map<String, _InMemoryEntry<T>> _old = <String, _InMemoryEntry<T>>{};
|
||||||
|
|
||||||
|
/// Maximum size before clearing old generation.
|
||||||
|
final int _maxSize;
|
||||||
|
|
||||||
|
/// Have this been closed.
|
||||||
|
bool _isClosed = false;
|
||||||
|
|
||||||
|
InMemoryCacheProvider(this._maxSize);
|
||||||
|
|
||||||
|
/// Clear old generation, if _maxSize have been reached.
|
||||||
|
void _maintainGenerations() {
|
||||||
|
if (_new.length >= _maxSize) {
|
||||||
|
_old = _new;
|
||||||
|
_new = {};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<T?> get(String key) async {
|
||||||
|
if (_isClosed) {
|
||||||
|
throw StateError('CacheProvider.close() have been called');
|
||||||
|
}
|
||||||
|
// Lookup in the new generation
|
||||||
|
var entry = _new[key];
|
||||||
|
if (entry != null) {
|
||||||
|
if (!entry.isExpired) {
|
||||||
|
return entry.value;
|
||||||
|
}
|
||||||
|
// Remove, if expired
|
||||||
|
_new.remove(key);
|
||||||
|
}
|
||||||
|
// Lookup in the old generation
|
||||||
|
entry = _old[key];
|
||||||
|
if (entry != null) {
|
||||||
|
if (!entry.isExpired) {
|
||||||
|
// If not expired, we insert the entry into the new generation
|
||||||
|
_new[key] = entry;
|
||||||
|
_maintainGenerations();
|
||||||
|
return entry.value;
|
||||||
|
}
|
||||||
|
// Remove, if expired
|
||||||
|
_old.remove(key);
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> set(String key, T value, [Duration? ttl]) async {
|
||||||
|
if (_isClosed) {
|
||||||
|
throw StateError('CacheProvider.close() have been called');
|
||||||
|
}
|
||||||
|
if (ttl == null) {
|
||||||
|
_new[key] = _InMemoryEntry(value);
|
||||||
|
} else {
|
||||||
|
_new[key] = _InMemoryEntry(value, DateTime.now().add(ttl));
|
||||||
|
}
|
||||||
|
// Always remove key from old generation to avoid risks of looking up there
|
||||||
|
// if it's overwritten by an entry with a shorter ttl
|
||||||
|
_old.remove(key);
|
||||||
|
_maintainGenerations();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> purge(String key) async {
|
||||||
|
if (_isClosed) {
|
||||||
|
throw StateError('CacheProvider.close() have been called');
|
||||||
|
}
|
||||||
|
_new.remove(key);
|
||||||
|
_old.remove(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> close() async {
|
||||||
|
_isClosed = true;
|
||||||
|
_old = {};
|
||||||
|
_new = {};
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,210 @@
|
|||||||
|
// Copyright 2019 Google LLC
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io' show IOException, Socket, SocketOption;
|
||||||
|
import 'dart:typed_data';
|
||||||
|
import 'resp.dart';
|
||||||
|
import 'package:logging/logging.dart';
|
||||||
|
import '../../cache_provider.dart';
|
||||||
|
|
||||||
|
final _log = Logger('neat_cache');
|
||||||
|
|
||||||
|
class _RedisContext {
|
||||||
|
final RespClient client;
|
||||||
|
_RedisContext({
|
||||||
|
required this.client,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
class RedisCacheProvider extends CacheProvider<List<int>> {
|
||||||
|
final Uri _connectionString;
|
||||||
|
final Duration _connectTimeLimit;
|
||||||
|
final Duration _commandTimeLimit;
|
||||||
|
final Duration _reconnectDelay;
|
||||||
|
|
||||||
|
Future<_RedisContext>? _context;
|
||||||
|
bool _isClosed = false;
|
||||||
|
|
||||||
|
RedisCacheProvider(
|
||||||
|
Uri connectionString, {
|
||||||
|
Duration connectTimeLimit = const Duration(seconds: 30),
|
||||||
|
Duration commandTimeLimit = const Duration(milliseconds: 200),
|
||||||
|
Duration reconnectDelay = const Duration(seconds: 30),
|
||||||
|
}) : _connectionString = connectionString,
|
||||||
|
_connectTimeLimit = connectTimeLimit,
|
||||||
|
_commandTimeLimit = commandTimeLimit,
|
||||||
|
_reconnectDelay = reconnectDelay {
|
||||||
|
if (!connectionString.isScheme('redis')) {
|
||||||
|
throw ArgumentError.value(
|
||||||
|
connectionString, 'connectionString', 'must have scheme redis://');
|
||||||
|
}
|
||||||
|
if (!connectionString.hasEmptyPath) {
|
||||||
|
throw ArgumentError.value(
|
||||||
|
connectionString, 'connectionString', 'cannot have a path');
|
||||||
|
}
|
||||||
|
if (connectTimeLimit.isNegative) {
|
||||||
|
throw ArgumentError.value(
|
||||||
|
connectTimeLimit, 'connectTimeLimit', 'must be positive');
|
||||||
|
}
|
||||||
|
if (commandTimeLimit.isNegative) {
|
||||||
|
throw ArgumentError.value(
|
||||||
|
commandTimeLimit, 'commandTimeLimit', 'must be positive');
|
||||||
|
}
|
||||||
|
if (reconnectDelay.isNegative) {
|
||||||
|
throw ArgumentError.value(
|
||||||
|
reconnectDelay, 'reconnectDelay', 'must be positive');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<_RedisContext> _createContext() async {
|
||||||
|
try {
|
||||||
|
_log.info('Connecting to redis');
|
||||||
|
final socket = await Socket.connect(
|
||||||
|
_connectionString.host,
|
||||||
|
_connectionString.port,
|
||||||
|
).timeout(_connectTimeLimit);
|
||||||
|
socket.setOption(SocketOption.tcpNoDelay, true);
|
||||||
|
|
||||||
|
|
||||||
|
var client = RespClient(socket, socket);
|
||||||
|
if (_connectionString.userInfo.isNotEmpty) {
|
||||||
|
await client.command(['AUTH', _connectionString.userInfo]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create context
|
||||||
|
return _RedisContext(
|
||||||
|
client: client,
|
||||||
|
);
|
||||||
|
} on RedisConnectionException {
|
||||||
|
throw IntermittentCacheException('connection failed');
|
||||||
|
} on TimeoutException {
|
||||||
|
throw IntermittentCacheException('connect failed with timeout');
|
||||||
|
} on IOException catch (e) {
|
||||||
|
throw IntermittentCacheException('connect failed with IOException: $e');
|
||||||
|
} on Exception {
|
||||||
|
throw IntermittentCacheException('connect failed with exception');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<_RedisContext> _getContext() {
|
||||||
|
if (_context != null) {
|
||||||
|
return _context!;
|
||||||
|
}
|
||||||
|
_context = _createContext();
|
||||||
|
scheduleMicrotask(() async {
|
||||||
|
_RedisContext ctx;
|
||||||
|
try {
|
||||||
|
ctx = await _context!;
|
||||||
|
} on IntermittentCacheException {
|
||||||
|
// If connecting fails, then we sleep and try again
|
||||||
|
await Future.delayed(_reconnectDelay);
|
||||||
|
_context = null; // reset _context, so next operation creates a new
|
||||||
|
return;
|
||||||
|
} catch (e) {
|
||||||
|
_log.shout('unknown error/exception connecting to redis', e);
|
||||||
|
_context = null; // reset _context, so next operation creates a new
|
||||||
|
rethrow; // propagate the error to crash to application.
|
||||||
|
}
|
||||||
|
// If connecting was successful, then we await the connection being
|
||||||
|
// closed or error, and we reset _context.
|
||||||
|
try {
|
||||||
|
await ctx.client.closed;
|
||||||
|
} catch (e) {
|
||||||
|
// ignore error
|
||||||
|
}
|
||||||
|
_context = null;
|
||||||
|
});
|
||||||
|
return _context!;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<T> _withResp<T>(Future<T> Function(RespClient) fn) async {
|
||||||
|
if (_isClosed) {
|
||||||
|
throw StateError('CacheProvider.closed() has been called');
|
||||||
|
}
|
||||||
|
final ctx = await _getContext();
|
||||||
|
try {
|
||||||
|
return await fn(ctx.client).timeout(_commandTimeLimit);
|
||||||
|
} on RedisCommandException catch (e) {
|
||||||
|
throw AssertionError('error from redis command: $e');
|
||||||
|
} on TimeoutException {
|
||||||
|
// If we had a timeout, doing the command we forcibly disconnect
|
||||||
|
// from the server, such that next retry will use a new connection.
|
||||||
|
await ctx.client.close(force: true);
|
||||||
|
throw IntermittentCacheException('redis command timeout');
|
||||||
|
} on RedisConnectionException catch (e) {
|
||||||
|
throw IntermittentCacheException('redis error: $e');
|
||||||
|
} on IOException catch (e) {
|
||||||
|
throw IntermittentCacheException('socket broken: $e');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> close() async {
|
||||||
|
_isClosed = true;
|
||||||
|
if (_context != null) {
|
||||||
|
try {
|
||||||
|
final ctx = await _context!;
|
||||||
|
await ctx.client.close();
|
||||||
|
} catch (e) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<List<int>?> get(String key) => _withResp((client) async {
|
||||||
|
final r = await client.command(['GET', key]).catchError((e) {
|
||||||
|
throw e;
|
||||||
|
});
|
||||||
|
if (r == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (r is Uint8List) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
assert(false, 'unexpected response from redis server');
|
||||||
|
|
||||||
|
// Force close the client
|
||||||
|
scheduleMicrotask(() => client.close(force: true));
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> set(String key, List<int> value, [Duration? ttl]) =>
|
||||||
|
_withResp((client) async {
|
||||||
|
final r = await client.command([
|
||||||
|
'SET',
|
||||||
|
key,
|
||||||
|
value,
|
||||||
|
if (ttl != null) ...<Object>['EX', ttl.inSeconds],
|
||||||
|
]);
|
||||||
|
if (r != 'OK') {
|
||||||
|
assert(false, 'unexpected response from redis server');
|
||||||
|
|
||||||
|
// Force close the client
|
||||||
|
scheduleMicrotask(() => client.close(force: true));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
@override
|
||||||
|
Future<void> purge(String key) => _withResp((client) async {
|
||||||
|
final r = await client.command(['DEL', key]);
|
||||||
|
if (r is! int) {
|
||||||
|
assert(false, 'unexpected response from redis server');
|
||||||
|
|
||||||
|
// Force close the client
|
||||||
|
scheduleMicrotask(() => client.close(force: true));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -0,0 +1,526 @@
|
|||||||
|
// Copyright 2021 Google LLC
|
||||||
|
//
|
||||||
|
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
// you may not use this file except in compliance with the License.
|
||||||
|
// You may obtain a copy of the License at
|
||||||
|
//
|
||||||
|
// https://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
//
|
||||||
|
// Unless required by applicable law or agreed to in writing, software
|
||||||
|
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
// See the License for the specific language governing permissions and
|
||||||
|
// limitations under the License.
|
||||||
|
|
||||||
|
/// Minimalistic [RESP[1] protocol implementation in Dart.
|
||||||
|
///
|
||||||
|
/// [1]: https://redis.io/topics/protocol
|
||||||
|
library resp;
|
||||||
|
|
||||||
|
import 'dart:async';
|
||||||
|
import 'dart:collection';
|
||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:typed_data';
|
||||||
|
|
||||||
|
import 'package:logging/logging.dart';
|
||||||
|
|
||||||
|
final _log = Logger('neat_cache:redis');
|
||||||
|
|
||||||
|
/// Thrown when the server returns an error in response to a command.
|
||||||
|
class RedisCommandException implements Exception {
|
||||||
|
final String type;
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
RedisCommandException._(this.type, this.message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'RedisCommandException: $type $message';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Thrown if the redis connection is broken.
|
||||||
|
///
|
||||||
|
/// This typically happens if the connection is unexpectedly closed, the
|
||||||
|
/// [RESP protocol][1] is violated, or there is an internal error.
|
||||||
|
///
|
||||||
|
/// [1]: https://redis.io/topics/protocol
|
||||||
|
class RedisConnectionException implements Exception {
|
||||||
|
final String message;
|
||||||
|
|
||||||
|
RedisConnectionException._(this.message);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => 'RedisConnectionException: $message';
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Client implementing the [RESP protocol][1].
|
||||||
|
///
|
||||||
|
/// [1]: https://redis.io/topics/protocol
|
||||||
|
class RespClient {
|
||||||
|
static final _newLine = ascii.encode('\r\n');
|
||||||
|
|
||||||
|
/// No value in redis can be more than [512 MB][1].
|
||||||
|
///
|
||||||
|
/// [1]: https://redis.io/topics/data-types
|
||||||
|
static const _maxValueSize = 512 * 1024 * 1024;
|
||||||
|
|
||||||
|
final _ByteStreamScanner _input;
|
||||||
|
final StreamSink<List<int>> _output;
|
||||||
|
Future _pendingStream = Future.value(null);
|
||||||
|
|
||||||
|
final _pending = Queue<Completer<Object?>>();
|
||||||
|
|
||||||
|
bool _closing = false;
|
||||||
|
final _closed = Completer<void>();
|
||||||
|
|
||||||
|
/// Creates an instance of [RespClient] given an [input]stream and an [output]
|
||||||
|
/// sink.
|
||||||
|
///
|
||||||
|
/// If connecting over TCP as usual the `Socket` object from `dart:io`
|
||||||
|
/// implements both [Stream<Uint8List>] and [StreamSink<List<int>>]. Thus,
|
||||||
|
/// the following example is a reasonable way to make a client:
|
||||||
|
///
|
||||||
|
/// ```dart
|
||||||
|
/// // Connect to redis server
|
||||||
|
/// final socket = await Socket.connect(host, port);
|
||||||
|
/// socket.setOption(SocketOption.tcpNoDelay, true);
|
||||||
|
///
|
||||||
|
/// // Create client
|
||||||
|
/// final client = RespClient(socket, socket);
|
||||||
|
/// ```
|
||||||
|
RespClient(
|
||||||
|
Stream<Uint8List> input,
|
||||||
|
StreamSink<List<int>> output,
|
||||||
|
) : _input = _ByteStreamScanner(input),
|
||||||
|
_output = output {
|
||||||
|
scheduleMicrotask(_readInput);
|
||||||
|
scheduleMicrotask(() async {
|
||||||
|
try {
|
||||||
|
await _output.done;
|
||||||
|
} catch (e, st) {
|
||||||
|
if (!_closing) {
|
||||||
|
return await _abort(e, st);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!_closing) {
|
||||||
|
await _abort(
|
||||||
|
RedisConnectionException._('outgoing connection closed'),
|
||||||
|
StackTrace.current,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a [Future] that is resolved when the connection is closed.
|
||||||
|
Future<void> get closed => _closed.future;
|
||||||
|
|
||||||
|
/// Send command to redis and return the result.
|
||||||
|
///
|
||||||
|
/// The [args] is a list of:
|
||||||
|
/// * [String],
|
||||||
|
/// * [List<int>], and,
|
||||||
|
/// * [int].
|
||||||
|
/// This is always encoded as an _RESP Array_ of _RESP Bulk Strings_.
|
||||||
|
///
|
||||||
|
/// Response will decoded as follows:
|
||||||
|
/// * RESP Simple String: returns [String],
|
||||||
|
/// * RESP Error: throws [RedisCommandException],
|
||||||
|
/// * RESP Integer: returns [int],
|
||||||
|
/// * RESP Bulk String: returns [Uint8List],
|
||||||
|
/// * RESP nil Bulk String: returns `null`,
|
||||||
|
/// * RESP Array: returns [List<Object?>], and,
|
||||||
|
/// * RESP nil Arrray: returns `null`.
|
||||||
|
///
|
||||||
|
/// Throws [RedisConnectionException] if underlying connection as been broken
|
||||||
|
/// or if the [RESP protocol][1] has been violated. After this, the client
|
||||||
|
/// should not be used further.
|
||||||
|
///
|
||||||
|
/// Forwards any [Exception] thrown by the underlying connection and aborts
|
||||||
|
/// the [RespClient]. Once aborted [closed] will be resolved, and further
|
||||||
|
/// attempts to call [command] will throw [RedisConnectionException].
|
||||||
|
///
|
||||||
|
/// Consumers are encouraged to handle [RedisConnectionException] and
|
||||||
|
/// reconnect, creating a new [RespClient], when [RedisConnectionException] is
|
||||||
|
/// encountered.
|
||||||
|
///
|
||||||
|
/// [1]: https://redis.io/topics/protocol
|
||||||
|
Future<Object?> command(List<Object> args) async {
|
||||||
|
if (_closing) {
|
||||||
|
throw RedisConnectionException._('redis connection is closed');
|
||||||
|
}
|
||||||
|
|
||||||
|
final out = BytesBuilder(copy: false);
|
||||||
|
out.addByte('*'.codeUnitAt(0));
|
||||||
|
out.add(ascii.encode(args.length.toString()));
|
||||||
|
out.add(_newLine);
|
||||||
|
for (final arg in args) {
|
||||||
|
List<int> bytes;
|
||||||
|
if (arg is String) {
|
||||||
|
bytes = utf8.encode(arg);
|
||||||
|
} else if (arg is List<int>) {
|
||||||
|
bytes = arg;
|
||||||
|
} else if (arg is int) {
|
||||||
|
bytes = ascii.encode(arg.toString());
|
||||||
|
} else {
|
||||||
|
throw ArgumentError.value(
|
||||||
|
args,
|
||||||
|
'args',
|
||||||
|
'arguments for redis must be String, List<int>, int',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
out.addByte(r'$'.codeUnitAt(0));
|
||||||
|
out.add(ascii.encode(bytes.length.toString()));
|
||||||
|
out.add(_newLine);
|
||||||
|
out.add(bytes);
|
||||||
|
out.add(_newLine);
|
||||||
|
}
|
||||||
|
|
||||||
|
final c = Completer<Object?>();
|
||||||
|
_pending.addLast(c);
|
||||||
|
try {
|
||||||
|
_pendingStream = _pendingStream
|
||||||
|
.then((value) => _output.addStream(Stream.value(out.toBytes())));
|
||||||
|
} on Exception catch (e, st) {
|
||||||
|
await _abort(e, st);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return await c.future;
|
||||||
|
} on RedisCommandException catch (e) {
|
||||||
|
// Don't use rethrow because the stack-trace really should start here.
|
||||||
|
// we always throw RedisCommandException with a StackTrace.empty, because
|
||||||
|
// it's a thing that happens on the server, and that stack-trace of the
|
||||||
|
// code that reads the value from the server is uninteresting.
|
||||||
|
throw e; // ignore: use_rethrow_when_possible
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send `QUIT` command to redis and close the connection.
|
||||||
|
///
|
||||||
|
/// If [force] is `true`, then the connection will be forcibly closed
|
||||||
|
/// immediately. Otherwise, connection will reject new commands, but wait for
|
||||||
|
/// existing commands to complete.
|
||||||
|
Future<void> close({bool force = false}) async {
|
||||||
|
_closing = true;
|
||||||
|
|
||||||
|
if (!_closing) {
|
||||||
|
// Always send QUIT message to be nice
|
||||||
|
try {
|
||||||
|
final quit = command(['QUIT']);
|
||||||
|
scheduleMicrotask(() async {
|
||||||
|
await quit.catchError((_) {/* ignore */});
|
||||||
|
});
|
||||||
|
} catch (_) {
|
||||||
|
// ignore
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!force) {
|
||||||
|
scheduleMicrotask(() async {
|
||||||
|
await _output.close().catchError((_) {/* ignore */});
|
||||||
|
});
|
||||||
|
await _closed.future;
|
||||||
|
} else {
|
||||||
|
await _output.close().catchError((_) {/* ignore */});
|
||||||
|
|
||||||
|
// Resolve all outstanding requests
|
||||||
|
final pending = _pending.toList(growable: false);
|
||||||
|
_pending.clear();
|
||||||
|
final e = RedisConnectionException._('redis client forcibly closed');
|
||||||
|
final st = StackTrace.current;
|
||||||
|
pending.forEach((c) => c.completeError(e, st));
|
||||||
|
}
|
||||||
|
await _input.cancel();
|
||||||
|
|
||||||
|
assert(_pending.isEmpty, 'new pending requests added after close()');
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Abort due to internal error
|
||||||
|
Future<void> _abort(Object e, StackTrace st) async {
|
||||||
|
if (!_closing) {
|
||||||
|
_log.warning('redis connection broken:', e, st);
|
||||||
|
}
|
||||||
|
|
||||||
|
_closing = true;
|
||||||
|
|
||||||
|
// Resolve all outstanding requests
|
||||||
|
final pending = _pending.toList(growable: false);
|
||||||
|
_pending.clear();
|
||||||
|
scheduleMicrotask(() {
|
||||||
|
pending.forEach((c) => c.completeError(e, st));
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!_closed.isCompleted) {
|
||||||
|
_closed.complete();
|
||||||
|
}
|
||||||
|
await _input.cancel();
|
||||||
|
|
||||||
|
assert(_pending.isEmpty, 'new pending requests added after aborting');
|
||||||
|
}
|
||||||
|
|
||||||
|
void _readInput() async {
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
Object? value;
|
||||||
|
try {
|
||||||
|
value = await _readValue();
|
||||||
|
} on RedisConnectionException catch (e, st) {
|
||||||
|
return await _abort(e, st);
|
||||||
|
}
|
||||||
|
if (_pending.isEmpty) {
|
||||||
|
return await _abort(
|
||||||
|
RedisConnectionException._('unexpected value from server'),
|
||||||
|
StackTrace.current,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final c = _pending.removeFirst();
|
||||||
|
if (value is RedisCommandException) {
|
||||||
|
// This is an error code returned by the server, it doesn't have a
|
||||||
|
// stack-trace!
|
||||||
|
c.completeError(value, StackTrace.empty);
|
||||||
|
} else {
|
||||||
|
c.complete(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_closing && _pending.isEmpty) {
|
||||||
|
return _closed.complete();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e, st) {
|
||||||
|
_log.shout('internal redis client error:', e, st);
|
||||||
|
await _abort(
|
||||||
|
RedisConnectionException._('internal redis client error: $e'),
|
||||||
|
st,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static final _whitespacePattern = RegExp(r'\s');
|
||||||
|
|
||||||
|
Future<Object?> _readValue() async {
|
||||||
|
Uint8List line;
|
||||||
|
try {
|
||||||
|
line = await _input.readLine(maxSize: _maxValueSize);
|
||||||
|
} on Exception catch (e, st) {
|
||||||
|
await _abort(e, st);
|
||||||
|
throw RedisConnectionException._('exception reading line: $e');
|
||||||
|
}
|
||||||
|
if (line.isEmpty) {
|
||||||
|
throw RedisConnectionException._('Incoming stream from server closed');
|
||||||
|
}
|
||||||
|
if (!_endsWithNewLine(line)) {
|
||||||
|
throw RedisConnectionException._(
|
||||||
|
'Invalid server message: missing newline',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final type = line[0];
|
||||||
|
final rest = Uint8List.sublistView(line, 1, line.length - 2);
|
||||||
|
|
||||||
|
// Handle simple strings
|
||||||
|
if (type == '+'.codeUnitAt(0)) {
|
||||||
|
try {
|
||||||
|
return utf8.decode(rest);
|
||||||
|
} on FormatException catch (e) {
|
||||||
|
throw RedisConnectionException._(
|
||||||
|
'Invalid simple string from server: $e',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle errors
|
||||||
|
if (type == '-'.codeUnitAt(0)) {
|
||||||
|
final message = utf8.decode(
|
||||||
|
rest,
|
||||||
|
allowMalformed: true,
|
||||||
|
);
|
||||||
|
final i = message.indexOf(_whitespacePattern);
|
||||||
|
if (i != -1 && i + 1 < message.length) {
|
||||||
|
return RedisCommandException._(
|
||||||
|
message.substring(0, i),
|
||||||
|
message.substring(i + 1),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return RedisCommandException._('ERR', message);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle integers
|
||||||
|
if (type == ':'.codeUnitAt(0)) {
|
||||||
|
int value;
|
||||||
|
try {
|
||||||
|
value = int.parse(ascii.decode(rest));
|
||||||
|
} on FormatException catch (e) {
|
||||||
|
throw RedisConnectionException._(
|
||||||
|
'Invalid integer from server: $e',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (value < 0) {
|
||||||
|
throw RedisConnectionException._(
|
||||||
|
'Invalid integer from server: value < 0',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle bulk strings (binary blobs)
|
||||||
|
if (type == r'$'.codeUnitAt(0)) {
|
||||||
|
int length;
|
||||||
|
try {
|
||||||
|
length = int.parse(ascii.decode(rest));
|
||||||
|
} on FormatException catch (e) {
|
||||||
|
throw RedisConnectionException._(
|
||||||
|
'Invalid bulk string length from server: $e',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (length == -1) {
|
||||||
|
return null; // Special case for nil value
|
||||||
|
}
|
||||||
|
if (length < 0 || length > _maxValueSize) {
|
||||||
|
throw RedisConnectionException._(
|
||||||
|
'Invalid bulk string length from server: $length',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Uint8List bytes;
|
||||||
|
try {
|
||||||
|
bytes = await _input.readBytes(length + 2);
|
||||||
|
} on Exception catch (e, st) {
|
||||||
|
await _abort(e, st);
|
||||||
|
throw RedisConnectionException._('exception reading bytes: $e');
|
||||||
|
}
|
||||||
|
if (bytes.length != length + 2) {
|
||||||
|
throw RedisConnectionException._('Incoming stream from server closed');
|
||||||
|
}
|
||||||
|
if (!_endsWithNewLine(bytes)) {
|
||||||
|
throw RedisConnectionException._('Invalid bulk string from server');
|
||||||
|
}
|
||||||
|
return Uint8List.sublistView(bytes, 0, length);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle arrays
|
||||||
|
if (type == '*'.codeUnitAt(0)) {
|
||||||
|
int length;
|
||||||
|
try {
|
||||||
|
length = int.parse(ascii.decode(rest));
|
||||||
|
} on FormatException catch (e) {
|
||||||
|
throw RedisConnectionException._(
|
||||||
|
'Invalid array length from server: $e',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (length == -1) {
|
||||||
|
return null; // Special case for nil value
|
||||||
|
}
|
||||||
|
if (length < 0) {
|
||||||
|
throw RedisConnectionException._(
|
||||||
|
'Invalid array length from server: $length',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
final values = <Object?>[];
|
||||||
|
for (var i = 0; i < length; i++) {
|
||||||
|
values.add(await _readValue());
|
||||||
|
}
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
throw RedisConnectionException._(
|
||||||
|
'Unknown type from server: ${String.fromCharCode(type)}',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool _endsWithNewLine(Uint8List line) {
|
||||||
|
final N = line.length;
|
||||||
|
return (N >= 2 &&
|
||||||
|
line[N - 2] == '\r'.codeUnitAt(0) &&
|
||||||
|
line[N - 1] == '\n'.codeUnitAt(0));
|
||||||
|
}
|
||||||
|
|
||||||
|
/// An stream wrapper for reading line-by-line or reading N bytes.
|
||||||
|
class _ByteStreamScanner {
|
||||||
|
static final _emptyList = Uint8List.fromList([]);
|
||||||
|
|
||||||
|
final StreamIterator<Uint8List> _input;
|
||||||
|
Uint8List _buffer = _emptyList;
|
||||||
|
|
||||||
|
_ByteStreamScanner(Stream<Uint8List> stream)
|
||||||
|
: _input = StreamIterator(stream);
|
||||||
|
|
||||||
|
/// Read a single byte, return zero if stream has ended.
|
||||||
|
Future<int?> readByte() async {
|
||||||
|
final bytes = await readBytes(1);
|
||||||
|
if (bytes.isEmpty) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return bytes[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read up to [size] bytes from stream, returns less than [size] bytes if
|
||||||
|
/// stream ends before [size] bytes are read.
|
||||||
|
Future<Uint8List> readBytes(int size) async {
|
||||||
|
RangeError.checkNotNegative(size, 'size');
|
||||||
|
|
||||||
|
final out = BytesBuilder(copy: false);
|
||||||
|
while (size > 0) {
|
||||||
|
if (_buffer.isEmpty) {
|
||||||
|
if (!(await _input.moveNext())) {
|
||||||
|
// Don't attempt to read more data, as there is no more data.
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_buffer = _input.current;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_buffer.isNotEmpty) {
|
||||||
|
if (size < _buffer.length) {
|
||||||
|
out.add(Uint8List.sublistView(_buffer, 0, size));
|
||||||
|
_buffer = Uint8List.sublistView(_buffer, size);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
out.add(_buffer);
|
||||||
|
size -= _buffer.length;
|
||||||
|
_buffer = _emptyList;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return out.toBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Read until the next `\n` inclusive.
|
||||||
|
///
|
||||||
|
/// Throws [RedisConnectionException] if [maxSize] is exceeded.
|
||||||
|
Future<Uint8List> readLine({int? maxSize}) async {
|
||||||
|
if (maxSize != null) {
|
||||||
|
RangeError.checkNotNegative(maxSize, 'maxSize');
|
||||||
|
}
|
||||||
|
|
||||||
|
final out = BytesBuilder(copy: false);
|
||||||
|
while (true) {
|
||||||
|
if (_buffer.isEmpty) {
|
||||||
|
if (!(await _input.moveNext())) {
|
||||||
|
// Don't attempt to read more data, as there is no more data.
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
_buffer = _input.current;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (_buffer.isNotEmpty) {
|
||||||
|
final i = _buffer.indexOf('\n'.codeUnitAt(0));
|
||||||
|
if (i != -1) {
|
||||||
|
out.add(Uint8List.sublistView(_buffer, 0, i + 1));
|
||||||
|
_buffer = Uint8List.sublistView(_buffer, i + 1);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
out.add(_buffer);
|
||||||
|
_buffer = _emptyList;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (maxSize != null && out.length > maxSize) {
|
||||||
|
throw RedisConnectionException._('Line exceeds maxSize: $maxSize');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return out.toBytes();
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Cancel underlying stream, ending it prematurely.
|
||||||
|
Future<void> cancel() async => await _input.cancel();
|
||||||
|
}
|
||||||
@ -0,0 +1,18 @@
|
|||||||
|
name: neat_cache
|
||||||
|
version: 2.0.1
|
||||||
|
description: |
|
||||||
|
A neat cache abstraction for wrapping in-memory or redis caches.
|
||||||
|
homepage: https://github.com/google/dart-neats/tree/master/neat_cache
|
||||||
|
repository: https://github.com/google/dart-neats.git
|
||||||
|
issue_tracker: https://github.com/google/dart-neats/labels/pkg:neat_cache
|
||||||
|
dependencies:
|
||||||
|
convert: ^3.0.0
|
||||||
|
logging: ^1.0.1
|
||||||
|
retry: ^3.0.0
|
||||||
|
async: ^2.7.0
|
||||||
|
meta: ^1.4.0
|
||||||
|
dev_dependencies:
|
||||||
|
test: ^1.5.1
|
||||||
|
pedantic: ^1.4.0
|
||||||
|
environment:
|
||||||
|
sdk: '>=2.12.0 <3.0.0'
|
||||||
@ -0,0 +1,12 @@
|
|||||||
|
Primary Authors
|
||||||
|
===============
|
||||||
|
|
||||||
|
* __[Thomas Hii](dukefirehawk.apps@gmail.com)__
|
||||||
|
|
||||||
|
Thomas is the current maintainer of the code base. He has refactored and migrated the
|
||||||
|
code base to support NNBD.
|
||||||
|
|
||||||
|
* __[Tobe O](thosakwe@gmail.com)__
|
||||||
|
|
||||||
|
Tobe has written much of the original code prior to NNBD migration. He has moved on and
|
||||||
|
is no longer involved with the project.
|
||||||
@ -0,0 +1,9 @@
|
|||||||
|
# Change Log
|
||||||
|
|
||||||
|
## 1.0.0
|
||||||
|
|
||||||
|
* Changed to use `angel3` packages
|
||||||
|
* Updated to support NNBD
|
||||||
|
* Updated README
|
||||||
|
* Updated default `postgresql` setup
|
||||||
|
* Updated linter to `package:lints`
|
||||||
@ -0,0 +1,24 @@
|
|||||||
|
# Contribution
|
||||||
|
|
||||||
|
Any help from the open-source community is always welcome and needed:
|
||||||
|
|
||||||
|
1. Found an issue?
|
||||||
|
- Please [fill a bug report][tracker] with error message and steps to reproduce it.
|
||||||
|
2. Wish a feature?
|
||||||
|
- Open a feature request with use cases.
|
||||||
|
3. Are you using and liking the project?
|
||||||
|
- Create an article about your use case
|
||||||
|
- Do a post on your likes and dislikes
|
||||||
|
- Make a donation.
|
||||||
|
4. Are you a developer?
|
||||||
|
- Fix a bug and send a [pull request][pull_request]
|
||||||
|
- Implement a new feature
|
||||||
|
- Improve the Unit Tests
|
||||||
|
- Improve the [User Guide][doc] and send a [document pull request][doc_repo]
|
||||||
|
5. Have you already helped in any way?
|
||||||
|
- **Many thanks to the contributors and everybody that uses this project!**
|
||||||
|
|
||||||
|
[tracker]: https://github.com/dukefirehawk/angel/issues
|
||||||
|
[pull_request]: https://github.com/dukefirehawk/angel/pulls
|
||||||
|
[doc]: https://angel3-docs.dukefirehawk.com
|
||||||
|
[doc_repo]: https://github.com/dukefirehawk/angel3-guide/pulls
|
||||||
@ -0,0 +1,14 @@
|
|||||||
|
FROM google/dart:latest
|
||||||
|
|
||||||
|
COPY ./ ./
|
||||||
|
|
||||||
|
# Install dependencies, pre-build
|
||||||
|
RUN pub get
|
||||||
|
|
||||||
|
# Optionally build generaed sources.
|
||||||
|
# RUN pub run build_runner build
|
||||||
|
|
||||||
|
# Set environment, start server
|
||||||
|
ENV ANGEL_ENV=production
|
||||||
|
EXPOSE 3000
|
||||||
|
CMD dart bin/prod.dart
|
||||||
@ -0,0 +1,29 @@
|
|||||||
|
BSD 3-Clause License
|
||||||
|
|
||||||
|
Copyright (c) 2021, dukefirehawk.com
|
||||||
|
All rights reserved.
|
||||||
|
|
||||||
|
Redistribution and use in source and binary forms, with or without
|
||||||
|
modification, are permitted provided that the following conditions are met:
|
||||||
|
|
||||||
|
1. Redistributions of source code must retain the above copyright notice, this
|
||||||
|
list of conditions and the following disclaimer.
|
||||||
|
|
||||||
|
2. Redistributions in binary form must reproduce the above copyright notice,
|
||||||
|
this list of conditions and the following disclaimer in the documentation
|
||||||
|
and/or other materials provided with the distribution.
|
||||||
|
|
||||||
|
3. Neither the name of the copyright holder nor the names of its
|
||||||
|
contributors may be used to endorse or promote products derived from
|
||||||
|
this software without specific prior written permission.
|
||||||
|
|
||||||
|
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||||
|
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||||
|
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||||
|
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||||
|
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||||
|
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||||
|
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||||
|
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||||
|
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||||
|
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||||
@ -1,37 +1,62 @@
|
|||||||
# dde_gesture_manager
|
# ORM Starter Application for Angel3 framework
|
||||||
|
|
||||||
## Running the Application Locally
|
This is an ORM starter application for [Angel3 framework](https://angel3-framework.web.app) which is a full-stack Web framework in Dart. The default database is `postgresql`. `mysql` support is still in active development.
|
||||||
|
|
||||||
Run `conduit serve` from this directory to run the application. For running within an IDE, run `bin/main.dart`. By default, a configuration file named `config.yaml` will be used.
|
## Installation & Setup
|
||||||
|
|
||||||
You must have a `config.yaml` file that has correct database connection info, which should point to a local database. To configure a database to match your application's schema, run the following commands:
|
1. Download and install [Dart](https://dart.dev/get-dart).
|
||||||
|
2. Install `postgresql` version 9, 10, 11 or 12. **postgresql 13 is not working as the driver do not support SCRAM**
|
||||||
|
3. Create a new user and database in postgres using `psql` cli. For example:
|
||||||
|
|
||||||
```
|
```sql
|
||||||
# if this is a project, run db generate first
|
postgres=# create database appdb;
|
||||||
conduit db generate
|
postgres=# create user appuser with encrypted password 'App1970#';
|
||||||
conduit db upgrade --connect postgres://user:password@localhost:5432/app_name
|
postgres=# grant all privileges on database appdb to appuser;
|
||||||
```
|
```
|
||||||
|
|
||||||
To generate a SwaggerUI client, run `conduit document client`.
|
4. Update the `postgres` section in the `config/default.yaml` file with the newly created user and database name.
|
||||||
|
|
||||||
## Running Application Tests
|
```yaml
|
||||||
|
postgres:
|
||||||
|
host: localhost
|
||||||
|
port: 5432
|
||||||
|
database_name: appdb
|
||||||
|
username: appuser
|
||||||
|
password: App1970#
|
||||||
|
useSSL: false
|
||||||
|
time_zone: UTC
|
||||||
|
```
|
||||||
|
|
||||||
Tests are run with a local PostgreSQL database named `conduit_test_db`. If this database does not exist, create it from your SQL prompt:
|
5. Run the migration to generate `migrations` and `greetings` tables in the database.
|
||||||
|
|
||||||
CREATE DATABASE conduit_test_db;
|
```bash
|
||||||
CREATE USER conduit_test_user WITH createdb;
|
dart bin/migration.dart
|
||||||
ALTER USER conduit_test_user WITH password 'conduit!';
|
```
|
||||||
GRANT all ON DATABASE conduit_test_db TO conduit_test_user;
|
|
||||||
|
|
||||||
|
### Development
|
||||||
|
|
||||||
To run all tests for this application, run the following in this directory:
|
1. Run the following command to start Angel3 server in dev mode to *hot-reloaded* on file changes:
|
||||||
|
|
||||||
```
|
```bash
|
||||||
pub run test
|
dart --observe bin/dev.dart
|
||||||
```
|
```
|
||||||
|
|
||||||
The default configuration file used when testing is `config.src.yaml`. This file should be checked into version control. It also the template for configuration files used in deployment.
|
2. Modify the code and watch the changes applied to the application
|
||||||
|
|
||||||
## Deploying an Application
|
### Production
|
||||||
|
|
||||||
See the documentation for [Deployment](https://conduit.io/docs/deploy/).
|
1. Run the following command:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
dart bin/prod.dart
|
||||||
|
```
|
||||||
|
|
||||||
|
2. Run as docker. Edit and run the provided `Dockerfile` to build the image.
|
||||||
|
|
||||||
|
## Resources
|
||||||
|
|
||||||
|
Visit the [Developer Guide](https://angel3-docs.dukefirehawk.com/guides) for dozens of guides and resources, including video tutorials, to get up and running as quickly as possible with Angel3.
|
||||||
|
|
||||||
|
Examples and complete projects can be found [here](https://angel3-framework.web.app/#/examples).
|
||||||
|
|
||||||
|
You can also view the [API Documentation](https://pub.dev/documentation/angel3_framework/latest/).
|
||||||
|
|||||||
@ -1,98 +1,7 @@
|
|||||||
analyzer:
|
include: package:lints/recommended.yaml
|
||||||
strong-mode:
|
|
||||||
implicit-casts: false
|
|
||||||
|
|
||||||
linter:
|
linter:
|
||||||
rules:
|
rules:
|
||||||
- always_declare_return_types
|
avoid_renaming_method_parameters: false
|
||||||
- always_put_control_body_on_new_line
|
overridden_fields: false
|
||||||
- always_put_required_named_parameters_first
|
unnecessary_statements: true
|
||||||
- always_require_non_null_named_parameters
|
|
||||||
- annotate_overrides
|
|
||||||
- avoid_bool_literals_in_conditional_expressions
|
|
||||||
- avoid_double_and_int_checks
|
|
||||||
- avoid_empty_else
|
|
||||||
- avoid_field_initializers_in_const_classes
|
|
||||||
- avoid_init_to_null
|
|
||||||
- avoid_null_checks_in_equality_operators
|
|
||||||
- avoid_positional_boolean_parameters
|
|
||||||
- avoid_relative_lib_imports
|
|
||||||
- avoid_renaming_method_parameters
|
|
||||||
- avoid_return_types_on_setters
|
|
||||||
- avoid_returning_null
|
|
||||||
- avoid_single_cascade_in_expression_statements
|
|
||||||
- avoid_slow_async_io
|
|
||||||
- avoid_types_as_parameter_names
|
|
||||||
- avoid_unused_constructor_parameters
|
|
||||||
- await_only_futures
|
|
||||||
- camel_case_types
|
|
||||||
- cancel_subscriptions
|
|
||||||
- close_sinks
|
|
||||||
- comment_references
|
|
||||||
- constant_identifier_names
|
|
||||||
- control_flow_in_finally
|
|
||||||
- directives_ordering
|
|
||||||
- empty_catches
|
|
||||||
- empty_constructor_bodies
|
|
||||||
- empty_statements
|
|
||||||
- hash_and_equals
|
|
||||||
- implementation_imports
|
|
||||||
- invariant_booleans
|
|
||||||
- iterable_contains_unrelated_type
|
|
||||||
- join_return_with_assignment
|
|
||||||
- library_names
|
|
||||||
- library_prefixes
|
|
||||||
- list_remove_unrelated_type
|
|
||||||
- literal_only_boolean_expressions
|
|
||||||
- no_duplicate_case_values
|
|
||||||
- non_constant_identifier_names
|
|
||||||
- null_closures
|
|
||||||
- package_api_docs
|
|
||||||
- package_names
|
|
||||||
- package_prefixed_library_names
|
|
||||||
- parameter_assignments
|
|
||||||
- prefer_adjacent_string_concatenation
|
|
||||||
- prefer_asserts_in_initializer_lists
|
|
||||||
- prefer_collection_literals
|
|
||||||
- prefer_conditional_assignment
|
|
||||||
- prefer_const_constructors
|
|
||||||
- prefer_const_constructors_in_immutables
|
|
||||||
- prefer_const_declarations
|
|
||||||
- prefer_const_literals_to_create_immutables
|
|
||||||
- prefer_constructors_over_static_methods
|
|
||||||
- prefer_contains
|
|
||||||
- prefer_equal_for_default_values
|
|
||||||
- prefer_final_fields
|
|
||||||
- prefer_final_locals
|
|
||||||
- prefer_foreach
|
|
||||||
- prefer_generic_function_type_aliases
|
|
||||||
- prefer_interpolation_to_compose_strings
|
|
||||||
- prefer_is_empty
|
|
||||||
- prefer_is_not_empty
|
|
||||||
- prefer_iterable_whereType
|
|
||||||
- prefer_typing_uninitialized_variables
|
|
||||||
- recursive_getters
|
|
||||||
- slash_for_doc_comments
|
|
||||||
- sort_constructors_first
|
|
||||||
- sort_unnamed_constructors_first
|
|
||||||
- test_types_in_equals
|
|
||||||
- throw_in_finally
|
|
||||||
- type_annotate_public_apis
|
|
||||||
- type_init_formals
|
|
||||||
- unawaited_futures
|
|
||||||
- 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
|
|
||||||
- use_string_buffers
|
|
||||||
- use_to_and_as_if_applicable
|
|
||||||
- valid_regexps
|
|
||||||
- void_checks
|
|
||||||
|
|||||||
@ -0,0 +1,28 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
import 'package:dde_gesture_manager_api/dde_gesture_manager_api.dart';
|
||||||
|
import 'package:belatuk_pretty_logging/belatuk_pretty_logging.dart';
|
||||||
|
import 'package:angel3_container/mirrors.dart';
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:angel3_hot/angel3_hot.dart';
|
||||||
|
import 'package:logging/logging.dart';
|
||||||
|
|
||||||
|
void main() async {
|
||||||
|
// Watch the config/ and web/ directories for changes, and hot-reload the server.
|
||||||
|
hierarchicalLoggingEnabled = true;
|
||||||
|
|
||||||
|
var hot = HotReloader(() async {
|
||||||
|
var logger = Logger.detached('dde_gesture_manager_api')
|
||||||
|
..level = Level.ALL
|
||||||
|
..onRecord.listen(prettyLog);
|
||||||
|
var app = Angel(logger: logger, reflector: MirrorsReflector());
|
||||||
|
await app.configure(configureServer);
|
||||||
|
return app;
|
||||||
|
}, [
|
||||||
|
Directory('config'),
|
||||||
|
Directory('lib'),
|
||||||
|
]);
|
||||||
|
|
||||||
|
var server = await hot.startServer('127.0.0.1', 3000);
|
||||||
|
print(
|
||||||
|
'dde_gesture_manager_api server listening at http://${server.address.address}:${server.port}');
|
||||||
|
}
|
||||||
@ -1,13 +0,0 @@
|
|||||||
import 'package:dde_gesture_manager/dde_gesture_manager.dart';
|
|
||||||
|
|
||||||
Future main() async {
|
|
||||||
final app = Application<DdeGestureManagerChannel>()
|
|
||||||
..options.configurationFilePath = "config.yaml"
|
|
||||||
..options.port = 8888;
|
|
||||||
|
|
||||||
await app.startOnCurrentIsolate();
|
|
||||||
|
|
||||||
print("Application started on port: ${app.options.port}.");
|
|
||||||
print("Click to open in browser: http://localhost:${app.options.port}");
|
|
||||||
print("Use Ctrl-C (SIGINT) to stop running the application.");
|
|
||||||
}
|
|
||||||
@ -0,0 +1,61 @@
|
|||||||
|
import 'package:angel3_migration/angel3_migration.dart';
|
||||||
|
import 'package:angel3_orm_postgres/angel3_orm_postgres.dart';
|
||||||
|
import 'package:dde_gesture_manager_api/src/config/plugins/orm.dart';
|
||||||
|
import 'package:dde_gesture_manager_api/models.dart';
|
||||||
|
import 'package:angel3_configuration/angel3_configuration.dart';
|
||||||
|
import 'package:angel3_migration_runner/angel3_migration_runner.dart';
|
||||||
|
import 'package:angel3_migration_runner/postgres.dart';
|
||||||
|
import 'package:file/local.dart';
|
||||||
|
import 'package:logging/logging.dart';
|
||||||
|
|
||||||
|
late Map configuration;
|
||||||
|
|
||||||
|
void main(List<String> args) async {
|
||||||
|
// Enable the logging
|
||||||
|
Logger.root.level = Level.INFO;
|
||||||
|
Logger.root.onRecord.listen((rec) {
|
||||||
|
print('${rec.time}: ${rec.level.name}: ${rec.loggerName}: ${rec.message}');
|
||||||
|
|
||||||
|
if (rec.error != null) {
|
||||||
|
print(rec.error);
|
||||||
|
print(rec.stackTrace);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
var fs = LocalFileSystem();
|
||||||
|
configuration = await loadStandaloneConfiguration(fs);
|
||||||
|
var connection = await connectToPostgres(configuration);
|
||||||
|
var migrationRunner = PostgresMigrationRunner(connection, migrations: [
|
||||||
|
UserMigration(),
|
||||||
|
UserSeed(),
|
||||||
|
]);
|
||||||
|
await runMigrations(migrationRunner, args);
|
||||||
|
}
|
||||||
|
|
||||||
|
class UserSeed extends Migration {
|
||||||
|
@override
|
||||||
|
void up(Schema schema) async {
|
||||||
|
await doUserSeed();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void down(Schema schema) async {}
|
||||||
|
}
|
||||||
|
|
||||||
|
Future doUserSeed() async {
|
||||||
|
var connection = await connectToPostgres(configuration);
|
||||||
|
await connection.open();
|
||||||
|
var executor = PostgreSqlExecutor(connection);
|
||||||
|
var userQuery = UserQuery();
|
||||||
|
userQuery.where?.email.equals('admin@admin.com');
|
||||||
|
var one = await userQuery.getOne(executor);
|
||||||
|
if (one.isEmpty) {
|
||||||
|
userQuery = UserQuery();
|
||||||
|
userQuery.values.copyFrom(User(
|
||||||
|
email: 'admin@admin.com',
|
||||||
|
password: '1234567890',
|
||||||
|
));
|
||||||
|
return userQuery.insert(executor).then((value) => connection.close());
|
||||||
|
}
|
||||||
|
return connection.close();
|
||||||
|
}
|
||||||
@ -0,0 +1,27 @@
|
|||||||
|
import 'package:dde_gesture_manager_api/dde_gesture_manager_api.dart';
|
||||||
|
import 'package:angel3_production/angel3_production.dart';
|
||||||
|
|
||||||
|
// NOTE: By default, the Runner class does not use the `MirrorsReflector`, or any
|
||||||
|
// reflector, by default.
|
||||||
|
//
|
||||||
|
// If your application is using any sort of functionality reliant on annotations or reflection,
|
||||||
|
// either include the MirrorsReflector, or use a static reflector variant.
|
||||||
|
//
|
||||||
|
// The following use cases require reflection:
|
||||||
|
// * Use of Controllers, via @Expose() or @ExposeWS()
|
||||||
|
// * Use of dependency injection into constructors, whether in controllers or plain `container.make` calls
|
||||||
|
// * Use of the `ioc` function in any route
|
||||||
|
//
|
||||||
|
// The `MirrorsReflector` from `package:angel_container/mirrors.dart` is by far the most convenient pattern,
|
||||||
|
// so use it if possible.
|
||||||
|
//
|
||||||
|
// However, the following alternatives exist:
|
||||||
|
// * Generation via `package:angel_container_generator`
|
||||||
|
// * Creating an instance of `StaticReflector`
|
||||||
|
// * Manually implementing the `Reflector` interface (cumbersome; not recommended)
|
||||||
|
//
|
||||||
|
// As of January 4th, 2018, the documentation has not yet been updated to state this,
|
||||||
|
// so in the meantime, visit the Angel chat for further questions:
|
||||||
|
//
|
||||||
|
// https://gitter.im/angel_dart/discussion
|
||||||
|
void main(List<String> args) => Runner('dde_gesture_manager_api', configureServer).run(args);
|
||||||
@ -1,6 +0,0 @@
|
|||||||
database:
|
|
||||||
username: conduit_test_user
|
|
||||||
password: conduit!
|
|
||||||
host: localhost
|
|
||||||
port: 15432 # change this value
|
|
||||||
databaseName: conduit_test_db
|
|
||||||
@ -0,0 +1,13 @@
|
|||||||
|
# Default server configuration.
|
||||||
|
host: 127.0.0.1
|
||||||
|
port: 3000
|
||||||
|
postgres:
|
||||||
|
host: localhost
|
||||||
|
port: 5432
|
||||||
|
database_name: appdb
|
||||||
|
username: appuser
|
||||||
|
password: App1970#
|
||||||
|
useSSL: false
|
||||||
|
time_zone: UTC
|
||||||
|
jwt_secret: "OvA9SBLnncot8gFHvt8Gh1qkQ1ptGIQW"
|
||||||
|
password_salt: "test"
|
||||||
@ -0,0 +1,96 @@
|
|||||||
|
class Apis {
|
||||||
|
static const apiScheme = 'http';
|
||||||
|
static const apiHost = '127.0.0.1';
|
||||||
|
static const apiPort = 3000;
|
||||||
|
|
||||||
|
static const appNewVersionUrl = 'https://www.debuggerx.com';
|
||||||
|
|
||||||
|
static final system = SystemApis();
|
||||||
|
static final auth = AuthApis();
|
||||||
|
}
|
||||||
|
|
||||||
|
class AuthApis {
|
||||||
|
static final String path = '/auth';
|
||||||
|
|
||||||
|
String get loginOrSignup => [path, 'login_or_signup'].joinPath();
|
||||||
|
|
||||||
|
String confirmSignup({required StringParam accessKey}) => [path, 'confirm_sign_up', accessKey].joinPath();
|
||||||
|
}
|
||||||
|
|
||||||
|
class SystemApis {
|
||||||
|
static final String path = '/system';
|
||||||
|
|
||||||
|
String get appVersion => [path, 'app-version'].joinPath();
|
||||||
|
}
|
||||||
|
|
||||||
|
final _paramsMap = {
|
||||||
|
'IntParam': IntParam.nameOnRoute,
|
||||||
|
'DoubleParam': DoubleParam.nameOnRoute,
|
||||||
|
'StringParam': StringParam.nameOnRoute,
|
||||||
|
};
|
||||||
|
|
||||||
|
extension JoinPath on List {
|
||||||
|
joinPath() => join('/');
|
||||||
|
}
|
||||||
|
|
||||||
|
extension RouteUrl on Function {
|
||||||
|
String get route {
|
||||||
|
var funStr = toString();
|
||||||
|
funStr = funStr.replaceAll(RegExp(r'.+\(\{'), ' ').replaceAll(RegExp(r'\}\).+'), ' ').replaceAll(' required ', '');
|
||||||
|
var parts = funStr.split(',');
|
||||||
|
Map<Symbol, dynamic> params = {};
|
||||||
|
for (var part in parts) {
|
||||||
|
var p = part.trim().split(' ');
|
||||||
|
params[Symbol(p.last)] = (_paramsMap[p.first] as Function).call(p.last);
|
||||||
|
}
|
||||||
|
return Function.apply(this, [], params);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class IntParam {
|
||||||
|
final int val;
|
||||||
|
String? name;
|
||||||
|
|
||||||
|
IntParam(this.val);
|
||||||
|
|
||||||
|
IntParam.nameOnRoute(this.name) : val = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => name == null ? val.toString() : 'int:$name';
|
||||||
|
}
|
||||||
|
|
||||||
|
class DoubleParam {
|
||||||
|
final double val;
|
||||||
|
String? name;
|
||||||
|
|
||||||
|
DoubleParam(this.val);
|
||||||
|
|
||||||
|
DoubleParam.nameOnRoute(this.name) : val = 0;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => name == null ? val.toString() : 'double:$name';
|
||||||
|
}
|
||||||
|
|
||||||
|
class StringParam {
|
||||||
|
final String val;
|
||||||
|
String? name;
|
||||||
|
|
||||||
|
StringParam(this.val);
|
||||||
|
|
||||||
|
StringParam.nameOnRoute(this.name) : val = '';
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => name == null ? val.toString() : ':$name';
|
||||||
|
}
|
||||||
|
|
||||||
|
extension IntParamExt on int {
|
||||||
|
IntParam get param => IntParam(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
extension DoubleParamExt on double {
|
||||||
|
DoubleParam get param => DoubleParam(this);
|
||||||
|
}
|
||||||
|
|
||||||
|
extension StringParamExt on String {
|
||||||
|
StringParam get param => StringParam(this);
|
||||||
|
}
|
||||||
@ -1,77 +0,0 @@
|
|||||||
import 'package:dde_gesture_manager/dde_gesture_manager.dart';
|
|
||||||
import 'package:dde_gesture_manager/model/model.dart';
|
|
||||||
|
|
||||||
/// This type initializes an application.
|
|
||||||
///
|
|
||||||
/// Override methods in this class to set up routes and initialize services like
|
|
||||||
/// database connections. See http://conduit.io/docs/http/channel/.
|
|
||||||
class DdeGestureManagerChannel extends ApplicationChannel {
|
|
||||||
late ManagedContext context;
|
|
||||||
|
|
||||||
/// Initialize services in this method.
|
|
||||||
///
|
|
||||||
/// Implement this method to initialize services, read values from [options]
|
|
||||||
/// and any other initialization required before constructing [entryPoint].
|
|
||||||
///
|
|
||||||
/// This method is invoked prior to [entryPoint] being accessed.
|
|
||||||
@override
|
|
||||||
Future prepare() async {
|
|
||||||
logger.onRecord.listen(
|
|
||||||
(rec) => print("$rec ${rec.error ?? ""} ${rec.stackTrace ?? ""}"));
|
|
||||||
|
|
||||||
final config =
|
|
||||||
DdeGestureManagerConfiguration(options!.configurationFilePath!);
|
|
||||||
context = contextWithConnectionInfo(config.database!);
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Construct the request channel.
|
|
||||||
///
|
|
||||||
/// Return an instance of some [Controller] that will be the initial receiver
|
|
||||||
/// of all [Request]s.
|
|
||||||
///
|
|
||||||
/// This method is invoked after [prepare].
|
|
||||||
@override
|
|
||||||
Controller get entryPoint {
|
|
||||||
final router = Router();
|
|
||||||
|
|
||||||
router
|
|
||||||
.route("/model/[:id]")
|
|
||||||
.link(() => ManagedObjectController<Model>(context));
|
|
||||||
|
|
||||||
router
|
|
||||||
.route("/")
|
|
||||||
.linkFunction((Request request) async => Response.ok('ok'));
|
|
||||||
|
|
||||||
return router;
|
|
||||||
}
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Helper methods
|
|
||||||
*/
|
|
||||||
|
|
||||||
ManagedContext contextWithConnectionInfo(
|
|
||||||
DatabaseConfiguration connectionInfo) {
|
|
||||||
final dataModel = ManagedDataModel.fromCurrentMirrorSystem();
|
|
||||||
final psc = PostgreSQLPersistentStore(
|
|
||||||
connectionInfo.username,
|
|
||||||
connectionInfo.password,
|
|
||||||
connectionInfo.host,
|
|
||||||
connectionInfo.port,
|
|
||||||
connectionInfo.databaseName);
|
|
||||||
|
|
||||||
return ManagedContext(dataModel, psc);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An instance of this class reads values from a configuration
|
|
||||||
/// file specific to this application.
|
|
||||||
///
|
|
||||||
/// Configuration files must have key-value for the properties in this class.
|
|
||||||
/// For more documentation on configuration files, see https://conduit.io/docs/configure/ and
|
|
||||||
/// https://pub.dartlang.org/packages/safe_config.
|
|
||||||
class DdeGestureManagerConfiguration extends Configuration {
|
|
||||||
DdeGestureManagerConfiguration(String fileName)
|
|
||||||
: super.fromFile(File(fileName));
|
|
||||||
|
|
||||||
DatabaseConfiguration? database;
|
|
||||||
}
|
|
||||||
@ -1,11 +0,0 @@
|
|||||||
/// dde_gesture_manager
|
|
||||||
///
|
|
||||||
/// A conduit web server.
|
|
||||||
library dde_gesture_manager;
|
|
||||||
|
|
||||||
export 'dart:async';
|
|
||||||
export 'dart:io';
|
|
||||||
|
|
||||||
export 'package:conduit/conduit.dart';
|
|
||||||
|
|
||||||
export 'channel.dart';
|
|
||||||
@ -0,0 +1,17 @@
|
|||||||
|
/// Your very own web application!
|
||||||
|
import 'dart:async';
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:file/local.dart';
|
||||||
|
import 'src/config/config.dart' as configuration;
|
||||||
|
import 'src/routes/routes.dart' as routes;
|
||||||
|
|
||||||
|
/// Configures the server instance.
|
||||||
|
Future configureServer(Angel app) async {
|
||||||
|
// Grab a handle to the file system, so that we can do things like
|
||||||
|
// serve static files.
|
||||||
|
var fs = const LocalFileSystem();
|
||||||
|
|
||||||
|
// Set up our application, using the plug-ins defined with this project.
|
||||||
|
await app.configure(configuration.configureServer(fs));
|
||||||
|
await app.configure(routes.configureServer(fs));
|
||||||
|
}
|
||||||
@ -1,18 +0,0 @@
|
|||||||
import 'package:dde_gesture_manager/dde_gesture_manager.dart';
|
|
||||||
|
|
||||||
class Model extends ManagedObject<_Model> implements _Model {
|
|
||||||
@override
|
|
||||||
void willInsert() {
|
|
||||||
createdAt = DateTime.now().toUtc();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class _Model {
|
|
||||||
@primaryKey
|
|
||||||
int? id;
|
|
||||||
|
|
||||||
@Column(indexed: true)
|
|
||||||
String? name;
|
|
||||||
|
|
||||||
DateTime? createdAt;
|
|
||||||
}
|
|
||||||
@ -0,0 +1,3 @@
|
|||||||
|
export 'src/models/user.dart';
|
||||||
|
export 'src/models/app_version.dart';
|
||||||
|
export 'src/models/login_success.dart';
|
||||||
@ -0,0 +1,30 @@
|
|||||||
|
import 'package:angel3_configuration/angel3_configuration.dart';
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:angel3_jinja/angel3_jinja.dart';
|
||||||
|
import 'package:file/file.dart';
|
||||||
|
import 'plugins/plugins.dart' as plugins;
|
||||||
|
|
||||||
|
/// This is a perfect place to include configuration and load plug-ins.
|
||||||
|
AngelConfigurer configureServer(FileSystem fileSystem) {
|
||||||
|
return (Angel app) async {
|
||||||
|
// Load configuration from the `config/` directory.
|
||||||
|
//
|
||||||
|
// See: https://github.com/angel-dart/configuration
|
||||||
|
await app.configure(configuration(fileSystem));
|
||||||
|
|
||||||
|
// Configure our application to render jinja templates from the `views/` directory.
|
||||||
|
//
|
||||||
|
// See: https://github.com/angel-dart/jinja
|
||||||
|
await app.configure(jinja(path: fileSystem.directory('views').path));
|
||||||
|
|
||||||
|
// Apply another plug-ins, i.e. ones that *you* have written.
|
||||||
|
//
|
||||||
|
// Typically, the plugins in `lib/src/config/plugins/plugins.dart` are plug-ins
|
||||||
|
// that add functionality specific to your application.
|
||||||
|
//
|
||||||
|
// If you write a plug-in that you plan to use again, or are
|
||||||
|
// using one created by the community, include it in
|
||||||
|
// `lib/src/config/config.dart`.
|
||||||
|
await plugins.configureServer(app);
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -0,0 +1,16 @@
|
|||||||
|
import 'package:angel3_auth/angel3_auth.dart';
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:angel3_orm/angel3_orm.dart' as orm;
|
||||||
|
import 'package:dde_gesture_manager_api/models.dart';
|
||||||
|
|
||||||
|
Future<void> configureServer(Angel app) async {
|
||||||
|
var auth = AngelAuth<User>(
|
||||||
|
jwtKey: app.configuration['jwt_secret'],
|
||||||
|
allowCookie: false,
|
||||||
|
deserializer: (p) async => (UserQuery()..where!.id.equals(int.parse(p)))
|
||||||
|
.getOne(app.container!.make<orm.QueryExecutor>())
|
||||||
|
.then((value) => value.value),
|
||||||
|
serializer: (p) => p.id ?? '',
|
||||||
|
);
|
||||||
|
await auth.configureServer(app);
|
||||||
|
}
|
||||||
@ -0,0 +1,35 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:io';
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:angel3_orm/angel3_orm.dart';
|
||||||
|
import 'package:angel3_orm_postgres/angel3_orm_postgres.dart';
|
||||||
|
import 'package:postgres/postgres.dart';
|
||||||
|
|
||||||
|
Future<void> configureServer(Angel app) async {
|
||||||
|
var connection = await connectToPostgres(app.configuration);
|
||||||
|
await connection.open();
|
||||||
|
|
||||||
|
var logger = app.environment.isProduction ? null : app.logger;
|
||||||
|
var executor = PostgreSqlExecutor(connection, logger: logger);
|
||||||
|
|
||||||
|
app
|
||||||
|
..container!.registerSingleton<QueryExecutor>(executor)
|
||||||
|
..shutdownHooks.add((_) => connection.close());
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<PostgreSQLConnection> connectToPostgres(Map configuration) async {
|
||||||
|
var postgresConfig = configuration['postgres'] as Map? ?? {};
|
||||||
|
var connection = PostgreSQLConnection(
|
||||||
|
postgresConfig['host'] as String? ?? 'localhost',
|
||||||
|
postgresConfig['port'] as int? ?? 5432,
|
||||||
|
postgresConfig['database_name'] as String? ??
|
||||||
|
Platform.environment['USER'] ??
|
||||||
|
Platform.environment['USERNAME'] ??
|
||||||
|
'',
|
||||||
|
username: postgresConfig['username'] as String?,
|
||||||
|
password: postgresConfig['password'] as String?,
|
||||||
|
timeZone: postgresConfig['time_zone'] as String? ?? 'UTC',
|
||||||
|
timeoutInSeconds: postgresConfig['timeout_in_seconds'] as int? ?? 30,
|
||||||
|
useSSL: postgresConfig['use_ssl'] as bool? ?? false);
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
@ -0,0 +1,12 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'orm.dart' as orm;
|
||||||
|
import 'jwt.dart' as jwt;
|
||||||
|
import 'redis_cache.dart' as redis_cache;
|
||||||
|
|
||||||
|
Future configureServer(Angel app) async {
|
||||||
|
// Include any plugins you have made here.
|
||||||
|
await app.configure(orm.configureServer);
|
||||||
|
await app.configure(jwt.configureServer);
|
||||||
|
await app.configure(redis_cache.configureServer);
|
||||||
|
}
|
||||||
@ -0,0 +1,36 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:logging/logging.dart';
|
||||||
|
import 'package:neat_cache/neat_cache.dart';
|
||||||
|
|
||||||
|
Future<void> configureServer(Angel app) async {
|
||||||
|
final _log = Logger('RedisPlugin');
|
||||||
|
|
||||||
|
if (app.container == null) {
|
||||||
|
_log.severe('Angel3 container is null');
|
||||||
|
throw StateError('Angel.container is null. All authentication will fail.');
|
||||||
|
}
|
||||||
|
var appContainer = app.container!;
|
||||||
|
final cache = RedisCache(app.configuration);
|
||||||
|
appContainer.registerSingleton(cache);
|
||||||
|
}
|
||||||
|
|
||||||
|
class RedisCache {
|
||||||
|
late Cache cache;
|
||||||
|
|
||||||
|
RedisCache(Map config) {
|
||||||
|
var redisConfig = config['redis'] as Map? ?? {};
|
||||||
|
|
||||||
|
final cacheProvider = Cache.redisCacheProvider(
|
||||||
|
Uri(
|
||||||
|
scheme: 'redis',
|
||||||
|
host: redisConfig['host'],
|
||||||
|
port: redisConfig['port'],
|
||||||
|
userInfo: redisConfig['password'],
|
||||||
|
),
|
||||||
|
commandTimeLimit: const Duration(seconds: 1),
|
||||||
|
);
|
||||||
|
cache = Cache(cacheProvider).withCodec(utf8);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,11 @@
|
|||||||
|
import 'package:angel3_serialize/angel3_serialize.dart';
|
||||||
|
part 'app_version.g.dart';
|
||||||
|
|
||||||
|
@serializable
|
||||||
|
abstract class _AppVersion {
|
||||||
|
@SerializableField(isNullable: false)
|
||||||
|
String? get versionName;
|
||||||
|
|
||||||
|
@SerializableField(isNullable: false)
|
||||||
|
int? get versionCode;
|
||||||
|
}
|
||||||
@ -0,0 +1,8 @@
|
|||||||
|
import 'package:angel3_orm/angel3_orm.dart';
|
||||||
|
import 'package:angel3_serialize/angel3_serialize.dart';
|
||||||
|
|
||||||
|
abstract class BaseModel extends Model {
|
||||||
|
@SerializableField(isNullable: true)
|
||||||
|
@Column(type: ColumnType.json)
|
||||||
|
Map<String, dynamic>? get metadata;
|
||||||
|
}
|
||||||
@ -0,0 +1,9 @@
|
|||||||
|
import 'package:angel3_serialize/angel3_serialize.dart';
|
||||||
|
|
||||||
|
part 'login_success.g.dart';
|
||||||
|
|
||||||
|
@serializable
|
||||||
|
class _LoginSuccess {
|
||||||
|
@SerializableField(isNullable: false)
|
||||||
|
String? token;
|
||||||
|
}
|
||||||
@ -0,0 +1,24 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:angel3_migration/angel3_migration.dart';
|
||||||
|
import 'package:angel3_serialize/angel3_serialize.dart';
|
||||||
|
import 'package:angel3_orm/angel3_orm.dart';
|
||||||
|
import 'package:dde_gesture_manager_api/src/models/base_model.dart';
|
||||||
|
import 'package:optional/optional.dart';
|
||||||
|
import 'package:crypto/crypto.dart';
|
||||||
|
|
||||||
|
part 'user.g.dart';
|
||||||
|
|
||||||
|
@serializable
|
||||||
|
@orm
|
||||||
|
abstract class _User extends BaseModel {
|
||||||
|
@Column(isNullable: false, indexType: IndexType.unique)
|
||||||
|
@SerializableField(isNullable: false)
|
||||||
|
String? get email;
|
||||||
|
|
||||||
|
@Column(isNullable: false, length: 32)
|
||||||
|
@SerializableField(isNullable: true, exclude: true)
|
||||||
|
String? get password;
|
||||||
|
|
||||||
|
String secret(String salt) => base64.encode(Hmac(sha256, salt.codeUnits).convert((password ?? '').codeUnits).bytes);
|
||||||
|
}
|
||||||
@ -0,0 +1,78 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'dart:convert';
|
||||||
|
|
||||||
|
import 'package:angel3_auth/angel3_auth.dart';
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:dde_gesture_manager_api/apis.dart';
|
||||||
|
import 'package:dde_gesture_manager_api/models.dart';
|
||||||
|
import 'package:mailer/mailer.dart';
|
||||||
|
import 'package:mailer/smtp_server.dart';
|
||||||
|
import 'package:uuid/uuid.dart';
|
||||||
|
|
||||||
|
import 'controller_extensions.dart';
|
||||||
|
|
||||||
|
Future configureServer(Angel app) async {
|
||||||
|
app.post(Apis.auth.loginOrSignup, (req, res) async {
|
||||||
|
var userParams = UserSerializer.fromMap(req.bodyAsMap);
|
||||||
|
userParams.password = req.bodyAsMap[UserFields.password];
|
||||||
|
var userQuery = UserQuery();
|
||||||
|
userQuery.where?.email.equals(userParams.email ?? '');
|
||||||
|
var user = await userQuery.getOne(req.queryExecutor);
|
||||||
|
|
||||||
|
if (user.isEmpty) {
|
||||||
|
String accessKey = Uuid().v1();
|
||||||
|
|
||||||
|
await req.cache
|
||||||
|
.withPrefix('sign_up:')[accessKey]
|
||||||
|
.set(json.encode({'email': userParams.email, 'password': userParams.password}), Duration(minutes: 30));
|
||||||
|
var smtpConfig = app.configuration['smtp'];
|
||||||
|
var smtpServer =
|
||||||
|
SmtpServer(smtpConfig['host'], ssl: true, username: smtpConfig['username'], password: smtpConfig['password']);
|
||||||
|
var message = Message()
|
||||||
|
..from = Address(smtpConfig['username'])
|
||||||
|
..recipients.add(userParams.email)
|
||||||
|
..subject = '确认注册'
|
||||||
|
..html = await app.viewGenerator!(
|
||||||
|
'confirm_sign_up.html',
|
||||||
|
{
|
||||||
|
"confirm_url": Uri(
|
||||||
|
scheme: Apis.apiScheme,
|
||||||
|
host: Apis.apiHost,
|
||||||
|
port: Apis.apiPort,
|
||||||
|
path: Apis.auth.confirmSignup(accessKey: accessKey.param),
|
||||||
|
),
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
send(message, smtpServer);
|
||||||
|
return res.notFound();
|
||||||
|
} else if (user.value.password != userParams.password) {
|
||||||
|
return res.unauthorized();
|
||||||
|
} else {
|
||||||
|
var angelAuth = req.container!.make<AngelAuth>();
|
||||||
|
await angelAuth.loginById(user.value.id!, req, res);
|
||||||
|
var authToken = req.container!.make<AuthToken>();
|
||||||
|
authToken.payload[UserFields.password] = user.value.secret(app.configuration['password_salt']);
|
||||||
|
var serializedToken = authToken.serialize(angelAuth.hmac);
|
||||||
|
return res.json(LoginSuccess(token: serializedToken));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
app.get(Apis.auth.confirmSignup.route, (req, res) async {
|
||||||
|
var accessKey = req.params['accessKey'];
|
||||||
|
var cache = req.cache.withPrefix('sign_up:');
|
||||||
|
var signupInfo = await cache[accessKey].get();
|
||||||
|
if (signupInfo != null && signupInfo is String && signupInfo.isNotEmpty) {
|
||||||
|
var decodedSignupInfo = json.decode(signupInfo);
|
||||||
|
var userQuery = UserQuery();
|
||||||
|
userQuery.values.copyFrom(User(
|
||||||
|
email: decodedSignupInfo[UserFields.email],
|
||||||
|
password: decodedSignupInfo[UserFields.password],
|
||||||
|
));
|
||||||
|
await userQuery.insert(req.queryExecutor);
|
||||||
|
cache[accessKey].purge();
|
||||||
|
return res.render('sign_up_result.html', {'success': true});
|
||||||
|
}
|
||||||
|
return res.render('sign_up_result.html', {'success': false});
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -0,0 +1,37 @@
|
|||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:angel3_orm/angel3_orm.dart' as orm;
|
||||||
|
import 'package:dde_gesture_manager_api/src/config/plugins/redis_cache.dart';
|
||||||
|
import 'package:neat_cache/neat_cache.dart';
|
||||||
|
|
||||||
|
extension ResponseNoContent on ResponseContext {
|
||||||
|
noContent() {
|
||||||
|
statusCode = HttpStatus.noContent;
|
||||||
|
return close();
|
||||||
|
}
|
||||||
|
|
||||||
|
notFound() {
|
||||||
|
statusCode = HttpStatus.notFound;
|
||||||
|
return close();
|
||||||
|
}
|
||||||
|
|
||||||
|
unauthorized() {
|
||||||
|
statusCode = HttpStatus.unauthorized;
|
||||||
|
return close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension QueryWhereId on orm.Query {
|
||||||
|
set whereId(int id) {
|
||||||
|
(where as dynamic).id.equals(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension QueryExecutor on RequestContext {
|
||||||
|
orm.QueryExecutor get queryExecutor => container!.make<orm.QueryExecutor>();
|
||||||
|
}
|
||||||
|
|
||||||
|
extension RedisExecutor on RequestContext {
|
||||||
|
Cache get cache => container!.make<RedisCache>().cache;
|
||||||
|
}
|
||||||
@ -0,0 +1,35 @@
|
|||||||
|
import 'package:angel3_auth/angel3_auth.dart';
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
|
||||||
|
import 'package:dde_gesture_manager_api/models.dart';
|
||||||
|
|
||||||
|
RequestHandler jwtMiddleware() {
|
||||||
|
return (RequestContext req, ResponseContext res, {bool throwError = true}) async {
|
||||||
|
bool _reject(ResponseContext res) {
|
||||||
|
if (throwError) {
|
||||||
|
res.statusCode = 403;
|
||||||
|
throw AngelHttpException.forbidden();
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.container != null) {
|
||||||
|
var reqContainer = req.container!;
|
||||||
|
if (reqContainer.has<User>() || req.method == 'OPTIONS') {
|
||||||
|
return true;
|
||||||
|
} else if (reqContainer.has<Future<User>>()) {
|
||||||
|
User user = await reqContainer.makeAsync<User>();
|
||||||
|
var authToken = req.container!.make<AuthToken>();
|
||||||
|
if (user.secret(req.app!.configuration['password_salt']) != authToken.payload[UserFields.password]) {
|
||||||
|
return _reject(res);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
return _reject(res);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return _reject(res);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -0,0 +1,26 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:dde_gesture_manager_api/apis.dart';
|
||||||
|
import 'package:dde_gesture_manager_api/src/models/app_version.dart';
|
||||||
|
import 'package:file/file.dart';
|
||||||
|
import 'package:yaml/yaml.dart';
|
||||||
|
|
||||||
|
late FileSystem fs;
|
||||||
|
|
||||||
|
Future configureServer(Angel app) async {
|
||||||
|
app.get(
|
||||||
|
Apis.system.appVersion,
|
||||||
|
(req, res) async {
|
||||||
|
var pubspec = fs.currentDirectory.parent.childDirectory('app').childFile('pubspec.yaml').readAsStringSync();
|
||||||
|
var version = loadYaml(pubspec)['version'] as String;
|
||||||
|
var versions = version.split('+');
|
||||||
|
return res.json(AppVersion(versionName: versions.first, versionCode: int.parse(versions.last)));
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
configureServerWithFileSystem(FileSystem fileSystem) {
|
||||||
|
fs = fileSystem;
|
||||||
|
return configureServer;
|
||||||
|
}
|
||||||
@ -0,0 +1,49 @@
|
|||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:file/file.dart';
|
||||||
|
import 'controllers/auth_controllers.dart' as auth_controllers;
|
||||||
|
import 'controllers/system_controllers.dart' as system_controllers;
|
||||||
|
|
||||||
|
/// Put your app routes here!
|
||||||
|
///
|
||||||
|
/// See the wiki for information about routing, requests, and responses:
|
||||||
|
/// * https://angel3-docs.dukefirehawk.com/guides/basic-routing
|
||||||
|
/// * https://angel3-docs.dukefirehawk.com/guides/requests-and-responses
|
||||||
|
|
||||||
|
AngelConfigurer configureServer(FileSystem fileSystem) {
|
||||||
|
return (Angel app) async {
|
||||||
|
// ParseBody middleware
|
||||||
|
app.fallback((req, res) async {
|
||||||
|
if (req.method == "POST") {
|
||||||
|
await req.parseBody();
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Typically, you want to mount controllers first, after any global middleware.
|
||||||
|
await app.configure(system_controllers.configureServerWithFileSystem(fileSystem));
|
||||||
|
await app.configure(auth_controllers.configureServer);
|
||||||
|
|
||||||
|
// Throw a 404 if no route matched the request.
|
||||||
|
app.fallback((req, res) => throw AngelHttpException.notFound());
|
||||||
|
|
||||||
|
// Set our application up to handle different errors.
|
||||||
|
//
|
||||||
|
// Read the following for documentation:
|
||||||
|
// * https://angel3-docs.dukefirehawk.com/guides/error-handling
|
||||||
|
|
||||||
|
var oldErrorHandler = app.errorHandler;
|
||||||
|
app.errorHandler = (e, req, res) async {
|
||||||
|
if (req.accepts('text/html', strict: true)) {
|
||||||
|
if (e.statusCode == 404 && req.accepts('text/html', strict: true)) {
|
||||||
|
await res.render('error.html', {'message': 'No router exists for ${req.uri}'});
|
||||||
|
} else {
|
||||||
|
return await res.render('error.html', {
|
||||||
|
'message': [e.message, '', e.stackTrace.toString().replaceAll('\n', '<br/>')].join('<br/>')
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return await oldErrorHandler(e, req, res);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
@ -1,13 +1,39 @@
|
|||||||
name: dde_gesture_manager
|
name: dde_gesture_manager_api
|
||||||
description: An conduit application with a database connection and data model.
|
version: 1.0.0
|
||||||
version: 0.0.1
|
description: An ORM starter application for Angel3 framework
|
||||||
|
publish_to: none
|
||||||
environment:
|
environment:
|
||||||
sdk: ">=2.12.0 <3.0.0"
|
sdk: '>=2.15.0 <3.0.0'
|
||||||
|
|
||||||
dependencies:
|
dependencies:
|
||||||
conduit: ^3.0.0
|
angel3_auth: ^4.0.0
|
||||||
|
angel3_configuration: ^4.1.0
|
||||||
|
angel3_framework: ^4.2.0
|
||||||
|
angel3_migration: ^4.0.0
|
||||||
|
angel3_orm: ^4.0.0
|
||||||
|
angel3_orm_postgres: ^3.0.0
|
||||||
|
angel3_serialize: ^4.1.0
|
||||||
|
angel3_production: ^3.1.0
|
||||||
|
angel3_static: ^4.1.0
|
||||||
|
angel3_validate: ^4.0.0
|
||||||
|
belatuk_pretty_logging: ^4.0.0
|
||||||
|
optional: ^6.0.0
|
||||||
|
logging: ^1.0.0
|
||||||
|
yaml: ^3.1.0
|
||||||
|
mailer: ^5.0.2
|
||||||
|
uuid: ^3.0.5
|
||||||
|
neat_cache:
|
||||||
|
path: 3rd_party/neat_cache
|
||||||
dev_dependencies:
|
dev_dependencies:
|
||||||
test: ^1.16.5
|
angel3_hot: ^4.2.0
|
||||||
conduit_test: ^3.0.0
|
angel3_jinja: ^2.0.1
|
||||||
|
angel3_migration_runner: ^4.0.0
|
||||||
|
angel3_orm_generator: ^4.1.0
|
||||||
|
angel3_serialize_generator: ^4.2.0
|
||||||
|
angel3_test: ^4.0.0
|
||||||
|
build_runner: ^2.0.3
|
||||||
|
io: ^1.0.0
|
||||||
|
test: ^1.17.5
|
||||||
|
lints: ^1.0.0
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -0,0 +1,4 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
|
||||||
|
dart pub get
|
||||||
|
dart run build_runner build
|
||||||
@ -0,0 +1,43 @@
|
|||||||
|
import 'package:dde_gesture_manager_api/dde_gesture_manager_api.dart';
|
||||||
|
import 'package:angel3_framework/angel3_framework.dart';
|
||||||
|
import 'package:angel3_test/angel3_test.dart';
|
||||||
|
import 'package:test/test.dart';
|
||||||
|
|
||||||
|
// Angel also includes facilities to make testing easier.
|
||||||
|
//
|
||||||
|
// `package:angel_test` ships a client that can test
|
||||||
|
// both plain HTTP and WebSockets.
|
||||||
|
//
|
||||||
|
// Tests do not require your server to actually be mounted on a port,
|
||||||
|
// so they will run faster than they would in other frameworks, where you
|
||||||
|
// would have to first bind a socket, and then account for network latency.
|
||||||
|
//
|
||||||
|
// See the documentation here:
|
||||||
|
// https://github.com/angel-dart/test
|
||||||
|
//
|
||||||
|
// If you are unfamiliar with Dart's advanced testing library, you can read up
|
||||||
|
// here:
|
||||||
|
// https://github.com/dart-lang/test
|
||||||
|
|
||||||
|
void main() async {
|
||||||
|
late TestClient client;
|
||||||
|
|
||||||
|
setUp(() async {
|
||||||
|
var app = Angel();
|
||||||
|
await app.configure(configureServer);
|
||||||
|
|
||||||
|
client = await connectTo(app);
|
||||||
|
});
|
||||||
|
|
||||||
|
tearDown(() async {
|
||||||
|
await client.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('index returns 200', () async {
|
||||||
|
// Request a resource at the given path.
|
||||||
|
var response = await client.get(Uri.parse('/'));
|
||||||
|
|
||||||
|
// Expect a 200 response.
|
||||||
|
expect(response, hasStatus(200));
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -1,38 +0,0 @@
|
|||||||
import 'package:conduit_test/conduit_test.dart';
|
|
||||||
import 'package:dde_gesture_manager/dde_gesture_manager.dart';
|
|
||||||
|
|
||||||
export 'package:conduit/conduit.dart';
|
|
||||||
export 'package:conduit_test/conduit_test.dart';
|
|
||||||
export 'package:dde_gesture_manager/dde_gesture_manager.dart';
|
|
||||||
export 'package:test/test.dart';
|
|
||||||
|
|
||||||
/// A testing harness for dde_gesture_manager.
|
|
||||||
///
|
|
||||||
/// A harness for testing an conduit application. Example test file:
|
|
||||||
///
|
|
||||||
/// void main() {
|
|
||||||
/// Harness harness = Harness()..install();
|
|
||||||
///
|
|
||||||
/// test("GET /path returns 200", () async {
|
|
||||||
/// final response = await harness.agent.get("/path");
|
|
||||||
/// expectResponse(response, 200);
|
|
||||||
/// });
|
|
||||||
/// }
|
|
||||||
///
|
|
||||||
class Harness extends TestHarness<DdeGestureManagerChannel> with TestHarnessORMMixin {
|
|
||||||
@override
|
|
||||||
ManagedContext? get context => channel?.context;
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future onSetUp() async {
|
|
||||||
await resetData();
|
|
||||||
}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future onTearDown() async {}
|
|
||||||
|
|
||||||
@override
|
|
||||||
Future seed() async {
|
|
||||||
// restore any static data. called by resetData.
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@ -1,32 +0,0 @@
|
|||||||
import 'harness/app.dart';
|
|
||||||
|
|
||||||
Future main() async {
|
|
||||||
final harness = Harness()..install();
|
|
||||||
|
|
||||||
tearDown(() async {
|
|
||||||
await harness.resetData();
|
|
||||||
});
|
|
||||||
|
|
||||||
test("POST /model", () async {
|
|
||||||
final response = await harness.agent!.post("/model", body: {"name": "Bob"});
|
|
||||||
expect(
|
|
||||||
response,
|
|
||||||
hasResponse(200,
|
|
||||||
body: {"id": isNotNull, "name": "Bob", "createdAt": isTimestamp}));
|
|
||||||
});
|
|
||||||
|
|
||||||
test("GET /model/:id returns previously created object", () async {
|
|
||||||
var response = await harness.agent!.post("/model", body: {"name": "Bob"});
|
|
||||||
|
|
||||||
final createdObject = response?.body.as();
|
|
||||||
response =
|
|
||||||
await harness.agent!.request("/model/${createdObject["id"]}").get();
|
|
||||||
expect(
|
|
||||||
response,
|
|
||||||
hasResponse(200, body: {
|
|
||||||
"id": createdObject["id"],
|
|
||||||
"name": createdObject["name"],
|
|
||||||
"createdAt": createdObject["createdAt"]
|
|
||||||
}));
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@ -0,0 +1,8 @@
|
|||||||
|
{% extends "layout.html" %}
|
||||||
|
{% block title %}确认注册{% endblock %}
|
||||||
|
{% block body %}
|
||||||
|
<h1>确认注册</h1>
|
||||||
|
<p>如果是您本人点击了《DDE手势管理器》的登录/注册按钮,并收到了本邮件,请点击下面的链接以完成注册,完成后请回到软件中使用之前填入的邮箱和密码登录账户。</p>
|
||||||
|
<p>如果您对上面的操作并不知情,则可能是其他用户错误使用了您的邮箱地址进行了注册,请无视本邮件,不要点击下面的链接,谢谢合作~</p>
|
||||||
|
<a href="{{ confirm_url }}">{{ confirm_url }}</a>
|
||||||
|
{% endblock %}
|
||||||
@ -0,0 +1,5 @@
|
|||||||
|
{% extends "layout.html" %}
|
||||||
|
{% block title %}Error{% endblock %}
|
||||||
|
{% block body %}
|
||||||
|
<p>Error: {{ message }}</p>
|
||||||
|
{% endblock %}
|
||||||
@ -0,0 +1,10 @@
|
|||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8" />
|
||||||
|
<title>{% block title %}{% endblock %}</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
{% block body %}{% endblock %}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@ -0,0 +1,16 @@
|
|||||||
|
{% extends "layout.html" %}
|
||||||
|
{% block title %}注册结果{% endblock %}
|
||||||
|
{% block body %}
|
||||||
|
<h1>注册结果</h1>
|
||||||
|
{% if success %}
|
||||||
|
<p>注册成功~</p>
|
||||||
|
{% else %}
|
||||||
|
<p>注册失败..</p>
|
||||||
|
<p>可能是因为:</p>
|
||||||
|
<ul>
|
||||||
|
<li>本链接已经超过三十分钟的有效期,请重新在软件中点击注册按钮</li>
|
||||||
|
<li>本链接已经被点击并注册成功,请勿重复点击</li>
|
||||||
|
<li>其他错误……非常抱歉,如果方便的话请通过邮件联系我~</li>
|
||||||
|
</ul>
|
||||||
|
{% endif%}
|
||||||
|
{% endblock %}
|
||||||
@ -0,0 +1,27 @@
|
|||||||
|
html, body {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
width: 100%;
|
||||||
|
display: table;
|
||||||
|
font-weight: 100;
|
||||||
|
font-family: 'Lato', sans-serif;
|
||||||
|
}
|
||||||
|
|
||||||
|
.container {
|
||||||
|
text-align: center;
|
||||||
|
display: table-cell;
|
||||||
|
vertical-align: middle;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content {
|
||||||
|
text-align: center;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.title {
|
||||||
|
font-size: 96px;
|
||||||
|
}
|
||||||
|
After Width: | Height: | Size: 10 KiB |
@ -1,29 +0,0 @@
|
|||||||
<!DOCTYPE html>
|
|
||||||
<html lang="en">
|
|
||||||
|
|
||||||
<head>
|
|
||||||
<meta charset="UTF-8">
|
|
||||||
<title>Login</title>
|
|
||||||
</head>
|
|
||||||
|
|
||||||
<body>
|
|
||||||
<div class="container">
|
|
||||||
<h1>Login</h1>
|
|
||||||
<form action="{{path}}" method="POST">
|
|
||||||
<input type="hidden" name="state" value="{{state}}">
|
|
||||||
<input type="hidden" name="client_id" value="{{client_id}}">
|
|
||||||
<input type="hidden" name="response_type" value="code">
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="username">User Name</label>
|
|
||||||
<input type="text" class="form-control" name="username" placeholder="Please enter your user name">
|
|
||||||
</div>
|
|
||||||
<div class="form-group">
|
|
||||||
<label for="password">Password</label>
|
|
||||||
<input type="password" class="form-control" name="password" placeholder="Please enter your password">
|
|
||||||
</div>
|
|
||||||
<button type="submit" class="btn btn-success">Login</button>
|
|
||||||
</form>
|
|
||||||
</div>
|
|
||||||
</body>
|
|
||||||
|
|
||||||
</html>
|
|
||||||
@ -0,0 +1,2 @@
|
|||||||
|
User-agent: *
|
||||||
|
Disallow: /admin
|
||||||
@ -0,0 +1,19 @@
|
|||||||
|
## [1.0.2] - 19/08/2021
|
||||||
|
|
||||||
|
* Add heartbeat animation on icon
|
||||||
|
* Customizable icon size and color
|
||||||
|
* Bug fixes
|
||||||
|
|
||||||
|
## [1.0.1] - 24/07/2021
|
||||||
|
|
||||||
|
* Add customizable border radius
|
||||||
|
|
||||||
|
## [1.0.0] - 20/07/2021
|
||||||
|
|
||||||
|
* Add support to all platforms
|
||||||
|
* Add support to null safety
|
||||||
|
* Add multiple built-in themes
|
||||||
|
* Add built-in animations
|
||||||
|
* Support LTR and RTL layout rendering
|
||||||
|
* Support Top and Bottom toast display
|
||||||
|
* Full customization to title, description and action components
|
||||||
@ -0,0 +1,674 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 3, 29 June 2007
|
||||||
|
|
||||||
|
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The GNU General Public License is a free, copyleft license for
|
||||||
|
software and other kinds of works.
|
||||||
|
|
||||||
|
The licenses for most software and other practical works are designed
|
||||||
|
to take away your freedom to share and change the works. By contrast,
|
||||||
|
the GNU General Public License is intended to guarantee your freedom to
|
||||||
|
share and change all versions of a program--to make sure it remains free
|
||||||
|
software for all its users. We, the Free Software Foundation, use the
|
||||||
|
GNU General Public License for most of our software; it applies also to
|
||||||
|
any other work released this way by its authors. You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
them if you wish), that you receive source code or can get it if you
|
||||||
|
want it, that you can change the software or use pieces of it in new
|
||||||
|
free programs, and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to prevent others from denying you
|
||||||
|
these rights or asking you to surrender the rights. Therefore, you have
|
||||||
|
certain responsibilities if you distribute copies of the software, or if
|
||||||
|
you modify it: responsibilities to respect the freedom of others.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must pass on to the recipients the same
|
||||||
|
freedoms that you received. You must make sure that they, too, receive
|
||||||
|
or can get the source code. And you must show them these terms so they
|
||||||
|
know their rights.
|
||||||
|
|
||||||
|
Developers that use the GNU GPL protect your rights with two steps:
|
||||||
|
(1) assert copyright on the software, and (2) offer you this License
|
||||||
|
giving you legal permission to copy, distribute and/or modify it.
|
||||||
|
|
||||||
|
For the developers' and authors' protection, the GPL clearly explains
|
||||||
|
that there is no warranty for this free software. For both users' and
|
||||||
|
authors' sake, the GPL requires that modified versions be marked as
|
||||||
|
changed, so that their problems will not be attributed erroneously to
|
||||||
|
authors of previous versions.
|
||||||
|
|
||||||
|
Some devices are designed to deny users access to install or run
|
||||||
|
modified versions of the software inside them, although the manufacturer
|
||||||
|
can do so. This is fundamentally incompatible with the aim of
|
||||||
|
protecting users' freedom to change the software. The systematic
|
||||||
|
pattern of such abuse occurs in the area of products for individuals to
|
||||||
|
use, which is precisely where it is most unacceptable. Therefore, we
|
||||||
|
have designed this version of the GPL to prohibit the practice for those
|
||||||
|
products. If such problems arise substantially in other domains, we
|
||||||
|
stand ready to extend this provision to those domains in future versions
|
||||||
|
of the GPL, as needed to protect the freedom of users.
|
||||||
|
|
||||||
|
Finally, every program is threatened constantly by software patents.
|
||||||
|
States should not allow patents to restrict development and use of
|
||||||
|
software on general-purpose computers, but in those that do, we wish to
|
||||||
|
avoid the special danger that patents applied to a free program could
|
||||||
|
make it effectively proprietary. To prevent this, the GPL assures that
|
||||||
|
patents cannot be used to render the program non-free.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
0. Definitions.
|
||||||
|
|
||||||
|
"This License" refers to version 3 of the GNU General Public License.
|
||||||
|
|
||||||
|
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||||
|
works, such as semiconductor masks.
|
||||||
|
|
||||||
|
"The Program" refers to any copyrightable work licensed under this
|
||||||
|
License. Each licensee is addressed as "you". "Licensees" and
|
||||||
|
"recipients" may be individuals or organizations.
|
||||||
|
|
||||||
|
To "modify" a work means to copy from or adapt all or part of the work
|
||||||
|
in a fashion requiring copyright permission, other than the making of an
|
||||||
|
exact copy. The resulting work is called a "modified version" of the
|
||||||
|
earlier work or a work "based on" the earlier work.
|
||||||
|
|
||||||
|
A "covered work" means either the unmodified Program or a work based
|
||||||
|
on the Program.
|
||||||
|
|
||||||
|
To "propagate" a work means to do anything with it that, without
|
||||||
|
permission, would make you directly or secondarily liable for
|
||||||
|
infringement under applicable copyright law, except executing it on a
|
||||||
|
computer or modifying a private copy. Propagation includes copying,
|
||||||
|
distribution (with or without modification), making available to the
|
||||||
|
public, and in some countries other activities as well.
|
||||||
|
|
||||||
|
To "convey" a work means any kind of propagation that enables other
|
||||||
|
parties to make or receive copies. Mere interaction with a user through
|
||||||
|
a computer network, with no transfer of a copy, is not conveying.
|
||||||
|
|
||||||
|
An interactive user interface displays "Appropriate Legal Notices"
|
||||||
|
to the extent that it includes a convenient and prominently visible
|
||||||
|
feature that (1) displays an appropriate copyright notice, and (2)
|
||||||
|
tells the user that there is no warranty for the work (except to the
|
||||||
|
extent that warranties are provided), that licensees may convey the
|
||||||
|
work under this License, and how to view a copy of this License. If
|
||||||
|
the interface presents a list of user commands or options, such as a
|
||||||
|
menu, a prominent item in the list meets this criterion.
|
||||||
|
|
||||||
|
1. Source Code.
|
||||||
|
|
||||||
|
The "source code" for a work means the preferred form of the work
|
||||||
|
for making modifications to it. "Object code" means any non-source
|
||||||
|
form of a work.
|
||||||
|
|
||||||
|
A "Standard Interface" means an interface that either is an official
|
||||||
|
standard defined by a recognized standards body, or, in the case of
|
||||||
|
interfaces specified for a particular programming language, one that
|
||||||
|
is widely used among developers working in that language.
|
||||||
|
|
||||||
|
The "System Libraries" of an executable work include anything, other
|
||||||
|
than the work as a whole, that (a) is included in the normal form of
|
||||||
|
packaging a Major Component, but which is not part of that Major
|
||||||
|
Component, and (b) serves only to enable use of the work with that
|
||||||
|
Major Component, or to implement a Standard Interface for which an
|
||||||
|
implementation is available to the public in source code form. A
|
||||||
|
"Major Component", in this context, means a major essential component
|
||||||
|
(kernel, window system, and so on) of the specific operating system
|
||||||
|
(if any) on which the executable work runs, or a compiler used to
|
||||||
|
produce the work, or an object code interpreter used to run it.
|
||||||
|
|
||||||
|
The "Corresponding Source" for a work in object code form means all
|
||||||
|
the source code needed to generate, install, and (for an executable
|
||||||
|
work) run the object code and to modify the work, including scripts to
|
||||||
|
control those activities. However, it does not include the work's
|
||||||
|
System Libraries, or general-purpose tools or generally available free
|
||||||
|
programs which are used unmodified in performing those activities but
|
||||||
|
which are not part of the work. For example, Corresponding Source
|
||||||
|
includes interface definition files associated with source files for
|
||||||
|
the work, and the source code for shared libraries and dynamically
|
||||||
|
linked subprograms that the work is specifically designed to require,
|
||||||
|
such as by intimate data communication or control flow between those
|
||||||
|
subprograms and other parts of the work.
|
||||||
|
|
||||||
|
The Corresponding Source need not include anything that users
|
||||||
|
can regenerate automatically from other parts of the Corresponding
|
||||||
|
Source.
|
||||||
|
|
||||||
|
The Corresponding Source for a work in source code form is that
|
||||||
|
same work.
|
||||||
|
|
||||||
|
2. Basic Permissions.
|
||||||
|
|
||||||
|
All rights granted under this License are granted for the term of
|
||||||
|
copyright on the Program, and are irrevocable provided the stated
|
||||||
|
conditions are met. This License explicitly affirms your unlimited
|
||||||
|
permission to run the unmodified Program. The output from running a
|
||||||
|
covered work is covered by this License only if the output, given its
|
||||||
|
content, constitutes a covered work. This License acknowledges your
|
||||||
|
rights of fair use or other equivalent, as provided by copyright law.
|
||||||
|
|
||||||
|
You may make, run and propagate covered works that you do not
|
||||||
|
convey, without conditions so long as your license otherwise remains
|
||||||
|
in force. You may convey covered works to others for the sole purpose
|
||||||
|
of having them make modifications exclusively for you, or provide you
|
||||||
|
with facilities for running those works, provided that you comply with
|
||||||
|
the terms of this License in conveying all material for which you do
|
||||||
|
not control copyright. Those thus making or running the covered works
|
||||||
|
for you must do so exclusively on your behalf, under your direction
|
||||||
|
and control, on terms that prohibit them from making any copies of
|
||||||
|
your copyrighted material outside their relationship with you.
|
||||||
|
|
||||||
|
Conveying under any other circumstances is permitted solely under
|
||||||
|
the conditions stated below. Sublicensing is not allowed; section 10
|
||||||
|
makes it unnecessary.
|
||||||
|
|
||||||
|
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||||
|
|
||||||
|
No covered work shall be deemed part of an effective technological
|
||||||
|
measure under any applicable law fulfilling obligations under article
|
||||||
|
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||||
|
similar laws prohibiting or restricting circumvention of such
|
||||||
|
measures.
|
||||||
|
|
||||||
|
When you convey a covered work, you waive any legal power to forbid
|
||||||
|
circumvention of technological measures to the extent such circumvention
|
||||||
|
is effected by exercising rights under this License with respect to
|
||||||
|
the covered work, and you disclaim any intention to limit operation or
|
||||||
|
modification of the work as a means of enforcing, against the work's
|
||||||
|
users, your or third parties' legal rights to forbid circumvention of
|
||||||
|
technological measures.
|
||||||
|
|
||||||
|
4. Conveying Verbatim Copies.
|
||||||
|
|
||||||
|
You may convey verbatim copies of the Program's source code as you
|
||||||
|
receive it, in any medium, provided that you conspicuously and
|
||||||
|
appropriately publish on each copy an appropriate copyright notice;
|
||||||
|
keep intact all notices stating that this License and any
|
||||||
|
non-permissive terms added in accord with section 7 apply to the code;
|
||||||
|
keep intact all notices of the absence of any warranty; and give all
|
||||||
|
recipients a copy of this License along with the Program.
|
||||||
|
|
||||||
|
You may charge any price or no price for each copy that you convey,
|
||||||
|
and you may offer support or warranty protection for a fee.
|
||||||
|
|
||||||
|
5. Conveying Modified Source Versions.
|
||||||
|
|
||||||
|
You may convey a work based on the Program, or the modifications to
|
||||||
|
produce it from the Program, in the form of source code under the
|
||||||
|
terms of section 4, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) The work must carry prominent notices stating that you modified
|
||||||
|
it, and giving a relevant date.
|
||||||
|
|
||||||
|
b) The work must carry prominent notices stating that it is
|
||||||
|
released under this License and any conditions added under section
|
||||||
|
7. This requirement modifies the requirement in section 4 to
|
||||||
|
"keep intact all notices".
|
||||||
|
|
||||||
|
c) You must license the entire work, as a whole, under this
|
||||||
|
License to anyone who comes into possession of a copy. This
|
||||||
|
License will therefore apply, along with any applicable section 7
|
||||||
|
additional terms, to the whole of the work, and all its parts,
|
||||||
|
regardless of how they are packaged. This License gives no
|
||||||
|
permission to license the work in any other way, but it does not
|
||||||
|
invalidate such permission if you have separately received it.
|
||||||
|
|
||||||
|
d) If the work has interactive user interfaces, each must display
|
||||||
|
Appropriate Legal Notices; however, if the Program has interactive
|
||||||
|
interfaces that do not display Appropriate Legal Notices, your
|
||||||
|
work need not make them do so.
|
||||||
|
|
||||||
|
A compilation of a covered work with other separate and independent
|
||||||
|
works, which are not by their nature extensions of the covered work,
|
||||||
|
and which are not combined with it such as to form a larger program,
|
||||||
|
in or on a volume of a storage or distribution medium, is called an
|
||||||
|
"aggregate" if the compilation and its resulting copyright are not
|
||||||
|
used to limit the access or legal rights of the compilation's users
|
||||||
|
beyond what the individual works permit. Inclusion of a covered work
|
||||||
|
in an aggregate does not cause this License to apply to the other
|
||||||
|
parts of the aggregate.
|
||||||
|
|
||||||
|
6. Conveying Non-Source Forms.
|
||||||
|
|
||||||
|
You may convey a covered work in object code form under the terms
|
||||||
|
of sections 4 and 5, provided that you also convey the
|
||||||
|
machine-readable Corresponding Source under the terms of this License,
|
||||||
|
in one of these ways:
|
||||||
|
|
||||||
|
a) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by the
|
||||||
|
Corresponding Source fixed on a durable physical medium
|
||||||
|
customarily used for software interchange.
|
||||||
|
|
||||||
|
b) Convey the object code in, or embodied in, a physical product
|
||||||
|
(including a physical distribution medium), accompanied by a
|
||||||
|
written offer, valid for at least three years and valid for as
|
||||||
|
long as you offer spare parts or customer support for that product
|
||||||
|
model, to give anyone who possesses the object code either (1) a
|
||||||
|
copy of the Corresponding Source for all the software in the
|
||||||
|
product that is covered by this License, on a durable physical
|
||||||
|
medium customarily used for software interchange, for a price no
|
||||||
|
more than your reasonable cost of physically performing this
|
||||||
|
conveying of source, or (2) access to copy the
|
||||||
|
Corresponding Source from a network server at no charge.
|
||||||
|
|
||||||
|
c) Convey individual copies of the object code with a copy of the
|
||||||
|
written offer to provide the Corresponding Source. This
|
||||||
|
alternative is allowed only occasionally and noncommercially, and
|
||||||
|
only if you received the object code with such an offer, in accord
|
||||||
|
with subsection 6b.
|
||||||
|
|
||||||
|
d) Convey the object code by offering access from a designated
|
||||||
|
place (gratis or for a charge), and offer equivalent access to the
|
||||||
|
Corresponding Source in the same way through the same place at no
|
||||||
|
further charge. You need not require recipients to copy the
|
||||||
|
Corresponding Source along with the object code. If the place to
|
||||||
|
copy the object code is a network server, the Corresponding Source
|
||||||
|
may be on a different server (operated by you or a third party)
|
||||||
|
that supports equivalent copying facilities, provided you maintain
|
||||||
|
clear directions next to the object code saying where to find the
|
||||||
|
Corresponding Source. Regardless of what server hosts the
|
||||||
|
Corresponding Source, you remain obligated to ensure that it is
|
||||||
|
available for as long as needed to satisfy these requirements.
|
||||||
|
|
||||||
|
e) Convey the object code using peer-to-peer transmission, provided
|
||||||
|
you inform other peers where the object code and Corresponding
|
||||||
|
Source of the work are being offered to the general public at no
|
||||||
|
charge under subsection 6d.
|
||||||
|
|
||||||
|
A separable portion of the object code, whose source code is excluded
|
||||||
|
from the Corresponding Source as a System Library, need not be
|
||||||
|
included in conveying the object code work.
|
||||||
|
|
||||||
|
A "User Product" is either (1) a "consumer product", which means any
|
||||||
|
tangible personal property which is normally used for personal, family,
|
||||||
|
or household purposes, or (2) anything designed or sold for incorporation
|
||||||
|
into a dwelling. In determining whether a product is a consumer product,
|
||||||
|
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||||
|
product received by a particular user, "normally used" refers to a
|
||||||
|
typical or common use of that class of product, regardless of the status
|
||||||
|
of the particular user or of the way in which the particular user
|
||||||
|
actually uses, or expects or is expected to use, the product. A product
|
||||||
|
is a consumer product regardless of whether the product has substantial
|
||||||
|
commercial, industrial or non-consumer uses, unless such uses represent
|
||||||
|
the only significant mode of use of the product.
|
||||||
|
|
||||||
|
"Installation Information" for a User Product means any methods,
|
||||||
|
procedures, authorization keys, or other information required to install
|
||||||
|
and execute modified versions of a covered work in that User Product from
|
||||||
|
a modified version of its Corresponding Source. The information must
|
||||||
|
suffice to ensure that the continued functioning of the modified object
|
||||||
|
code is in no case prevented or interfered with solely because
|
||||||
|
modification has been made.
|
||||||
|
|
||||||
|
If you convey an object code work under this section in, or with, or
|
||||||
|
specifically for use in, a User Product, and the conveying occurs as
|
||||||
|
part of a transaction in which the right of possession and use of the
|
||||||
|
User Product is transferred to the recipient in perpetuity or for a
|
||||||
|
fixed term (regardless of how the transaction is characterized), the
|
||||||
|
Corresponding Source conveyed under this section must be accompanied
|
||||||
|
by the Installation Information. But this requirement does not apply
|
||||||
|
if neither you nor any third party retains the ability to install
|
||||||
|
modified object code on the User Product (for example, the work has
|
||||||
|
been installed in ROM).
|
||||||
|
|
||||||
|
The requirement to provide Installation Information does not include a
|
||||||
|
requirement to continue to provide support service, warranty, or updates
|
||||||
|
for a work that has been modified or installed by the recipient, or for
|
||||||
|
the User Product in which it has been modified or installed. Access to a
|
||||||
|
network may be denied when the modification itself materially and
|
||||||
|
adversely affects the operation of the network or violates the rules and
|
||||||
|
protocols for communication across the network.
|
||||||
|
|
||||||
|
Corresponding Source conveyed, and Installation Information provided,
|
||||||
|
in accord with this section must be in a format that is publicly
|
||||||
|
documented (and with an implementation available to the public in
|
||||||
|
source code form), and must require no special password or key for
|
||||||
|
unpacking, reading or copying.
|
||||||
|
|
||||||
|
7. Additional Terms.
|
||||||
|
|
||||||
|
"Additional permissions" are terms that supplement the terms of this
|
||||||
|
License by making exceptions from one or more of its conditions.
|
||||||
|
Additional permissions that are applicable to the entire Program shall
|
||||||
|
be treated as though they were included in this License, to the extent
|
||||||
|
that they are valid under applicable law. If additional permissions
|
||||||
|
apply only to part of the Program, that part may be used separately
|
||||||
|
under those permissions, but the entire Program remains governed by
|
||||||
|
this License without regard to the additional permissions.
|
||||||
|
|
||||||
|
When you convey a copy of a covered work, you may at your option
|
||||||
|
remove any additional permissions from that copy, or from any part of
|
||||||
|
it. (Additional permissions may be written to require their own
|
||||||
|
removal in certain cases when you modify the work.) You may place
|
||||||
|
additional permissions on material, added by you to a covered work,
|
||||||
|
for which you have or can give appropriate copyright permission.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, for material you
|
||||||
|
add to a covered work, you may (if authorized by the copyright holders of
|
||||||
|
that material) supplement the terms of this License with terms:
|
||||||
|
|
||||||
|
a) Disclaiming warranty or limiting liability differently from the
|
||||||
|
terms of sections 15 and 16 of this License; or
|
||||||
|
|
||||||
|
b) Requiring preservation of specified reasonable legal notices or
|
||||||
|
author attributions in that material or in the Appropriate Legal
|
||||||
|
Notices displayed by works containing it; or
|
||||||
|
|
||||||
|
c) Prohibiting misrepresentation of the origin of that material, or
|
||||||
|
requiring that modified versions of such material be marked in
|
||||||
|
reasonable ways as different from the original version; or
|
||||||
|
|
||||||
|
d) Limiting the use for publicity purposes of names of licensors or
|
||||||
|
authors of the material; or
|
||||||
|
|
||||||
|
e) Declining to grant rights under trademark law for use of some
|
||||||
|
trade names, trademarks, or service marks; or
|
||||||
|
|
||||||
|
f) Requiring indemnification of licensors and authors of that
|
||||||
|
material by anyone who conveys the material (or modified versions of
|
||||||
|
it) with contractual assumptions of liability to the recipient, for
|
||||||
|
any liability that these contractual assumptions directly impose on
|
||||||
|
those licensors and authors.
|
||||||
|
|
||||||
|
All other non-permissive additional terms are considered "further
|
||||||
|
restrictions" within the meaning of section 10. If the Program as you
|
||||||
|
received it, or any part of it, contains a notice stating that it is
|
||||||
|
governed by this License along with a term that is a further
|
||||||
|
restriction, you may remove that term. If a license document contains
|
||||||
|
a further restriction but permits relicensing or conveying under this
|
||||||
|
License, you may add to a covered work material governed by the terms
|
||||||
|
of that license document, provided that the further restriction does
|
||||||
|
not survive such relicensing or conveying.
|
||||||
|
|
||||||
|
If you add terms to a covered work in accord with this section, you
|
||||||
|
must place, in the relevant source files, a statement of the
|
||||||
|
additional terms that apply to those files, or a notice indicating
|
||||||
|
where to find the applicable terms.
|
||||||
|
|
||||||
|
Additional terms, permissive or non-permissive, may be stated in the
|
||||||
|
form of a separately written license, or stated as exceptions;
|
||||||
|
the above requirements apply either way.
|
||||||
|
|
||||||
|
8. Termination.
|
||||||
|
|
||||||
|
You may not propagate or modify a covered work except as expressly
|
||||||
|
provided under this License. Any attempt otherwise to propagate or
|
||||||
|
modify it is void, and will automatically terminate your rights under
|
||||||
|
this License (including any patent licenses granted under the third
|
||||||
|
paragraph of section 11).
|
||||||
|
|
||||||
|
However, if you cease all violation of this License, then your
|
||||||
|
license from a particular copyright holder is reinstated (a)
|
||||||
|
provisionally, unless and until the copyright holder explicitly and
|
||||||
|
finally terminates your license, and (b) permanently, if the copyright
|
||||||
|
holder fails to notify you of the violation by some reasonable means
|
||||||
|
prior to 60 days after the cessation.
|
||||||
|
|
||||||
|
Moreover, your license from a particular copyright holder is
|
||||||
|
reinstated permanently if the copyright holder notifies you of the
|
||||||
|
violation by some reasonable means, this is the first time you have
|
||||||
|
received notice of violation of this License (for any work) from that
|
||||||
|
copyright holder, and you cure the violation prior to 30 days after
|
||||||
|
your receipt of the notice.
|
||||||
|
|
||||||
|
Termination of your rights under this section does not terminate the
|
||||||
|
licenses of parties who have received copies or rights from you under
|
||||||
|
this License. If your rights have been terminated and not permanently
|
||||||
|
reinstated, you do not qualify to receive new licenses for the same
|
||||||
|
material under section 10.
|
||||||
|
|
||||||
|
9. Acceptance Not Required for Having Copies.
|
||||||
|
|
||||||
|
You are not required to accept this License in order to receive or
|
||||||
|
run a copy of the Program. Ancillary propagation of a covered work
|
||||||
|
occurring solely as a consequence of using peer-to-peer transmission
|
||||||
|
to receive a copy likewise does not require acceptance. However,
|
||||||
|
nothing other than this License grants you permission to propagate or
|
||||||
|
modify any covered work. These actions infringe copyright if you do
|
||||||
|
not accept this License. Therefore, by modifying or propagating a
|
||||||
|
covered work, you indicate your acceptance of this License to do so.
|
||||||
|
|
||||||
|
10. Automatic Licensing of Downstream Recipients.
|
||||||
|
|
||||||
|
Each time you convey a covered work, the recipient automatically
|
||||||
|
receives a license from the original licensors, to run, modify and
|
||||||
|
propagate that work, subject to this License. You are not responsible
|
||||||
|
for enforcing compliance by third parties with this License.
|
||||||
|
|
||||||
|
An "entity transaction" is a transaction transferring control of an
|
||||||
|
organization, or substantially all assets of one, or subdividing an
|
||||||
|
organization, or merging organizations. If propagation of a covered
|
||||||
|
work results from an entity transaction, each party to that
|
||||||
|
transaction who receives a copy of the work also receives whatever
|
||||||
|
licenses to the work the party's predecessor in interest had or could
|
||||||
|
give under the previous paragraph, plus a right to possession of the
|
||||||
|
Corresponding Source of the work from the predecessor in interest, if
|
||||||
|
the predecessor has it or can get it with reasonable efforts.
|
||||||
|
|
||||||
|
You may not impose any further restrictions on the exercise of the
|
||||||
|
rights granted or affirmed under this License. For example, you may
|
||||||
|
not impose a license fee, royalty, or other charge for exercise of
|
||||||
|
rights granted under this License, and you may not initiate litigation
|
||||||
|
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||||
|
any patent claim is infringed by making, using, selling, offering for
|
||||||
|
sale, or importing the Program or any portion of it.
|
||||||
|
|
||||||
|
11. Patents.
|
||||||
|
|
||||||
|
A "contributor" is a copyright holder who authorizes use under this
|
||||||
|
License of the Program or a work on which the Program is based. The
|
||||||
|
work thus licensed is called the contributor's "contributor version".
|
||||||
|
|
||||||
|
A contributor's "essential patent claims" are all patent claims
|
||||||
|
owned or controlled by the contributor, whether already acquired or
|
||||||
|
hereafter acquired, that would be infringed by some manner, permitted
|
||||||
|
by this License, of making, using, or selling its contributor version,
|
||||||
|
but do not include claims that would be infringed only as a
|
||||||
|
consequence of further modification of the contributor version. For
|
||||||
|
purposes of this definition, "control" includes the right to grant
|
||||||
|
patent sublicenses in a manner consistent with the requirements of
|
||||||
|
this License.
|
||||||
|
|
||||||
|
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||||
|
patent license under the contributor's essential patent claims, to
|
||||||
|
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||||
|
propagate the contents of its contributor version.
|
||||||
|
|
||||||
|
In the following three paragraphs, a "patent license" is any express
|
||||||
|
agreement or commitment, however denominated, not to enforce a patent
|
||||||
|
(such as an express permission to practice a patent or covenant not to
|
||||||
|
sue for patent infringement). To "grant" such a patent license to a
|
||||||
|
party means to make such an agreement or commitment not to enforce a
|
||||||
|
patent against the party.
|
||||||
|
|
||||||
|
If you convey a covered work, knowingly relying on a patent license,
|
||||||
|
and the Corresponding Source of the work is not available for anyone
|
||||||
|
to copy, free of charge and under the terms of this License, through a
|
||||||
|
publicly available network server or other readily accessible means,
|
||||||
|
then you must either (1) cause the Corresponding Source to be so
|
||||||
|
available, or (2) arrange to deprive yourself of the benefit of the
|
||||||
|
patent license for this particular work, or (3) arrange, in a manner
|
||||||
|
consistent with the requirements of this License, to extend the patent
|
||||||
|
license to downstream recipients. "Knowingly relying" means you have
|
||||||
|
actual knowledge that, but for the patent license, your conveying the
|
||||||
|
covered work in a country, or your recipient's use of the covered work
|
||||||
|
in a country, would infringe one or more identifiable patents in that
|
||||||
|
country that you have reason to believe are valid.
|
||||||
|
|
||||||
|
If, pursuant to or in connection with a single transaction or
|
||||||
|
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||||
|
covered work, and grant a patent license to some of the parties
|
||||||
|
receiving the covered work authorizing them to use, propagate, modify
|
||||||
|
or convey a specific copy of the covered work, then the patent license
|
||||||
|
you grant is automatically extended to all recipients of the covered
|
||||||
|
work and works based on it.
|
||||||
|
|
||||||
|
A patent license is "discriminatory" if it does not include within
|
||||||
|
the scope of its coverage, prohibits the exercise of, or is
|
||||||
|
conditioned on the non-exercise of one or more of the rights that are
|
||||||
|
specifically granted under this License. You may not convey a covered
|
||||||
|
work if you are a party to an arrangement with a third party that is
|
||||||
|
in the business of distributing software, under which you make payment
|
||||||
|
to the third party based on the extent of your activity of conveying
|
||||||
|
the work, and under which the third party grants, to any of the
|
||||||
|
parties who would receive the covered work from you, a discriminatory
|
||||||
|
patent license (a) in connection with copies of the covered work
|
||||||
|
conveyed by you (or copies made from those copies), or (b) primarily
|
||||||
|
for and in connection with specific products or compilations that
|
||||||
|
contain the covered work, unless you entered into that arrangement,
|
||||||
|
or that patent license was granted, prior to 28 March 2007.
|
||||||
|
|
||||||
|
Nothing in this License shall be construed as excluding or limiting
|
||||||
|
any implied license or other defenses to infringement that may
|
||||||
|
otherwise be available to you under applicable patent law.
|
||||||
|
|
||||||
|
12. No Surrender of Others' Freedom.
|
||||||
|
|
||||||
|
If conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot convey a
|
||||||
|
covered work so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you may
|
||||||
|
not convey it at all. For example, if you agree to terms that obligate you
|
||||||
|
to collect a royalty for further conveying from those to whom you convey
|
||||||
|
the Program, the only way you could satisfy both those terms and this
|
||||||
|
License would be to refrain entirely from conveying the Program.
|
||||||
|
|
||||||
|
13. Use with the GNU Affero General Public License.
|
||||||
|
|
||||||
|
Notwithstanding any other provision of this License, you have
|
||||||
|
permission to link or combine any covered work with a work licensed
|
||||||
|
under version 3 of the GNU Affero General Public License into a single
|
||||||
|
combined work, and to convey the resulting work. The terms of this
|
||||||
|
License will continue to apply to the part which is the covered work,
|
||||||
|
but the special requirements of the GNU Affero General Public License,
|
||||||
|
section 13, concerning interaction through a network will apply to the
|
||||||
|
combination as such.
|
||||||
|
|
||||||
|
14. Revised Versions of this License.
|
||||||
|
|
||||||
|
The Free Software Foundation may publish revised and/or new versions of
|
||||||
|
the GNU General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the
|
||||||
|
Program specifies that a certain numbered version of the GNU General
|
||||||
|
Public License "or any later version" applies to it, you have the
|
||||||
|
option of following the terms and conditions either of that numbered
|
||||||
|
version or of any later version published by the Free Software
|
||||||
|
Foundation. If the Program does not specify a version number of the
|
||||||
|
GNU General Public License, you may choose any version ever published
|
||||||
|
by the Free Software Foundation.
|
||||||
|
|
||||||
|
If the Program specifies that a proxy can decide which future
|
||||||
|
versions of the GNU General Public License can be used, that proxy's
|
||||||
|
public statement of acceptance of a version permanently authorizes you
|
||||||
|
to choose that version for the Program.
|
||||||
|
|
||||||
|
Later license versions may give you additional or different
|
||||||
|
permissions. However, no additional obligations are imposed on any
|
||||||
|
author or copyright holder as a result of your choosing to follow a
|
||||||
|
later version.
|
||||||
|
|
||||||
|
15. Disclaimer of Warranty.
|
||||||
|
|
||||||
|
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||||
|
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||||
|
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||||
|
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||||
|
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||||
|
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||||
|
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||||
|
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
16. Limitation of Liability.
|
||||||
|
|
||||||
|
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||||
|
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||||
|
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||||
|
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||||
|
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||||
|
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||||
|
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||||
|
SUCH DAMAGES.
|
||||||
|
|
||||||
|
17. Interpretation of Sections 15 and 16.
|
||||||
|
|
||||||
|
If the disclaimer of warranty and limitation of liability provided
|
||||||
|
above cannot be given local legal effect according to their terms,
|
||||||
|
reviewing courts shall apply local law that most closely approximates
|
||||||
|
an absolute waiver of all civil liability in connection with the
|
||||||
|
Program, unless a warranty or assumption of liability accompanies a
|
||||||
|
copy of the Program in return for a fee.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
state the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software: you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation, either version 3 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License
|
||||||
|
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program does terminal interaction, make it output a short
|
||||||
|
notice like this when it starts in an interactive mode:
|
||||||
|
|
||||||
|
<program> Copyright (C) <year> <name of author>
|
||||||
|
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, your program's commands
|
||||||
|
might be different; for a GUI interface, you would use an "about box".
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or school,
|
||||||
|
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||||
|
For more information on this, and how to apply and follow the GNU GPL, see
|
||||||
|
<https://www.gnu.org/licenses/>.
|
||||||
|
|
||||||
|
The GNU General Public License does not permit incorporating your program
|
||||||
|
into proprietary programs. If your program is a subroutine library, you
|
||||||
|
may consider it more useful to permit linking proprietary applications with
|
||||||
|
the library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License. But first, please read
|
||||||
|
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||||
@ -0,0 +1,202 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
# Cherry Toast
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="https://github.com/koukibadr/Cherry-Toast/blob/main/cherry_toast_logo.gif?raw=true" height="200"/>
|
||||||
|
<br>
|
||||||
|
<b>A new way to display toasts in Flutter in an elegant design and animations</b>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
|
||||||
|
|  |  |  |
|
||||||
|
|--|--|--|
|
||||||
|
|  |  |  |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Cherry Toast v1.0.2
|
||||||
|
|
||||||
|
|
||||||
|
- Support all platforms
|
||||||
|
- Top and Bottom display position
|
||||||
|
- Multiple built-in themes
|
||||||
|
- Built-in animations
|
||||||
|
- Support null safety
|
||||||
|
- Elegant design
|
||||||
|
- Full customizable
|
||||||
|
- Heartbeat animation on icons
|
||||||
|
- Customizable icon size and color and display
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
|
||||||
|
To add cherry toast to your project add this line to your `pubspec.yaml` file
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
dependencies:
|
||||||
|
cherry_toast: ^1.0.2
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Parameters
|
||||||
|
|
||||||
|
|
||||||
|
| Name | Description | Required | Default Value |
|
||||||
|
|--|--|--|--|
|
||||||
|
| title | The toast title `String` | true | N/A |
|
||||||
|
| description | the toast description text (nullable) | false | null |
|
||||||
|
| action | the toast action text (clickable text) | false | null |
|
||||||
|
| titleStyle | the title text style | false | `TextStyle(color: Colors.black, fontWeight: FontWeight.bold)` |
|
||||||
|
| descriptionStyle | the description text style | false | `TextStyle(color: Colors.black)` |
|
||||||
|
| actionStyle | the action text style | false | `TextStyle(color: Colors.black, fontWeight: FontWeight.bold)` |
|
||||||
|
| displayTitle | indicates whether the title will be rendered or not | false | true |
|
||||||
|
| icon | the toast displayed icon (IconData) | required when using the default constructor otherwise it's not required | N/A |
|
||||||
|
| toastPosition | the position of the toast (Top/Bottom) | false | `POSITION.TOP` |
|
||||||
|
| themeColor | the color that will be applied on the icon back circle (for built-in themes it will match the action text color | required when using the default constructor otherwise it's not required | N/A |
|
||||||
|
| actionHandler | Function that will be invoked when clicking on the action text | false | null |
|
||||||
|
| animationDuration | the duration of the animation display and hide | false | `Duration(milliseconds: 1500)` |
|
||||||
|
| animationCurve | the display animation curve | false | `Curves.ease` |
|
||||||
|
| animationType | the type of the animation that will be applied on the toast (From left, From right, From top) | false | `ANIMATION_TYPE.FROM_LEFT` |
|
||||||
|
| autoDismiss | indicates whether the toast will be dismissed automatically or not | false | false |
|
||||||
|
| toastDuration | the duration of the toast when `autoDismiss` is true | false | `Duration(milliseconds: 3000)` |
|
||||||
|
| layout | the taost's layout rendering (LTR, RTL) | false | `TOAST_LAYOUT.LTR` |
|
||||||
|
| displayCloseButton | indicates whether display or not the close button | false | true |
|
||||||
|
| borderRadius| define the toast border radius | false | 20 |
|
||||||
|
| iconColor| define the icon color | false | `Colors.black`|
|
||||||
|
| displayIcon| hide or show the icon on the toast | false | true |
|
||||||
|
| enableIconAnimation | define wether apply an animation on the icon or not | false | true |
|
||||||
|
| iconSize | define the icon size | false | 20 |
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
- Simple cherry toast with only title
|
||||||
|
|
||||||
|
```dart
|
||||||
|
|
||||||
|
CherryToast.success(
|
||||||
|
title: "The simplest cherry toast"
|
||||||
|
).show(context);
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
- Simple cherry toast with action button
|
||||||
|
|
||||||
|
```dart
|
||||||
|
|
||||||
|
CherryToast.info(
|
||||||
|
title: "User added",
|
||||||
|
action: "Display information",
|
||||||
|
actionHandler: (){
|
||||||
|
print("Action button pressed");
|
||||||
|
},
|
||||||
|
).show(context);
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
<p align="center">
|
||||||
|
<img src="https://github.com/koukibadr/Cherry-Toast/blob/main/example/cherry_toast_animation.gif?raw=true" height="600"/>
|
||||||
|
<br>
|
||||||
|
<b>A new way to display toasts in Flutter in an elegant design and animations</b>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
- Toast with description without title
|
||||||
|
|
||||||
|
```dart
|
||||||
|
|
||||||
|
CherryToast.warning(
|
||||||
|
title: "",
|
||||||
|
displayTitle: false,
|
||||||
|
description: "All information may be deleted after this action",
|
||||||
|
animationType: ANIMATION_TYPE.FROM_TOP,
|
||||||
|
action: "Backup data",
|
||||||
|
actionHandler: (){
|
||||||
|
print("Hello World!!");
|
||||||
|
},
|
||||||
|
).show(context);
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
- Toast with nothing but description with different animation type and auto dismiss
|
||||||
|
|
||||||
|
```dart
|
||||||
|
CherryToast.error(
|
||||||
|
title: "",
|
||||||
|
displayTitle: false,
|
||||||
|
description: "Invalid account information",
|
||||||
|
animationType: ANIMATION_TYPE.FROM_RIGHT,
|
||||||
|
animationDuration: Duration(milliseconds: 1000),
|
||||||
|
autoDismiss: true)
|
||||||
|
.show(context);
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
- Bottom displayed cherry toast
|
||||||
|
|
||||||
|
```dart
|
||||||
|
CherryToast(
|
||||||
|
icon: Icons.alarm_add,
|
||||||
|
themeColor: Colors.pink,
|
||||||
|
title: "",
|
||||||
|
displayTitle: false,
|
||||||
|
description: "A bottom cherry toast example",
|
||||||
|
toastPosition: POSITION.BOTTOM,
|
||||||
|
animationDuration: Duration(milliseconds: 1000),
|
||||||
|
autoDismiss: true)
|
||||||
|
.show(context);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
- Right layout rendered cherry toast
|
||||||
|
|
||||||
|
```dart
|
||||||
|
CherryToast(
|
||||||
|
icon: Icon(Icons.car_repair),
|
||||||
|
themeColor: Colors.green,
|
||||||
|
title: "",
|
||||||
|
displayTitle: false,
|
||||||
|
description: "هذا مثال تصميم من اليمين",
|
||||||
|
toastPosition: POSITION.BOTTOM,
|
||||||
|
layout: TOAST_LAYOUT.RTL,
|
||||||
|
animationType: ANIMATION_TYPE.FROM_RIGHT,
|
||||||
|
action: "انقر هنا",
|
||||||
|
actionStyle: TextStyle(color: Colors.green),
|
||||||
|
animationDuration: Duration(milliseconds: 1000),
|
||||||
|
autoDismiss: true)
|
||||||
|
.show(context);
|
||||||
|
|
||||||
|
```
|
||||||
|
|
||||||
|
## Contribution
|
||||||
|
|
||||||
|
Of course the project is open source, and you can contribute to it [repository link](https://github.com/koukibadr/Cherry-Toast)
|
||||||
|
|
||||||
|
- If you **found a bug**, open an issue.
|
||||||
|
- If you **have a feature request**, open an issue.
|
||||||
|
- If you **want to contribute**, submit a pull request.
|
||||||
@ -0,0 +1,515 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
import 'package:cherry_toast/cherry_toast_icon.dart';
|
||||||
|
import 'package:cherry_toast/resources/arrays.dart';
|
||||||
|
import 'package:cherry_toast/resources/colors.dart';
|
||||||
|
import 'package:cherry_toast/resources/constants.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
// ignore: must_be_immutable
|
||||||
|
class CherryToast extends StatefulWidget {
|
||||||
|
CherryToast({
|
||||||
|
required this.title,
|
||||||
|
required this.icon,
|
||||||
|
required this.themeColor,
|
||||||
|
this.iconColor = Colors.black,
|
||||||
|
this.action,
|
||||||
|
this.actionHandler,
|
||||||
|
this.description,
|
||||||
|
this.descriptionStyle = DEFAULT_DESCRIPTION_STYLE,
|
||||||
|
this.titleStyle = DEFAULT_TITLTE_STYLE,
|
||||||
|
this.actionStyle = const TextStyle(color: Colors.black, fontWeight: FontWeight.bold),
|
||||||
|
this.displayTitle = true,
|
||||||
|
this.toastPosition = POSITION.TOP,
|
||||||
|
this.animationDuration = DEFAULT_ANIMATION_DURATION,
|
||||||
|
this.animationCurve = DEFAULT_ANIMATION_CURVE,
|
||||||
|
this.animationType = ANIMATION_TYPE.FROM_LEFT,
|
||||||
|
this.autoDismiss = false,
|
||||||
|
this.toastDuration = DEFAULT_TOAST_DURATION,
|
||||||
|
this.layout = TOAST_LAYOUT.LTR,
|
||||||
|
this.displayCloseButton = true,
|
||||||
|
this.borderRadius = DEFAULT_RADIUS,
|
||||||
|
this.displayIcon = true,
|
||||||
|
this.enableIconAnimation = true,
|
||||||
|
this.iconSize = DEFAULT_ICON_SIZE,
|
||||||
|
this.backgroundColor,
|
||||||
|
});
|
||||||
|
|
||||||
|
CherryToast.success({
|
||||||
|
required this.title,
|
||||||
|
this.action,
|
||||||
|
this.actionHandler,
|
||||||
|
this.description,
|
||||||
|
this.descriptionStyle = DEFAULT_DESCRIPTION_STYLE,
|
||||||
|
this.titleStyle = DEFAULT_TITLTE_STYLE,
|
||||||
|
this.actionStyle = const TextStyle(color: SUCCESS_COLOR, fontWeight: FontWeight.bold),
|
||||||
|
this.displayTitle = true,
|
||||||
|
this.toastPosition = POSITION.TOP,
|
||||||
|
this.animationDuration = DEFAULT_ANIMATION_DURATION,
|
||||||
|
this.animationCurve = DEFAULT_ANIMATION_CURVE,
|
||||||
|
this.animationType = ANIMATION_TYPE.FROM_LEFT,
|
||||||
|
this.autoDismiss = false,
|
||||||
|
this.toastDuration = DEFAULT_TOAST_DURATION,
|
||||||
|
this.layout = TOAST_LAYOUT.LTR,
|
||||||
|
this.displayCloseButton = true,
|
||||||
|
this.borderRadius = DEFAULT_RADIUS,
|
||||||
|
this.displayIcon = true,
|
||||||
|
this.enableIconAnimation = true,
|
||||||
|
this.backgroundColor,
|
||||||
|
}) {
|
||||||
|
this.icon = Icons.check_circle;
|
||||||
|
this.themeColor = SUCCESS_COLOR;
|
||||||
|
this.iconColor = SUCCESS_COLOR;
|
||||||
|
this.iconSize = DEFAULT_ICON_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
CherryToast.error({
|
||||||
|
required this.title,
|
||||||
|
this.action,
|
||||||
|
this.actionHandler,
|
||||||
|
this.description,
|
||||||
|
this.descriptionStyle = DEFAULT_DESCRIPTION_STYLE,
|
||||||
|
this.titleStyle = DEFAULT_TITLTE_STYLE,
|
||||||
|
this.actionStyle = const TextStyle(color: ERROR_COLOR, fontWeight: FontWeight.bold),
|
||||||
|
this.displayTitle = true,
|
||||||
|
this.toastPosition = POSITION.TOP,
|
||||||
|
this.animationDuration = DEFAULT_ANIMATION_DURATION,
|
||||||
|
this.animationCurve = DEFAULT_ANIMATION_CURVE,
|
||||||
|
this.animationType = ANIMATION_TYPE.FROM_LEFT,
|
||||||
|
this.autoDismiss = false,
|
||||||
|
this.toastDuration = DEFAULT_TOAST_DURATION,
|
||||||
|
this.layout = TOAST_LAYOUT.LTR,
|
||||||
|
this.displayCloseButton = true,
|
||||||
|
this.borderRadius = DEFAULT_RADIUS,
|
||||||
|
this.displayIcon = true,
|
||||||
|
this.enableIconAnimation = true,
|
||||||
|
this.backgroundColor,
|
||||||
|
}) {
|
||||||
|
this.icon = Icons.error_rounded;
|
||||||
|
this.themeColor = ERROR_COLOR;
|
||||||
|
this.iconColor = ERROR_COLOR;
|
||||||
|
this.iconSize = DEFAULT_ICON_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
CherryToast.warning({
|
||||||
|
required this.title,
|
||||||
|
this.action,
|
||||||
|
this.actionHandler,
|
||||||
|
this.description,
|
||||||
|
this.descriptionStyle = DEFAULT_DESCRIPTION_STYLE,
|
||||||
|
this.titleStyle = DEFAULT_TITLTE_STYLE,
|
||||||
|
this.actionStyle = const TextStyle(color: WARINING_COLOR, fontWeight: FontWeight.bold),
|
||||||
|
this.displayTitle = true,
|
||||||
|
this.toastPosition = POSITION.TOP,
|
||||||
|
this.animationDuration = DEFAULT_ANIMATION_DURATION,
|
||||||
|
this.animationCurve = DEFAULT_ANIMATION_CURVE,
|
||||||
|
this.animationType = ANIMATION_TYPE.FROM_LEFT,
|
||||||
|
this.autoDismiss = false,
|
||||||
|
this.toastDuration = DEFAULT_TOAST_DURATION,
|
||||||
|
this.layout = TOAST_LAYOUT.LTR,
|
||||||
|
this.displayCloseButton = true,
|
||||||
|
this.borderRadius = DEFAULT_RADIUS,
|
||||||
|
this.displayIcon = true,
|
||||||
|
this.enableIconAnimation = true,
|
||||||
|
this.backgroundColor,
|
||||||
|
}) {
|
||||||
|
this.icon = Icons.warning_rounded;
|
||||||
|
this.themeColor = WARINING_COLOR;
|
||||||
|
this.iconColor = WARINING_COLOR;
|
||||||
|
this.iconSize = DEFAULT_ICON_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
CherryToast.info({
|
||||||
|
required this.title,
|
||||||
|
this.action,
|
||||||
|
this.actionHandler,
|
||||||
|
this.description,
|
||||||
|
this.descriptionStyle = DEFAULT_DESCRIPTION_STYLE,
|
||||||
|
this.titleStyle = DEFAULT_TITLTE_STYLE,
|
||||||
|
this.actionStyle = const TextStyle(color: INFO_COLOR, fontWeight: FontWeight.bold),
|
||||||
|
this.displayTitle = true,
|
||||||
|
this.toastPosition = POSITION.TOP,
|
||||||
|
this.animationDuration = DEFAULT_ANIMATION_DURATION,
|
||||||
|
this.animationCurve = DEFAULT_ANIMATION_CURVE,
|
||||||
|
this.animationType = ANIMATION_TYPE.FROM_LEFT,
|
||||||
|
this.autoDismiss = false,
|
||||||
|
this.toastDuration = DEFAULT_TOAST_DURATION,
|
||||||
|
this.layout = TOAST_LAYOUT.LTR,
|
||||||
|
this.displayCloseButton = true,
|
||||||
|
this.borderRadius = DEFAULT_RADIUS,
|
||||||
|
this.displayIcon = true,
|
||||||
|
this.enableIconAnimation = true,
|
||||||
|
this.backgroundColor,
|
||||||
|
}) {
|
||||||
|
this.icon = Icons.info_rounded;
|
||||||
|
this.themeColor = INFO_COLOR;
|
||||||
|
this.iconColor = INFO_COLOR;
|
||||||
|
this.iconSize = DEFAULT_ICON_SIZE;
|
||||||
|
}
|
||||||
|
|
||||||
|
///the toast title string
|
||||||
|
///
|
||||||
|
final String title;
|
||||||
|
|
||||||
|
///The toast description text
|
||||||
|
///
|
||||||
|
final String? description;
|
||||||
|
|
||||||
|
///The toast action button text
|
||||||
|
///
|
||||||
|
final String? action;
|
||||||
|
|
||||||
|
///the text style that will be applied on the title
|
||||||
|
///by default it's `TextStyle(color: Colors.black, fontWeight: FontWeight.bold)`
|
||||||
|
///
|
||||||
|
final TextStyle titleStyle;
|
||||||
|
|
||||||
|
///the text style that will be applied on the description
|
||||||
|
///
|
||||||
|
final TextStyle descriptionStyle;
|
||||||
|
|
||||||
|
///the action button text style
|
||||||
|
///
|
||||||
|
final TextStyle actionStyle;
|
||||||
|
|
||||||
|
///indicates whether display or not the title
|
||||||
|
///
|
||||||
|
final bool displayTitle;
|
||||||
|
|
||||||
|
///the toast icon, it's required when using the default constructor
|
||||||
|
///
|
||||||
|
late IconData icon;
|
||||||
|
|
||||||
|
///the Icon color
|
||||||
|
///this parameter is only available on the default constructor
|
||||||
|
///for the built-in themes the color will be set automatically
|
||||||
|
late Color iconColor;
|
||||||
|
|
||||||
|
///the icon size
|
||||||
|
///by default is 20
|
||||||
|
///this parameter is available in default constructor
|
||||||
|
late double iconSize;
|
||||||
|
|
||||||
|
///the toast display postion, possible values
|
||||||
|
///```dart
|
||||||
|
///{
|
||||||
|
///TOP,
|
||||||
|
///BOTTOM
|
||||||
|
///}
|
||||||
|
///```
|
||||||
|
final POSITION toastPosition;
|
||||||
|
|
||||||
|
///The color that will be applied on the circle behind the icon
|
||||||
|
///for better rendering the action button must have the same color
|
||||||
|
///
|
||||||
|
late Color themeColor;
|
||||||
|
|
||||||
|
///the function invoked when clicking on the action button
|
||||||
|
///
|
||||||
|
final Function? actionHandler;
|
||||||
|
|
||||||
|
///The duration of the animation by default it's 1.5 seconds
|
||||||
|
///
|
||||||
|
final Duration animationDuration;
|
||||||
|
|
||||||
|
///the animation curve by default it's set to `Curves.ease`
|
||||||
|
///
|
||||||
|
final Cubic animationCurve;
|
||||||
|
|
||||||
|
///The animation type applied on the toast
|
||||||
|
///```dart
|
||||||
|
///{
|
||||||
|
///FROM_TOP,
|
||||||
|
///FROM_LEFT,
|
||||||
|
///FROM_RIGHT
|
||||||
|
///}
|
||||||
|
///```
|
||||||
|
final ANIMATION_TYPE animationType;
|
||||||
|
|
||||||
|
///indicates whether the toast will be hidden automatically or not
|
||||||
|
///
|
||||||
|
final bool autoDismiss;
|
||||||
|
|
||||||
|
///the duration of the toast if [autoDismiss] is true
|
||||||
|
///by default it's 3 seconds
|
||||||
|
///
|
||||||
|
final Duration toastDuration;
|
||||||
|
|
||||||
|
///the layout of the toast
|
||||||
|
///```dart
|
||||||
|
///{
|
||||||
|
///LTR,
|
||||||
|
///RTL
|
||||||
|
///}
|
||||||
|
///```
|
||||||
|
final TOAST_LAYOUT layout;
|
||||||
|
|
||||||
|
///Display / Hide the close button icon
|
||||||
|
///by default it's true
|
||||||
|
final bool displayCloseButton;
|
||||||
|
|
||||||
|
///define the border radius applied on the toast
|
||||||
|
///by default it's 20
|
||||||
|
///
|
||||||
|
final double borderRadius;
|
||||||
|
|
||||||
|
///Define whether the icon will be rendered or not
|
||||||
|
///
|
||||||
|
final bool displayIcon;
|
||||||
|
|
||||||
|
///Define wether the animation on the icon will be rendered or not
|
||||||
|
///
|
||||||
|
final bool enableIconAnimation;
|
||||||
|
|
||||||
|
final Color? backgroundColor;
|
||||||
|
|
||||||
|
///Display the created cherry toast
|
||||||
|
///[context] the context of the application
|
||||||
|
///
|
||||||
|
show(BuildContext context) {
|
||||||
|
Navigator.of(context).push(
|
||||||
|
PageRouteBuilder(
|
||||||
|
pageBuilder: (context, _, __) => AlertDialog(
|
||||||
|
backgroundColor: Colors.transparent,
|
||||||
|
contentPadding: EdgeInsets.all(0),
|
||||||
|
insetPadding: EdgeInsets.all(70),
|
||||||
|
elevation: 0,
|
||||||
|
content: this,
|
||||||
|
),
|
||||||
|
opaque: false),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
_CherryToastState createState() => _CherryToastState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _CherryToastState extends State<CherryToast> with TickerProviderStateMixin {
|
||||||
|
late Animation<Offset> offsetAnimation;
|
||||||
|
late AnimationController slideController;
|
||||||
|
late BoxDecoration toastDecoration;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_initAnimation();
|
||||||
|
var _shadowHSLColor = HSLColor.fromColor(widget.backgroundColor ?? Colors.white);
|
||||||
|
toastDecoration = BoxDecoration(
|
||||||
|
color: widget.backgroundColor ?? Colors.white,
|
||||||
|
borderRadius: BorderRadius.circular(this.widget.borderRadius),
|
||||||
|
boxShadow: [
|
||||||
|
BoxShadow(
|
||||||
|
color: _shadowHSLColor
|
||||||
|
.withLightness(_shadowHSLColor.lightness - 0.1 < 0 ? 0 : _shadowHSLColor.lightness - 0.1)
|
||||||
|
.toColor(),
|
||||||
|
spreadRadius: 2,
|
||||||
|
blurRadius: 3,
|
||||||
|
offset: Offset(0, 1), // changes position of shadow
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
if (this.widget.autoDismiss) {
|
||||||
|
Timer(this.widget.toastDuration, () {
|
||||||
|
slideController.reverse();
|
||||||
|
Timer(this.widget.animationDuration, () {
|
||||||
|
if (mounted) Navigator.pop(context);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///Initialize animation parameters [slideController] and [offsetAnimation]
|
||||||
|
_initAnimation() {
|
||||||
|
slideController = AnimationController(
|
||||||
|
duration: this.widget.animationDuration,
|
||||||
|
vsync: this,
|
||||||
|
);
|
||||||
|
switch (this.widget.animationType) {
|
||||||
|
case ANIMATION_TYPE.FROM_LEFT:
|
||||||
|
offsetAnimation = Tween<Offset>(
|
||||||
|
begin: const Offset(-2, 0),
|
||||||
|
end: const Offset(0, 0),
|
||||||
|
).animate(CurvedAnimation(parent: slideController, curve: this.widget.animationCurve));
|
||||||
|
break;
|
||||||
|
case ANIMATION_TYPE.FROM_RIGHT:
|
||||||
|
offsetAnimation = Tween<Offset>(
|
||||||
|
begin: const Offset(2, 0),
|
||||||
|
end: const Offset(0, 0),
|
||||||
|
).animate(CurvedAnimation(parent: slideController, curve: this.widget.animationCurve));
|
||||||
|
break;
|
||||||
|
case ANIMATION_TYPE.FROM_TOP:
|
||||||
|
offsetAnimation = Tween<Offset>(
|
||||||
|
begin: const Offset(0, -2),
|
||||||
|
end: const Offset(0, 0),
|
||||||
|
).animate(CurvedAnimation(parent: slideController, curve: this.widget.animationCurve));
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
WidgetsBinding.instance!.addPostFrameCallback((_) {
|
||||||
|
slideController.forward();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
if (this.widget.layout == TOAST_LAYOUT.LTR) {
|
||||||
|
return _renderLeftLayoutToast(context);
|
||||||
|
} else {
|
||||||
|
return _renderRightLayoutToast(context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
///render a left layout toast if [this.widget.layout] set to LTR
|
||||||
|
///
|
||||||
|
Widget _renderLeftLayoutToast(BuildContext context) {
|
||||||
|
return Column(
|
||||||
|
mainAxisAlignment: this.widget.toastPosition == POSITION.TOP ? MainAxisAlignment.start : MainAxisAlignment.end,
|
||||||
|
children: [
|
||||||
|
SlideTransition(
|
||||||
|
position: offsetAnimation,
|
||||||
|
child: Container(
|
||||||
|
decoration: toastDecoration,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(8.0),
|
||||||
|
child: Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
Expanded(
|
||||||
|
flex: 2,
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.center,
|
||||||
|
children: [
|
||||||
|
this.widget.displayIcon
|
||||||
|
? CherryToatIcon(
|
||||||
|
color: this.widget.themeColor,
|
||||||
|
icon: this.widget.icon,
|
||||||
|
iconSize: this.widget.iconSize,
|
||||||
|
iconColor: this.widget.iconColor,
|
||||||
|
enableAnimation: this.widget.enableIconAnimation,
|
||||||
|
)
|
||||||
|
: Container(),
|
||||||
|
_renderToastContent(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
this.widget.displayCloseButton
|
||||||
|
? Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 10, right: 10),
|
||||||
|
child: _renderCloseButton(context),
|
||||||
|
)
|
||||||
|
: Container(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
///render a right layout toast if [this.widget.layout] set to RTL
|
||||||
|
///
|
||||||
|
Column _renderRightLayoutToast(BuildContext context) {
|
||||||
|
return Column(
|
||||||
|
mainAxisAlignment: this.widget.toastPosition == POSITION.TOP ? MainAxisAlignment.start : MainAxisAlignment.end,
|
||||||
|
children: [
|
||||||
|
SlideTransition(
|
||||||
|
position: offsetAnimation,
|
||||||
|
child: Container(
|
||||||
|
decoration: toastDecoration,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.all(8.0),
|
||||||
|
child: Row(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.spaceBetween,
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
this.widget.displayCloseButton
|
||||||
|
? Padding(
|
||||||
|
padding: const EdgeInsets.only(top: 10, left: 10),
|
||||||
|
child: _renderCloseButton(context),
|
||||||
|
)
|
||||||
|
: Container(),
|
||||||
|
Expanded(
|
||||||
|
flex: 2,
|
||||||
|
child: Row(
|
||||||
|
crossAxisAlignment: this.widget.description == null && this.widget.action == null
|
||||||
|
? CrossAxisAlignment.center
|
||||||
|
: CrossAxisAlignment.start,
|
||||||
|
children: [
|
||||||
|
_renderToastContent(),
|
||||||
|
CherryToatIcon(
|
||||||
|
color: this.widget.themeColor,
|
||||||
|
icon: this.widget.icon,
|
||||||
|
iconSize: this.widget.iconSize,
|
||||||
|
iconColor: this.widget.iconColor,
|
||||||
|
enableAnimation: this.widget.enableIconAnimation),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// render the close button icon with a clickable widget that
|
||||||
|
/// will hide the toast
|
||||||
|
///
|
||||||
|
InkWell _renderCloseButton(BuildContext context) {
|
||||||
|
return InkWell(
|
||||||
|
onTap: () {
|
||||||
|
slideController.reverse();
|
||||||
|
Timer(this.widget.animationDuration, () {
|
||||||
|
if (mounted) Navigator.pop(context);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
child: Icon(Icons.close, color: Colors.grey[500], size: CLOSE_BUTTON_SIZE),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
///render the toast content (Title, Description and Action)
|
||||||
|
///
|
||||||
|
Expanded _renderToastContent() {
|
||||||
|
return Expanded(
|
||||||
|
flex: 2,
|
||||||
|
child: Padding(
|
||||||
|
padding: const EdgeInsets.only(left: 10, right: 10),
|
||||||
|
child: Column(
|
||||||
|
mainAxisAlignment: MainAxisAlignment.center,
|
||||||
|
crossAxisAlignment:
|
||||||
|
this.widget.layout == TOAST_LAYOUT.LTR ? CrossAxisAlignment.start : CrossAxisAlignment.end,
|
||||||
|
children: [
|
||||||
|
this.widget.displayTitle ? Text(this.widget.title, style: this.widget.titleStyle) : Container(),
|
||||||
|
this.widget.description == null
|
||||||
|
? Container()
|
||||||
|
: Column(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
height: 5,
|
||||||
|
),
|
||||||
|
Text(this.widget.description ?? "", style: this.widget.descriptionStyle)
|
||||||
|
],
|
||||||
|
),
|
||||||
|
this.widget.action != null
|
||||||
|
? Column(
|
||||||
|
children: [
|
||||||
|
SizedBox(
|
||||||
|
height: 5,
|
||||||
|
),
|
||||||
|
InkWell(
|
||||||
|
onTap: () {
|
||||||
|
this.widget.actionHandler?.call();
|
||||||
|
},
|
||||||
|
child: Text(this.widget.action ?? "", style: this.widget.actionStyle))
|
||||||
|
],
|
||||||
|
)
|
||||||
|
: Container()
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,90 @@
|
|||||||
|
import 'package:cherry_toast/resources/constants.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
class CherryToatIcon extends StatefulWidget {
|
||||||
|
///the color that will be applied on the circle behind the icon
|
||||||
|
///(required)
|
||||||
|
final Color color;
|
||||||
|
|
||||||
|
///The toast icon widget (required)
|
||||||
|
///
|
||||||
|
final IconData icon;
|
||||||
|
|
||||||
|
///the size of the icon (required)
|
||||||
|
///
|
||||||
|
final double iconSize;
|
||||||
|
|
||||||
|
///the icon color (required)
|
||||||
|
final Color iconColor;
|
||||||
|
|
||||||
|
///define wether the animation will be applied on the icon or not
|
||||||
|
///
|
||||||
|
final bool enableAnimation;
|
||||||
|
|
||||||
|
CherryToatIcon(
|
||||||
|
{required this.color,
|
||||||
|
required this.icon,
|
||||||
|
required this.iconSize,
|
||||||
|
required this.iconColor,
|
||||||
|
required this.enableAnimation});
|
||||||
|
|
||||||
|
@override
|
||||||
|
_CherryToatIconState createState() => _CherryToatIconState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class _CherryToatIconState extends State<CherryToatIcon>
|
||||||
|
with TickerProviderStateMixin {
|
||||||
|
late Animation _heartAnimation;
|
||||||
|
late AnimationController _heartAnimationController;
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
if (this.widget.enableAnimation) {
|
||||||
|
_heartAnimationController = AnimationController(
|
||||||
|
vsync: this, duration: Duration(milliseconds: 1200));
|
||||||
|
_heartAnimation = Tween(
|
||||||
|
begin: this.widget.iconSize * 0.7,
|
||||||
|
end: this.widget.iconSize * 0.95)
|
||||||
|
.animate(CurvedAnimation(
|
||||||
|
curve: Curves.bounceOut, parent: _heartAnimationController));
|
||||||
|
|
||||||
|
_heartAnimationController.addStatusListener((AnimationStatus status) {
|
||||||
|
if (status == AnimationStatus.completed) {
|
||||||
|
_heartAnimationController.repeat();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
_heartAnimationController.forward();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Container(
|
||||||
|
width: DEFAULT_ICON_LAYOUT_SIZE,
|
||||||
|
height: DEFAULT_ICON_LAYOUT_SIZE,
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
shape: BoxShape.circle, color: this.widget.color.withAlpha(20)),
|
||||||
|
child: Center(
|
||||||
|
child: this.widget.enableAnimation
|
||||||
|
? AnimatedBuilder(
|
||||||
|
builder: (context, child) {
|
||||||
|
return Icon(this.widget.icon,
|
||||||
|
size: this._heartAnimation.value,
|
||||||
|
color: this.widget.iconColor);
|
||||||
|
},
|
||||||
|
animation: this._heartAnimationController,
|
||||||
|
)
|
||||||
|
: Icon(this.widget.icon,
|
||||||
|
size: this.widget.iconSize, color: this.widget.iconColor)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void dispose() {
|
||||||
|
if (this.widget.enableAnimation) {
|
||||||
|
_heartAnimationController.dispose();
|
||||||
|
}
|
||||||
|
super.dispose();
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,7 @@
|
|||||||
|
enum CHERRY_TYPE { SUCCESS, WARINING, ERROR, INFO, CUSTOM }
|
||||||
|
|
||||||
|
enum POSITION { TOP, BOTTOM }
|
||||||
|
|
||||||
|
enum ANIMATION_TYPE { FROM_TOP, FROM_LEFT, FROM_RIGHT }
|
||||||
|
|
||||||
|
enum TOAST_LAYOUT { LTR, RTL }
|
||||||
@ -0,0 +1,6 @@
|
|||||||
|
import 'dart:ui';
|
||||||
|
|
||||||
|
const Color ERROR_COLOR = Color(0xffE43837);
|
||||||
|
const Color SUCCESS_COLOR = Color(0xFF2F9449);
|
||||||
|
const Color INFO_COLOR = Color(0xFF4E5CB9);
|
||||||
|
const Color WARINING_COLOR = Color(0xffFC9F00);
|
||||||
@ -0,0 +1,18 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
const String PACKAGE_NAME = "cherry_toast";
|
||||||
|
|
||||||
|
const TextStyle DEFAULT_TITLTE_STYLE =
|
||||||
|
const TextStyle(color: Colors.black, fontWeight: FontWeight.bold);
|
||||||
|
const TextStyle DEFAULT_DESCRIPTION_STYLE =
|
||||||
|
const TextStyle(color: Colors.black);
|
||||||
|
|
||||||
|
const Duration DEFAULT_ANIMATION_DURATION = Duration(milliseconds: 1500);
|
||||||
|
const Duration DEFAULT_TOAST_DURATION = Duration(milliseconds: 3000);
|
||||||
|
const Cubic DEFAULT_ANIMATION_CURVE = Curves.ease;
|
||||||
|
|
||||||
|
const double CLOSE_BUTTON_SIZE = 15;
|
||||||
|
|
||||||
|
const double DEFAULT_ICON_SIZE = 20;
|
||||||
|
const double DEFAULT_ICON_LAYOUT_SIZE = 40;
|
||||||
|
const double DEFAULT_RADIUS = 20;
|
||||||
@ -0,0 +1,18 @@
|
|||||||
|
name: cherry_toast
|
||||||
|
description: A new way to display toasts in flutter with elegant design and animations
|
||||||
|
version: 1.0.2
|
||||||
|
homepage: https://github.com/koukibadr/Cherry-Toast
|
||||||
|
|
||||||
|
environment:
|
||||||
|
sdk: '>=2.12.0 <3.0.0'
|
||||||
|
flutter: ">=1.17.0"
|
||||||
|
|
||||||
|
dependencies:
|
||||||
|
flutter:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
|
dev_dependencies:
|
||||||
|
flutter_test:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
|
flutter:
|
||||||
@ -0,0 +1,3 @@
|
|||||||
|
## 1.0.0
|
||||||
|
|
||||||
|
* first version
|
||||||
@ -0,0 +1,201 @@
|
|||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
@ -0,0 +1,17 @@
|
|||||||
|
# markdown_core
|
||||||
|
|
||||||
|
Parse markdown and render it into rich text.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
``` dart
|
||||||
|
Markdown(
|
||||||
|
data: markdownDataString,
|
||||||
|
linkTap: (link) => print('点击了链接 $link'),
|
||||||
|
textStyle: // your text style ,
|
||||||
|
image: (imageUrl) {
|
||||||
|
print('imageUrl $imageUrl');
|
||||||
|
return // Your image widget ;
|
||||||
|
},
|
||||||
|
)
|
||||||
|
```
|
||||||
@ -0,0 +1,67 @@
|
|||||||
|
library markdown_core;
|
||||||
|
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:markdown/markdown.dart';
|
||||||
|
import 'package:markdown_core/builder.dart';
|
||||||
|
import 'package:markdown_core/text_style.dart';
|
||||||
|
|
||||||
|
class Markdown extends StatefulWidget {
|
||||||
|
const Markdown({
|
||||||
|
Key? key,
|
||||||
|
required this.data,
|
||||||
|
required this.linkTap,
|
||||||
|
required this.image,
|
||||||
|
required this.onCodeCopied,
|
||||||
|
this.maxWidth,
|
||||||
|
this.textStyle,
|
||||||
|
}) : super(key: key);
|
||||||
|
|
||||||
|
final String data;
|
||||||
|
|
||||||
|
final LinkTap linkTap;
|
||||||
|
|
||||||
|
final WidgetImage image;
|
||||||
|
|
||||||
|
final double? maxWidth;
|
||||||
|
|
||||||
|
final TextStyle? textStyle;
|
||||||
|
|
||||||
|
final Function onCodeCopied;
|
||||||
|
|
||||||
|
@override
|
||||||
|
MarkdownState createState() => MarkdownState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class MarkdownState extends State<Markdown> {
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
return Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: _parseMarkdown(),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Widget> _parseMarkdown() {
|
||||||
|
// debugPrint(markdownToHtml(
|
||||||
|
// widget.data,
|
||||||
|
// extensionSet: ExtensionSet.gi法inaltHubWeb,
|
||||||
|
// ));
|
||||||
|
final List<String> lines = widget.data.split(RegExp(r'\r?\n'));
|
||||||
|
final nodes = Document(
|
||||||
|
extensionSet: ExtensionSet.gitHubWeb,
|
||||||
|
).parseLines(lines);
|
||||||
|
return MarkdownBuilder(
|
||||||
|
context,
|
||||||
|
widget.linkTap,
|
||||||
|
widget.image,
|
||||||
|
widget.maxWidth ?? MediaQuery.of(context).size.width,
|
||||||
|
widget.textStyle ?? defaultTextStyle(context),
|
||||||
|
onCodeCopied: widget.onCodeCopied,
|
||||||
|
).build(nodes);
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,107 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
const List<String> kTextTags = const <String>[
|
||||||
|
'h1',
|
||||||
|
'h2',
|
||||||
|
'h3',
|
||||||
|
'h4',
|
||||||
|
'h5',
|
||||||
|
'h6',
|
||||||
|
'p',
|
||||||
|
'code',
|
||||||
|
'strong',
|
||||||
|
'em',
|
||||||
|
'del',
|
||||||
|
'a',
|
||||||
|
];
|
||||||
|
|
||||||
|
const List<String> kTextParentTags = const <String>[
|
||||||
|
'h1',
|
||||||
|
'h2',
|
||||||
|
'h3',
|
||||||
|
'h4',
|
||||||
|
'h5',
|
||||||
|
'h6',
|
||||||
|
'p',
|
||||||
|
'li',
|
||||||
|
];
|
||||||
|
|
||||||
|
TextStyle defaultTextStyle(BuildContext context) => TextStyle(
|
||||||
|
fontSize: 18,
|
||||||
|
height: 1.8,
|
||||||
|
color: Theme.of(context).brightness == Brightness.dark
|
||||||
|
? const Color(0xffaaaaaa)
|
||||||
|
: const Color(0xff444444),
|
||||||
|
);
|
||||||
|
|
||||||
|
TextStyle defaultTagTextStyle(String lastTag, String tag, TextStyle textStyle) {
|
||||||
|
switch (tag) {
|
||||||
|
case 'h1':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
fontSize: (textStyle.fontSize ?? 0) + 9,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'h2':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
fontSize: (textStyle.fontSize ?? 0) + 6,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'h3':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
fontSize: (textStyle.fontSize ?? 0) + 4,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'h4':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
fontSize: (textStyle.fontSize ?? 0) + 3,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'h5':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
fontSize: (textStyle.fontSize ?? 0) + 2,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'h6':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
fontSize: (textStyle.fontSize ?? 0) + 1,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'p':
|
||||||
|
break;
|
||||||
|
case 'li':
|
||||||
|
break;
|
||||||
|
case 'code':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
fontSize: (textStyle.fontSize ?? 0) - 3,
|
||||||
|
color: textStyle.color?.withAlpha(200),
|
||||||
|
);
|
||||||
|
if (lastTag == 'p') {
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
color: Colors.red.shade800,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
break;
|
||||||
|
case 'strong':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
fontWeight: FontWeight.bold,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'em':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
fontStyle: FontStyle.italic,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'del':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
decoration: TextDecoration.lineThrough,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
case 'a':
|
||||||
|
textStyle = textStyle.copyWith(
|
||||||
|
color: Colors.blue,
|
||||||
|
);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return textStyle;
|
||||||
|
}
|
||||||
@ -0,0 +1,56 @@
|
|||||||
|
name: markdown_core
|
||||||
|
description: Parse markdown and render it into rich text.
|
||||||
|
version: 1.0.0
|
||||||
|
homepage: https://github.com/xia-weiyang/markdown_core
|
||||||
|
repository: https://github.com/xia-weiyang/markdown_core
|
||||||
|
|
||||||
|
environment:
|
||||||
|
sdk: '>=2.12.0 <3.0.0'
|
||||||
|
|
||||||
|
dependencies:
|
||||||
|
flutter:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
|
markdown: ^4.0.1
|
||||||
|
html_unescape: ^2.0.0
|
||||||
|
|
||||||
|
dev_dependencies:
|
||||||
|
flutter_test:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
|
# For information on the generic Dart part of this file, see the
|
||||||
|
# following page: https://dart.dev/tools/pub/pubspec
|
||||||
|
|
||||||
|
# The following section is specific to Flutter.
|
||||||
|
flutter:
|
||||||
|
|
||||||
|
# To add assets to your package, add an assets section, like this:
|
||||||
|
# assets:
|
||||||
|
# - images/a_dot_burr.jpeg
|
||||||
|
# - images/a_dot_ham.jpeg
|
||||||
|
#
|
||||||
|
# For details regarding assets in packages, see
|
||||||
|
# https://flutter.dev/assets-and-images/#from-packages
|
||||||
|
#
|
||||||
|
# An image asset can refer to one or more resolution-specific "variants", see
|
||||||
|
# https://flutter.dev/assets-and-images/#resolution-aware.
|
||||||
|
|
||||||
|
# To add custom fonts to your package, add a fonts section here,
|
||||||
|
# in this "flutter" section. Each entry in this list should have a
|
||||||
|
# "family" key with the font family name, and a "fonts" key with a
|
||||||
|
# list giving the asset and other descriptors for the font. For
|
||||||
|
# example:
|
||||||
|
# fonts:
|
||||||
|
# - family: Schyler
|
||||||
|
# fonts:
|
||||||
|
# - asset: fonts/Schyler-Regular.ttf
|
||||||
|
# - asset: fonts/Schyler-Italic.ttf
|
||||||
|
# style: italic
|
||||||
|
# - family: Trajan Pro
|
||||||
|
# fonts:
|
||||||
|
# - asset: fonts/TrajanPro.ttf
|
||||||
|
# - asset: fonts/TrajanPro_Bold.ttf
|
||||||
|
# weight: 700
|
||||||
|
#
|
||||||
|
# For details regarding fonts in packages, see
|
||||||
|
# https://flutter.dev/custom-fonts/#from-packages
|
||||||
@ -0,0 +1,15 @@
|
|||||||
|
.DS_Store
|
||||||
|
.dart_tool/
|
||||||
|
|
||||||
|
.packages
|
||||||
|
.flutter-plugins
|
||||||
|
.pub/
|
||||||
|
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
*.lock
|
||||||
|
|
||||||
|
|
||||||
|
build/
|
||||||
|
ios/
|
||||||
|
android/
|
||||||
@ -0,0 +1,5 @@
|
|||||||
|
## 1.0.2
|
||||||
|
* Fix icon not display.
|
||||||
|
## 1.0.1
|
||||||
|
* Change directory structure.
|
||||||
|
## 1.0.0
|
||||||
@ -0,0 +1,339 @@
|
|||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
Version 2, June 1991
|
||||||
|
|
||||||
|
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
|
||||||
|
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
|
||||||
|
Everyone is permitted to copy and distribute verbatim copies
|
||||||
|
of this license document, but changing it is not allowed.
|
||||||
|
|
||||||
|
Preamble
|
||||||
|
|
||||||
|
The licenses for most software are designed to take away your
|
||||||
|
freedom to share and change it. By contrast, the GNU General Public
|
||||||
|
License is intended to guarantee your freedom to share and change free
|
||||||
|
software--to make sure the software is free for all its users. This
|
||||||
|
General Public License applies to most of the Free Software
|
||||||
|
Foundation's software and to any other program whose authors commit to
|
||||||
|
using it. (Some other Free Software Foundation software is covered by
|
||||||
|
the GNU Lesser General Public License instead.) You can apply it to
|
||||||
|
your programs, too.
|
||||||
|
|
||||||
|
When we speak of free software, we are referring to freedom, not
|
||||||
|
price. Our General Public Licenses are designed to make sure that you
|
||||||
|
have the freedom to distribute copies of free software (and charge for
|
||||||
|
this service if you wish), that you receive source code or can get it
|
||||||
|
if you want it, that you can change the software or use pieces of it
|
||||||
|
in new free programs; and that you know you can do these things.
|
||||||
|
|
||||||
|
To protect your rights, we need to make restrictions that forbid
|
||||||
|
anyone to deny you these rights or to ask you to surrender the rights.
|
||||||
|
These restrictions translate to certain responsibilities for you if you
|
||||||
|
distribute copies of the software, or if you modify it.
|
||||||
|
|
||||||
|
For example, if you distribute copies of such a program, whether
|
||||||
|
gratis or for a fee, you must give the recipients all the rights that
|
||||||
|
you have. You must make sure that they, too, receive or can get the
|
||||||
|
source code. And you must show them these terms so they know their
|
||||||
|
rights.
|
||||||
|
|
||||||
|
We protect your rights with two steps: (1) copyright the software, and
|
||||||
|
(2) offer you this license which gives you legal permission to copy,
|
||||||
|
distribute and/or modify the software.
|
||||||
|
|
||||||
|
Also, for each author's protection and ours, we want to make certain
|
||||||
|
that everyone understands that there is no warranty for this free
|
||||||
|
software. If the software is modified by someone else and passed on, we
|
||||||
|
want its recipients to know that what they have is not the original, so
|
||||||
|
that any problems introduced by others will not reflect on the original
|
||||||
|
authors' reputations.
|
||||||
|
|
||||||
|
Finally, any free program is threatened constantly by software
|
||||||
|
patents. We wish to avoid the danger that redistributors of a free
|
||||||
|
program will individually obtain patent licenses, in effect making the
|
||||||
|
program proprietary. To prevent this, we have made it clear that any
|
||||||
|
patent must be licensed for everyone's free use or not licensed at all.
|
||||||
|
|
||||||
|
The precise terms and conditions for copying, distribution and
|
||||||
|
modification follow.
|
||||||
|
|
||||||
|
GNU GENERAL PUBLIC LICENSE
|
||||||
|
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
|
||||||
|
|
||||||
|
0. This License applies to any program or other work which contains
|
||||||
|
a notice placed by the copyright holder saying it may be distributed
|
||||||
|
under the terms of this General Public License. The "Program", below,
|
||||||
|
refers to any such program or work, and a "work based on the Program"
|
||||||
|
means either the Program or any derivative work under copyright law:
|
||||||
|
that is to say, a work containing the Program or a portion of it,
|
||||||
|
either verbatim or with modifications and/or translated into another
|
||||||
|
language. (Hereinafter, translation is included without limitation in
|
||||||
|
the term "modification".) Each licensee is addressed as "you".
|
||||||
|
|
||||||
|
Activities other than copying, distribution and modification are not
|
||||||
|
covered by this License; they are outside its scope. The act of
|
||||||
|
running the Program is not restricted, and the output from the Program
|
||||||
|
is covered only if its contents constitute a work based on the
|
||||||
|
Program (independent of having been made by running the Program).
|
||||||
|
Whether that is true depends on what the Program does.
|
||||||
|
|
||||||
|
1. You may copy and distribute verbatim copies of the Program's
|
||||||
|
source code as you receive it, in any medium, provided that you
|
||||||
|
conspicuously and appropriately publish on each copy an appropriate
|
||||||
|
copyright notice and disclaimer of warranty; keep intact all the
|
||||||
|
notices that refer to this License and to the absence of any warranty;
|
||||||
|
and give any other recipients of the Program a copy of this License
|
||||||
|
along with the Program.
|
||||||
|
|
||||||
|
You may charge a fee for the physical act of transferring a copy, and
|
||||||
|
you may at your option offer warranty protection in exchange for a fee.
|
||||||
|
|
||||||
|
2. You may modify your copy or copies of the Program or any portion
|
||||||
|
of it, thus forming a work based on the Program, and copy and
|
||||||
|
distribute such modifications or work under the terms of Section 1
|
||||||
|
above, provided that you also meet all of these conditions:
|
||||||
|
|
||||||
|
a) You must cause the modified files to carry prominent notices
|
||||||
|
stating that you changed the files and the date of any change.
|
||||||
|
|
||||||
|
b) You must cause any work that you distribute or publish, that in
|
||||||
|
whole or in part contains or is derived from the Program or any
|
||||||
|
part thereof, to be licensed as a whole at no charge to all third
|
||||||
|
parties under the terms of this License.
|
||||||
|
|
||||||
|
c) If the modified program normally reads commands interactively
|
||||||
|
when run, you must cause it, when started running for such
|
||||||
|
interactive use in the most ordinary way, to print or display an
|
||||||
|
announcement including an appropriate copyright notice and a
|
||||||
|
notice that there is no warranty (or else, saying that you provide
|
||||||
|
a warranty) and that users may redistribute the program under
|
||||||
|
these conditions, and telling the user how to view a copy of this
|
||||||
|
License. (Exception: if the Program itself is interactive but
|
||||||
|
does not normally print such an announcement, your work based on
|
||||||
|
the Program is not required to print an announcement.)
|
||||||
|
|
||||||
|
These requirements apply to the modified work as a whole. If
|
||||||
|
identifiable sections of that work are not derived from the Program,
|
||||||
|
and can be reasonably considered independent and separate works in
|
||||||
|
themselves, then this License, and its terms, do not apply to those
|
||||||
|
sections when you distribute them as separate works. But when you
|
||||||
|
distribute the same sections as part of a whole which is a work based
|
||||||
|
on the Program, the distribution of the whole must be on the terms of
|
||||||
|
this License, whose permissions for other licensees extend to the
|
||||||
|
entire whole, and thus to each and every part regardless of who wrote it.
|
||||||
|
|
||||||
|
Thus, it is not the intent of this section to claim rights or contest
|
||||||
|
your rights to work written entirely by you; rather, the intent is to
|
||||||
|
exercise the right to control the distribution of derivative or
|
||||||
|
collective works based on the Program.
|
||||||
|
|
||||||
|
In addition, mere aggregation of another work not based on the Program
|
||||||
|
with the Program (or with a work based on the Program) on a volume of
|
||||||
|
a storage or distribution medium does not bring the other work under
|
||||||
|
the scope of this License.
|
||||||
|
|
||||||
|
3. You may copy and distribute the Program (or a work based on it,
|
||||||
|
under Section 2) in object code or executable form under the terms of
|
||||||
|
Sections 1 and 2 above provided that you also do one of the following:
|
||||||
|
|
||||||
|
a) Accompany it with the complete corresponding machine-readable
|
||||||
|
source code, which must be distributed under the terms of Sections
|
||||||
|
1 and 2 above on a medium customarily used for software interchange; or,
|
||||||
|
|
||||||
|
b) Accompany it with a written offer, valid for at least three
|
||||||
|
years, to give any third party, for a charge no more than your
|
||||||
|
cost of physically performing source distribution, a complete
|
||||||
|
machine-readable copy of the corresponding source code, to be
|
||||||
|
distributed under the terms of Sections 1 and 2 above on a medium
|
||||||
|
customarily used for software interchange; or,
|
||||||
|
|
||||||
|
c) Accompany it with the information you received as to the offer
|
||||||
|
to distribute corresponding source code. (This alternative is
|
||||||
|
allowed only for noncommercial distribution and only if you
|
||||||
|
received the program in object code or executable form with such
|
||||||
|
an offer, in accord with Subsection b above.)
|
||||||
|
|
||||||
|
The source code for a work means the preferred form of the work for
|
||||||
|
making modifications to it. For an executable work, complete source
|
||||||
|
code means all the source code for all modules it contains, plus any
|
||||||
|
associated interface definition files, plus the scripts used to
|
||||||
|
control compilation and installation of the executable. However, as a
|
||||||
|
special exception, the source code distributed need not include
|
||||||
|
anything that is normally distributed (in either source or binary
|
||||||
|
form) with the major components (compiler, kernel, and so on) of the
|
||||||
|
operating system on which the executable runs, unless that component
|
||||||
|
itself accompanies the executable.
|
||||||
|
|
||||||
|
If distribution of executable or object code is made by offering
|
||||||
|
access to copy from a designated place, then offering equivalent
|
||||||
|
access to copy the source code from the same place counts as
|
||||||
|
distribution of the source code, even though third parties are not
|
||||||
|
compelled to copy the source along with the object code.
|
||||||
|
|
||||||
|
4. You may not copy, modify, sublicense, or distribute the Program
|
||||||
|
except as expressly provided under this License. Any attempt
|
||||||
|
otherwise to copy, modify, sublicense or distribute the Program is
|
||||||
|
void, and will automatically terminate your rights under this License.
|
||||||
|
However, parties who have received copies, or rights, from you under
|
||||||
|
this License will not have their licenses terminated so long as such
|
||||||
|
parties remain in full compliance.
|
||||||
|
|
||||||
|
5. You are not required to accept this License, since you have not
|
||||||
|
signed it. However, nothing else grants you permission to modify or
|
||||||
|
distribute the Program or its derivative works. These actions are
|
||||||
|
prohibited by law if you do not accept this License. Therefore, by
|
||||||
|
modifying or distributing the Program (or any work based on the
|
||||||
|
Program), you indicate your acceptance of this License to do so, and
|
||||||
|
all its terms and conditions for copying, distributing or modifying
|
||||||
|
the Program or works based on it.
|
||||||
|
|
||||||
|
6. Each time you redistribute the Program (or any work based on the
|
||||||
|
Program), the recipient automatically receives a license from the
|
||||||
|
original licensor to copy, distribute or modify the Program subject to
|
||||||
|
these terms and conditions. You may not impose any further
|
||||||
|
restrictions on the recipients' exercise of the rights granted herein.
|
||||||
|
You are not responsible for enforcing compliance by third parties to
|
||||||
|
this License.
|
||||||
|
|
||||||
|
7. If, as a consequence of a court judgment or allegation of patent
|
||||||
|
infringement or for any other reason (not limited to patent issues),
|
||||||
|
conditions are imposed on you (whether by court order, agreement or
|
||||||
|
otherwise) that contradict the conditions of this License, they do not
|
||||||
|
excuse you from the conditions of this License. If you cannot
|
||||||
|
distribute so as to satisfy simultaneously your obligations under this
|
||||||
|
License and any other pertinent obligations, then as a consequence you
|
||||||
|
may not distribute the Program at all. For example, if a patent
|
||||||
|
license would not permit royalty-free redistribution of the Program by
|
||||||
|
all those who receive copies directly or indirectly through you, then
|
||||||
|
the only way you could satisfy both it and this License would be to
|
||||||
|
refrain entirely from distribution of the Program.
|
||||||
|
|
||||||
|
If any portion of this section is held invalid or unenforceable under
|
||||||
|
any particular circumstance, the balance of the section is intended to
|
||||||
|
apply and the section as a whole is intended to apply in other
|
||||||
|
circumstances.
|
||||||
|
|
||||||
|
It is not the purpose of this section to induce you to infringe any
|
||||||
|
patents or other property right claims or to contest validity of any
|
||||||
|
such claims; this section has the sole purpose of protecting the
|
||||||
|
integrity of the free software distribution system, which is
|
||||||
|
implemented by public license practices. Many people have made
|
||||||
|
generous contributions to the wide range of software distributed
|
||||||
|
through that system in reliance on consistent application of that
|
||||||
|
system; it is up to the author/donor to decide if he or she is willing
|
||||||
|
to distribute software through any other system and a licensee cannot
|
||||||
|
impose that choice.
|
||||||
|
|
||||||
|
This section is intended to make thoroughly clear what is believed to
|
||||||
|
be a consequence of the rest of this License.
|
||||||
|
|
||||||
|
8. If the distribution and/or use of the Program is restricted in
|
||||||
|
certain countries either by patents or by copyrighted interfaces, the
|
||||||
|
original copyright holder who places the Program under this License
|
||||||
|
may add an explicit geographical distribution limitation excluding
|
||||||
|
those countries, so that distribution is permitted only in or among
|
||||||
|
countries not thus excluded. In such case, this License incorporates
|
||||||
|
the limitation as if written in the body of this License.
|
||||||
|
|
||||||
|
9. The Free Software Foundation may publish revised and/or new versions
|
||||||
|
of the General Public License from time to time. Such new versions will
|
||||||
|
be similar in spirit to the present version, but may differ in detail to
|
||||||
|
address new problems or concerns.
|
||||||
|
|
||||||
|
Each version is given a distinguishing version number. If the Program
|
||||||
|
specifies a version number of this License which applies to it and "any
|
||||||
|
later version", you have the option of following the terms and conditions
|
||||||
|
either of that version or of any later version published by the Free
|
||||||
|
Software Foundation. If the Program does not specify a version number of
|
||||||
|
this License, you may choose any version ever published by the Free Software
|
||||||
|
Foundation.
|
||||||
|
|
||||||
|
10. If you wish to incorporate parts of the Program into other free
|
||||||
|
programs whose distribution conditions are different, write to the author
|
||||||
|
to ask for permission. For software which is copyrighted by the Free
|
||||||
|
Software Foundation, write to the Free Software Foundation; we sometimes
|
||||||
|
make exceptions for this. Our decision will be guided by the two goals
|
||||||
|
of preserving the free status of all derivatives of our free software and
|
||||||
|
of promoting the sharing and reuse of software generally.
|
||||||
|
|
||||||
|
NO WARRANTY
|
||||||
|
|
||||||
|
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
|
||||||
|
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
|
||||||
|
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
|
||||||
|
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
|
||||||
|
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
||||||
|
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
|
||||||
|
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
|
||||||
|
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
|
||||||
|
REPAIR OR CORRECTION.
|
||||||
|
|
||||||
|
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||||
|
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
|
||||||
|
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
|
||||||
|
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
|
||||||
|
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
|
||||||
|
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
|
||||||
|
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
|
||||||
|
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
|
||||||
|
POSSIBILITY OF SUCH DAMAGES.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
How to Apply These Terms to Your New Programs
|
||||||
|
|
||||||
|
If you develop a new program, and you want it to be of the greatest
|
||||||
|
possible use to the public, the best way to achieve this is to make it
|
||||||
|
free software which everyone can redistribute and change under these terms.
|
||||||
|
|
||||||
|
To do so, attach the following notices to the program. It is safest
|
||||||
|
to attach them to the start of each source file to most effectively
|
||||||
|
convey the exclusion of warranty; and each file should have at least
|
||||||
|
the "copyright" line and a pointer to where the full notice is found.
|
||||||
|
|
||||||
|
<one line to give the program's name and a brief idea of what it does.>
|
||||||
|
Copyright (C) <year> <name of author>
|
||||||
|
|
||||||
|
This program is free software; you can redistribute it and/or modify
|
||||||
|
it under the terms of the GNU General Public License as published by
|
||||||
|
the Free Software Foundation; either version 2 of the License, or
|
||||||
|
(at your option) any later version.
|
||||||
|
|
||||||
|
This program is distributed in the hope that it will be useful,
|
||||||
|
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||||
|
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||||
|
GNU General Public License for more details.
|
||||||
|
|
||||||
|
You should have received a copy of the GNU General Public License along
|
||||||
|
with this program; if not, write to the Free Software Foundation, Inc.,
|
||||||
|
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||||
|
|
||||||
|
Also add information on how to contact you by electronic and paper mail.
|
||||||
|
|
||||||
|
If the program is interactive, make it output a short notice like this
|
||||||
|
when it starts in an interactive mode:
|
||||||
|
|
||||||
|
Gnomovision version 69, Copyright (C) year name of author
|
||||||
|
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||||
|
This is free software, and you are welcome to redistribute it
|
||||||
|
under certain conditions; type `show c' for details.
|
||||||
|
|
||||||
|
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||||
|
parts of the General Public License. Of course, the commands you use may
|
||||||
|
be called something other than `show w' and `show c'; they could even be
|
||||||
|
mouse-clicks or menu items--whatever suits your program.
|
||||||
|
|
||||||
|
You should also get your employer (if you work as a programmer) or your
|
||||||
|
school, if any, to sign a "copyright disclaimer" for the program, if
|
||||||
|
necessary. Here is a sample; alter the names:
|
||||||
|
|
||||||
|
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
|
||||||
|
`Gnomovision' (which makes passes at compilers) written by James Hacker.
|
||||||
|
|
||||||
|
<signature of Ty Coon>, 1 April 1989
|
||||||
|
Ty Coon, President of Vice
|
||||||
|
|
||||||
|
This General Public License does not permit incorporating your program into
|
||||||
|
proprietary programs. If your program is a subroutine library, you may
|
||||||
|
consider it more useful to permit linking proprietary applications with the
|
||||||
|
library. If this is what you want to do, use the GNU Lesser General
|
||||||
|
Public License instead of this License.
|
||||||
@ -0,0 +1,23 @@
|
|||||||
|
# markdown_editor
|
||||||
|
|
||||||
|
Simple and easy to implement your markdown editor, it uses its own parser.
|
||||||
|
|
||||||
|

|
||||||
|
|
||||||
|
If you only need to render, you can refer to [https://github.com/xia-weiyang/markdown_core](https://github.com/xia-weiyang/markdown_core)
|
||||||
|
|
||||||
|
``` dart
|
||||||
|
MarkdownEditor(
|
||||||
|
initText: 'initText',
|
||||||
|
initTitle: 'initText',
|
||||||
|
onTapLink: (link){
|
||||||
|
print('点击了链接 $link');
|
||||||
|
},
|
||||||
|
imageWidget: (imageUrl) {
|
||||||
|
return // Your image widget ;
|
||||||
|
},
|
||||||
|
imageSelect: (){ // Click image select btn
|
||||||
|
return // selected image link;
|
||||||
|
},
|
||||||
|
)
|
||||||
|
```
|
||||||
@ -0,0 +1,539 @@
|
|||||||
|
/* Logo 字体 */
|
||||||
|
@font-face {
|
||||||
|
font-family: "iconfont logo";
|
||||||
|
src: url('https://at.alicdn.com/t/font_985780_km7mi63cihi.eot?t=1545807318834');
|
||||||
|
src: url('https://at.alicdn.com/t/font_985780_km7mi63cihi.eot?t=1545807318834#iefix') format('embedded-opentype'),
|
||||||
|
url('https://at.alicdn.com/t/font_985780_km7mi63cihi.woff?t=1545807318834') format('woff'),
|
||||||
|
url('https://at.alicdn.com/t/font_985780_km7mi63cihi.ttf?t=1545807318834') format('truetype'),
|
||||||
|
url('https://at.alicdn.com/t/font_985780_km7mi63cihi.svg?t=1545807318834#iconfont') format('svg');
|
||||||
|
}
|
||||||
|
|
||||||
|
.logo {
|
||||||
|
font-family: "iconfont logo";
|
||||||
|
font-size: 160px;
|
||||||
|
font-style: normal;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* tabs */
|
||||||
|
.nav-tabs {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
|
.nav-tabs .nav-more {
|
||||||
|
position: absolute;
|
||||||
|
right: 0;
|
||||||
|
bottom: 0;
|
||||||
|
height: 42px;
|
||||||
|
line-height: 42px;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
#tabs {
|
||||||
|
border-bottom: 1px solid #eee;
|
||||||
|
}
|
||||||
|
|
||||||
|
#tabs li {
|
||||||
|
cursor: pointer;
|
||||||
|
width: 100px;
|
||||||
|
height: 40px;
|
||||||
|
line-height: 40px;
|
||||||
|
text-align: center;
|
||||||
|
font-size: 16px;
|
||||||
|
border-bottom: 2px solid transparent;
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
margin-bottom: -1px;
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
#tabs .active {
|
||||||
|
border-bottom-color: #f00;
|
||||||
|
color: #222;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab-container .content {
|
||||||
|
display: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 页面布局 */
|
||||||
|
.main {
|
||||||
|
padding: 30px 100px;
|
||||||
|
width: 960px;
|
||||||
|
margin: 0 auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main .logo {
|
||||||
|
color: #333;
|
||||||
|
text-align: left;
|
||||||
|
margin-bottom: 30px;
|
||||||
|
line-height: 1;
|
||||||
|
height: 110px;
|
||||||
|
margin-top: -50px;
|
||||||
|
overflow: hidden;
|
||||||
|
*zoom: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.main .logo a {
|
||||||
|
font-size: 160px;
|
||||||
|
color: #333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.helps {
|
||||||
|
margin-top: 40px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.helps pre {
|
||||||
|
padding: 20px;
|
||||||
|
margin: 10px 0;
|
||||||
|
border: solid 1px #e7e1cd;
|
||||||
|
background-color: #fffdef;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon_lists {
|
||||||
|
width: 100% !important;
|
||||||
|
overflow: hidden;
|
||||||
|
*zoom: 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon_lists li {
|
||||||
|
width: 100px;
|
||||||
|
margin-bottom: 10px;
|
||||||
|
margin-right: 20px;
|
||||||
|
text-align: center;
|
||||||
|
list-style: none !important;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon_lists li .code-name {
|
||||||
|
line-height: 1.2;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon_lists .icon {
|
||||||
|
display: block;
|
||||||
|
height: 100px;
|
||||||
|
line-height: 100px;
|
||||||
|
font-size: 42px;
|
||||||
|
margin: 10px auto;
|
||||||
|
color: #333;
|
||||||
|
-webkit-transition: font-size 0.25s linear, width 0.25s linear;
|
||||||
|
-moz-transition: font-size 0.25s linear, width 0.25s linear;
|
||||||
|
transition: font-size 0.25s linear, width 0.25s linear;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon_lists .icon:hover {
|
||||||
|
font-size: 100px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon_lists .svg-icon {
|
||||||
|
/* 通过设置 font-size 来改变图标大小 */
|
||||||
|
width: 1em;
|
||||||
|
/* 图标和文字相邻时,垂直对齐 */
|
||||||
|
vertical-align: -0.15em;
|
||||||
|
/* 通过设置 color 来改变 SVG 的颜色/fill */
|
||||||
|
fill: currentColor;
|
||||||
|
/* path 和 stroke 溢出 viewBox 部分在 IE 下会显示
|
||||||
|
normalize.css 中也包含这行 */
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon_lists li .name,
|
||||||
|
.icon_lists li .code-name {
|
||||||
|
color: #666;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* markdown 样式 */
|
||||||
|
.markdown {
|
||||||
|
color: #666;
|
||||||
|
font-size: 14px;
|
||||||
|
line-height: 1.8;
|
||||||
|
}
|
||||||
|
|
||||||
|
.highlight {
|
||||||
|
line-height: 1.5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown img {
|
||||||
|
vertical-align: middle;
|
||||||
|
max-width: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown h1 {
|
||||||
|
color: #404040;
|
||||||
|
font-weight: 500;
|
||||||
|
line-height: 40px;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown h2,
|
||||||
|
.markdown h3,
|
||||||
|
.markdown h4,
|
||||||
|
.markdown h5,
|
||||||
|
.markdown h6 {
|
||||||
|
color: #404040;
|
||||||
|
margin: 1.6em 0 0.6em 0;
|
||||||
|
font-weight: 500;
|
||||||
|
clear: both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown h1 {
|
||||||
|
font-size: 28px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown h2 {
|
||||||
|
font-size: 22px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown h3 {
|
||||||
|
font-size: 16px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown h4 {
|
||||||
|
font-size: 14px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown h5 {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown h6 {
|
||||||
|
font-size: 12px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown hr {
|
||||||
|
height: 1px;
|
||||||
|
border: 0;
|
||||||
|
background: #e9e9e9;
|
||||||
|
margin: 16px 0;
|
||||||
|
clear: both;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown p {
|
||||||
|
margin: 1em 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown>p,
|
||||||
|
.markdown>blockquote,
|
||||||
|
.markdown>.highlight,
|
||||||
|
.markdown>ol,
|
||||||
|
.markdown>ul {
|
||||||
|
width: 80%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown ul>li {
|
||||||
|
list-style: circle;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown>ul li,
|
||||||
|
.markdown blockquote ul>li {
|
||||||
|
margin-left: 20px;
|
||||||
|
padding-left: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown>ul li p,
|
||||||
|
.markdown>ol li p {
|
||||||
|
margin: 0.6em 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown ol>li {
|
||||||
|
list-style: decimal;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown>ol li,
|
||||||
|
.markdown blockquote ol>li {
|
||||||
|
margin-left: 20px;
|
||||||
|
padding-left: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown code {
|
||||||
|
margin: 0 3px;
|
||||||
|
padding: 0 5px;
|
||||||
|
background: #eee;
|
||||||
|
border-radius: 3px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown strong,
|
||||||
|
.markdown b {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown>table {
|
||||||
|
border-collapse: collapse;
|
||||||
|
border-spacing: 0px;
|
||||||
|
empty-cells: show;
|
||||||
|
border: 1px solid #e9e9e9;
|
||||||
|
width: 95%;
|
||||||
|
margin-bottom: 24px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown>table th {
|
||||||
|
white-space: nowrap;
|
||||||
|
color: #333;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown>table th,
|
||||||
|
.markdown>table td {
|
||||||
|
border: 1px solid #e9e9e9;
|
||||||
|
padding: 8px 16px;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown>table th {
|
||||||
|
background: #F7F7F7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown blockquote {
|
||||||
|
font-size: 90%;
|
||||||
|
color: #999;
|
||||||
|
border-left: 4px solid #e9e9e9;
|
||||||
|
padding-left: 0.8em;
|
||||||
|
margin: 1em 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown blockquote p {
|
||||||
|
margin: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown .anchor {
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.3s ease;
|
||||||
|
margin-left: 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown .waiting {
|
||||||
|
color: #ccc;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown h1:hover .anchor,
|
||||||
|
.markdown h2:hover .anchor,
|
||||||
|
.markdown h3:hover .anchor,
|
||||||
|
.markdown h4:hover .anchor,
|
||||||
|
.markdown h5:hover .anchor,
|
||||||
|
.markdown h6:hover .anchor {
|
||||||
|
opacity: 1;
|
||||||
|
display: inline-block;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown>br,
|
||||||
|
.markdown>p>br {
|
||||||
|
clear: both;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
.hljs {
|
||||||
|
display: block;
|
||||||
|
background: white;
|
||||||
|
padding: 0.5em;
|
||||||
|
color: #333333;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs-comment,
|
||||||
|
.hljs-meta {
|
||||||
|
color: #969896;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs-string,
|
||||||
|
.hljs-variable,
|
||||||
|
.hljs-template-variable,
|
||||||
|
.hljs-strong,
|
||||||
|
.hljs-emphasis,
|
||||||
|
.hljs-quote {
|
||||||
|
color: #df5000;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs-keyword,
|
||||||
|
.hljs-selector-tag,
|
||||||
|
.hljs-type {
|
||||||
|
color: #a71d5d;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs-literal,
|
||||||
|
.hljs-symbol,
|
||||||
|
.hljs-bullet,
|
||||||
|
.hljs-attribute {
|
||||||
|
color: #0086b3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs-section,
|
||||||
|
.hljs-name {
|
||||||
|
color: #63a35c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs-tag {
|
||||||
|
color: #333333;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs-title,
|
||||||
|
.hljs-attr,
|
||||||
|
.hljs-selector-id,
|
||||||
|
.hljs-selector-class,
|
||||||
|
.hljs-selector-attr,
|
||||||
|
.hljs-selector-pseudo {
|
||||||
|
color: #795da3;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs-addition {
|
||||||
|
color: #55a532;
|
||||||
|
background-color: #eaffea;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs-deletion {
|
||||||
|
color: #bd2c00;
|
||||||
|
background-color: #ffecec;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hljs-link {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* 代码高亮 */
|
||||||
|
/* PrismJS 1.15.0
|
||||||
|
https://prismjs.com/download.html#themes=prism&languages=markup+css+clike+javascript */
|
||||||
|
/**
|
||||||
|
* prism.js default theme for JavaScript, CSS and HTML
|
||||||
|
* Based on dabblet (http://dabblet.com)
|
||||||
|
* @author Lea Verou
|
||||||
|
*/
|
||||||
|
code[class*="language-"],
|
||||||
|
pre[class*="language-"] {
|
||||||
|
color: black;
|
||||||
|
background: none;
|
||||||
|
text-shadow: 0 1px white;
|
||||||
|
font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
|
||||||
|
text-align: left;
|
||||||
|
white-space: pre;
|
||||||
|
word-spacing: normal;
|
||||||
|
word-break: normal;
|
||||||
|
word-wrap: normal;
|
||||||
|
line-height: 1.5;
|
||||||
|
|
||||||
|
-moz-tab-size: 4;
|
||||||
|
-o-tab-size: 4;
|
||||||
|
tab-size: 4;
|
||||||
|
|
||||||
|
-webkit-hyphens: none;
|
||||||
|
-moz-hyphens: none;
|
||||||
|
-ms-hyphens: none;
|
||||||
|
hyphens: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
pre[class*="language-"]::-moz-selection,
|
||||||
|
pre[class*="language-"] ::-moz-selection,
|
||||||
|
code[class*="language-"]::-moz-selection,
|
||||||
|
code[class*="language-"] ::-moz-selection {
|
||||||
|
text-shadow: none;
|
||||||
|
background: #b3d4fc;
|
||||||
|
}
|
||||||
|
|
||||||
|
pre[class*="language-"]::selection,
|
||||||
|
pre[class*="language-"] ::selection,
|
||||||
|
code[class*="language-"]::selection,
|
||||||
|
code[class*="language-"] ::selection {
|
||||||
|
text-shadow: none;
|
||||||
|
background: #b3d4fc;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media print {
|
||||||
|
|
||||||
|
code[class*="language-"],
|
||||||
|
pre[class*="language-"] {
|
||||||
|
text-shadow: none;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Code blocks */
|
||||||
|
pre[class*="language-"] {
|
||||||
|
padding: 1em;
|
||||||
|
margin: .5em 0;
|
||||||
|
overflow: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
:not(pre)>code[class*="language-"],
|
||||||
|
pre[class*="language-"] {
|
||||||
|
background: #f5f2f0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Inline code */
|
||||||
|
:not(pre)>code[class*="language-"] {
|
||||||
|
padding: .1em;
|
||||||
|
border-radius: .3em;
|
||||||
|
white-space: normal;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.comment,
|
||||||
|
.token.prolog,
|
||||||
|
.token.doctype,
|
||||||
|
.token.cdata {
|
||||||
|
color: slategray;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.punctuation {
|
||||||
|
color: #999;
|
||||||
|
}
|
||||||
|
|
||||||
|
.namespace {
|
||||||
|
opacity: .7;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.property,
|
||||||
|
.token.tag,
|
||||||
|
.token.boolean,
|
||||||
|
.token.number,
|
||||||
|
.token.constant,
|
||||||
|
.token.symbol,
|
||||||
|
.token.deleted {
|
||||||
|
color: #905;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.selector,
|
||||||
|
.token.attr-name,
|
||||||
|
.token.string,
|
||||||
|
.token.char,
|
||||||
|
.token.builtin,
|
||||||
|
.token.inserted {
|
||||||
|
color: #690;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.operator,
|
||||||
|
.token.entity,
|
||||||
|
.token.url,
|
||||||
|
.language-css .token.string,
|
||||||
|
.style .token.string {
|
||||||
|
color: #9a6e3a;
|
||||||
|
background: hsla(0, 0%, 100%, .5);
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.atrule,
|
||||||
|
.token.attr-value,
|
||||||
|
.token.keyword {
|
||||||
|
color: #07a;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.function,
|
||||||
|
.token.class-name {
|
||||||
|
color: #DD4A68;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.regex,
|
||||||
|
.token.important,
|
||||||
|
.token.variable {
|
||||||
|
color: #e90;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.important,
|
||||||
|
.token.bold {
|
||||||
|
font-weight: bold;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.italic {
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
.token.entity {
|
||||||
|
cursor: help;
|
||||||
|
}
|
||||||
@ -0,0 +1,113 @@
|
|||||||
|
@font-face {font-family: "iconfont";
|
||||||
|
src: url('iconfont.eot?t=1556453824121'); /* IE9 */
|
||||||
|
src: url('iconfont.eot?t=1556453824121#iefix') format('embedded-opentype'), /* IE6-IE8 */
|
||||||
|
url('data:application/x-font-woff2;charset=utf-8;base64,d09GMgABAAAAAAj4AAsAAAAAEpAAAAirAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHEIGVgCGCgqSBI8oATYCJANkCzQABCAFhG0HgyMbNxBRlHJSPrI/QCa34oe0RdSJe8owZa62zYloz17rYnli8QhMmvikYAJefgAAFkwnj+C///1e97kz73EAQWVFEThWKQpT476tirE1joVEVznJ8tWPB55x2B+ERoUMVlB97otIe4tCOrheBeu5wvfqXuWEZRdZfdlKzPrW2VYk+X7P5wBPxZXXzJ06TDQ2c5O5+H85258Enamgvp7sOqIysiJ2A+8EPEVM20VPIl4FP1lZ/N0p8e/uXvtGkTVvyxNII0m4Hmji/ecGB0gDD7rYiQT+JbnBtek20CLtkw0iRzifEVSqP7/fzyqi0eyQCO3X9Aw53/1iapEkXmmQRLwx8dJYMw19pa20Poux6cEqwLcKK5Z5NQRq80oF1Jy6cEN0cYIvVJuxuRZdIQXP8JVSnCuODEY7ZMrAj2lK4Ml+//osqlNCkgUhrvUwdtKII+/FSwK9TnofNEGvOR0wOQ4M7IJDr5SGn4Jc3LUFtap+sE8A0+Jj935/J/KjMEqiMuqjIfJh5bnxY3ho44Nojyx1RHGUR53tskNYZ0RZmZYtX0YUKlVuWymoZv+BlxiXyRVKlVqj1affgEEJEiVJliJVmnQUCqvaAlSJwkminQBCdAASohtgiB6AI3oBGaIPkCP6AQViAFAihgAVYgRQI0YBDWIC0CImAX2IKUA/Yh4wgFgADBIngCHiBWCY52UZI7ZwBTJGIfwMwBgvYTLGIQyHjAkIy9CASYAp84g9OCDdgB0gRD+4ySTJuAK7N0V5WCQlYzv4WuHlgJVt0061s6bW2kWnlLfuVaWnuahX521RlKXLNceyweWeecvb2hF3c9Oh8aV4DhiRY5RXM7W/AUvmvtMzEOCWJtZgUBiBsqyMzGwirIzk5hGFqKQJVrGCrYioFAnShEDSPq2TVzJ04TY85kvApVfw+5k8F0utOc5VRZwPyj0sTaGIQByMaAnIGN6iXYVZ4WWAdM9oZQJS3KzZ56PbzG/D01g7S7ajApDB4CS3SVoNZ0xDqoAsMis4y69nh9kN2YGOQbF53bjBHMxQOJV5ZXZkU8hW1VNCB45CZ7aKeA2JoS2C64hQLQrJt5h9uIBKkEUAKdKUoKzWaO592G8dQeVjUZ4KSYNYdMzoQVMoe/Wh+fj6BeTX9fvLmGC2mqb7h7MP65Nt8tjP/tpl2+RJs0PAECLoZH5JZx5J1d1njTPXL5sXY+nJBnla7HC2TyTUZ/I86XMOpsRuyLVLzitniC5UVttuLPQE+DFE1mFtp38YtapVpk+4SD8hMcKXAT3bktBZgs9kGRjiHWMPfJ28OWe0mc8DuCwdZq+VdfKJirMsMOs4S6OshWCJyJJelMdsJhez6AHSHp/Pz1es/EbwDNIpZYQZ8ARQEa5eYcx5JSpGhoppus7x6Lu+Xof84/b4AMMz4vs2ue1g2oC0sw5pvaOu8lf/z3mARm7uJMAzfiwSmTA2UqbCLkeJtdi6oUM0P9FBksbzQxQcy8ANrEaPI8b3Vw4rqhzKgFXyGoAe40uff1o1gf0YrSMYTOj8CTAReY0mRDaUPXsPeas9jyNaR5BVZ7pbIAPtjhPROh99YD8g98UxTee6n2o7q3c0QsHod7N2KqOJeXkTEatPwXr1g2u+w7a5NlsPgSZZH7raAlw+mbuJzpXMKg3ajDPQy3Bf5cG0/geQInXX/+7YPRWJBbAuxiVTYgN/2JaMaKlNnWKuwXQX13QtzFON2noHrkmXBEqbsFMAYsJ1SlInDxwjdUkJDF9WBCQEonUcboJSBvJTJHU4TJkLLro6jSChUYK/rX01Vo02jOJZFevBT/GhHHv4UqU6YX2ozArHths3wvxI4/vIcp0a3sLXgu9jnkbsjHgybJRLD92+fdQwF4s/hP9le5+EvgljPX09fbZtaz08bfiaw09yPWzrpxGw1dULWwdT2KH8Opmwqqh3ZOWZxfVoeKnd3bVbSrhBBxbHTZsWV1zPKIvy1hi4jW2bhaqq0CxJmZSx8b+ly66EvodCT5Ytm+Y7Y7XCfYlyYtUxTk6cXKL49jjniYYOT6T65VeTg+tPTNrMdNARm/ybQ0s6PeN+Sa/0wbH/nFtHW6KVOG3vtS/sN8SbwZ8/7q6t7e0/qe3DVfSpl5ObtZue/wId119QPxZcH73pH7gXqetn70WELR+fIsurp6Mnj8UZSZlnPx2Jx5L1ay5MTV1Yf1XQ8KwLp5pXz5xu7yDZlfW3y5XmidX/S0D6ln4KYKmfiyprCw/Hmi2Bvl9U/iXpsb/jouISXsqA7sGi6HhtMbgqsdtaF6NTbwvTEN3PMj1rcX8db8W/qcuTj+cc+F/GH9GT/n6+9cXO6FRQPb2UCNSa/fLlCvbydYpQTtXy3yW2w4gptTryEqjlKPgqtgx7NyzRWGHuP0A05kclhTk0leMqOhx3ozKNfczheBpV21F/fGPEklYKroBt24iSQedRSb/PaHB8ig7Ht1GZcV/TcnjGomqPAQvO2FjPB3mcQDMY1RhUNsUy09UsnerXIK+9JpYy2ukWUGWxVFs3bdkWn4YSqIl9qr58G3OmMsKgTml7gPeomoS9kPKmAkXNfZs3Z7N7bEoxCOkSARoDhjJk0Ew6KYVK2cRMxh7/GpCreRpltLtKegsgFWtQqn5n2i1ge1pQFmp3KHWX9clts8J0GUVNCQqUOqYDXhYgZUG9WS+QYptMVMhr2qeC9TdWVLCpe1G4LWYBNXH4VJJMrky5CpWqvgZfZKs+9WtAgxrSsEY0qjGNa0KTmtI0UWNIQfPGBnozz7dJmyBtZBjg2bFVFKAN0MY5s/62jnlt47Wd1w7PnbOqWtbepgsnOm+roaxQew8MZkECKevQuLZEyaL4aY0Mvc+u7BBU3rlisg64IKzzomAituxhrqwuWSxvS2i3uhwS7yC3sU+T1SW3ERhMjJRY2Xa2ASgpkbrktwXKzO4HzcVe1Es91mZQCA==') format('woff2'),
|
||||||
|
url('iconfont.woff?t=1556453824121') format('woff'),
|
||||||
|
url('iconfont.ttf?t=1556453824121') format('truetype'), /* chrome, firefox, opera, Safari, Android, iOS 4.2+ */
|
||||||
|
url('iconfont.svg?t=1556453824121#iconfont') format('svg'); /* iOS 4.1- */
|
||||||
|
}
|
||||||
|
|
||||||
|
.iconfont {
|
||||||
|
font-family: "iconfont" !important;
|
||||||
|
font-size: 16px;
|
||||||
|
font-style: normal;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
-moz-osx-font-smoothing: grayscale;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-bold:before {
|
||||||
|
content: "\e757";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-color-text:before {
|
||||||
|
content: "\e758";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-header-:before {
|
||||||
|
content: "\e75b";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-header-1:before {
|
||||||
|
content: "\e75c";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-header-2:before {
|
||||||
|
content: "\e75d";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-header-3:before {
|
||||||
|
content: "\e75e";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-header-4:before {
|
||||||
|
content: "\e75f";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-header-5:before {
|
||||||
|
content: "\e760";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-italic:before {
|
||||||
|
content: "\e762";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-list-bulleted:before {
|
||||||
|
content: "\e764";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-list-numbers:before {
|
||||||
|
content: "\e765";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-quote:before {
|
||||||
|
content: "\e768";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-size:before {
|
||||||
|
content: "\e769";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-strikethrough:before {
|
||||||
|
content: "\e76a";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-title:before {
|
||||||
|
content: "\e76f";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-format-underline:before {
|
||||||
|
content: "\e770";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-image:before {
|
||||||
|
content: "\e7ac";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-link-variant:before {
|
||||||
|
content: "\e7d8";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-redo:before {
|
||||||
|
content: "\e873";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-redo-variant:before {
|
||||||
|
content: "\e874";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-timer:before {
|
||||||
|
content: "\e8eb";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-undo-variant:before {
|
||||||
|
content: "\e907";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-undo:before {
|
||||||
|
content: "\e908";
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon-weather-cloudy:before {
|
||||||
|
content: "\e92d";
|
||||||
|
}
|
||||||
|
|
||||||
Binary file not shown.
File diff suppressed because one or more lines are too long
|
After Width: | Height: | Size: 12 KiB |
Binary file not shown.
Binary file not shown.
Binary file not shown.
@ -0,0 +1,29 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
class CustomizePhysics extends ScrollPhysics {
|
||||||
|
const CustomizePhysics({
|
||||||
|
ScrollPhysics? parent,
|
||||||
|
}) : super(parent: parent);
|
||||||
|
|
||||||
|
@override
|
||||||
|
CustomizePhysics applyTo(ScrollPhysics? ancestor) {
|
||||||
|
return CustomizePhysics(parent: buildParent(ancestor));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool shouldAcceptUserOffset(ScrollMetrics position) => false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get allowImplicitScrolling => false;
|
||||||
|
|
||||||
|
@override
|
||||||
|
double applyBoundaryConditions(ScrollMetrics position, double value) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Simulation? createBallisticSimulation(
|
||||||
|
ScrollMetrics position, double velocity) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
@ -0,0 +1,4 @@
|
|||||||
|
library markdown_editor;
|
||||||
|
|
||||||
|
export 'package:markdown_editor_ot/src/editor.dart';
|
||||||
|
export 'package:markdown_editor_ot/src/preview.dart';
|
||||||
@ -0,0 +1,82 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
|
||||||
|
/// 撤销与前进
|
||||||
|
class EditPerform {
|
||||||
|
EditPerform(
|
||||||
|
this._textEditingController, {
|
||||||
|
this.initText = '',
|
||||||
|
});
|
||||||
|
|
||||||
|
/// 最大的存储长度
|
||||||
|
final _maxLength = 50;
|
||||||
|
|
||||||
|
/// 初始文本
|
||||||
|
final String initText;
|
||||||
|
|
||||||
|
var _undoList = <_EditData>[];
|
||||||
|
var _redoList = <_EditData>[];
|
||||||
|
|
||||||
|
final TextEditingController _textEditingController;
|
||||||
|
|
||||||
|
void change(text) {
|
||||||
|
if (_textEditingController.text != '') {
|
||||||
|
if (_undoList.isNotEmpty) {
|
||||||
|
if (_textEditingController.text == _undoList.last.text) return;
|
||||||
|
}
|
||||||
|
if (_undoList.length >= _maxLength) _undoList.removeAt(0);
|
||||||
|
_undoList.add(_EditData(_textEditingController.text,
|
||||||
|
_textEditingController.selection.baseOffset));
|
||||||
|
_redoList.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 撤销
|
||||||
|
void undo() {
|
||||||
|
// print(_undoList);
|
||||||
|
if (_undoList.isNotEmpty) {
|
||||||
|
_redoList.add(_undoList.last);
|
||||||
|
_undoList.removeLast();
|
||||||
|
if (_undoList.isNotEmpty) {
|
||||||
|
_textEditingController.value = TextEditingValue(
|
||||||
|
text: _undoList.last.text,
|
||||||
|
selection: TextSelection(
|
||||||
|
extentOffset: _undoList.last.position,
|
||||||
|
baseOffset: _undoList.last.position),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
_textEditingController.value = TextEditingValue(
|
||||||
|
text: initText,
|
||||||
|
selection: TextSelection(
|
||||||
|
extentOffset: initText.length, baseOffset: initText.length),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 恢复
|
||||||
|
void redo() {
|
||||||
|
// print(_redoList);
|
||||||
|
if (_redoList.isNotEmpty) {
|
||||||
|
_textEditingController.value = TextEditingValue(
|
||||||
|
text: _redoList.last.text,
|
||||||
|
selection: TextSelection(
|
||||||
|
extentOffset: _redoList.last.position,
|
||||||
|
baseOffset: _redoList.last.position),
|
||||||
|
);
|
||||||
|
_undoList.add(_redoList.last);
|
||||||
|
_redoList.removeLast();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class _EditData {
|
||||||
|
final String text;
|
||||||
|
final int position;
|
||||||
|
|
||||||
|
_EditData(this.text, this.position);
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() {
|
||||||
|
return 'text:$text position:$position';
|
||||||
|
}
|
||||||
|
}
|
||||||
@ -0,0 +1,352 @@
|
|||||||
|
import 'dart:async';
|
||||||
|
|
||||||
|
import 'package:flutter/foundation.dart';
|
||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:markdown_editor_ot/src/action.dart';
|
||||||
|
import 'package:markdown_editor_ot/customize_physics.dart';
|
||||||
|
import 'package:markdown_editor_ot/src/edit_perform.dart';
|
||||||
|
import 'package:shared_preferences/shared_preferences.dart';
|
||||||
|
|
||||||
|
typedef void OnComplete(String content);
|
||||||
|
|
||||||
|
class MdEditor extends StatefulWidget {
|
||||||
|
MdEditor({
|
||||||
|
Key? key,
|
||||||
|
this.textStyle,
|
||||||
|
this.padding = const EdgeInsets.all(0.0),
|
||||||
|
this.initText,
|
||||||
|
this.hintText,
|
||||||
|
this.hintTextStyle,
|
||||||
|
this.imageSelect,
|
||||||
|
this.textChange,
|
||||||
|
this.actionIconColor,
|
||||||
|
this.cursorColor,
|
||||||
|
this.appendBottomWidget,
|
||||||
|
this.splitWidget,
|
||||||
|
this.textFocusNode,
|
||||||
|
required this.onComplete,
|
||||||
|
}) : super(key: key);
|
||||||
|
|
||||||
|
final TextStyle? textStyle;
|
||||||
|
final TextStyle? hintTextStyle;
|
||||||
|
final EdgeInsetsGeometry padding;
|
||||||
|
final String? initText;
|
||||||
|
final String? hintText;
|
||||||
|
|
||||||
|
/// see [ImageSelectCallback]
|
||||||
|
final ImageSelectCallback? imageSelect;
|
||||||
|
|
||||||
|
final VoidCallback? textChange;
|
||||||
|
|
||||||
|
/// Change icon color, eg: color of font_bold icon.
|
||||||
|
final Color? actionIconColor;
|
||||||
|
|
||||||
|
final Color? cursorColor;
|
||||||
|
|
||||||
|
final Widget? appendBottomWidget;
|
||||||
|
|
||||||
|
final Widget? splitWidget;
|
||||||
|
|
||||||
|
final FocusNode? textFocusNode;
|
||||||
|
|
||||||
|
final OnComplete onComplete;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<StatefulWidget> createState() => MdEditorState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class MdEditorState extends State<MdEditor> with AutomaticKeepAliveClientMixin {
|
||||||
|
final _textEditingController = TextEditingController(text: '');
|
||||||
|
var _editPerform;
|
||||||
|
SharedPreferences? _pres;
|
||||||
|
|
||||||
|
String getText() {
|
||||||
|
return _textEditingController.value.text;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 将文本框光标移动至末尾
|
||||||
|
void moveTextCursorToEnd() {
|
||||||
|
final str = _textEditingController.text;
|
||||||
|
_textEditingController.value = TextEditingValue(text: str, selection: TextSelection.collapsed(offset: str.length));
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
void initState() {
|
||||||
|
super.initState();
|
||||||
|
_textEditingController.text = widget.initText ?? '';
|
||||||
|
|
||||||
|
_editPerform = EditPerform(
|
||||||
|
_textEditingController,
|
||||||
|
initText: _textEditingController.text,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void _disposeText(
|
||||||
|
ActionType type,
|
||||||
|
String text,
|
||||||
|
int index, [
|
||||||
|
int? cursorPosition,
|
||||||
|
]) {
|
||||||
|
final _tempKey = 'markdown_editor_${type.toString()}';
|
||||||
|
_pres?.setInt(_tempKey, (_pres?.getInt(_tempKey) ?? 0) + 1);
|
||||||
|
debugPrint('$_tempKey ${_pres?.getInt(_tempKey)}');
|
||||||
|
|
||||||
|
var position = cursorPosition ?? _textEditingController.selection.base.offset;
|
||||||
|
|
||||||
|
if (position < 0) {
|
||||||
|
print('WARN: The insert position value is $position');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
var startText = _textEditingController.text.substring(0, position);
|
||||||
|
var endText = _textEditingController.text.substring(position);
|
||||||
|
|
||||||
|
var str = startText + text + endText;
|
||||||
|
_textEditingController.value =
|
||||||
|
TextEditingValue(text: str, selection: TextSelection.collapsed(offset: startText.length + text.length - index));
|
||||||
|
|
||||||
|
if (widget.textChange != null) widget.textChange!();
|
||||||
|
|
||||||
|
_editPerform.change(_textEditingController.text);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 获取光标位置
|
||||||
|
int _getCursorPosition() {
|
||||||
|
if (_textEditingController.text.isEmpty) return 0;
|
||||||
|
if (_textEditingController.selection.base.offset < 0) return _textEditingController.text.length;
|
||||||
|
return _textEditingController.selection.base.offset;
|
||||||
|
}
|
||||||
|
|
||||||
|
Future<void> _initSharedPreferences() async {
|
||||||
|
_pres = await SharedPreferences.getInstance();
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
super.build(context);
|
||||||
|
return Stack(
|
||||||
|
children: [
|
||||||
|
Padding(
|
||||||
|
padding: const EdgeInsets.only(bottom: 40.0),
|
||||||
|
child: SingleChildScrollView(
|
||||||
|
child: Padding(
|
||||||
|
padding: widget.padding,
|
||||||
|
child: Column(
|
||||||
|
crossAxisAlignment: CrossAxisAlignment.start,
|
||||||
|
children: <Widget>[
|
||||||
|
TextField(
|
||||||
|
maxLines: null,
|
||||||
|
minLines: 7,
|
||||||
|
textAlignVertical: TextAlignVertical.top,
|
||||||
|
cursorColor: widget.cursorColor,
|
||||||
|
cursorWidth: 1.5,
|
||||||
|
controller: _textEditingController,
|
||||||
|
focusNode: widget.textFocusNode,
|
||||||
|
autofocus: false,
|
||||||
|
scrollPhysics: const CustomizePhysics(),
|
||||||
|
style: widget.textStyle ??
|
||||||
|
TextStyle(
|
||||||
|
fontSize: 17,
|
||||||
|
height: kIsWeb ? null : 1.3,
|
||||||
|
),
|
||||||
|
onChanged: (text) {
|
||||||
|
_editPerform.change(text);
|
||||||
|
if (widget.textChange != null) widget.textChange!();
|
||||||
|
},
|
||||||
|
decoration: InputDecoration(
|
||||||
|
hintText: widget.hintText ?? '请输入内容',
|
||||||
|
border: InputBorder.none,
|
||||||
|
hintStyle: widget.hintTextStyle,
|
||||||
|
),
|
||||||
|
),
|
||||||
|
widget.appendBottomWidget ?? const SizedBox(),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
Align(
|
||||||
|
alignment: Alignment.bottomLeft,
|
||||||
|
child: Container(
|
||||||
|
height: 40.0,
|
||||||
|
width: MediaQuery.of(context).size.width,
|
||||||
|
child: Ink(
|
||||||
|
decoration: BoxDecoration(
|
||||||
|
color: Theme.of(context).brightness == Brightness.dark ? Colors.black87 : const Color(0xFFF0F0F0),
|
||||||
|
boxShadow: [
|
||||||
|
BoxShadow(
|
||||||
|
color:
|
||||||
|
Theme.of(context).brightness == Brightness.dark ? Colors.black87 : const Color(0xAAF0F0F0)),
|
||||||
|
],
|
||||||
|
),
|
||||||
|
child: FutureBuilder(
|
||||||
|
future: _pres == null ? _initSharedPreferences() : null,
|
||||||
|
builder: (con, snap) {
|
||||||
|
final widgets = <ActionImage>[];
|
||||||
|
|
||||||
|
widgets.add(ActionImage(
|
||||||
|
type: ActionType.done,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: (t, s, i, [p]) {
|
||||||
|
widget.onComplete(getText());
|
||||||
|
},
|
||||||
|
));
|
||||||
|
|
||||||
|
widgets.add(ActionImage(
|
||||||
|
type: ActionType.undo,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: (t, s, i, [p]) {
|
||||||
|
_editPerform.undo();
|
||||||
|
},
|
||||||
|
));
|
||||||
|
widgets.add(ActionImage(
|
||||||
|
type: ActionType.redo,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: (t, s, i, [p]) {
|
||||||
|
_editPerform.redo();
|
||||||
|
},
|
||||||
|
));
|
||||||
|
|
||||||
|
// sort
|
||||||
|
if (snap.connectionState == ConnectionState.done || snap.connectionState == ConnectionState.none)
|
||||||
|
widgets.addAll(_getSortActionWidgets().map((sort) => sort.widget));
|
||||||
|
|
||||||
|
return SingleChildScrollView(
|
||||||
|
scrollDirection: Axis.horizontal,
|
||||||
|
child: Row(
|
||||||
|
children: widgets,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sort action buttons by used count.
|
||||||
|
List<_SortActionWidget> _getSortActionWidgets() {
|
||||||
|
final sortWidget = <_SortActionWidget>[];
|
||||||
|
final key = 'markdown_editor';
|
||||||
|
final getSortValue = (ActionType type) {
|
||||||
|
return int.parse((_pres?.get('${key}_${type.toString()}') ?? '0').toString());
|
||||||
|
};
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.image),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.image,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
imageSelect: widget.imageSelect,
|
||||||
|
getCursorPosition: _getCursorPosition,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.link),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.link,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.fontBold),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.fontBold,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.fontItalic),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.fontItalic,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.fontStrikethrough),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.fontStrikethrough,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.textQuote),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.textQuote,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.list),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.list,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.h4),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.h4,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.h5),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.h5,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.h1),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.h1,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.h2),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.h2,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
sortWidget.add(_SortActionWidget(
|
||||||
|
sortValue: getSortValue(ActionType.h3),
|
||||||
|
widget: ActionImage(
|
||||||
|
type: ActionType.h3,
|
||||||
|
color: widget.actionIconColor,
|
||||||
|
tap: _disposeText,
|
||||||
|
),
|
||||||
|
));
|
||||||
|
|
||||||
|
sortWidget.sort((a, b) => (b.sortValue).compareTo(a.sortValue));
|
||||||
|
|
||||||
|
return sortWidget;
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get wantKeepAlive => true;
|
||||||
|
}
|
||||||
|
|
||||||
|
class _SortActionWidget {
|
||||||
|
final ActionImage widget;
|
||||||
|
final int sortValue;
|
||||||
|
|
||||||
|
_SortActionWidget({
|
||||||
|
required this.widget,
|
||||||
|
required this.sortValue,
|
||||||
|
});
|
||||||
|
}
|
||||||
@ -0,0 +1,64 @@
|
|||||||
|
import 'package:flutter/material.dart';
|
||||||
|
import 'package:markdown_core/builder.dart';
|
||||||
|
import 'package:markdown_core/markdown.dart';
|
||||||
|
|
||||||
|
class MdPreview extends StatefulWidget {
|
||||||
|
MdPreview({
|
||||||
|
Key? key,
|
||||||
|
required this.text,
|
||||||
|
this.padding = const EdgeInsets.all(0.0),
|
||||||
|
this.onTapLink,
|
||||||
|
required this.widgetImage,
|
||||||
|
required this.onCodeCopied,
|
||||||
|
this.textStyle,
|
||||||
|
}) : super(key: key);
|
||||||
|
|
||||||
|
final String text;
|
||||||
|
final EdgeInsetsGeometry padding;
|
||||||
|
final WidgetImage widgetImage;
|
||||||
|
final TextStyle? textStyle;
|
||||||
|
|
||||||
|
final Function onCodeCopied;
|
||||||
|
|
||||||
|
/// Call this method when it tap link of markdown.
|
||||||
|
/// If [onTapLink] is null,it will open the link with your default browser.
|
||||||
|
final TapLinkCallback? onTapLink;
|
||||||
|
|
||||||
|
@override
|
||||||
|
State<StatefulWidget> createState() => MdPreviewState();
|
||||||
|
}
|
||||||
|
|
||||||
|
class MdPreviewState extends State<MdPreview>
|
||||||
|
with AutomaticKeepAliveClientMixin {
|
||||||
|
@override
|
||||||
|
Widget build(BuildContext context) {
|
||||||
|
super.build(context);
|
||||||
|
return SingleChildScrollView(
|
||||||
|
child: Padding(
|
||||||
|
padding: widget.padding,
|
||||||
|
child: LayoutBuilder(
|
||||||
|
builder: (BuildContext context, BoxConstraints constraints) {
|
||||||
|
return Markdown(
|
||||||
|
data: widget.text,
|
||||||
|
maxWidth: constraints.maxWidth,
|
||||||
|
linkTap: (link) {
|
||||||
|
debugPrint(link);
|
||||||
|
if (widget.onTapLink != null) {
|
||||||
|
widget.onTapLink!(link);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
image: widget.widgetImage,
|
||||||
|
textStyle: widget.textStyle,
|
||||||
|
onCodeCopied: widget.onCodeCopied,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@override
|
||||||
|
bool get wantKeepAlive => true;
|
||||||
|
}
|
||||||
|
|
||||||
|
typedef void TapLinkCallback(String link);
|
||||||
@ -0,0 +1,63 @@
|
|||||||
|
name: markdown_editor_ot
|
||||||
|
description: Simple and easy to implement your markdown editor, it uses its own parser.
|
||||||
|
version: 1.0.2
|
||||||
|
homepage: https://github.com/xia-weiyang/markdown_editor_ot
|
||||||
|
|
||||||
|
environment:
|
||||||
|
sdk: '>=2.12.0 <3.0.0'
|
||||||
|
|
||||||
|
dependencies:
|
||||||
|
flutter:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
|
shared_preferences: ^2.0.4
|
||||||
|
markdown_core:
|
||||||
|
path:
|
||||||
|
../markdown_core
|
||||||
|
|
||||||
|
dev_dependencies:
|
||||||
|
flutter_test:
|
||||||
|
sdk: flutter
|
||||||
|
|
||||||
|
# For information on the generic Dart part of this file, see the
|
||||||
|
# following page: https://www.dartlang.org/tools/pub/pubspec
|
||||||
|
|
||||||
|
# The following section is specific to Flutter.
|
||||||
|
flutter:
|
||||||
|
|
||||||
|
# To add assets to your package, add an assets section, like this:
|
||||||
|
# assets:
|
||||||
|
# - images/a_dot_burr.jpeg
|
||||||
|
# - images/a_dot_ham.jpeg
|
||||||
|
#
|
||||||
|
# For details regarding assets in packages, see
|
||||||
|
# https://flutter.io/assets-and-images/#from-packages
|
||||||
|
#
|
||||||
|
# An image asset can refer to one or more resolution-specific "variants", see
|
||||||
|
# https://flutter.io/assets-and-images/#resolution-aware.
|
||||||
|
|
||||||
|
# To add custom fonts to your package, add a fonts section here,
|
||||||
|
# in this "flutter" section. Each entry in this list should have a
|
||||||
|
# "family" key with the font family name, and a "fonts" key with a
|
||||||
|
# list giving the asset and other descriptors for the font. For
|
||||||
|
|
||||||
|
fonts:
|
||||||
|
- family: MyIconFont
|
||||||
|
fonts:
|
||||||
|
- asset: packages/markdown_editor_ot/fonts/iconfont.ttf
|
||||||
|
|
||||||
|
# example:
|
||||||
|
# fonts:
|
||||||
|
# - family: Schyler
|
||||||
|
# fonts:
|
||||||
|
# - asset: fonts/Schyler-Regular.ttf
|
||||||
|
# - asset: fonts/Schyler-Italic.ttf
|
||||||
|
# style: italic
|
||||||
|
# - family: Trajan Pro
|
||||||
|
# fonts:
|
||||||
|
# - asset: fonts/TrajanPro.ttf
|
||||||
|
# - asset: fonts/TrajanPro_Bold.ttf
|
||||||
|
# weight: 700
|
||||||
|
#
|
||||||
|
# For details regarding fonts in packages, see
|
||||||
|
# https://flutter.io/custom-fonts/#from-packages
|
||||||
@ -1,4 +1,8 @@
|
|||||||
class SPKeys {
|
class SPKeys {
|
||||||
static final String brightnessMode = 'BRIGHTNESS_MODE';
|
static final String brightnessMode = 'BRIGHTNESS_MODE';
|
||||||
|
static final String appliedSchemeId = 'APPLIED_SCHEME_ID';
|
||||||
static final String userLanguage = 'USER_LANGUAGE';
|
static final String userLanguage = 'USER_LANGUAGE';
|
||||||
|
static final String accessToken = 'USER_ACCESS_TOKEN';
|
||||||
|
static final String loginEmail = 'USER_LOGIN_EMAIL';
|
||||||
|
static final String ignoredUpdateVersion = 'IGNORED_UPDATE_VERSION';
|
||||||
}
|
}
|
||||||
|
|||||||
@ -1,3 +1,5 @@
|
|||||||
extension StringNotNull on String? {
|
extension StringNotNull on String? {
|
||||||
bool get notNull => this != null && this != '';
|
bool get notNull => this != null && this != '';
|
||||||
|
|
||||||
|
bool get isNull => !notNull;
|
||||||
}
|
}
|
||||||
@ -0,0 +1,135 @@
|
|||||||
|
import 'dart:convert';
|
||||||
|
import 'dart:io';
|
||||||
|
|
||||||
|
import 'package:dde_gesture_manager/constants/sp_keys.dart';
|
||||||
|
import 'package:dde_gesture_manager/extensions.dart';
|
||||||
|
import 'package:dde_gesture_manager/utils/helper.dart';
|
||||||
|
import 'package:dde_gesture_manager/utils/notificator.dart';
|
||||||
|
import 'package:dde_gesture_manager_api/apis.dart';
|
||||||
|
import 'package:dde_gesture_manager_api/models.dart';
|
||||||
|
import 'package:http/http.dart' as http;
|
||||||
|
|
||||||
|
typedef T BeanBuilder<T>(Map res);
|
||||||
|
|
||||||
|
typedef T HandleRespBuild<T>(http.Response resp);
|
||||||
|
|
||||||
|
getStatusCodeFunc<int>(Map resp) => resp["statusCode"];
|
||||||
|
|
||||||
|
class HttpErrorCode extends Error {
|
||||||
|
int statusCode;
|
||||||
|
|
||||||
|
HttpErrorCode(this.statusCode, {this.message});
|
||||||
|
|
||||||
|
String? message;
|
||||||
|
|
||||||
|
@override
|
||||||
|
String toString() => '[$statusCode] $message';
|
||||||
|
}
|
||||||
|
|
||||||
|
class Api {
|
||||||
|
static _handleHttpError(e) {
|
||||||
|
if (e is SocketException) {
|
||||||
|
Notificator.error(
|
||||||
|
H().topContext,
|
||||||
|
title: LocaleKeys.info_server_error_title.tr(),
|
||||||
|
description: LocaleKeys.info_server_error_description.tr(),
|
||||||
|
);
|
||||||
|
} else {
|
||||||
|
throw e;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static HandleRespBuild<T> _handleRespBuild<T>(BeanBuilder<T> builder) => (http.Response resp) {
|
||||||
|
if (builder == getStatusCodeFunc) return builder({"statusCode": resp.statusCode});
|
||||||
|
T res;
|
||||||
|
try {
|
||||||
|
res = builder(json.decode(resp.body));
|
||||||
|
} catch (e) {
|
||||||
|
throw HttpErrorCode(resp.statusCode, message: resp.body);
|
||||||
|
}
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
static Future<T> _get<T>(
|
||||||
|
String path,
|
||||||
|
BeanBuilder<T> builder, {
|
||||||
|
Map<String, dynamic>? queryParams,
|
||||||
|
bool ignoreToken = false,
|
||||||
|
bool ignoreErrorHandle = false,
|
||||||
|
}) =>
|
||||||
|
http
|
||||||
|
.get(
|
||||||
|
Uri(
|
||||||
|
scheme: Apis.apiScheme,
|
||||||
|
host: Apis.apiHost,
|
||||||
|
port: Apis.apiPort,
|
||||||
|
queryParameters: queryParams,
|
||||||
|
path: path,
|
||||||
|
),
|
||||||
|
headers: <String, String>{
|
||||||
|
HttpHeaders.contentTypeHeader: ContentType.json.value,
|
||||||
|
}..addAll(
|
||||||
|
ignoreToken ? {} : {HttpHeaders.authorizationHeader: 'Bearer ${H().sp.getString(SPKeys.accessToken)}'}),
|
||||||
|
)
|
||||||
|
.then(
|
||||||
|
_handleRespBuild<T>(builder),
|
||||||
|
onError: (e) {
|
||||||
|
if (ignoreErrorHandle)
|
||||||
|
throw e;
|
||||||
|
else
|
||||||
|
return _handleHttpError(e);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
static Future<T> _post<T>(
|
||||||
|
String path,
|
||||||
|
BeanBuilder<T> builder, {
|
||||||
|
Map<String, dynamic>? body,
|
||||||
|
bool ignoreToken = false,
|
||||||
|
bool ignoreErrorHandle = false,
|
||||||
|
}) =>
|
||||||
|
http
|
||||||
|
.post(
|
||||||
|
Uri(
|
||||||
|
scheme: Apis.apiScheme,
|
||||||
|
host: Apis.apiHost,
|
||||||
|
port: Apis.apiPort,
|
||||||
|
path: path,
|
||||||
|
),
|
||||||
|
body: jsonEncode(body),
|
||||||
|
headers: <String, String>{
|
||||||
|
HttpHeaders.contentTypeHeader: ContentType.json.value,
|
||||||
|
}..addAll(
|
||||||
|
ignoreToken ? {} : {HttpHeaders.authorizationHeader: 'Bearer ${H().sp.getString(SPKeys.accessToken)}'}),
|
||||||
|
)
|
||||||
|
.then(
|
||||||
|
_handleRespBuild<T>(builder),
|
||||||
|
onError: (e) {
|
||||||
|
if (ignoreErrorHandle)
|
||||||
|
throw e;
|
||||||
|
else
|
||||||
|
return _handleHttpError(e);
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
static Future<LoginSuccess?> loginOrSignup({
|
||||||
|
required String email,
|
||||||
|
required String password,
|
||||||
|
}) =>
|
||||||
|
_post<LoginSuccess?>(
|
||||||
|
Apis.auth.loginOrSignup,
|
||||||
|
LoginSuccessSerializer.fromMap,
|
||||||
|
body: {
|
||||||
|
UserFields.email: email,
|
||||||
|
UserFields.password: password,
|
||||||
|
},
|
||||||
|
ignoreToken: true,
|
||||||
|
);
|
||||||
|
|
||||||
|
static Future<AppVersion?> checkAppVersion({ignoreErrorHandle = false}) => _get<AppVersion?>(
|
||||||
|
Apis.system.appVersion,
|
||||||
|
AppVersionSerializer.fromMap,
|
||||||
|
ignoreToken: true,
|
||||||
|
ignoreErrorHandle: ignoreErrorHandle,
|
||||||
|
);
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in new issue