Advertisement
Guest User

Untitled

a guest
Sep 15th, 2020
475
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Dart 12.03 KB | None | 0 0
  1. import 'dart:async';
  2. import 'dart:convert';
  3. import 'dart:developer';
  4. import 'dart:io';
  5.  
  6. import 'package:cached_network_image/cached_network_image.dart';
  7. import 'package:firebase_auth/firebase_auth.dart';
  8. import 'package:flutter/material.dart';
  9. import 'package:flutter/services.dart';
  10. import 'package:path_provider/path_provider.dart';
  11. import 'package:ruthumana/components/drawer.dart';
  12. import 'package:ruthumana/entities/attachment.dart';
  13. import 'package:ruthumana/entities/downloads.dart';
  14. import 'package:ruthumana/entities/product.dart';
  15. import 'package:ruthumana/loading_state.dart';
  16. import 'package:ruthumana/local_databases/review_download.dart';
  17. import 'package:ruthumana/services/api.dart';
  18. import 'package:ruthumana/services/folio.dart' as folio;
  19. import 'package:ruthumana/services/web.dart';
  20. import 'package:ruthumana/services/audio.dart' as Audio;
  21.  
  22. import 'package:dio/dio.dart';
  23.  
  24. class NewReviewScreen extends StatefulWidget {
  25.   @override
  26.   _NewReviewScreenState createState() {
  27.     return _NewReviewScreenState();
  28.   }
  29. }
  30.  
  31. class _NewReviewScreenState extends State<NewReviewScreen> with LoadingState {
  32.   Set<Product> _products = {};
  33.   Map<String, double> _downloadProgress = {};
  34.   List knownDownloads = [];
  35.  
  36.   @override
  37.   void setState(fn) {
  38.     if (mounted) {
  39.       super.setState(fn);
  40.     }
  41.   }
  42.  
  43.   @override
  44.   void initState() {
  45.     super.initState();
  46.     init();
  47.   }
  48.  
  49.   init() => work(context, () async {
  50.         var currentUser = await FirebaseAuth.instance.currentUser();
  51.         if (currentUser == null) {
  52.           return Navigator.of(context).pushReplacementNamed('/auth');
  53.         }
  54.         knownDownloads = await ReviewDownloadsDB().listAll();
  55.         final ebookResponse = await api.get(path: 'product-types/1');
  56.         final audiobookResponse = await api.get(path: 'product-types/2');
  57.         return setState(() {
  58.           final ebookResponseJson = jsonDecode(ebookResponse.body);
  59.           final audiobookResponseJson = jsonDecode(audiobookResponse.body);
  60.           _products = {
  61.             ...Set<Product>.from(ebookResponseJson['products']
  62.                     .map((json) => Product.fromJson(json)))
  63.                 .where((element) => element.status == ProductStatus.Review),
  64.             ...Set<Product>.from(audiobookResponseJson['products']
  65.                     .map((json) => Product.fromJson(json)))
  66.                 .where((element) => element.status == ProductStatus.Review)
  67.           };
  68.         });
  69.       });
  70.  
  71.   download(Attachment attachment) => work(context, () async {
  72.         final dio = Dio();
  73.         final path = await getLocalFilePath(attachment);
  74.         _downloadProgress[attachment.url] = 0.1;
  75.         var downloadRequest = dio.download(
  76.           attachment.url,
  77.           path,
  78.           deleteOnError: true,
  79.           onReceiveProgress: (count, total) {
  80.             setState(
  81.               () {
  82.                 _downloadProgress[attachment.url] = count / total;
  83.               },
  84.             );
  85.           },
  86.         ).then(
  87.           (value) async {
  88.             await ReviewDownloadsDB().add({
  89.               'id': attachment.id,
  90.               'name': attachment.name,
  91.               'url': attachment.url,
  92.               'path': path
  93.             });
  94.             knownDownloads = await ReviewDownloadsDB().listAll();
  95.           },
  96.         );
  97.         Future.wait([downloadRequest]);
  98.       });
  99.  
  100.   _deleteDownload(Attachment attachment) async {
  101.     setState(() {
  102.       _downloadProgress.remove(attachment.url);
  103.     });
  104.     await ReviewDownloadsDB().remove({'id': attachment.id}).then((value) async {
  105.       final file = File(await getLocalFilePath(attachment));
  106.       if (file.existsSync()) {
  107.         file.deleteSync();
  108.       }
  109.     });
  110.   }
  111.  
  112.   openEpub(Attachment attachment) async {
  113.     String path = await getLocalFilePath(attachment);
  114.     return folio.openEpub(name: attachment.name, path: path);
  115.   }
  116.  
  117.   Future<String> getLocalFilePath(Attachment attachment) async {
  118.     final documentDirectory = await getApplicationDocumentsDirectory();
  119.     final fileName = attachment.url.split('/').last;
  120.     final path = '${documentDirectory.path}/$fileName';
  121.     return path;
  122.   }
  123.  
  124.   openMp3(Attachment attachment) async {
  125.     final path = await getLocalFilePath(attachment);
  126.     return Audio.openMp3(path);
  127.   }
  128.  
  129.   FutureBuilder buildAttachmentCta(Attachment attachment) {
  130.     final fileBuilder = () async {
  131.       final path = await getLocalFilePath(attachment);
  132.       final downloadProgress = await ReviewDownloadsDB().check({
  133.         'id': attachment.id,
  134.         'name': attachment.name,
  135.         'url': attachment.url,
  136.         'path': path
  137.       });
  138.       if (downloadProgress.isEmpty &&
  139.           _downloadProgress[attachment.url] == null) {
  140.         return IconButton(
  141.             icon: Icon(Icons.cloud_download),
  142.             onPressed: () async {
  143.               download(attachment);
  144.             });
  145.       }
  146.  
  147.       if (downloadProgress.isNotEmpty ||
  148.           _downloadProgress[attachment.url] == 1.0) {
  149.         return Row(
  150.           children: [
  151.             if (attachment.fileType == 'epub')
  152.               IconButton(
  153.                 icon: Icon(Icons.book),
  154.                 onPressed: () => openEpub(attachment),
  155.               ),
  156.             if (attachment.fileType == 'audiobook')
  157.               IconButton(
  158.                 icon: Icon(Icons.play_circle_outline),
  159.                 onPressed: () => openMp3(attachment),
  160.               ),
  161.             IconButton(
  162.               icon: Icon(Icons.delete),
  163.               onPressed: () {
  164.                 return _deleteDownload(attachment);
  165.               },
  166.             )
  167.           ],
  168.         );
  169.       }
  170.  
  171.       return Container();
  172.     };
  173.     return FutureBuilder<Widget>(
  174.       builder: (BuildContext context, AsyncSnapshot<Widget> snapshot) {
  175.         return snapshot.data;
  176.       },
  177.       initialData:
  178.           IconButton(icon: CircularProgressIndicator(), onPressed: () {}),
  179.       future: fileBuilder(),
  180.     );
  181.   }
  182.  
  183.   @override
  184.   Widget build(BuildContext context) {
  185.     return WillPopScope(
  186.       onWillPop: () => SystemNavigator.pop(),
  187.       child: Scaffold(
  188.           appBar: AppBar(title: Text('Review')),
  189.           drawer: DrawerWidget(
  190.             selectedPath: '/review',
  191.           ),
  192.           body: (loading && _products.isEmpty)
  193.               ? Center(child: CircularProgressIndicator())
  194.               : ListView.builder(
  195.                   itemBuilder: (context, index) {
  196.                     final product = _products.elementAt(index);
  197.                     return Card(
  198.                       margin: EdgeInsets.all(16.0),
  199.                       child: ExpansionTile(
  200.                         leading: Padding(
  201.                           padding: const EdgeInsets.symmetric(vertical: 8),
  202.                           child: CachedNetworkImage(
  203.                             imageUrl: product.image,
  204.                             fit: BoxFit.cover,
  205.                             placeholder: (context, url) => Container(
  206.                               width: 64,
  207.                               height: 64,
  208.                               color: Colors.grey[300],
  209.                             ),
  210.                           ),
  211.                         ),
  212.                         title: Text(product.name),
  213.                         children: product.attachments.map((attachment) {
  214.                           return Padding(
  215.                             padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
  216.                             child: Row(
  217.                               mainAxisAlignment: MainAxisAlignment.spaceBetween,
  218.                               children: <Widget>[
  219.                                 Expanded(
  220.                                   child: Padding(
  221.                                     padding: const EdgeInsets.only(right: 8.0),
  222.                                     child: Text(attachment.name),
  223.                                   ),
  224.                                 ),
  225.                                 // buildAttachmentCta(attachment),
  226.                                 FutureBuilder(
  227.                                     future: myFuture(attachment),
  228.                                     builder: (context, snapshot) {
  229.                                       if (snapshot.hasData) {
  230.                                         if (snapshot.data &&
  231.                                             _downloadProgress[attachment.url] ==
  232.                                                 null) {
  233.                                           return IconButton(
  234.                                               icon: Icon(Icons.cloud_download),
  235.                                               onPressed: () async {
  236.                                                 download(attachment);
  237.                                               });
  238.                                         }
  239.  
  240.                                         if (!snapshot.data ||
  241.                                             _downloadProgress[attachment.url] ==
  242.                                                 1.0) {
  243.                                           return Row(
  244.                                             children: [
  245.                                               if (attachment.fileType == 'epub')
  246.                                                 IconButton(
  247.                                                   icon: Icon(Icons.book),
  248.                                                   onPressed: () =>
  249.                                                       openEpub(attachment),
  250.                                                 ),
  251.                                               if (attachment.fileType ==
  252.                                                   'audiobook')
  253.                                                 IconButton(
  254.                                                   icon: Icon(Icons
  255.                                                       .play_circle_outline),
  256.                                                   onPressed: () =>
  257.                                                       openMp3(attachment),
  258.                                                 ),
  259.                                               IconButton(
  260.                                                 icon: Icon(Icons.delete),
  261.                                                 onPressed: () {
  262.                                                   return _deleteDownload(
  263.                                                       attachment);
  264.                                                 },
  265.                                               )
  266.                                             ],
  267.                                           );
  268.                                         }
  269.                                         if (_downloadProgress[attachment.url] !=
  270.                                                 null &&
  271.                                             _downloadProgress[attachment.url] <
  272.                                                 1.0)
  273.                                           return Container(
  274.                                             width: 28,
  275.                                             height: 28,
  276.                                             child: CircularProgressIndicator(
  277.                                               value: _downloadProgress[
  278.                                                   attachment.url],
  279.                                             ),
  280.                                           );
  281.                                       }
  282.                                       return Container();
  283.                                     })
  284.                               ],
  285.                             ),
  286.                           );
  287.                         }).toList(),
  288.                       ),
  289.                     );
  290.                   },
  291.                   itemCount: _products.length,
  292.                 )),
  293.     );
  294.   }
  295.  
  296.   myFuture(attachment) async {
  297.     final path = await getLocalFilePath(attachment);
  298.     final downloadProgress = await ReviewDownloadsDB().check({
  299.       'id': attachment.id,
  300.       'name': attachment.name,
  301.       'url': attachment.url,
  302.       'path': path
  303.     });
  304.     return downloadProgress.isEmpty;
  305.   }
  306. }
  307.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement