Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import 'dart:async';
- import 'dart:convert';
- import 'dart:developer';
- import 'dart:io';
- import 'package:cached_network_image/cached_network_image.dart';
- import 'package:firebase_auth/firebase_auth.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter/services.dart';
- import 'package:path_provider/path_provider.dart';
- import 'package:ruthumana/components/drawer.dart';
- import 'package:ruthumana/entities/attachment.dart';
- import 'package:ruthumana/entities/downloads.dart';
- import 'package:ruthumana/entities/product.dart';
- import 'package:ruthumana/loading_state.dart';
- import 'package:ruthumana/local_databases/review_download.dart';
- import 'package:ruthumana/services/api.dart';
- import 'package:ruthumana/services/folio.dart' as folio;
- import 'package:ruthumana/services/web.dart';
- import 'package:ruthumana/services/audio.dart' as Audio;
- import 'package:dio/dio.dart';
- class NewReviewScreen extends StatefulWidget {
- @override
- _NewReviewScreenState createState() {
- return _NewReviewScreenState();
- }
- }
- class _NewReviewScreenState extends State<NewReviewScreen> with LoadingState {
- Set<Product> _products = {};
- Map<String, double> _downloadProgress = {};
- List knownDownloads = [];
- @override
- void setState(fn) {
- if (mounted) {
- super.setState(fn);
- }
- }
- @override
- void initState() {
- super.initState();
- init();
- }
- init() => work(context, () async {
- var currentUser = await FirebaseAuth.instance.currentUser();
- if (currentUser == null) {
- return Navigator.of(context).pushReplacementNamed('/auth');
- }
- knownDownloads = await ReviewDownloadsDB().listAll();
- final ebookResponse = await api.get(path: 'product-types/1');
- final audiobookResponse = await api.get(path: 'product-types/2');
- return setState(() {
- final ebookResponseJson = jsonDecode(ebookResponse.body);
- final audiobookResponseJson = jsonDecode(audiobookResponse.body);
- _products = {
- ...Set<Product>.from(ebookResponseJson['products']
- .map((json) => Product.fromJson(json)))
- .where((element) => element.status == ProductStatus.Review),
- ...Set<Product>.from(audiobookResponseJson['products']
- .map((json) => Product.fromJson(json)))
- .where((element) => element.status == ProductStatus.Review)
- };
- });
- });
- download(Attachment attachment) => work(context, () async {
- final dio = Dio();
- final path = await getLocalFilePath(attachment);
- _downloadProgress[attachment.url] = 0.1;
- var downloadRequest = dio.download(
- attachment.url,
- path,
- deleteOnError: true,
- onReceiveProgress: (count, total) {
- setState(
- () {
- _downloadProgress[attachment.url] = count / total;
- },
- );
- },
- ).then(
- (value) async {
- await ReviewDownloadsDB().add({
- 'id': attachment.id,
- 'name': attachment.name,
- 'url': attachment.url,
- 'path': path
- });
- knownDownloads = await ReviewDownloadsDB().listAll();
- },
- );
- Future.wait([downloadRequest]);
- });
- _deleteDownload(Attachment attachment) async {
- setState(() {
- _downloadProgress.remove(attachment.url);
- });
- await ReviewDownloadsDB().remove({'id': attachment.id}).then((value) async {
- final file = File(await getLocalFilePath(attachment));
- if (file.existsSync()) {
- file.deleteSync();
- }
- });
- }
- openEpub(Attachment attachment) async {
- String path = await getLocalFilePath(attachment);
- return folio.openEpub(name: attachment.name, path: path);
- }
- Future<String> getLocalFilePath(Attachment attachment) async {
- final documentDirectory = await getApplicationDocumentsDirectory();
- final fileName = attachment.url.split('/').last;
- final path = '${documentDirectory.path}/$fileName';
- return path;
- }
- openMp3(Attachment attachment) async {
- final path = await getLocalFilePath(attachment);
- return Audio.openMp3(path);
- }
- FutureBuilder buildAttachmentCta(Attachment attachment) {
- final fileBuilder = () async {
- final path = await getLocalFilePath(attachment);
- final downloadProgress = await ReviewDownloadsDB().check({
- 'id': attachment.id,
- 'name': attachment.name,
- 'url': attachment.url,
- 'path': path
- });
- if (downloadProgress.isEmpty &&
- _downloadProgress[attachment.url] == null) {
- return IconButton(
- icon: Icon(Icons.cloud_download),
- onPressed: () async {
- download(attachment);
- });
- }
- if (downloadProgress.isNotEmpty ||
- _downloadProgress[attachment.url] == 1.0) {
- return Row(
- children: [
- if (attachment.fileType == 'epub')
- IconButton(
- icon: Icon(Icons.book),
- onPressed: () => openEpub(attachment),
- ),
- if (attachment.fileType == 'audiobook')
- IconButton(
- icon: Icon(Icons.play_circle_outline),
- onPressed: () => openMp3(attachment),
- ),
- IconButton(
- icon: Icon(Icons.delete),
- onPressed: () {
- return _deleteDownload(attachment);
- },
- )
- ],
- );
- }
- return Container();
- };
- return FutureBuilder<Widget>(
- builder: (BuildContext context, AsyncSnapshot<Widget> snapshot) {
- return snapshot.data;
- },
- initialData:
- IconButton(icon: CircularProgressIndicator(), onPressed: () {}),
- future: fileBuilder(),
- );
- }
- @override
- Widget build(BuildContext context) {
- return WillPopScope(
- onWillPop: () => SystemNavigator.pop(),
- child: Scaffold(
- appBar: AppBar(title: Text('Review')),
- drawer: DrawerWidget(
- selectedPath: '/review',
- ),
- body: (loading && _products.isEmpty)
- ? Center(child: CircularProgressIndicator())
- : ListView.builder(
- itemBuilder: (context, index) {
- final product = _products.elementAt(index);
- return Card(
- margin: EdgeInsets.all(16.0),
- child: ExpansionTile(
- leading: Padding(
- padding: const EdgeInsets.symmetric(vertical: 8),
- child: CachedNetworkImage(
- imageUrl: product.image,
- fit: BoxFit.cover,
- placeholder: (context, url) => Container(
- width: 64,
- height: 64,
- color: Colors.grey[300],
- ),
- ),
- ),
- title: Text(product.name),
- children: product.attachments.map((attachment) {
- return Padding(
- padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
- child: Row(
- mainAxisAlignment: MainAxisAlignment.spaceBetween,
- children: <Widget>[
- Expanded(
- child: Padding(
- padding: const EdgeInsets.only(right: 8.0),
- child: Text(attachment.name),
- ),
- ),
- // buildAttachmentCta(attachment),
- FutureBuilder(
- future: myFuture(attachment),
- builder: (context, snapshot) {
- if (snapshot.hasData) {
- if (snapshot.data &&
- _downloadProgress[attachment.url] ==
- null) {
- return IconButton(
- icon: Icon(Icons.cloud_download),
- onPressed: () async {
- download(attachment);
- });
- }
- if (!snapshot.data ||
- _downloadProgress[attachment.url] ==
- 1.0) {
- return Row(
- children: [
- if (attachment.fileType == 'epub')
- IconButton(
- icon: Icon(Icons.book),
- onPressed: () =>
- openEpub(attachment),
- ),
- if (attachment.fileType ==
- 'audiobook')
- IconButton(
- icon: Icon(Icons
- .play_circle_outline),
- onPressed: () =>
- openMp3(attachment),
- ),
- IconButton(
- icon: Icon(Icons.delete),
- onPressed: () {
- return _deleteDownload(
- attachment);
- },
- )
- ],
- );
- }
- if (_downloadProgress[attachment.url] !=
- null &&
- _downloadProgress[attachment.url] <
- 1.0)
- return Container(
- width: 28,
- height: 28,
- child: CircularProgressIndicator(
- value: _downloadProgress[
- attachment.url],
- ),
- );
- }
- return Container();
- })
- ],
- ),
- );
- }).toList(),
- ),
- );
- },
- itemCount: _products.length,
- )),
- );
- }
- myFuture(attachment) async {
- final path = await getLocalFilePath(attachment);
- final downloadProgress = await ReviewDownloadsDB().check({
- 'id': attachment.id,
- 'name': attachment.name,
- 'url': attachment.url,
- 'path': path
- });
- return downloadProgress.isEmpty;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement